Skip to content

feat: add "Ask AI on a block" popover for block-document blocks - #798

Merged
ilyabo merged 33 commits into
mainfrom
feat/block-ai-popover
Jul 9, 2026
Merged

ilyabo merged 33 commits into
mainfrom
feat/block-ai-popover

Conversation

@ilyabo

@ilyabo ilyabo commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds a header "Ask AI" affordance to stateful block-document blocks. Submitting a prompt seeds an artifact-scoped chat with an explicit kind:'block' context item and routes the agent to edit that specific block. Chats stay artifact-scoped — a block is represented as a context item, not a new ownership dimension. Users can also add block-document blocks to the prompt context manually via the existing context selector.

v1 scope: the SQLRooms CLI app covers chart, dashboard, html-app (experimental), and map. (The FSQ Spatial Desktop consumer, in a separate repo, covers chart + map.)

What's included

Shared packages

  • @sqlrooms/documents: BlockAiTarget + escape-safe blockContextItemId/parseBlockContextItemId/defaultBlockTitle; an AI-agnostic renderBlockHeaderActions header slot + hasOwnHeaderActions flag on the stateful/chart renderer providers and node-views; optional BlockDocumentAiAdapter.updateBlock.
  • @sqlrooms/ai-config: createBlockContextItem(...) returning an AiRunContextItem (re-exported through @sqlrooms/ai-core → @sqlrooms/ai).
  • @sqlrooms/ai-core: presentational BlockAiPromptPopover; new startAnalysisWhenReady(sessionId) slice action (extracted from startNewSession's mount-poll).
  • @sqlrooms/artifacts/ai: pure findAiSessionForArtifactWithContextItem(...) (reuse-or-create key).
  • @sqlrooms/mosaic: createBlockDocumentChartTools gains an optional targetBlockId to update a chart block in place instead of appending.
  • @sqlrooms/deck: optional headerActions prop on DeckMapBlockRenderer so a map block can render an inline header action next to its settings button.

CLI app (apps/sqlrooms-cli-ui)

  • 'block' context-item resolve/format; block items in the context selector + selected-id validation; startBlockScopedChat (find-or-create artifact-scoped session, seed draft context, reveal assistant, run); optional targetBlock routing in the block-document agent (dashboard→embedded dashboard agent, html-app→embedded html-app agent, map→map tool with mapId, chart→in-place chart update); adapter updateBlock backed by the block-document.update-block command.

Boundaries

  • Shared packages use block-document vocabulary only; product terms (worksheet) stay in the app layer. No @sqlrooms/ai-core block/artifact awareness. Dependency graph documents → artifacts → ai-config preserved (no cycle).

Testing

  • @sqlrooms/documents BlockAiTarget: 12/12 pass.
  • @sqlrooms/ai-config createBlockContextItem: 1/1 pass.
  • @sqlrooms/artifacts artifactAiSessions (incl. new findAiSessionForArtifactWithContextItem cases): 19/19 pass.

Note on the base

This branch is stacked on 2 unmerged local worksheets-base commits — chore: workspace block-document renames (ac9b4c31) and feedback (c85473a5) — that are not yet on any origin branch, so they appear in this PR's diff (11 files). Review the feat: add "Ask AI on a block" popover… commit for this feature. The base can be retargeted if a worksheets integration branch is available.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added “Ask AI” for eligible worksheet blocks using block-scoped prompts and context.
    • AI can now target and update specific block instances (e.g., dashboards, HTML apps, maps, charts).
    • Chart, dashboard, map, and HTML app block headers can now render host-provided action buttons.
  • Bug Fixes
    • Improved AI session selection to resume the correct chat for the selected block context.
    • Added clearer handling for missing/deleted blocks with an “unresolved or deleted” fallback.
    • When updating block metadata, preserves existing values for fields not explicitly provided.

ilyabo and others added 3 commits July 6, 2026 19:25
Add a header "Ask AI" affordance to stateful block-document blocks that
opens a prompt popover, seeds an artifact-scoped chat with an explicit
block context item, and routes the agent to edit that specific block.

Shared:
- @sqlrooms/documents: BlockAiTarget + blockContextItemId/parse/defaultBlockTitle;
  renderBlockHeaderActions slot + hasOwnHeaderActions on renderer providers/node-views;
  optional BlockDocumentAiAdapter.updateBlock.
- @sqlrooms/ai-config: createBlockContextItem (re-exported via ai-core/ai).
- @sqlrooms/ai-core: BlockAiPromptPopover; startAnalysisWhenReady.
- @sqlrooms/artifacts/ai: findAiSessionForArtifactWithContextItem.
- @sqlrooms/mosaic: createBlockDocumentChartTools targetBlockId (in-place chart edit).
- @sqlrooms/deck: optional headerActions prop on DeckMapBlockRenderer.

CLI app (chart/dashboard/html-app/map): block context resolve/format, selector
items + validation, startBlockScopedChat, header wiring, targetBlock routing.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR adds block-context AI primitives, target-block-aware CLI AI routing, block-scoped chat entry points, and header-action rendering support across worksheet, mosaic, deck, and HTML app surfaces.

Changes

Block-context AI and block-scoped chat

Layer / File(s) Summary
Block context contracts
packages/documents/src/BlockAiTarget.ts, packages/documents/src/BlockDocumentAi.ts, packages/documents/src/BlockDocumentSliceConfig.ts, packages/ai-config/src/createBlockContextItem.ts, packages/ai-config/src/index.ts, packages/ai-core/src/index.ts, packages/ai/src/index.ts, packages/documents/src/index.ts, packages/documents/src/createMoveBlockDocumentBlockTool.ts, packages/documents/__tests__/BlockAiTarget.test.ts, packages/ai-config/__tests__/createBlockContextItem.test.ts
Adds block-target identity, parsing, title, and run-context item helpers; extends the block-document adapter interface; and expands package exports and tests around those contracts.
Block run-context lookup
apps/sqlrooms-cli-ui/src/context/formatRunContextInstructions.ts, apps/sqlrooms-cli-ui/src/context/getRunContext.ts, apps/sqlrooms-cli-ui/src/components/useAssistantContextItems.ts, packages/artifacts/src/ai/artifactAiSessionHelpers.ts, packages/artifacts/src/ai/index.ts, packages/artifacts/__tests__/artifactAiSessions.test.ts, packages/ai-core/src/AiSlice.ts
Formats block-specific run-context instructions, resolves block context items, extends assistant context selection and validation for block items, and adds context-scoped AI session lookup plus analysis readiness polling.
CLI target-block agent routing
apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts, packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts, apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts, apps/sqlrooms-cli-ui/src/createCliBlockDocumentAiAdapter.ts, apps/sqlrooms-cli-ui/src/createBlockDocumentAgent.ts, apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts, apps/sqlrooms-cli-ui/src/store.ts, packages/mosaic/__tests__/block-document-ai.test.ts
Renames the CLI AI tool factory for block-document context, wires target-block-aware chart editing and block-document adapter updates, and updates agent tool execution, command messaging, store instructions, and chart-tool tests.
Block-scoped Ask AI entry points
apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts, apps/sqlrooms-cli-ui/src/artifactTypeIds.ts, apps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsx, packages/ai-core/src/components/BlockAiPromptPopover.tsx, packages/ai-core/src/components/context/ContextSelectorItem.tsx, packages/ai-core/src/components/context/ContextSelectorSearchDropdown.tsx, packages/ai-core/src/components/context/types.ts, packages/ai-core/src/components/context/utils.ts
Adds the block prompt popover, block-scoped chat startup, eligible block-type gating, and worksheet block header wiring for the Ask AI action.
Header-actions rendering pipeline
packages/documents/src/BlockDocumentBlockHeaderActions.ts, packages/documents/src/BlockDocumentChartRendererContext.tsx, packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx, packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsx, packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentStatefulBlockNodeView.tsx, packages/deck/src/block.tsx, packages/mosaic/src/charts/block-document/ChartBlockHeader.tsx, packages/mosaic/src/charts/block-document/ChartBlockRenderer.tsx, packages/mosaic/src/dashboard/MosaicDashboard.tsx, packages/mosaic/src/dashboard/MosaicDashboardContext.tsx, packages/mosaic/src/dashboard/MosaicDashboardToolbar.tsx, packages/app-runtime/src/html-app.tsx, apps/sqlrooms-cli-ui/src/workspace/WorksheetDashboardBlockRenderer.tsx, apps/sqlrooms-cli-ui/src/workspace/WorksheetMapBlockRenderer.tsx
Threads optional header-actions props and render callbacks through chart and stateful block renderers and into dashboard, map, deck, and HTML app surfaces.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant WorksheetArtifact
  participant startBlockScopedChat
  participant RoomStore
  participant AiSlice

  User->>WorksheetArtifact: Submit prompt via BlockAiPromptPopover
  WorksheetArtifact->>startBlockScopedChat: target, prompt, revealAssistant
  startBlockScopedChat->>RoomStore: setCurrentArtifact(worksheet)
  startBlockScopedChat->>RoomStore: findAiSessionForArtifactWithContextItem
  alt no existing session
    startBlockScopedChat->>AiSlice: startNewSession
  else existing session found
    startBlockScopedChat->>AiSlice: switch to session
  end
  startBlockScopedChat->>AiSlice: update draftContextItemIds with block context
  startBlockScopedChat->>WorksheetArtifact: revealAssistant()
  startBlockScopedChat->>AiSlice: startAnalysisWhenReady(sessionId)
Loading

Possibly related PRs

  • sqlrooms/sqlrooms#598: Adds the block run-context schema and createBlockContextItem primitives used by this PR’s block-context flow.
  • sqlrooms/sqlrooms#707: Introduces the session draft-context APIs that this PR uses when starting block-scoped chat.
  • sqlrooms/sqlrooms#757: Adds the map block/tooling that this PR targets with targetBlock routing and blockInstanceId handling.
  • sqlrooms/sqlrooms#761: Touches the same chart rendering path that this PR extends with header actions.
  • sqlrooms/sqlrooms#766: Extends the block-document command/adapter layer that this PR uses for updateBlock.
  • sqlrooms/sqlrooms#780: Updates the CLI AI instruction wiring and block-document terminology that this PR builds on.
  • sqlrooms/sqlrooms#797: Modifies the same CLI block-document AI tool layer that this PR extends with target-block behavior.

Suggested reviewers: dmitriy-kostianetskiy, igorDykhta

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding an Ask AI popover for block-document blocks.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/block-ai-popover

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1a0f350c56

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

)}
{blockHeaderActions ? (
<div
className="absolute top-2 right-2 z-20 flex items-center gap-1"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep Ask AI from covering chart settings

When a chart block is configured, ChartBlockRenderer already renders its settings button in the header at the top right, and this new absolute top-2 right-2 z-20 wrapper is rendered above that same area. In that state the Ask AI trigger intercepts clicks on the chart settings button, so users cannot open chart settings for chart blocks; render the action inside the chart header or offset it away from the existing controls.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/ai-core/src/AiSlice.ts (1)

1370-1375: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Unhandled rejection risk on fire-and-forget startAnalysisWhenReady call.

startAnalysisWhenReady awaits startAnalysis, which synchronously calls sendMessage({text: promptText}); if that throws (or any step in the chain throws), the rejection propagates out of startAnalysisWhenReady uncaught here, since the call is void-fired with no .catch. Consider attaching an error handler.

🛡️ Proposed fix
-          // Wait for SessionChatProvider to mount and register sendMessage
-          void get().ai.startAnalysisWhenReady(session.id);
+          // Wait for SessionChatProvider to mount and register sendMessage
+          get().ai.startAnalysisWhenReady(session.id).catch((error) => {
+            console.error('Failed to start analysis for new session:', error);
+          });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ai-core/src/AiSlice.ts` around lines 1370 - 1375, The
fire-and-forget call to `startAnalysisWhenReady` in `AiSlice` can surface an
unhandled rejection if `startAnalysis` or `sendMessage` throws. Update this call
site to attach explicit error handling instead of using a bare `void`, and make
sure any rejection from `startAnalysisWhenReady(session.id)` is caught and
logged or otherwise handled. Use the `setPrompt` and `startAnalysisWhenReady`
flow in `AiSlice` to locate the spot and keep the async chain safe.
🧹 Nitpick comments (18)
packages/ai-config/src/createBlockContextItem.ts (1)

16-32: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Export a typed block item variant here. AiRunContextItem only covers the base fields, so the block-specific keys added in this factory stay untyped through the public API. Extending the schema or exporting a BlockAiRunContextItem type would make those fields safe for consumers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ai-config/src/createBlockContextItem.ts` around lines 16 - 32, The
block item factory is returning block-specific fields that are not represented
in the public type, so consumers only see the base AiRunContextItem shape.
Update createBlockContextItem and the related schema/types to expose a typed
block variant, such as a BlockAiRunContextItem, and ensure the block-specific
keys like blockDocumentId, blockId, blockType, subtitle, blockInstanceId, and
panelId are included in the exported type/schema used by
AiRunContextItemSchema.parse.
apps/sqlrooms-cli-ui/src/createCliBlockDocumentAiAdapter.ts (1)

42-46: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Error message says "worksheet block" instead of generic block-document terminology.

Rest of the migration renames worksheet-scoped naming to block-document terminology; this thrown error text is a leftover.

✏️ Suggested wording
         throw new Error(
           result.error ??
             result.message ??
-            'Failed to update worksheet block.',
+            'Failed to update block document block.',
         );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/createCliBlockDocumentAiAdapter.ts` around lines 42
- 46, The thrown error in createCliBlockDocumentAiAdapter still uses
worksheet-specific wording, which is inconsistent with the block-document
migration. Update the fallback message in the error handling path that throws
from result.error/result.message so it uses generic block-document terminology
instead of “worksheet block,” and keep the change localized to the
createCliBlockDocumentAiAdapter flow.
apps/sqlrooms-cli-ui/src/__tests__/createCliBlockDocumentAiAdapter.test.ts (1)

8-8: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the new updateBlock adapter method.

The suite covers addBlock success/failure but not the newly added updateBlock (success path invoking block-document.update-block, and failure path throwing on result.success === false).

As per coding guidelines, "Add or update tests when changing behavior or public API, when practical."

Also applies to: 53-56, 89-89

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/__tests__/createCliBlockDocumentAiAdapter.test.ts`
at line 8, Add test coverage in createCliBlockDocumentAiAdapter.test for the new
updateBlock method on createCliBlockDocumentAiAdapter, covering both the success
path where it invokes block-document.update-block and the failure path where it
throws when result.success is false. Mirror the existing addBlock test patterns
so the new adapter behavior is asserted consistently, and make sure the new
cases are added alongside the current createCliBlockDocumentAiAdapter suite.

Source: Coding guidelines

apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts (1)

152-160: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor: map guidance in usageHint doesn't name the actual tool.

The html-app branch names the concrete tool (${KnownBlockDocumentTools.add_html_app_block}), but the map branch just says "a direct worksheet map tool when available" instead of referencing ${KnownBlockDocumentTools.create_block_document_map_block}. Since that constant already exists, using it here would keep the guidance consistent and reduce ambiguity for the agent.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts` around lines
152 - 160, The map guidance in createCliBlockDocumentAiTools’s usageHint is too
vague because it does not name the concrete map tool. Update the map branch so
it references KnownBlockDocumentTools.create_block_document_map_block
explicitly, matching the style used for embedded_html_app_agent and
add_html_app_block, and keep the rest of the usageHint wording unchanged.
apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts (3)

290-317: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Same identifier reused for both the schema value and its inferred type.

BlockDocumentAgentInputSchema is declared as a const (the zod schema) and then re-declared as a type via z.infer<typeof BlockDocumentAgentInputSchema> (line 315-317). This is legal TypeScript since types and values live in separate namespaces, but reusing the exact same name for both is easy to misread at call sites like BlockDocumentAgentInputSchema['targetBlock'] (a type position). A distinct name for the inferred type (e.g. BlockDocumentAgentInput) would improve readability.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts` around lines
290 - 317, The schema value and inferred type currently share the same
identifier, which makes `BlockDocumentAgentInputSchema` hard to read and easy to
confuse in type positions. Rename the inferred `z.infer<typeof
BlockDocumentAgentInputSchema>` alias to a distinct type name such as
`BlockDocumentAgentInput`, and update any references in
`createCliBlockDocumentAgentTool` that use the inferred type so the schema
constant and type are clearly separated.

415-423: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Hardcoded tool name instead of constant reference.

Line 419 hardcodes the literal string create_block_document_map_block instead of interpolating ${KnownBlockDocumentTools.create_block_document_map_block} like every other tool reference in this description (including the line right above it). Functionally harmless today since the constant's value matches, but it will silently go stale if the tool key is ever renamed.

🔧 Proposed fix
     ? `1. For a new map, call ${KnownBlockDocumentTools.create_block_document_map_block} directly
-2. For an existing map, call ${KnownBlockDocumentTools.list_blocks} and pass statefulBlock.blockInstanceId as mapId to create_block_document_map_block`
+2. For an existing map, call ${KnownBlockDocumentTools.list_blocks} and pass statefulBlock.blockInstanceId as mapId to ${KnownBlockDocumentTools.create_block_document_map_block}`
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts` around lines
415 - 423, The MAP worksheet guidance in createCliBlockDocumentAgentTool uses a
hardcoded tool name for the existing-map case, which can drift from the source
constant. Update the string in the map-block instructions to reference
KnownBlockDocumentTools.create_block_document_map_block consistently in both
branches, matching the other tool references in this block so the prompt stays
aligned if the tool key changes.

453-462: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Validation error message is discarded in the friendly output on failure.

When the blockInstanceId guard throws (a plain Error, not AiAgentError), the catch block collapses finalOutput to the generic 'Worksheet update failed.' even though the thrown message is a precise, actionable diagnostic (e.g. "dashboard block X is missing blockInstanceId."). The detail is preserved in error, but if finalOutput is what's surfaced to the end user/chat, this specific failure mode becomes indistinguishable from any other error.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts` around lines
453 - 462, The blockInstanceId validation in createCliBlockDocumentAgentTool is
throwing a plain Error with a useful diagnostic, but the catch path turns the
user-facing finalOutput into the generic failure text. Update the failure
handling around the try/catch so the specific validation message from the thrown
error is preserved in finalOutput when the error is not an AiAgentError, while
still keeping the existing fallback for truly generic failures; use the
createCliBlockDocumentAgentTool flow and the targetBlock guard as the key
locations to adjust.
apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAiTools.test.ts (1)

1-140: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing coverage for targetBlockId chart-editing wiring.

This test suite covers the rename, move_block, and HTML-app-block behavior, but doesn't exercise the new targetBlockId parameter that createCliBlockDocumentAiTools now forwards to createBlockDocumentChartTools for in-place chart edits. A quick test asserting createBlockDocumentChartTools/chartTools receive targetBlockId when supplied would guard this new capability against regressions.
As per coding guidelines, **/*.{js,ts,jsx,tsx}: "Add or update tests when changing behavior or public API, when practical."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAiTools.test.ts`
around lines 1 - 140, Add test coverage for the new targetBlockId wiring in
createCliBlockDocumentAiTools. Update the test setup to pass a targetBlockId
through createOptions and assert that createBlockDocumentChartTools (and the
returned chartTools path) receives it when chart tools are created. Use the
existing createCliBlockDocumentAiTools and createOptions helpers, plus the
chartTools/createBlockDocumentChartTools symbols, so the in-place chart editing
behavior is guarded against regressions.

Source: Coding guidelines

apps/sqlrooms-cli-ui/src/createBlockDocumentAgent.ts (1)

218-229: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Tight coupling between extraTools gating and the outer experimentalEnabled flag.

extraTools checks the closure-captured experimentalEnabled rather than the htmlAppBlocksEnabled/mapBlocksEnabled values threaded into blockDocumentAgentOptions. Today they're always equal (htmlAppBlocksEnabled: experimentalEnabled, mapBlocksEnabled: experimentalEnabled), so there's no active bug, but if these two flags are ever decoupled (e.g., enabling maps without enabling HTML apps), extraTools would silently provide/withhold the wrong tool set relative to what getBlockDocumentAgentInstructions/selectTargetBlockTools expect.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/createBlockDocumentAgent.ts` around lines 218 - 229,
The extraTools gating is too tightly coupled to the outer experimentalEnabled
flag instead of the blockDocumentAgentOptions feature flags. Update
createBlockDocumentAgent so extraTools decides which tools to expose based on
the same htmlAppBlocksEnabled and mapBlocksEnabled values used by
getBlockDocumentAgentInstructions and selectTargetBlockTools, rather than
assuming they always match experimentalEnabled. Keep the tool map in sync with
those flags so each tool is included or omitted independently and future flag
decoupling does not change behavior unexpectedly.
apps/sqlrooms-cli-ui/src/store.ts (1)

180-187: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop blockDocumentAgentToolName from BLOCK_DOCUMENT_OPTIONS unless it’s wired into the command factory; it isn’t consumed anywhere and reads as dead config.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/store.ts` around lines 180 - 187, Remove the unused
blockDocumentAgentToolName entry from BLOCK_DOCUMENT_OPTIONS in store.ts unless
it is actually passed through the command factory; the current constant only
defines dead config. Check the BLOCK_DOCUMENT_OPTIONS object and any related
command creation path to confirm nothing consumes
CLI_BLOCK_DOCUMENT_AGENT_TOOL_NAME, and keep the options object limited to
values that are wired into the worksheet/block-document setup.
packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx (2)

29-40: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing tsdoc on new exported types/hook.

BlockDocumentBlockHeaderActionsRenderContext, BlockDocumentBlockHeaderActionsRenderer, and useBlockDocumentRenderBlockHeaderActions are all new public exports without tsdoc.

As per coding guidelines, "Add tsdoc to exported types and functions in @sqlrooms/* packages."

Also applies to: 124-128

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx` around
lines 29 - 40, Add tsdoc for the new public exports in
BlockDocumentStatefulBlockRendererContext: document
BlockDocumentBlockHeaderActionsRenderContext and
BlockDocumentBlockHeaderActionsRenderer, and also add tsdoc to
useBlockDocumentRenderBlockHeaderActions. Make the comments describe the purpose
of each export and its parameters/shape so the API is documented consistently
with other `@sqlrooms` exports.

Source: Coding guidelines


29-40: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Deduplicate the shared header-actions types

BlockDocumentBlockHeaderActionsRenderContext and BlockDocumentBlockHeaderActionsRenderer are duplicated in both renderer-context files. Extract them into a shared module so the shape stays in sync across chart and stateful block renderers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx` around
lines 29 - 40, The header-actions context and renderer types are duplicated
across the renderer-context files, so move
BlockDocumentBlockHeaderActionsRenderContext and
BlockDocumentBlockHeaderActionsRenderer into a shared module and update both the
chart and stateful block renderer contexts to import them. Keep the shared
definitions as the single source of truth so both callers use the same shape
without drifting.
apps/sqlrooms-cli-ui/src/context/formatRunContextInstructions.ts (1)

82-119: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider unit tests for the new block-context formatting branches.

formatBlockContextInstructions has distinct branches (unresolved/deleted block vs. resolved, plus type-specific delegation text for dashboard/html-app/map/chart) that aren't covered by any provided tests.

As per coding guidelines, "Add or update tests when changing behavior or public API, when practical."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/context/formatRunContextInstructions.ts` around
lines 82 - 119, Add unit tests for formatBlockContextInstructions to cover both
branches: unresolved/deleted blocks returning the “Target block is unresolved or
deleted” message, and resolved blocks returning the “Target block” message with
artifact title and instanceId. Also add type-specific assertions for the
dashboard, HTML app, map, and chart delegation text so the new behavior in
formatBlockContextInstructions is locked down.

Source: Coding guidelines

apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts (1)

1-67: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add unit tests for the new session-orchestration flow.

This file introduces non-trivial branching (missing artifact, session reuse vs creation, session-creation failure, analysis-start timeout) with no accompanying tests, unlike the sibling packages called out as tested in the PR description.

As per coding guidelines, "Add or update tests when changing behavior or public API, when practical."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts` around lines 1 - 67, Add
unit tests for startBlockScopedChat to cover the new session-orchestration
branches: missing/non-worksheet artifact, existing session reuse, new session
creation, session creation failure, and analysis-start timeout. Mock
useRoomStore, findAiSessionForArtifactWithContextItem, toast, and
revealAssistant so you can assert the correct calls and early returns without
relying on real state. Focus the tests around startBlockScopedChat and the
session/artifact store interactions to match the behavior introduced here.

Source: Coding guidelines

apps/sqlrooms-cli-ui/src/components/useAssistantContextItems.ts (2)

13-27: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing test coverage for the new block-context selection/validation logic.

This adds substantial new behavior — deriving BlockAiTargets from document nodes, building block-kind selector items, and validating selected block context ids against live document content — with no accompanying test updates in this cohort. As per coding guidelines, **/*.{js,ts,jsx,tsx} changes should add or update tests when changing behavior or public API, when practical.

Also applies to: 36-71, 105-108, 144-174, 189-191, 205-214, 223-223, 245-257

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/components/useAssistantContextItems.ts` around lines
13 - 27, Add or update tests for the new block-context behavior in
useAssistantContextItems: cover deriving BlockAiTarget values from
blockDocumentNodeToBlock, building block-kind selector items in
getAssistantContextItems, and validating selected block ids against current
document content in the useMemo/useRoomStore flow. Add cases for
parseBlockContextItemId, blockContextItemId, and defaultBlockTitle handling so
the selection/filtering logic is verified when document nodes or artifact types
change.

Source: Coding guidelines


245-257: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Full node→block conversion on every validation check is wasteful.

For each selected block context id, this validates by calling blockDocumentNodeToBlock(node) (which does a full zod safeParse per node type) over every node in the document just to compare block?.id === blockContext.blockId. This recomputes inside useMemo whenever blockDocuments changes (i.e. on every document edit), and scales as O(selectedIds * nodeCount) with repeated zod parsing overhead that isn't needed for a simple id lookup.

♻️ Suggested direction

Expose a lightweight id-only lookup (e.g. reuse the internal nodeId(node) helper from packages/documents/src/BlockDocumentSliceConfig.ts instead of the full blockDocumentNodeToBlock conversion) so validation doesn't pay for full schema parsing on every node.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/components/useAssistantContextItems.ts` around lines
245 - 257, The block-context validation in useAssistantContextItems is doing
full blockDocumentNodeToBlock conversion for every node just to compare ids,
which is too expensive. Replace that scan with a lightweight id-only lookup
using the existing nodeId helper from BlockDocumentSliceConfig (or an equivalent
internal id accessor) so the useMemo check avoids zod parsing. Keep the logic in
the blockContext branch and ensure the comparison still matches
blockContext.blockId against the node’s id without materializing full blocks.
apps/sqlrooms-cli-ui/src/context/getRunContext.ts (1)

91-96: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid double-parsing the matched node.

blockDocumentNodeToBlock is called once per candidate inside .find, then re-called on the matched node to obtain block. Consider tracking the parsed block during the search to skip the redundant re-parse.

♻️ Proposed refactor
-  const node = blockDocument?.content.content.find((candidate) => {
-    const block = blockDocumentNodeToBlock(candidate);
-    return block?.id === parsedId.blockId;
-  });
-  const block = node ? blockDocumentNodeToBlock(node) : undefined;
-  if (!block) return undefined;
+  let block: ReturnType<typeof blockDocumentNodeToBlock> | undefined;
+  for (const candidate of blockDocument?.content.content ?? []) {
+    const candidateBlock = blockDocumentNodeToBlock(candidate);
+    if (candidateBlock?.id === parsedId.blockId) {
+      block = candidateBlock;
+      break;
+    }
+  }
+  if (!block) return undefined;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/context/getRunContext.ts` around lines 91 - 96, The
matching logic in getRunContext currently parses each candidate with
blockDocumentNodeToBlock inside the find callback and then parses the winning
node again afterward. Refactor this blockId lookup to reuse the parsed block
from the search phase so the matched candidate is not decoded twice; keep the
behavior the same by returning or storing the parsed Block alongside the node
and using that value directly when setting block.
packages/ai-core/src/components/BlockAiPromptPopover.tsx (1)

1-149: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add tests for the new BlockAiPromptPopover public component.

This is a new exported component (from @sqlrooms/ai-core, re-exported via @sqlrooms/ai) with non-trivial interactive behavior (Enter-to-submit, Escape-to-close, disabled/running guards, controlled/uncontrolled open state). The PR description only confirms tests passing for @sqlrooms/documents, @sqlrooms/ai-config, and @sqlrooms/artifacts — not @sqlrooms/ai-core. Consider adding RTL-based tests covering submit-on-Enter, no-submit-on-Shift+Enter, Escape-to-close, and disabled/running states.

Do you want me to draft a test file for this component?

As per coding guidelines, "Add or update tests when changing behavior or public API, when practical."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ai-core/src/components/BlockAiPromptPopover.tsx` around lines 1 -
149, Add RTL coverage for the new public BlockAiPromptPopover component so its
interactive behavior is verified in `@sqlrooms/ai-core`. Create tests around
BlockAiPromptPopover for submit-on-Enter, no submit on Shift+Enter, Escape
closing the popover, and disabled/isRunning guards, including both controlled
and uncontrolled open state paths. Use the component’s key symbols
(BlockAiPromptPopover, handleSubmit, handleKeyDown, setOpen) to locate the
behavior and assert the trigger, textarea, and submit button wiring works as
intended.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts`:
- Around line 51-57: The session draft context update in startBlockScopedChat is
appending contextItemId unconditionally, which can duplicate ids when reuse is
based on an existing draft context match. Update the logic around
useRoomStore.getState(), ai.getSessionDraftContextItemIds, and
ai.setSessionDraftContextItemIds so contextItemId is only added if it is not
already present in draftContextItemIds. Keep the reuse behavior intact for
existing sessions, but avoid growing the draft array with repeated clicks on the
same artifact block.

In `@apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts`:
- Line 246: The runtime success messages still use the old “worksheet”
terminology, so update the `message` strings returned from
`createCliBlockDocumentCommands` to consistently say “block document” (or
matching block-document wording) for each affected action. Replace the stale
text in the command result payloads for the add/update/delete-style branches so
callers and the AI tool output no longer expose the renamed terminology
mismatch.
- Around line 349-381: The update-block-metadata command in execute is returning
raw input fields instead of the persisted block values, so its result can ցույց
undefined for unchanged caption/height. Update the returned data to reflect the
actual post-update state by using the object from
state.blockDocuments.updateBlock (or by re-reading the block) and returning its
title, caption, and height, while keeping blockDocumentId and blockId unchanged.
Locate this in createCliBlockDocumentCommands.ts within the update block
metadata command handler.

In `@packages/documents/src/BlockAiTarget.ts`:
- Around line 28-77: Add tsdoc comments to the public helper exports in
BlockAiTarget.ts: blockContextItemId, parseBlockContextItemId, and
defaultBlockTitle. Document what each helper accepts, returns, and any special
cases (for example when parseBlockContextItemId returns undefined or when
defaultBlockTitle falls back to "Block"), matching the style used for
BlockAiTarget field comments and the package guideline for exported symbols.

In `@packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts`:
- Around line 54-78: The chart edit flow in createBlockDocumentChartTools
currently rebuilds the block payload with caption: title ?? 'Chart', which
overwrites an existing user caption on partial updates. In the targetBlockId
branch, fetch and merge the current chart block caption from the existing block
state before calling blockDocumentAdapter.updateBlock, and only use the default
when neither the edit payload nor the existing caption provides one. Keep the
fix localized to createBlockDocumentChartTools and preserve the existing
updateBlock behavior and return path.

---

Outside diff comments:
In `@packages/ai-core/src/AiSlice.ts`:
- Around line 1370-1375: The fire-and-forget call to `startAnalysisWhenReady` in
`AiSlice` can surface an unhandled rejection if `startAnalysis` or `sendMessage`
throws. Update this call site to attach explicit error handling instead of using
a bare `void`, and make sure any rejection from
`startAnalysisWhenReady(session.id)` is caught and logged or otherwise handled.
Use the `setPrompt` and `startAnalysisWhenReady` flow in `AiSlice` to locate the
spot and keep the async chain safe.

---

Nitpick comments:
In `@apps/sqlrooms-cli-ui/src/__tests__/createCliBlockDocumentAiAdapter.test.ts`:
- Line 8: Add test coverage in createCliBlockDocumentAiAdapter.test for the new
updateBlock method on createCliBlockDocumentAiAdapter, covering both the success
path where it invokes block-document.update-block and the failure path where it
throws when result.success is false. Mirror the existing addBlock test patterns
so the new adapter behavior is asserted consistently, and make sure the new
cases are added alongside the current createCliBlockDocumentAiAdapter suite.

In `@apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAiTools.test.ts`:
- Around line 1-140: Add test coverage for the new targetBlockId wiring in
createCliBlockDocumentAiTools. Update the test setup to pass a targetBlockId
through createOptions and assert that createBlockDocumentChartTools (and the
returned chartTools path) receives it when chart tools are created. Use the
existing createCliBlockDocumentAiTools and createOptions helpers, plus the
chartTools/createBlockDocumentChartTools symbols, so the in-place chart editing
behavior is guarded against regressions.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts`:
- Around line 290-317: The schema value and inferred type currently share the
same identifier, which makes `BlockDocumentAgentInputSchema` hard to read and
easy to confuse in type positions. Rename the inferred `z.infer<typeof
BlockDocumentAgentInputSchema>` alias to a distinct type name such as
`BlockDocumentAgentInput`, and update any references in
`createCliBlockDocumentAgentTool` that use the inferred type so the schema
constant and type are clearly separated.
- Around line 415-423: The MAP worksheet guidance in
createCliBlockDocumentAgentTool uses a hardcoded tool name for the existing-map
case, which can drift from the source constant. Update the string in the
map-block instructions to reference
KnownBlockDocumentTools.create_block_document_map_block consistently in both
branches, matching the other tool references in this block so the prompt stays
aligned if the tool key changes.
- Around line 453-462: The blockInstanceId validation in
createCliBlockDocumentAgentTool is throwing a plain Error with a useful
diagnostic, but the catch path turns the user-facing finalOutput into the
generic failure text. Update the failure handling around the try/catch so the
specific validation message from the thrown error is preserved in finalOutput
when the error is not an AiAgentError, while still keeping the existing fallback
for truly generic failures; use the createCliBlockDocumentAgentTool flow and the
targetBlock guard as the key locations to adjust.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts`:
- Around line 152-160: The map guidance in createCliBlockDocumentAiTools’s
usageHint is too vague because it does not name the concrete map tool. Update
the map branch so it references
KnownBlockDocumentTools.create_block_document_map_block explicitly, matching the
style used for embedded_html_app_agent and add_html_app_block, and keep the rest
of the usageHint wording unchanged.

In `@apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts`:
- Around line 1-67: Add unit tests for startBlockScopedChat to cover the new
session-orchestration branches: missing/non-worksheet artifact, existing session
reuse, new session creation, session creation failure, and analysis-start
timeout. Mock useRoomStore, findAiSessionForArtifactWithContextItem, toast, and
revealAssistant so you can assert the correct calls and early returns without
relying on real state. Focus the tests around startBlockScopedChat and the
session/artifact store interactions to match the behavior introduced here.

In `@apps/sqlrooms-cli-ui/src/components/useAssistantContextItems.ts`:
- Around line 13-27: Add or update tests for the new block-context behavior in
useAssistantContextItems: cover deriving BlockAiTarget values from
blockDocumentNodeToBlock, building block-kind selector items in
getAssistantContextItems, and validating selected block ids against current
document content in the useMemo/useRoomStore flow. Add cases for
parseBlockContextItemId, blockContextItemId, and defaultBlockTitle handling so
the selection/filtering logic is verified when document nodes or artifact types
change.
- Around line 245-257: The block-context validation in useAssistantContextItems
is doing full blockDocumentNodeToBlock conversion for every node just to compare
ids, which is too expensive. Replace that scan with a lightweight id-only lookup
using the existing nodeId helper from BlockDocumentSliceConfig (or an equivalent
internal id accessor) so the useMemo check avoids zod parsing. Keep the logic in
the blockContext branch and ensure the comparison still matches
blockContext.blockId against the node’s id without materializing full blocks.

In `@apps/sqlrooms-cli-ui/src/context/formatRunContextInstructions.ts`:
- Around line 82-119: Add unit tests for formatBlockContextInstructions to cover
both branches: unresolved/deleted blocks returning the “Target block is
unresolved or deleted” message, and resolved blocks returning the “Target block”
message with artifact title and instanceId. Also add type-specific assertions
for the dashboard, HTML app, map, and chart delegation text so the new behavior
in formatBlockContextInstructions is locked down.

In `@apps/sqlrooms-cli-ui/src/context/getRunContext.ts`:
- Around line 91-96: The matching logic in getRunContext currently parses each
candidate with blockDocumentNodeToBlock inside the find callback and then parses
the winning node again afterward. Refactor this blockId lookup to reuse the
parsed block from the search phase so the matched candidate is not decoded
twice; keep the behavior the same by returning or storing the parsed Block
alongside the node and using that value directly when setting block.

In `@apps/sqlrooms-cli-ui/src/createBlockDocumentAgent.ts`:
- Around line 218-229: The extraTools gating is too tightly coupled to the outer
experimentalEnabled flag instead of the blockDocumentAgentOptions feature flags.
Update createBlockDocumentAgent so extraTools decides which tools to expose
based on the same htmlAppBlocksEnabled and mapBlocksEnabled values used by
getBlockDocumentAgentInstructions and selectTargetBlockTools, rather than
assuming they always match experimentalEnabled. Keep the tool map in sync with
those flags so each tool is included or omitted independently and future flag
decoupling does not change behavior unexpectedly.

In `@apps/sqlrooms-cli-ui/src/createCliBlockDocumentAiAdapter.ts`:
- Around line 42-46: The thrown error in createCliBlockDocumentAiAdapter still
uses worksheet-specific wording, which is inconsistent with the block-document
migration. Update the fallback message in the error handling path that throws
from result.error/result.message so it uses generic block-document terminology
instead of “worksheet block,” and keep the change localized to the
createCliBlockDocumentAiAdapter flow.

In `@apps/sqlrooms-cli-ui/src/store.ts`:
- Around line 180-187: Remove the unused blockDocumentAgentToolName entry from
BLOCK_DOCUMENT_OPTIONS in store.ts unless it is actually passed through the
command factory; the current constant only defines dead config. Check the
BLOCK_DOCUMENT_OPTIONS object and any related command creation path to confirm
nothing consumes CLI_BLOCK_DOCUMENT_AGENT_TOOL_NAME, and keep the options object
limited to values that are wired into the worksheet/block-document setup.

In `@packages/ai-config/src/createBlockContextItem.ts`:
- Around line 16-32: The block item factory is returning block-specific fields
that are not represented in the public type, so consumers only see the base
AiRunContextItem shape. Update createBlockContextItem and the related
schema/types to expose a typed block variant, such as a BlockAiRunContextItem,
and ensure the block-specific keys like blockDocumentId, blockId, blockType,
subtitle, blockInstanceId, and panelId are included in the exported type/schema
used by AiRunContextItemSchema.parse.

In `@packages/ai-core/src/components/BlockAiPromptPopover.tsx`:
- Around line 1-149: Add RTL coverage for the new public BlockAiPromptPopover
component so its interactive behavior is verified in `@sqlrooms/ai-core`. Create
tests around BlockAiPromptPopover for submit-on-Enter, no submit on Shift+Enter,
Escape closing the popover, and disabled/isRunning guards, including both
controlled and uncontrolled open state paths. Use the component’s key symbols
(BlockAiPromptPopover, handleSubmit, handleKeyDown, setOpen) to locate the
behavior and assert the trigger, textarea, and submit button wiring works as
intended.

In `@packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx`:
- Around line 29-40: Add tsdoc for the new public exports in
BlockDocumentStatefulBlockRendererContext: document
BlockDocumentBlockHeaderActionsRenderContext and
BlockDocumentBlockHeaderActionsRenderer, and also add tsdoc to
useBlockDocumentRenderBlockHeaderActions. Make the comments describe the purpose
of each export and its parameters/shape so the API is documented consistently
with other `@sqlrooms` exports.
- Around line 29-40: The header-actions context and renderer types are
duplicated across the renderer-context files, so move
BlockDocumentBlockHeaderActionsRenderContext and
BlockDocumentBlockHeaderActionsRenderer into a shared module and update both the
chart and stateful block renderer contexts to import them. Keep the shared
definitions as the single source of truth so both callers use the same shape
without drifting.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3d4a131c-16ee-45a3-8ad3-8bf900a7f4c0

📥 Commits

Reviewing files that changed from the base of the PR and between cbe35fd and 1a0f350.

📒 Files selected for processing (39)
  • apps/sqlrooms-cli-ui/src/__tests__/createCliBlockDocumentAiAdapter.test.ts
  • apps/sqlrooms-cli-ui/src/__tests__/createCliBlockDocumentCommands.test.ts
  • apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAiTools.test.ts
  • apps/sqlrooms-cli-ui/src/ai/constants.ts
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts
  • apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts
  • apps/sqlrooms-cli-ui/src/artifactTypeIds.ts
  • apps/sqlrooms-cli-ui/src/components/useAssistantContextItems.ts
  • apps/sqlrooms-cli-ui/src/components/useLocalFileLoader.ts
  • apps/sqlrooms-cli-ui/src/context/formatRunContextInstructions.ts
  • apps/sqlrooms-cli-ui/src/context/getRunContext.ts
  • apps/sqlrooms-cli-ui/src/createBlockDocumentAgent.ts
  • apps/sqlrooms-cli-ui/src/createCliBlockDocumentAiAdapter.ts
  • apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts
  • apps/sqlrooms-cli-ui/src/createWorksheetAiAdapter.ts
  • apps/sqlrooms-cli-ui/src/store.ts
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsx
  • packages/ai-config/__tests__/createBlockContextItem.test.ts
  • packages/ai-config/src/createBlockContextItem.ts
  • packages/ai-config/src/index.ts
  • packages/ai-core/src/AiSlice.ts
  • packages/ai-core/src/components/BlockAiPromptPopover.tsx
  • packages/ai-core/src/index.ts
  • packages/ai/src/index.ts
  • packages/artifacts/__tests__/artifactAiSessions.test.ts
  • packages/artifacts/src/ai/artifactAiSessionHelpers.ts
  • packages/artifacts/src/ai/index.ts
  • packages/deck/src/block.tsx
  • packages/documents/__tests__/BlockAiTarget.test.ts
  • packages/documents/src/BlockAiTarget.ts
  • packages/documents/src/BlockDocumentAi.ts
  • packages/documents/src/BlockDocumentChartRendererContext.tsx
  • packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsx
  • packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentStatefulBlockNodeView.tsx
  • packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx
  • packages/documents/src/createMoveBlockDocumentBlockTool.ts
  • packages/documents/src/index.ts
  • packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts
💤 Files with no reviewable changes (1)
  • apps/sqlrooms-cli-ui/src/createWorksheetAiAdapter.ts

Comment thread apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts Outdated
Comment thread apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts Outdated
Comment thread apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts
Comment thread packages/documents/src/BlockAiTarget.ts
Comment thread packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 94bee8f663

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

)}
{blockHeaderActions ? (
<div
className="absolute top-2 right-2 z-20 flex items-center gap-1"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid overlaying stateful block header controls

In CLI worksheets, stateful blocks such as dashboards and maps already render controls in the top-right of their own headers (for example the dashboard toolbar buttons and the map fit/settings buttons). Because no entries from createStatefulBlockTypes set hasOwnHeaderActions, this absolute top-2 right-2 z-20 Ask AI wrapper is rendered over those controls and intercepts clicks, making the underlying block controls inaccessible whenever Ask AI is available for that block type. Render the action through the block header/renderer or offset it away from existing controls.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts (3)

298-377: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

No test coverage for the new targetBlock validation/routing logic.

This adds non-trivial behavior: blockInstanceId validation, tool-set restriction by block type, and structured failure when no tool matches. None of this is covered by tests in the provided files, unlike other layers in this cohort (documents/ai-config/artifacts). As per coding guidelines, "Add or update tests when changing behavior or public API, when practical."

Also applies to: 448-517

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts` around lines
298 - 377, Add tests for the new targetBlock behavior in
createCliBlockDocumentAgentTool, covering validation of blockInstanceId, the
tool selection/routing performed by selectTargetBlockTools, and the
targetBlock-specific prompt/instructions from getTargetBlockInstructions and
targetBlockPrompt. Include cases for each supported blockType (dashboard,
html-app, map, chart) plus the failure path when no matching tool is available,
and verify the agent only exposes the restricted tool set when a targetBlock is
provided.

Source: Coding guidelines


537-542: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

"Worksheet created successfully" is misleading for target-block edits.

When targetBlock is set, the agent is editing an existing block, not creating a worksheet; the fallback success text should reflect that.

💬 Suggested fix
-          finalOutput: result.finalOutput || 'Worksheet created successfully.',
+          finalOutput:
+            result.finalOutput ||
+            (targetBlock
+              ? 'Worksheet block updated successfully.'
+              : 'Worksheet created successfully.'),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts` around lines
537 - 542, The fallback success message in createCliBlockDocumentAgentTool is
misleading when targetBlock is present because the agent is updating an existing
block rather than creating a worksheet. Update the finalOutput fallback in the
return object so it uses a target-block edit message when targetBlock is set,
while keeping the existing worksheet-created text only for the create flow. Use
the createCliBlockDocumentAgentTool logic and the targetBlock check to choose
the appropriate success text.

322-331: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Pre-bind the target instance ids for dashboard, HTML app, and map tools
targetBlock only scopes chart programmatically; dashboard/html-app/map still rely on prompt text plus a generic tool. createBlockDocumentMapBlockTool also only fixes blockDocumentId, so dashboardId/appId/mapId can still drift if the model misreads the target. Bind targetBlock.blockInstanceId into those tool calls before exposing them.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts` around lines
322 - 331, The target block routing text in createCliBlockDocumentAgentTool
still leaves dashboard, html-app, and map instance IDs to the model, which can
drift from targetBlock.blockInstanceId. Update the tool-binding flow so
embedded_dashboard_agent, embedded_html_app_agent, and
create_block_document_map_block are pre-bound with the target block’s instance
id before they are exposed, keeping the existing chart in-place behavior tied to
targetBlock.blockId.
packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsx (1)

47-48: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Memoize blockHeaderActions to preserve ChartRendererBoundary memoization.

renderBlockHeaderActions(...) is invoked fresh on every render, producing a new ReactNode reference each time. Passing this into the memo-wrapped ChartRendererBoundary as headerActions defeats its shallow-equality memoization, causing the chart Renderer to re-render on every parent render regardless of whether documentId/blockId/config/etc. actually changed.

⚡ Proposed fix
-  const blockHeaderActions =
-    !readOnly && renderBlockHeaderActions
-      ? renderBlockHeaderActions({
-          blockDocumentId: documentId,
-          blockId,
-          blockType: 'chart',
-          title: caption,
-        })
-      : null;
+  const blockHeaderActions = useMemo(
+    () =>
+      !readOnly && renderBlockHeaderActions
+        ? renderBlockHeaderActions({
+            blockDocumentId: documentId,
+            blockId,
+            blockType: 'chart',
+            title: caption,
+          })
+        : null,
+    [readOnly, renderBlockHeaderActions, documentId, blockId, caption],
+  );

Also applies to: 57-65, 123-123

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsx`
around lines 47 - 48, `ChartRendererBoundary` is losing memoization because
`renderBlockHeaderActions()` returns a fresh ReactNode on every render in
`BlockDocumentChartNodeView`. Memoize the computed `blockHeaderActions` value
with the relevant inputs so the same reference is passed through to
`ChartRendererBoundary`, and keep using the existing
`useBlockDocumentChartRenderBlockHeaderActions` hook plus the
`documentId`/`blockId`/`config`-driven render path to avoid unnecessary
`Renderer` re-renders.
🧹 Nitpick comments (3)
packages/ai-config/src/createBlockContextItem.ts (1)

1-41: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing tsdoc on exported schema/type/function.

BlockAiRunContextItemSchema, BlockAiRunContextItem, and createBlockContextItem are all exported public API from this @sqlrooms/* package but have no tsdoc comments.

As per coding guidelines, "Add tsdoc to exported types and functions in @sqlrooms/* packages."

📝 Proposed tsdoc additions
+/**
+ * Schema for a run-context item that targets a specific block within a block document.
+ */
 export const BlockAiRunContextItemSchema = AiRunContextItemSchema.extend({
   kind: z.literal('block'),
   blockDocumentId: z.string(),
   blockId: z.string(),
   blockType: z.string(),
   blockInstanceId: z.string().optional(),
   panelId: z.string().optional(),
 });

+/** Inferred type for a block-scoped AI run-context item. */
 export type BlockAiRunContextItem = z.infer<typeof BlockAiRunContextItemSchema>;
+/**
+ * Constructs and validates a block-scoped AI run-context item.
+ */
 export function createBlockContextItem(fields: {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ai-config/src/createBlockContextItem.ts` around lines 1 - 41, Add
tsdoc comments for the exported public API in createBlockContextItem.ts:
BlockAiRunContextItemSchema, BlockAiRunContextItem, and createBlockContextItem.
Describe what each schema/type/function represents and the key fields/behavior
so the generated docs align with the `@sqlrooms/`* guideline for exported types
and functions.

Source: Coding guidelines

apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts (1)

543-552: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant AiAgentError branch — both arms return the same value.

error instanceof AiAgentError ? errorMessage : error instanceof Error ? errorMessage : ... returns errorMessage in both the AiAgentError and generic Error cases (and AiAgentError presumably extends Error), so the extra check is dead weight.

♻️ Simplify
-        const friendlyMessage =
-          error instanceof AiAgentError
-            ? errorMessage
-            : error instanceof Error
-              ? errorMessage
-              : 'Worksheet update failed.';
+        const friendlyMessage =
+          error instanceof Error ? errorMessage : 'Worksheet update failed.';
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts` around lines
543 - 552, The friendly message selection in createCliBlockDocumentAgentTool is
redundant because the AiAgentError branch and the generic Error branch both
return the same value. Simplify the catch block by removing the AiAgentError
instanceof check and keep a single Error case that uses errorMessage, with the
fallback message only for non-Error values.
packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx (1)

49-49: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add tsdoc for new header-actions fields.

hasOwnHeaderActions, the context's renderBlockHeaderActions, and the provider prop of the same name lack doc comments, unlike the new useBlockDocumentRenderBlockHeaderActions() hook which is documented. As per coding guidelines, "Add tsdoc to exported types and functions in @sqlrooms/* packages."

Also applies to: 59-59, 72-77

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx` at line
49, Add TSDoc for the new header-actions API surface in
BlockDocumentStatefulBlockRendererContext: document the exported
hasOwnHeaderActions field, the renderBlockHeaderActions context property, and
the matching provider prop so they match the style of
useBlockDocumentRenderBlockHeaderActions(). Update the relevant exported
type/interface and provider declaration in
BlockDocumentStatefulBlockRendererContext.tsx, keeping the comments concise and
aligned with the existing documentation conventions for `@sqlrooms/`* exports.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts`:
- Around line 298-377: Add tests for the new targetBlock behavior in
createCliBlockDocumentAgentTool, covering validation of blockInstanceId, the
tool selection/routing performed by selectTargetBlockTools, and the
targetBlock-specific prompt/instructions from getTargetBlockInstructions and
targetBlockPrompt. Include cases for each supported blockType (dashboard,
html-app, map, chart) plus the failure path when no matching tool is available,
and verify the agent only exposes the restricted tool set when a targetBlock is
provided.
- Around line 537-542: The fallback success message in
createCliBlockDocumentAgentTool is misleading when targetBlock is present
because the agent is updating an existing block rather than creating a
worksheet. Update the finalOutput fallback in the return object so it uses a
target-block edit message when targetBlock is set, while keeping the existing
worksheet-created text only for the create flow. Use the
createCliBlockDocumentAgentTool logic and the targetBlock check to choose the
appropriate success text.
- Around line 322-331: The target block routing text in
createCliBlockDocumentAgentTool still leaves dashboard, html-app, and map
instance IDs to the model, which can drift from targetBlock.blockInstanceId.
Update the tool-binding flow so embedded_dashboard_agent,
embedded_html_app_agent, and create_block_document_map_block are pre-bound with
the target block’s instance id before they are exposed, keeping the existing
chart in-place behavior tied to targetBlock.blockId.

In
`@packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsx`:
- Around line 47-48: `ChartRendererBoundary` is losing memoization because
`renderBlockHeaderActions()` returns a fresh ReactNode on every render in
`BlockDocumentChartNodeView`. Memoize the computed `blockHeaderActions` value
with the relevant inputs so the same reference is passed through to
`ChartRendererBoundary`, and keep using the existing
`useBlockDocumentChartRenderBlockHeaderActions` hook plus the
`documentId`/`blockId`/`config`-driven render path to avoid unnecessary
`Renderer` re-renders.

---

Nitpick comments:
In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts`:
- Around line 543-552: The friendly message selection in
createCliBlockDocumentAgentTool is redundant because the AiAgentError branch and
the generic Error branch both return the same value. Simplify the catch block by
removing the AiAgentError instanceof check and keep a single Error case that
uses errorMessage, with the fallback message only for non-Error values.

In `@packages/ai-config/src/createBlockContextItem.ts`:
- Around line 1-41: Add tsdoc comments for the exported public API in
createBlockContextItem.ts: BlockAiRunContextItemSchema, BlockAiRunContextItem,
and createBlockContextItem. Describe what each schema/type/function represents
and the key fields/behavior so the generated docs align with the `@sqlrooms/`*
guideline for exported types and functions.

In `@packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx`:
- Line 49: Add TSDoc for the new header-actions API surface in
BlockDocumentStatefulBlockRendererContext: document the exported
hasOwnHeaderActions field, the renderBlockHeaderActions context property, and
the matching provider prop so they match the style of
useBlockDocumentRenderBlockHeaderActions(). Update the relevant exported
type/interface and provider declaration in
BlockDocumentStatefulBlockRendererContext.tsx, keeping the comments concise and
aligned with the existing documentation conventions for `@sqlrooms/`* exports.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 18c06733-da08-4906-94f4-3ee41259dde5

📥 Commits

Reviewing files that changed from the base of the PR and between 1a0f350 and 94bee8f.

📒 Files selected for processing (25)
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts
  • apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts
  • apps/sqlrooms-cli-ui/src/components/useAssistantContextItems.ts
  • apps/sqlrooms-cli-ui/src/context/getRunContext.ts
  • apps/sqlrooms-cli-ui/src/createBlockDocumentAgent.ts
  • apps/sqlrooms-cli-ui/src/createCliBlockDocumentAiAdapter.ts
  • apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts
  • apps/sqlrooms-cli-ui/src/store.ts
  • packages/ai-config/src/createBlockContextItem.ts
  • packages/ai-config/src/index.ts
  • packages/ai-core/src/AiSlice.ts
  • packages/ai-core/src/index.ts
  • packages/ai/src/index.ts
  • packages/documents/src/BlockAiTarget.ts
  • packages/documents/src/BlockDocumentBlockHeaderActions.ts
  • packages/documents/src/BlockDocumentChartRendererContext.tsx
  • packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsx
  • packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentStatefulBlockNodeView.tsx
  • packages/documents/src/BlockDocumentSliceConfig.ts
  • packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx
  • packages/documents/src/index.ts
  • packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts
  • packages/mosaic/src/charts/block-document/ChartBlockHeader.tsx
  • packages/mosaic/src/charts/block-document/ChartBlockRenderer.tsx
💤 Files with no reviewable changes (1)
  • apps/sqlrooms-cli-ui/src/store.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/ai-core/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • packages/ai-config/src/index.ts
  • packages/documents/src/index.ts
  • packages/documents/src/BlockAiTarget.ts
  • packages/ai/src/index.ts
  • packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentStatefulBlockNodeView.tsx
  • packages/ai-core/src/AiSlice.ts
  • apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts
  • apps/sqlrooms-cli-ui/src/createCliBlockDocumentAiAdapter.ts
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts
  • packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts
  • apps/sqlrooms-cli-ui/src/context/getRunContext.ts
  • apps/sqlrooms-cli-ui/src/components/useAssistantContextItems.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fb272fd398

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +76 to +82
{
type: 'chart',
id: targetBlockId,
config,
tableName: tableIdentity,
caption,
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve chart selection groups when editing

When Ask AI edits an existing chart block, this replacement omits the existing selectionGroupId. updateBlock replaces the whole chart block, and BlockDocumentChartBlock/the node view use selectionGroupId for linked chart interactions, so editing a chart that participates in a selection group silently disconnects it from cross-filtering. Preserve existingBlock.selectionGroupId when existingBlock.type === 'chart'.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/mosaic/src/dashboard/MosaicDashboard.tsx (1)

29-33: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Missing tsdoc on headerActions (inconsistent with sibling type in this file).

MosaicDashboardProps.headerActions (Line 143) has a doc comment, but MosaicDashboardRootProps.headerActions here does not.

As per coding guidelines, "Add tsdoc to exported types and functions in @sqlrooms/* packages."

📝 Proposed fix
 export type MosaicDashboardRootProps = PropsWithChildren<{
   dashboardId: string;
   readOnly?: boolean;
+  /** Actions rendered at the end of the dashboard toolbar. */
   headerActions?: ReactNode;
 }>;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/mosaic/src/dashboard/MosaicDashboard.tsx` around lines 29 - 33, Add
tsdoc for the exported MosaicDashboardRootProps.headerActions field to match the
documented sibling prop in MosaicDashboardProps. Update the
MosaicDashboardRootProps type near the headerActions declaration in
MosaicDashboard.tsx so the exported type complies with the `@sqlrooms/`* tsdoc
guideline and stays consistent with the rest of the file.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAgentTool.test.ts`:
- Around line 21-31: The `createBlockDocumentAdapter` test helper is returning
the wrong type for `updateBlock`, causing the TS2322 build failure. Update the
mock in `createCliBlockDocumentAgentTool.test` so `updateBlock` matches
`BlockDocumentAiAdapter['updateBlock']` and returns `void` or a `Promise<void>`
instead of `boolean`, keeping the rest of the adapter stub (`addBlock`,
`moveBlock`, etc.) unchanged.

---

Nitpick comments:
In `@packages/mosaic/src/dashboard/MosaicDashboard.tsx`:
- Around line 29-33: Add tsdoc for the exported
MosaicDashboardRootProps.headerActions field to match the documented sibling
prop in MosaicDashboardProps. Update the MosaicDashboardRootProps type near the
headerActions declaration in MosaicDashboard.tsx so the exported type complies
with the `@sqlrooms/`* tsdoc guideline and stays consistent with the rest of the
file.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 226a959f-ef7d-4095-b177-00fc096197c2

📥 Commits

Reviewing files that changed from the base of the PR and between 94bee8f and fb272fd.

📒 Files selected for processing (14)
  • apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAgentTool.test.ts
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsx
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetDashboardBlockRenderer.tsx
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetMapBlockRenderer.tsx
  • packages/ai-config/src/createBlockContextItem.ts
  • packages/app-runtime/src/html-app.tsx
  • packages/deck/src/block.tsx
  • packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsx
  • packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentStatefulBlockNodeView.tsx
  • packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx
  • packages/mosaic/src/dashboard/MosaicDashboard.tsx
  • packages/mosaic/src/dashboard/MosaicDashboardContext.tsx
  • packages/mosaic/src/dashboard/toolbar/MosaicDashboardToolbar.tsx
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/ai-config/src/createBlockContextItem.ts
  • packages/deck/src/block.tsx
  • packages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsx
  • packages/documents/src/BlockDocumentStatefulBlockRendererContext.tsx
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsx
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts

Comment thread apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAgentTool.test.ts Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 67a9d3c351

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +351 to +353
return {
...targetTool,
execute: (input: unknown, toolOptions?: unknown) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make pre-bound target IDs pass tool validation

When the target block is a dashboard or HTML app and the model follows the new instruction that dashboardId/appId is “pre-bound” by omitting that field, this wrapper only injects the value inside execute. The production embedded dashboard and HTML-app tools still require those fields in their inputSchema, so AI SDK validation can reject the tool call before this execute wrapper runs; either wrap/relax the schema as well or keep requiring the model to provide the ID.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b9d3a2880a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +397 to +402
case 'chart':
return Object.fromEntries(
Object.entries(tools).filter(([toolName]) =>
toolName.startsWith(BLOCK_DOCUMENT_CHART_TOOL_PREFIX),
),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include chart table context for target edits

When Ask AI is invoked on a chart block, this branch exposes only the chart tools, while the target prompt/context only carries the block ids and type. The worksheet chart tools still require tableName, and the existing chart's tableName is only available from the document block, so prompts like “change this chart to a scatter plot” on a worksheet with multiple tables leave the agent unable to discover the correct table and it will fail or guess. Include the existing chart block/tableName in the target prompt or keep a read-only inspect/list tool available for chart targets.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/ai-core/src/components/context/types.ts (1)

53-54: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Missing tsdoc for new exported prop fields.

side and avoidCollisions are added to the exported ContextSelectorSearchDropdownProps without documentation comments.

As per coding guidelines, "Add tsdoc to exported types and functions in @sqlrooms/* packages."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ai-core/src/components/context/types.ts` around lines 53 - 54, Add
tsdoc comments for the newly exported ContextSelectorSearchDropdownProps fields
so they comply with the `@sqlrooms` documentation guideline. Update the type
definition in types.ts to document both side and avoidCollisions with brief
descriptions, keeping the comments alongside the existing prop declarations and
matching the style used for other exported types in this package.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/ai-core/src/components/context/types.ts`:
- Around line 53-54: Add tsdoc comments for the newly exported
ContextSelectorSearchDropdownProps fields so they comply with the `@sqlrooms`
documentation guideline. Update the type definition in types.ts to document both
side and avoidCollisions with brief descriptions, keeping the comments alongside
the existing prop declarations and matching the style used for other exported
types in this package.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6aba85a6-d843-43a7-995e-5d6561d5668c

📥 Commits

Reviewing files that changed from the base of the PR and between fb272fd and b9d3a28.

📒 Files selected for processing (9)
  • apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAgentTool.test.ts
  • apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts
  • packages/ai-core/src/components/context/ContextSelectorItem.tsx
  • packages/ai-core/src/components/context/ContextSelectorSearchDropdown.tsx
  • packages/ai-core/src/components/context/types.ts
  • packages/ai-core/src/components/context/utils.ts
  • packages/mosaic/__tests__/block-document-ai.test.ts
  • packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts
  • packages/mosaic/src/charts/block-document/ChartBlockHeader.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/mosaic/src/charts/block-document/ChartBlockHeader.tsx
  • packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts
  • apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts
  • apps/sqlrooms-cli-ui/src/ai/tests/createCliBlockDocumentAgentTool.test.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d63fcc36b0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +387 to +390
case 'map':
return {
[KnownBlockDocumentTools.create_block_document_map_block]:
bindTargetToolInputField({

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Expose map state before scoped map edits

For a targeted map block this restricts the sub-agent to the write-only map creation/update tool, while the target prompt only contains IDs. In the common Ask AI flow for an existing map, requests such as “change this map’s colors/title/layer” require the current Deck panel config to preserve datasets and layers; without a read/list tool or injected existing config, the agent has to invent a full replacement config and can overwrite or fail incremental edits. Include the existing map panel config in the target context or keep an inspect/list tool available for map targets.

Useful? React with 👍 / 👎.

Comment on lines +65 to +68
getBlocks: () => [
{
type: 'chart',
id: 'chart-block-1',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Return nodes from the chart update mock

This mock returns a chart-block-shaped object, but the production path now runs blockDocumentNodeToBlock over getBlocks() before matching chart-block-1. Because this object has no TipTap attrs.id, the tool treats the block as missing, so this newly added test gets success: false and updateBlock is never called; return blockDocumentBlockToNode(...) here as in the later selection-group test.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 31af0e0bae

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +55 to +57
latestState.ai.setSessionDraftContextItemIds(sessionId, [
...draftContextItemIds,
contextItemId,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Replace stale block targets before starting scoped chat

When this reuses a session that already has a draft context for a different block (for example, the user selected another block in the context selector but has not sent that draft), the clicked block is appended instead of replacing the previous block target. The next run context then contains multiple kind: "block" targets, and formatRunContextInstructions presents all of them as edit targets, so an Ask AI action launched from one block can be routed to the stale block instead. Filter out existing block context ids before adding the clicked block, while preserving non-block context such as tables.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5cbcdf666e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +213 to +215
if (!WORKSHEET_AI_BLOCK_TYPES.has(blockType)) {
return null;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Gate Ask AI to enabled block tools

When experimentalEnabled is false, worksheet map and HTML-app blocks are rendered as ExperimentalStatefulBlockPlaceholder, and the block-document agent disables the corresponding mapBlocksEnabled/htmlAppBlocksEnabled tools. This check still enables the Ask AI popover for every CLI_AI_BLOCK_TYPES member, so opening a saved worksheet with a map or HTML-app block in the default non-experimental mode shows an action that can only fail with “No target-block tool available…”. Gate the map/html-app entries on experimentalEnabled or on the actual enabled tool set.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0dada9258f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

ilyabo and others added 5 commits July 8, 2026 12:10
Stateful blocks reused `title` for two unrelated purposes: the embedded
artifact's name (dashboards, SQL queries, Python blocks, etc.) and — for
`data-table` only — the bound table identity. Data-table even initialized
`title` to the artifact name then silently overwrote it with a table
reference, which was confusing and diverged from the sibling `chart` block's
`tableName`.

Add a dedicated `tableName` attribute to stateful blocks and switch the
data-table binding to it, aligning with the `chart` convention. `title` now
consistently means the embedded artifact name across all block types.

- schema + Tiptap node attr + node<->block round-trip carry `tableName`
- renderer context exposes `tableName` / `onTableNameChange`
- DataTableBlockRenderer reads/writes `tableName` instead of `title`
- create-stateful-block command gains an optional `tableName` param
- list-blocks summary surfaces `tableName`; tsdoc + README document the
  title / caption / tableName distinction

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a9be87569b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2adbc930bb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/sqlrooms-cli-ui/src/components/useAssistantContextItems.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 483e1dbd93

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/sqlrooms-cli-ui/src/store.ts Outdated
Comment thread apps/sqlrooms-cli-ui/src/workspace/WorksheetDashboardBlockRenderer.tsx Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c11c1e4fc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 35e6feb66e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.ts
Comment thread apps/sqlrooms-cli-ui/src/workspace/WorksheetMapBlockRenderer.tsx

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9104e5adee

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

const title = params.title || 'Map';

P2 Badge Preserve existing map titles on map edits

When mapId is provided for an existing worksheet map edit and the user only asks for a config change, the AI tool schema/defaults can omit a meaningful title and this fallback turns it into "Map". The existing-map path then calls ensureDashboard(mapId, title, ...) and later writes caption: title, so prompts like “change the colors” silently rename the saved map dashboard/panel caption to “Map”; preserve the current title/caption unless the request explicitly supplies a new title.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ilyabo
ilyabo merged commit 1f748a6 into main Jul 9, 2026
4 checks passed
@ilyabo
ilyabo deleted the feat/block-ai-popover branch July 9, 2026 08:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant