Repository navigation
feat: add "Ask AI on a block" popover for block-document blocks - #798
Conversation
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]>
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe 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. ChangesBlock-context AI and block-scoped chat
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)
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 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" |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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 winUnhandled rejection risk on fire-and-forget
startAnalysisWhenReadycall.
startAnalysisWhenReadyawaitsstartAnalysis, which synchronously callssendMessage({text: promptText}); if that throws (or any step in the chain throws), the rejection propagates out ofstartAnalysisWhenReadyuncaught here, since the call isvoid-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 winExport a typed block item variant here.
AiRunContextItemonly covers the base fields, so the block-specific keys added in this factory stay untyped through the public API. Extending the schema or exporting aBlockAiRunContextItemtype 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 valueError 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 winAdd coverage for the new
updateBlockadapter method.The suite covers
addBlocksuccess/failure but not the newly addedupdateBlock(success path invokingblock-document.update-block, and failure path throwing onresult.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 valueMinor: map guidance in
usageHintdoesn'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 valueSame identifier reused for both the schema value and its inferred type.
BlockDocumentAgentInputSchemais declared as aconst(the zod schema) and then re-declared as atypeviaz.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 likeBlockDocumentAgentInputSchema['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 winHardcoded tool name instead of constant reference.
Line 419 hardcodes the literal string
create_block_document_map_blockinstead 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 valueValidation error message is discarded in the friendly output on failure.
When the
blockInstanceIdguard throws (a plainError, notAiAgentError), thecatchblock collapsesfinalOutputto 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 inerror, but iffinalOutputis 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 winMissing coverage for
targetBlockIdchart-editing wiring.This test suite covers the rename,
move_block, and HTML-app-block behavior, but doesn't exercise the newtargetBlockIdparameter thatcreateCliBlockDocumentAiToolsnow forwards tocreateBlockDocumentChartToolsfor in-place chart edits. A quick test assertingcreateBlockDocumentChartTools/chartToolsreceivetargetBlockIdwhen 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 valueTight coupling between
extraToolsgating and the outerexperimentalEnabledflag.
extraToolschecks the closure-capturedexperimentalEnabledrather than thehtmlAppBlocksEnabled/mapBlocksEnabledvalues threaded intoblockDocumentAgentOptions. 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),extraToolswould silently provide/withhold the wrong tool set relative to whatgetBlockDocumentAgentInstructions/selectTargetBlockToolsexpect.🤖 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 valueDrop
blockDocumentAgentToolNamefromBLOCK_DOCUMENT_OPTIONSunless 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 winMissing tsdoc on new exported types/hook.
BlockDocumentBlockHeaderActionsRenderContext,BlockDocumentBlockHeaderActionsRenderer, anduseBlockDocumentRenderBlockHeaderActionsare 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 valueDeduplicate the shared header-actions types
BlockDocumentBlockHeaderActionsRenderContextandBlockDocumentBlockHeaderActionsRendererare 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 winConsider unit tests for the new block-context formatting branches.
formatBlockContextInstructionshas 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 winAdd 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 winMissing test coverage for the new block-context selection/validation logic.
This adds substantial new behavior — deriving
BlockAiTargets from document nodes, buildingblock-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 winFull 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 zodsafeParseper node type) over every node in the document just to compareblock?.id === blockContext.blockId. This recomputes insideuseMemowheneverblockDocumentschanges (i.e. on every document edit), and scales asO(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 frompackages/documents/src/BlockDocumentSliceConfig.tsinstead of the fullblockDocumentNodeToBlockconversion) 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 valueAvoid double-parsing the matched node.
blockDocumentNodeToBlockis called once per candidate inside.find, then re-called on the matched node to obtainblock. 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 winAdd tests for the new
BlockAiPromptPopoverpublic 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
📒 Files selected for processing (39)
apps/sqlrooms-cli-ui/src/__tests__/createCliBlockDocumentAiAdapter.test.tsapps/sqlrooms-cli-ui/src/__tests__/createCliBlockDocumentCommands.test.tsapps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAiTools.test.tsapps/sqlrooms-cli-ui/src/ai/constants.tsapps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.tsapps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.tsapps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.tsapps/sqlrooms-cli-ui/src/artifactTypeIds.tsapps/sqlrooms-cli-ui/src/components/useAssistantContextItems.tsapps/sqlrooms-cli-ui/src/components/useLocalFileLoader.tsapps/sqlrooms-cli-ui/src/context/formatRunContextInstructions.tsapps/sqlrooms-cli-ui/src/context/getRunContext.tsapps/sqlrooms-cli-ui/src/createBlockDocumentAgent.tsapps/sqlrooms-cli-ui/src/createCliBlockDocumentAiAdapter.tsapps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.tsapps/sqlrooms-cli-ui/src/createWorksheetAiAdapter.tsapps/sqlrooms-cli-ui/src/store.tsapps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsxpackages/ai-config/__tests__/createBlockContextItem.test.tspackages/ai-config/src/createBlockContextItem.tspackages/ai-config/src/index.tspackages/ai-core/src/AiSlice.tspackages/ai-core/src/components/BlockAiPromptPopover.tsxpackages/ai-core/src/index.tspackages/ai/src/index.tspackages/artifacts/__tests__/artifactAiSessions.test.tspackages/artifacts/src/ai/artifactAiSessionHelpers.tspackages/artifacts/src/ai/index.tspackages/deck/src/block.tsxpackages/documents/__tests__/BlockAiTarget.test.tspackages/documents/src/BlockAiTarget.tspackages/documents/src/BlockDocumentAi.tspackages/documents/src/BlockDocumentChartRendererContext.tsxpackages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsxpackages/documents/src/BlockDocumentEditor/node-views/BlockDocumentStatefulBlockNodeView.tsxpackages/documents/src/BlockDocumentStatefulBlockRendererContext.tsxpackages/documents/src/createMoveBlockDocumentBlockTool.tspackages/documents/src/index.tspackages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts
💤 Files with no reviewable changes (1)
- apps/sqlrooms-cli-ui/src/createWorksheetAiAdapter.ts
There was a problem hiding this comment.
💡 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" |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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 liftNo test coverage for the new targetBlock validation/routing logic.
This adds non-trivial behavior:
blockInstanceIdvalidation, 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
targetBlockis 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 liftPre-bind the target instance ids for dashboard, HTML app, and map tools
targetBlockonly scopes chart programmatically; dashboard/html-app/map still rely on prompt text plus a generic tool.createBlockDocumentMapBlockToolalso only fixesblockDocumentId, sodashboardId/appId/mapIdcan still drift if the model misreads the target. BindtargetBlock.blockInstanceIdinto 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 winMemoize
blockHeaderActionsto preserveChartRendererBoundarymemoization.
renderBlockHeaderActions(...)is invoked fresh on every render, producing a newReactNodereference each time. Passing this into thememo-wrappedChartRendererBoundaryasheaderActionsdefeats its shallow-equality memoization, causing the chartRendererto re-render on every parent render regardless of whetherdocumentId/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 winMissing tsdoc on exported schema/type/function.
BlockAiRunContextItemSchema,BlockAiRunContextItem, andcreateBlockContextItemare 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 valueRedundant
AiAgentErrorbranch — both arms return the same value.
error instanceof AiAgentError ? errorMessage : error instanceof Error ? errorMessage : ...returnserrorMessagein both theAiAgentErrorand genericErrorcases (andAiAgentErrorpresumably extendsError), 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 valueAdd tsdoc for new header-actions fields.
hasOwnHeaderActions, the context'srenderBlockHeaderActions, and the provider prop of the same name lack doc comments, unlike the newuseBlockDocumentRenderBlockHeaderActions()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
📒 Files selected for processing (25)
apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.tsapps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.tsapps/sqlrooms-cli-ui/src/ai/startBlockScopedChat.tsapps/sqlrooms-cli-ui/src/components/useAssistantContextItems.tsapps/sqlrooms-cli-ui/src/context/getRunContext.tsapps/sqlrooms-cli-ui/src/createBlockDocumentAgent.tsapps/sqlrooms-cli-ui/src/createCliBlockDocumentAiAdapter.tsapps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.tsapps/sqlrooms-cli-ui/src/store.tspackages/ai-config/src/createBlockContextItem.tspackages/ai-config/src/index.tspackages/ai-core/src/AiSlice.tspackages/ai-core/src/index.tspackages/ai/src/index.tspackages/documents/src/BlockAiTarget.tspackages/documents/src/BlockDocumentBlockHeaderActions.tspackages/documents/src/BlockDocumentChartRendererContext.tsxpackages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsxpackages/documents/src/BlockDocumentEditor/node-views/BlockDocumentStatefulBlockNodeView.tsxpackages/documents/src/BlockDocumentSliceConfig.tspackages/documents/src/BlockDocumentStatefulBlockRendererContext.tsxpackages/documents/src/index.tspackages/mosaic/src/ai/block-document/createBlockDocumentChartTools.tspackages/mosaic/src/charts/block-document/ChartBlockHeader.tsxpackages/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
There was a problem hiding this comment.
💡 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".
| { | ||
| type: 'chart', | ||
| id: targetBlockId, | ||
| config, | ||
| tableName: tableIdentity, | ||
| caption, | ||
| }, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/mosaic/src/dashboard/MosaicDashboard.tsx (1)
29-33: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMissing tsdoc on
headerActions(inconsistent with sibling type in this file).
MosaicDashboardProps.headerActions(Line 143) has a doc comment, butMosaicDashboardRootProps.headerActionshere 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
📒 Files selected for processing (14)
apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAgentTool.test.tsapps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.tsapps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsxapps/sqlrooms-cli-ui/src/workspace/WorksheetDashboardBlockRenderer.tsxapps/sqlrooms-cli-ui/src/workspace/WorksheetMapBlockRenderer.tsxpackages/ai-config/src/createBlockContextItem.tspackages/app-runtime/src/html-app.tsxpackages/deck/src/block.tsxpackages/documents/src/BlockDocumentEditor/node-views/BlockDocumentChartNodeView.tsxpackages/documents/src/BlockDocumentEditor/node-views/BlockDocumentStatefulBlockNodeView.tsxpackages/documents/src/BlockDocumentStatefulBlockRendererContext.tsxpackages/mosaic/src/dashboard/MosaicDashboard.tsxpackages/mosaic/src/dashboard/MosaicDashboardContext.tsxpackages/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
There was a problem hiding this comment.
💡 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".
| return { | ||
| ...targetTool, | ||
| execute: (input: unknown, toolOptions?: unknown) => { |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| case 'chart': | ||
| return Object.fromEntries( | ||
| Object.entries(tools).filter(([toolName]) => | ||
| toolName.startsWith(BLOCK_DOCUMENT_CHART_TOOL_PREFIX), | ||
| ), | ||
| ); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/ai-core/src/components/context/types.ts (1)
53-54: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMissing tsdoc for new exported prop fields.
sideandavoidCollisionsare added to the exportedContextSelectorSearchDropdownPropswithout 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
📒 Files selected for processing (9)
apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAgentTool.test.tsapps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.tspackages/ai-core/src/components/context/ContextSelectorItem.tsxpackages/ai-core/src/components/context/ContextSelectorSearchDropdown.tsxpackages/ai-core/src/components/context/types.tspackages/ai-core/src/components/context/utils.tspackages/mosaic/__tests__/block-document-ai.test.tspackages/mosaic/src/ai/block-document/createBlockDocumentChartTools.tspackages/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
There was a problem hiding this comment.
💡 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".
| case 'map': | ||
| return { | ||
| [KnownBlockDocumentTools.create_block_document_map_block]: | ||
| bindTargetToolInputField({ |
There was a problem hiding this comment.
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 👍 / 👎.
| getBlocks: () => [ | ||
| { | ||
| type: 'chart', | ||
| id: 'chart-block-1', |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| latestState.ai.setSessionDraftContextItemIds(sessionId, [ | ||
| ...draftContextItemIds, | ||
| contextItemId, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| if (!WORKSHEET_AI_BLOCK_TYPES.has(blockType)) { | ||
| return null; | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
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]>
…qlrooms into feat/block-ai-popover
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 Codex Review
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".
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-safeblockContextItemId/parseBlockContextItemId/defaultBlockTitle; an AI-agnosticrenderBlockHeaderActionsheader slot +hasOwnHeaderActionsflag on the stateful/chart renderer providers and node-views; optionalBlockDocumentAiAdapter.updateBlock.@sqlrooms/ai-config:createBlockContextItem(...)returning anAiRunContextItem(re-exported through@sqlrooms/ai-core→@sqlrooms/ai).@sqlrooms/ai-core: presentationalBlockAiPromptPopover; newstartAnalysisWhenReady(sessionId)slice action (extracted fromstartNewSession's mount-poll).@sqlrooms/artifacts/ai: purefindAiSessionForArtifactWithContextItem(...)(reuse-or-create key).@sqlrooms/mosaic:createBlockDocumentChartToolsgains an optionaltargetBlockIdto update a chart block in place instead of appending.@sqlrooms/deck: optionalheaderActionsprop onDeckMapBlockRendererso 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); optionaltargetBlockrouting in the block-document agent (dashboard→embedded dashboard agent, html-app→embedded html-app agent, map→map tool withmapId, chart→in-place chart update); adapterupdateBlockbacked by theblock-document.update-blockcommand.Boundaries
worksheet) stay in the app layer. No@sqlrooms/ai-coreblock/artifact awareness. Dependency graphdocuments → artifacts → ai-configpreserved (no cycle).Testing
@sqlrooms/documentsBlockAiTarget: 12/12 pass.@sqlrooms/ai-configcreateBlockContextItem: 1/1 pass.@sqlrooms/artifactsartifactAiSessions(incl. newfindAiSessionForArtifactWithContextItemcases): 19/19 pass.Note on the base
This branch is stacked on 2 unmerged local worksheets-base commits —
chore: workspace block-document renames(ac9b4c31) andfeedback(c85473a5) — that are not yet on any origin branch, so they appear in this PR's diff (11 files). Review thefeat: 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