Skip to content

feat: share block-document Ask AI and Deck map helpers across hosts - #805

Merged
ilyabo merged 40 commits into
mainfrom
feat/block-document-sharing-stages-1-5
Jul 12, 2026
Merged

ilyabo merged 40 commits into
mainfrom
feat/block-document-sharing-stages-1-5

Conversation

@ilyabo

@ilyabo ilyabo commented Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Promote shared startBlockScopedChat into @sqlrooms/documents and Ask AI header helper into @sqlrooms/ai-core / @sqlrooms/ai
  • Export Deck point-map normalization, dataset-source utils, createOrUpdateDeckMapBlock, and map block registration helpers from @sqlrooms/deck
  • Wire CLI to the shared APIs and delete local duplicates (stages 1–5 of the block-document sharing plan; stage 6 registry deferred)

Follow-up

This PR consolidates the current Mosaic-dashboard-backed worksheet-map implementation. The immediately subsequent Deck Map Resource Decoupling change will introduce canonical deckMaps, a resource-native createOrUpdateDeckMapResource, and a Mosaic adapter with no dashboard or panel concepts in the resource API. No legacy worksheet-map migration or panelId compatibility will be required.

Test plan

  • Ask AI on chart + map in CLI seeds context, reuses session, edits in place
  • block-document.add-map-block create/update still works (command path)
  • Point-map configs without transformSql get WKB normalize via normalizeDeckMapPointConfig
  • Unit tests: startBlockScopedChat, datasetSourceUtils, normalizeDeckMapPointConfig, createOrUpdateDeckMapBlock
  • Vocabulary leak check: no product worksheet terms in package sources

Made with Cursor

Summary by CodeRabbit

  • New Features
    • Added block-scoped “Ask AI” header actions and reusable block-scoped chat start flow.
    • Enhanced deck map block create/update via a new orchestration helper, plus reusable block-document registration helpers.
    • Improved map config handling with dataset/table-backed resolution and point-layer normalization utilities.
    • Updated data-table editing to use tableName for identity.
  • Bug Fixes
    • Strengthened CLI AI/tool validation and clearer failures for missing/stale/mismatched block state.
    • Improved map panel rendering resilience with error fallback and recovery on success.
  • Tests
    • Expanded Jest coverage for AI agent tooling, map orchestration, and deck normalization utilities.
  • Documentation
    • Documented block-scoped “Ask AI” and the new deck map helper APIs.

ilyabo and others added 27 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]>
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]>
Promote startBlockScopedChat, Ask AI header actions, point-map
normalization, createOrUpdateDeckMapBlock, dataset-source utils, and
map block registration so FSQ and CLI stop duplicating host glue.

Co-authored-by: Cursor <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 9, 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

This PR adds shared Deck map create/update and normalization helpers, block-scoped Ask AI chat wiring, block-document agent validation, and related export, store, and package metadata updates.

Changes

Deck map block create/update orchestration

Layer / File(s) Summary
Dataset source utilities and AI re-export
packages/deck/src/datasetSourceUtils.ts, packages/deck/src/ai.ts, packages/deck/__tests__/datasetSourceUtils.test.ts
Adds dataset-source inspection helpers, re-exports them through deck AI entry points, updates Deck AI instructions text, and adds helper tests.
Point-layer geometry normalization
packages/deck/src/mapConfigUtils.ts, packages/deck/__tests__/normalizeDeckMapPointConfig.test.ts
Exports point transform SQL helpers and adds point-config normalization that patches dataset transforms, geometry columns, layer bindings, and fit-to-data values, with tests.
Block document registration
packages/deck/src/blockDocumentRegistration.ts
Adds Deck map block constants and registration helpers for block-document type and command state initialization.
createOrUpdateDeckMapBlock orchestration
packages/deck/src/createOrUpdateDeckMapBlock.ts, packages/deck/__tests__/createOrUpdateDeckMapBlock.test.ts
Implements the host contract and shared orchestration for creating or updating Deck map blocks and panels, including validation branches and test coverage.
Block renderer error boundary and header actions
packages/deck/src/block.tsx
Adds render-error recovery for map panels, clears stale panel issues on successful renders, and exposes header actions in the map renderer.
Deck package public exports
packages/deck/src/index.ts
Expands the deck package barrel exports for point normalization, dataset-source helpers, map block orchestration types, and block document registration APIs.
CLI block-document command wiring
apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts
Updates block-document commands to use shared map orchestration, adjusts success messages and metadata payloads, and removes inline map-table helper logic.

Block-scoped Ask AI chat

Layer / File(s) Summary
Ask AI block header action component
packages/ai-core/src/components/createAskAiBlockHeaderAction.tsx, packages/ai-core/src/index.ts, packages/ai-core/README.md
Adds the Ask AI block header action component, its public types, and the supporting ai-core exports and documentation.
ai package re-exports
packages/ai/src/index.ts
Extends the ai package barrel exports for the new block prompt UI, header action APIs, and ai-config items/types.
startBlockScopedChat session flow
packages/documents/src/startBlockScopedChat.ts, packages/documents/__tests__/startBlockScopedChat.test.ts
Adds block-scoped chat session selection, reuse, context seeding, assistant reveal, prompt setting, and analysis startup, with tests for the main session paths.
documents package re-exports
packages/documents/src/index.ts
Updates the documents package barrel exports for block AI target helpers, block-scoped chat helpers, chart header actions, and summary augmentation types.
Worksheet header AI wiring
apps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsx
Switches worksheet block updates to tableName, derives block titles from store state, and wires block-scoped Ask AI header actions into worksheet renderers and providers.
CLI store AI instructions and ensureState fix
apps/sqlrooms-cli-ui/src/store.ts
Adds block run-context instructions for invoking the block-document agent tool and removes the title argument from owned stateful block initialization.
Dashboard props and context extension
packages/mosaic/src/dashboard/MosaicDashboard.tsx
Extends Mosaic dashboard props and context with default title, default layout type, and header actions, and changes dashboard initialization to preserve existing titles.

Block-document agent tool targetBlock validation

Layer / File(s) Summary
targetBlock blockInstanceId validation and tests
apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts, apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAgentTool.test.ts
Adds the guard for missing stateful block instance ids and tests tool exposure, pre-bound execution, prompt content, and validation failures.

Package metadata and exports

Layer / File(s) Summary
Package export and test dependency updates
packages/artifacts/package.json, packages/documents/package.json
Adds the artifacts AI subpath default export and the documents test dependency needed by the new Jest suite.

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

Sequence Diagram(s)

sequenceDiagram
  participant CLI as CLI Command
  participant Orchestrator as createOrUpdateDeckMapBlock
  participant Host as CreateOrUpdateDeckMapBlockHost
  participant Panel as Deck Map Panel

  CLI->>Orchestrator: params (mapId, config, tableName)
  Orchestrator->>Host: findMapBlock / findMapPanel
  Orchestrator->>Host: findTable(tableName)
  alt block exists
    Orchestrator->>Host: updateBlockMetadata
  else create new
    Orchestrator->>Host: createMapBlock
  end
  Orchestrator->>Host: ensureDashboard / ensureMapState
  Orchestrator->>Panel: build panel from prepared config
  Orchestrator->>Host: addOrUpdateMapPanel
  Orchestrator-->>CLI: result (blockId, panelId, selectedTable, created)
Loading
sequenceDiagram
  participant UI as Worksheet Header Action
  participant Chat as startBlockScopedChat
  participant Actions as StartBlockScopedChatActions
  participant Toast as toast.error

  UI->>Chat: startBlockScopedChat(target, prompt)
  Chat->>Actions: validate artifact / select artifact
  Chat->>Actions: findAiSessionForArtifactWithContextItem(running)
  alt session already running
    Chat->>Toast: error("AI chat already running")
    Chat->>Actions: switch to running session
  else no running session
    Chat->>Actions: reuse or create session
    Chat->>Actions: set draft context item ids
    Chat->>UI: revealAssistant()
    Chat->>Actions: setPrompt / startAnalysisWhenReady
  end
Loading

Possibly related PRs

  • sqlrooms/sqlrooms#707: Introduced the session draft-context plumbing used by the block-scoped chat flow.
  • sqlrooms/sqlrooms#780: Updated CLI AI/tool wiring toward block-document vocabulary in the same store/instruction area.
  • sqlrooms/sqlrooms#797: Also changes apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts and related validation behavior.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.04% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: sharing block-document Ask AI and Deck map helpers across hosts.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/block-document-sharing-stages-1-5

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: b3e56ceeb9

ℹ️ 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 packages/mosaic/src/dashboard/MosaicDashboard.tsx Outdated
Comment thread packages/deck/src/block.tsx

@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: 12

Caution

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

⚠️ Outside diff range comments (2)
packages/deck/src/block.tsx (1)

343-361: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add stopPropagation wrapper for headerActions to match ChartBlockHeader.

At line 346, {headerActions} is rendered directly without click propagation stopping. ChartBlockHeader wraps headerActions in a <div onClick={(event) => event.stopPropagation()}> to prevent triggering BlockDocumentStatefulBlockNodeView's onClick={handleClick} (which selects the block). Since DeckMapBlockRenderer is rendered inside the same NodeViewWrapper, clicking AI actions on the map block will unintentionally trigger block selection.

🔧 Proposed fix to stop propagation on map header actions
         <div className="flex items-center gap-0.5">
-          {headerActions}
+          {headerActions ? (
+            <div
+              className="flex items-center gap-0.5"
+              onClick={(event) => event.stopPropagation()}
+            >
+              {headerActions}
+            </div>
+          ) : null}
           {HeaderActions ? <HeaderActions {...rendererProps} /> : null}
🤖 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/deck/src/block.tsx` around lines 343 - 361, `DeckMapBlockRenderer`
is rendering `headerActions` directly, so clicks can bubble to
`BlockDocumentStatefulBlockNodeView` and select the block. Update the header
actions area in `block.tsx` to wrap `headerActions` with a click-stopping
container, matching the pattern used in `ChartBlockHeader`, and keep
`HeaderActions`/`Button` behavior unchanged.
apps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsx (1)

167-282: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Document startBlockScopedChat in packages/documents/README.md. The package exports this new public helper from src/index.ts, but the README doesn’t mention it yet.

🤖 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/workspace/WorksheetArtifact.tsx` around lines 167 -
282, The new public helper startBlockScopedChat is exported via src/index.ts but
is missing from the package documentation. Update packages/documents/README.md
to mention startBlockScopedChat alongside the other public APIs, using the same
naming as the call site in WorksheetArtifact and the export surface in
src/index.ts so consumers can discover it.
🧹 Nitpick comments (9)
apps/sqlrooms-cli-ui/src/context/getRunContext.ts (1)

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

Extract resolveCliBlockLabel and CLI_BLOCK_CONTEXT_TYPES to a shared module.

Both resolveCliBlockLabel and CLI_BLOCK_CONTEXT_TYPES are duplicated identically in useAssistantContextItems.ts (lines 31, 48-53). If the label resolution logic or supported block types change, both copies must be updated in sync. Extract these to a shared utility (e.g., in statefulBlockArtifactConfigs.ts or a new blockContextUtils.ts) and import from both call sites.

♻️ Proposed extraction
# In a shared file, e.g. apps/sqlrooms-cli-ui/src/blockContextUtils.ts

+import {CLI_AI_BLOCK_TYPES} from './artifactTypeIds';
+import {
+  getStatefulBlockArtifactConfig,
+  isStatefulBlockArtifactType,
+} from './statefulBlockArtifactConfigs';
+
+export const CLI_BLOCK_CONTEXT_TYPES = new Set<string>(CLI_AI_BLOCK_TYPES);
+
+export function resolveCliBlockLabel(blockType: string): string | undefined {
+  if (blockType === 'chart') return 'Chart';
+  return isStatefulBlockArtifactType(blockType)
+    ? getStatefulBlockArtifactConfig(blockType).label
+    : undefined;
+}

Then in both getRunContext.ts and useAssistantContextItems.ts:

-const CLI_BLOCK_CONTEXT_TYPES = new Set<string>(CLI_AI_BLOCK_TYPES);
+import {CLI_BLOCK_CONTEXT_TYPES, resolveCliBlockLabel} from '../blockContextUtils';
-function resolveCliBlockLabel(blockType: string): string | undefined {
-  if (blockType === 'chart') return 'Chart';
-  return isStatefulBlockArtifactType(blockType)
-    ? getStatefulBlockArtifactConfig(blockType).label
-    : undefined;
-}

Also applies to: 87-92

🤖 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` at line 28,
`resolveCliBlockLabel` and `CLI_BLOCK_CONTEXT_TYPES` are duplicated in both
`getRunContext` and `useAssistantContextItems`, so extract them into one shared
utility module and import them from both places. Put the shared label-resolution
logic and the `CLI_BLOCK_CONTEXT_TYPES` set in a common file such as
`blockContextUtils` or `statefulBlockArtifactConfigs`, then update
`getRunContext` and `useAssistantContextItems` to use the shared symbols instead
of maintaining separate copies.
packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts (1)

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

Redundant type check after prior validation.

existingBlock?.type === 'chart' is redundant — line 72 already throws if existingBlock.type !== 'chart', and line 68 throws if !existingBlock. The optional chaining and type narrowing are unnecessary at this point.

♻️ Simplify selectionGroupId extraction
-        const selectionGroupId =
-          existingBlock?.type === 'chart'
-            ? existingBlock.selectionGroupId
-            : undefined;
+        const selectionGroupId = existingBlock.selectionGroupId;
🤖 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/ai/block-document/createBlockDocumentChartTools.ts`
around lines 79 - 82, Simplify the selectionGroupId logic in
createBlockDocumentChartTools: after the existing validation in the same
function already guarantees existingBlock is present and of type chart, remove
the redundant optional chaining and chart type check when reading
existingBlock.selectionGroupId. Update the assignment to access
existingBlock.selectionGroupId directly so the code reflects the prior guards
and stays easier to read.
apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts (1)

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

Remove unnecessary type assertion on augmentBlockSummary options

The as Parameters<typeof createListBlockDocumentBlocksTool>[0] & {...} cast is unnecessary. The callback ({block}) => {...} is compatible with the exported BlockDocumentBlockSummaryAugmenter type through contextual typing — TypeScript permits ignoring extra parameters (summary, index). The assertion also narrows the param type to only {block: BlockDocumentBlock}, bypassing the package's exported type and potentially masking future type errors.

♻️ Proposed fix
     augmentBlockSummary: ({block}) => {
       if (
         !getState ||
         block.type !== 'statefulBlock' ||
         block.blockType !== 'map' ||
         !block.blockInstanceId
       ) {
         return undefined;
       }

       const runtimeIssues = getMapBlockRuntimeIssues(
         getState(),
         block.blockInstanceId,
       );
       return runtimeIssues.length > 0 ? {runtimeIssues} : undefined;
     },
-  } as Parameters<typeof createListBlockDocumentBlocksTool>[0] & {
-    augmentBlockSummary: (params: {
-      block: BlockDocumentBlock;
-    }) => Record<string, unknown> | 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/ai/createCliBlockDocumentAiTools.ts` around lines
181 - 185, The `createCliBlockDocumentAiTools` setup is using an unnecessary `as
Parameters<typeof createListBlockDocumentBlocksTool>[0] & {...}` assertion
around `augmentBlockSummary`, which bypasses the exported
`BlockDocumentBlockSummaryAugmenter` type. Remove the cast and let TypeScript
infer the callback shape directly from
`createListBlockDocumentBlocksTool`/`BlockDocumentBlockSummaryAugmenter`,
keeping the `({ block }) => ...` implementation contextually typed while
preserving the package’s public type contract.
packages/documents/src/createListBlockDocumentBlocksTool.ts (1)

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

Add tsdoc to exported BlockDocumentBlockSummaryAugmenter

As per coding guidelines, exported types in @sqlrooms/* packages should have tsdoc. BlockDocumentBlockSummaryAugmenter is a new public export from @sqlrooms/documents but lacks a tsdoc annotation.

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/documents/src/createListBlockDocumentBlocksTool.ts` around lines 31
- 36, Add tsdoc for the exported BlockDocumentBlockSummaryAugmenter type in
createListBlockDocumentBlocksTool.ts. Document that it is a callback used to
augment a BlockDocumentBlockSummary, and describe the params block, summary, and
index so the public API in `@sqlrooms/documents` follows the exported-type tsdoc
guideline.

Source: Coding guidelines

packages/pivot/src/PivotBlock.tsx (2)

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

Add unit tests for the new PivotBlock component

PivotBlock is a new public export with non-trivial logic (useEffect calling ensurePivot, conditional fallback rendering). No test file was found in the provided changes.

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/pivot/src/PivotBlock.tsx` around lines 25 - 63, Add unit tests for
the new PivotBlock public export to cover its behavior. Verify PivotBlock calls
useBaseRoomStore’s ensurePivot inside the useEffect with the resolved pivotId
and the expected payload (title/defaultTitle, source, config), and that it falls
back to the missing pivot id message when both pivotId and blockId are absent.
Also assert it renders PivotView with the resolved pivotId when present, using
the PivotBlock and PivotBlockProps symbols to locate the component.

Source: Coding guidelines


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

Add tsdoc to exported PivotBlockProps and PivotBlock

As per coding guidelines, exported types and functions in @sqlrooms/* packages should have tsdoc. Both PivotBlockProps (line 25) and PivotBlock (line 32) are new public exports from @sqlrooms/pivot but lack tsdoc annotations.

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/pivot/src/PivotBlock.tsx` around lines 25 - 63, Add tsdoc comments
for the new public exports in PivotBlock.tsx: document PivotBlockProps and
PivotBlock so they comply with the `@sqlrooms` package guidelines. Place concise
tsdoc directly above the PivotBlockProps type and the PivotBlock component
declaration, describing their purpose and key props/behavior without changing
runtime logic.

Source: Coding guidelines

packages/ai-core/src/components/BlockAiPromptPopover.tsx (1)

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

Add tsdoc to the exported type/function.

Neither BlockAiPromptPopoverProps nor BlockAiPromptPopover has tsdoc, but both are re-exported as public API from @sqlrooms/ai-core's index.

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

📝 Example tsdoc addition
+/**
+ * Props for {`@link` BlockAiPromptPopover}.
+ */
 export type BlockAiPromptPopoverProps = {
   trigger: ReactNode;
   onSubmit: (prompt: string) => void;
   placeholder?: string;
   label?: string;
   isRunning?: boolean;
   disabled?: boolean;
   open?: boolean;
   onOpenChange?: (open: boolean) => void;
 };

+/**
+ * A popover-based prompt input for triggering block-scoped Ask AI actions.
+ */
 export function BlockAiPromptPopover({
🤖 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 19 -
39, Add TSDoc comments to the public API symbols BlockAiPromptPopoverProps and
BlockAiPromptPopover in BlockAiPromptPopover.tsx. Document the purpose of the
props type and the component, including the main behavior and key props like
trigger, onSubmit, open, and onOpenChange, so the re-exported `@sqlrooms/ai-core`
API follows the package guideline for exported types/functions.

Source: Coding guidelines

packages/deck/src/createOrUpdateDeckMapBlock.ts (1)

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

DECK_MAP_DASHBOARD_PANEL_TYPE is imported but only re-exported, never used in the function body.

The symbol is imported at line 4 and re-exported at line 254, but createOrUpdateDeckMapBlock never references it. Since index.ts already exports DECK_MAP_DASHBOARD_PANEL_TYPE from ./dashboardConfig (line 46), this re-export is redundant for package consumers. Consider removing both the import and the re-export to reduce confusion.

♻️ Proposed cleanup
 import {
-  DECK_MAP_DASHBOARD_PANEL_TYPE,
   type DeckMapDashboardPanelConfig,
 } from './dashboardConfig';

And remove the re-export at the end:

-export {DECK_MAP_DASHBOARD_PANEL_TYPE};

Also applies to: 254-254

🤖 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/deck/src/createOrUpdateDeckMapBlock.ts` around lines 1 - 10,
`DECK_MAP_DASHBOARD_PANEL_TYPE` is only being re-exported and never used inside
`createOrUpdateDeckMapBlock`, so remove the unused import from the module header
and delete the matching export at the end of `createOrUpdateDeckMapBlock` to
avoid redundant re-exporting. Keep the function’s existing behavior intact; the
symbol is already exported through `index.ts` via `dashboardConfig`, so no
additional package-level export is needed here.
packages/deck/__tests__/createOrUpdateDeckMapBlock.test.ts (1)

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

Consider adding tests for missingMapBlockBehavior: 'create' and SQL-only source validation.

The three tests cover the main create, update, and throw paths. Two important branches in createOrUpdateDeckMapBlock are untested:

  1. missingMapBlockBehavior: 'create' — generates a fresh mapId via createMapId() even when params.mapId is provided but no block exists (FSQ path).
  2. SQL-only dataset source validation (lines 172-181) — throws when updating with sqlQuery sources and no tableName.

Adding these would improve confidence in the shared orchestration before both CLI and FSQ consume it.

🤖 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/deck/__tests__/createOrUpdateDeckMapBlock.test.ts` around lines 56 -
107, Add tests for the uncovered branches in createOrUpdateDeckMapBlock: verify
that when missingMapBlockBehavior is set to create and the provided mapId does
not exist, the function uses createMapId() to create a new block instead of
throwing, and verify the SQL-only source validation path by asserting that an
update with sqlQuery sources and no tableName fails as expected. Use the
existing createOrUpdateDeckMapBlock test setup, especially createHost,
createMapId, and the mapId/blockId behavior, to keep the new cases consistent
with the current create/update/throw coverage.
🤖 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/createCliBlockDocumentCommands.ts`:
- Around line 407-421: The updateBlockMetadata callback in
createCliBlockDocumentCommands is dropping the height field before forwarding
metadata updates. Update the async callback that calls invokeRequiredCommand so
it also destructures and passes height alongside blockDocumentId, blockId, and
caption, matching the BlockDocumentUpdateBlockMetadataInput schema and the
createOrUpdateDeckMapBlock caller’s payload.

In `@apps/sqlrooms-cli-ui/src/workspace/WorksheetPivotBlockRenderer.tsx`:
- Around line 25-30: The JSX for PivotBlock in WorksheetPivotBlockRenderer is
passing an unsupported blockType prop, which triggers a type error because
PivotBlockProps in PivotBlock does not declare it. Remove the blockType prop
from the PivotBlock usage here, or only reintroduce it if PivotBlock is updated
to accept and use that prop consistently.

In `@packages/ai-config/src/createBlockContextItem.ts`:
- Around line 1-60: Add documentation for the new block-scoped AI context APIs
exposed from `@sqlrooms/ai-config`. Update the package README to mention
BlockAiRunContextItemSchema, BlockAiRunContextItem, and createBlockContextItem,
and briefly describe that createBlockContextItem builds and validates a
block-level run context item via BlockAiRunContextItemSchema. Place this
alongside the existing exported symbols so users can discover the new block
context helpers easily.

In `@packages/ai-core/__tests__/BlockAiPromptPopover.test.tsx`:
- Around line 78-81: The test is clicking the wrong button by selecting the
first button[type="button"] in DOM order, which can hit “Close” instead of
“Open.” Update BlockAiPromptPopover.test.tsx to use a text-based query for the
intended “Open” button, matching the existing approach used later in the test,
so the interaction is explicit and resilient to DOM changes.

In `@packages/ai-core/src/components/createAskAiBlockHeaderAction.tsx`:
- Around line 1-78: The public API documentation in the ai-core README is
missing the new Ask AI header action symbols introduced by
createAskAiBlockHeaderAction.tsx. Update the README’s exported API list to
include createAskAiBlockHeaderAction, AskAiBlockHeaderActionRenderContext, and
CreateAskAiBlockHeaderActionOptions, matching the naming used in the
createAskAiBlockHeaderAction module.

In `@packages/ai/src/index.ts`:
- Around line 195-201: The public export surface in packages/ai/src/index.ts has
expanded, but packages/ai/README.md still documents the older API. Update the
README’s API/export section to mention the new re-exports, specifically
BlockAiPromptPopover, createAskAiBlockHeaderAction, createBlockContextItem, and
the BlockAiRunContextItem* types, so the documented public surface matches the
index exports.

In `@packages/deck/__tests__/normalizeDeckMapPointConfig.test.ts`:
- Around line 70-88: The test fixture passed to normalizeDeckMapPointConfig is
missing the required config.spec field from DeckMapDashboardPanelConfig, so make
the fixture type-safe by adding a minimal spec value or by defining it as an
explicit DeckMapDashboardPanelConfig. Update the object in
normalizeDeckMapPointConfig.test so the config used in the "skips datasets that
already have transformSql or sqlQuery" case satisfies the generic constraint
without changing the test behavior.

In `@packages/deck/src/blockDocumentRegistration.ts`:
- Around line 13-32: Add TSDoc to the exported
DeckMapBlockDocumentRegistrationOptions type and document the missing
defaultHeight, minHeight, and maxHeight fields. Update the type declaration in
blockDocumentRegistration.ts so the symbol itself has a top-level TSDoc, and add
concise field-level docs alongside the existing label, description,
defaultTitle, and afterEnsureState comments to match `@sqlrooms/`* documentation
conventions.

In `@packages/deck/src/index.ts`:
- Around line 55-60: The new public API in the deck package is exported from the
main index, but the README still omits several surfaced helpers. Update
`packages/deck/README.md` to document the full `@sqlrooms/deck` API surface,
explicitly covering `getFirstDatasetSourceTableName`, `hasSqlOnlyDatasetSource`,
`createOrUpdateDeckMapBlock`, `createDeckMapPointTransformSql`,
`normalizeDeckMapPointConfig`, and the block document registration helpers so
consumers can find the available entry points.

In `@packages/documents/src/BlockDocumentChartRendererContext.tsx`:
- Around line 70-73: The exported hook
useBlockDocumentChartRenderBlockHeaderActions is missing TSDoc, unlike the
similar useBlockDocumentRenderBlockHeaderActions in
BlockDocumentStatefulBlockRendererContext.tsx. Add a brief TSDoc comment
directly above useBlockDocumentChartRenderBlockHeaderActions describing that it
returns the renderBlockHeaderActions callback from
BlockDocumentChartRendererContext, and keep the style consistent with other
exported hooks in the `@sqlrooms/`* packages.

In `@packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts`:
- Around line 84-95: The chart update payload in createBlockDocumentChartTools
should preserve the existing block’s intent, since updateBlock replaces the
stored block and currently drops that field. In the block update object built
for blockDocumentAdapter.updateBlock, carry over existingBlock.intent the same
way selectionGroupId is conditionally forwarded, so chart edits keep the durable
objective intact.

In `@packages/pivot/src/index.ts`:
- Around line 18-24: The package README is missing the newly exposed public
pivot API, so update packages/pivot/README.md to document the exports from the
package entrypoint in index.ts. Add PivotBlock and PivotBlockProps alongside
createPivotBlockDefinition in the public API section, using the same naming as
the exported symbols so the README matches the actual `@sqlrooms/pivot` surface.

---

Outside diff comments:
In `@apps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsx`:
- Around line 167-282: The new public helper startBlockScopedChat is exported
via src/index.ts but is missing from the package documentation. Update
packages/documents/README.md to mention startBlockScopedChat alongside the other
public APIs, using the same naming as the call site in WorksheetArtifact and the
export surface in src/index.ts so consumers can discover it.

In `@packages/deck/src/block.tsx`:
- Around line 343-361: `DeckMapBlockRenderer` is rendering `headerActions`
directly, so clicks can bubble to `BlockDocumentStatefulBlockNodeView` and
select the block. Update the header actions area in `block.tsx` to wrap
`headerActions` with a click-stopping container, matching the pattern used in
`ChartBlockHeader`, and keep `HeaderActions`/`Button` behavior unchanged.

---

Nitpick comments:
In `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts`:
- Around line 181-185: The `createCliBlockDocumentAiTools` setup is using an
unnecessary `as Parameters<typeof createListBlockDocumentBlocksTool>[0] & {...}`
assertion around `augmentBlockSummary`, which bypasses the exported
`BlockDocumentBlockSummaryAugmenter` type. Remove the cast and let TypeScript
infer the callback shape directly from
`createListBlockDocumentBlocksTool`/`BlockDocumentBlockSummaryAugmenter`,
keeping the `({ block }) => ...` implementation contextually typed while
preserving the package’s public type contract.

In `@apps/sqlrooms-cli-ui/src/context/getRunContext.ts`:
- Line 28: `resolveCliBlockLabel` and `CLI_BLOCK_CONTEXT_TYPES` are duplicated
in both `getRunContext` and `useAssistantContextItems`, so extract them into one
shared utility module and import them from both places. Put the shared
label-resolution logic and the `CLI_BLOCK_CONTEXT_TYPES` set in a common file
such as `blockContextUtils` or `statefulBlockArtifactConfigs`, then update
`getRunContext` and `useAssistantContextItems` to use the shared symbols instead
of maintaining separate copies.

In `@packages/ai-core/src/components/BlockAiPromptPopover.tsx`:
- Around line 19-39: Add TSDoc comments to the public API symbols
BlockAiPromptPopoverProps and BlockAiPromptPopover in BlockAiPromptPopover.tsx.
Document the purpose of the props type and the component, including the main
behavior and key props like trigger, onSubmit, open, and onOpenChange, so the
re-exported `@sqlrooms/ai-core` API follows the package guideline for exported
types/functions.

In `@packages/deck/__tests__/createOrUpdateDeckMapBlock.test.ts`:
- Around line 56-107: Add tests for the uncovered branches in
createOrUpdateDeckMapBlock: verify that when missingMapBlockBehavior is set to
create and the provided mapId does not exist, the function uses createMapId() to
create a new block instead of throwing, and verify the SQL-only source
validation path by asserting that an update with sqlQuery sources and no
tableName fails as expected. Use the existing createOrUpdateDeckMapBlock test
setup, especially createHost, createMapId, and the mapId/blockId behavior, to
keep the new cases consistent with the current create/update/throw coverage.

In `@packages/deck/src/createOrUpdateDeckMapBlock.ts`:
- Around line 1-10: `DECK_MAP_DASHBOARD_PANEL_TYPE` is only being re-exported
and never used inside `createOrUpdateDeckMapBlock`, so remove the unused import
from the module header and delete the matching export at the end of
`createOrUpdateDeckMapBlock` to avoid redundant re-exporting. Keep the
function’s existing behavior intact; the symbol is already exported through
`index.ts` via `dashboardConfig`, so no additional package-level export is
needed here.

In `@packages/documents/src/createListBlockDocumentBlocksTool.ts`:
- Around line 31-36: Add tsdoc for the exported
BlockDocumentBlockSummaryAugmenter type in createListBlockDocumentBlocksTool.ts.
Document that it is a callback used to augment a BlockDocumentBlockSummary, and
describe the params block, summary, and index so the public API in
`@sqlrooms/documents` follows the exported-type tsdoc guideline.

In `@packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts`:
- Around line 79-82: Simplify the selectionGroupId logic in
createBlockDocumentChartTools: after the existing validation in the same
function already guarantees existingBlock is present and of type chart, remove
the redundant optional chaining and chart type check when reading
existingBlock.selectionGroupId. Update the assignment to access
existingBlock.selectionGroupId directly so the code reflects the prior guards
and stays easier to read.

In `@packages/pivot/src/PivotBlock.tsx`:
- Around line 25-63: Add unit tests for the new PivotBlock public export to
cover its behavior. Verify PivotBlock calls useBaseRoomStore’s ensurePivot
inside the useEffect with the resolved pivotId and the expected payload
(title/defaultTitle, source, config), and that it falls back to the missing
pivot id message when both pivotId and blockId are absent. Also assert it
renders PivotView with the resolved pivotId when present, using the PivotBlock
and PivotBlockProps symbols to locate the component.
- Around line 25-63: Add tsdoc comments for the new public exports in
PivotBlock.tsx: document PivotBlockProps and PivotBlock so they comply with the
`@sqlrooms` package guidelines. Place concise tsdoc directly above the
PivotBlockProps type and the PivotBlock component declaration, describing their
purpose and key props/behavior without changing runtime logic.
🪄 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: a2ab8eff-c317-4986-a196-5b529ba5810f

📥 Commits

Reviewing files that changed from the base of the PR and between 1f748a6 and b3e56ce.

📒 Files selected for processing (87)
  • apps/sqlrooms-cli-ui/src/__tests__/createCliBlockDocumentCommands.test.ts
  • apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAgentTool.test.ts
  • apps/sqlrooms-cli-ui/src/ai/__tests__/createCliBlockDocumentAiTools.test.ts
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAiTools.ts
  • apps/sqlrooms-cli-ui/src/ai/getMapBlockRuntimeIssues.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/statefulBlockArtifactConfigs.ts
  • apps/sqlrooms-cli-ui/src/store.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
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetPivotBlockRenderer.tsx
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetSqlQueryBlockRenderer.tsx
  • packages/ai-config/__tests__/createBlockContextItem.test.ts
  • packages/ai-config/src/createBlockContextItem.ts
  • packages/ai-config/src/index.ts
  • packages/ai-core/__tests__/BlockAiPromptPopover.test.tsx
  • packages/ai-core/src/AiSlice.ts
  • packages/ai-core/src/components/BlockAiPromptPopover.tsx
  • packages/ai-core/src/components/context/ContextSelectorBadge.tsx
  • packages/ai-core/src/components/context/ContextSelectorItem.tsx
  • packages/ai-core/src/components/context/ContextSelectorSearchDropdown.tsx
  • packages/ai-core/src/components/context/ContextSelectorSortableChip.tsx
  • packages/ai-core/src/components/context/types.ts
  • packages/ai-core/src/components/context/utils.ts
  • packages/ai-core/src/components/createAskAiBlockHeaderAction.tsx
  • packages/ai-core/src/index.ts
  • packages/ai/src/index.ts
  • packages/app-runtime/src/html-app-block-document.ts
  • packages/app-runtime/src/html-app.tsx
  • packages/artifacts/__tests__/artifactAiSessions.test.ts
  • packages/artifacts/src/ai/artifactAiSessionHelpers.ts
  • packages/artifacts/src/ai/index.ts
  • packages/deck/__tests__/createOrUpdateDeckMapBlock.test.ts
  • packages/deck/__tests__/datasetSourceUtils.test.ts
  • packages/deck/__tests__/normalizeDeckMapPointConfig.test.ts
  • packages/deck/src/ai.ts
  • packages/deck/src/block.tsx
  • packages/deck/src/blockDocumentRegistration.ts
  • packages/deck/src/createOrUpdateDeckMapBlock.ts
  • packages/deck/src/datasetSourceUtils.ts
  • packages/deck/src/index.ts
  • packages/deck/src/mapConfigUtils.ts
  • packages/documents/README.md
  • packages/documents/__tests__/BlockAiTarget.test.ts
  • packages/documents/__tests__/BlockDocumentAi.test.ts
  • packages/documents/__tests__/BlockDocumentCommands.test.ts
  • packages/documents/__tests__/BlockDocumentsSlice.test.ts
  • packages/documents/__tests__/documentsCrdt.test.ts
  • packages/documents/__tests__/startBlockScopedChat.test.ts
  • packages/documents/src/BlockAiTarget.ts
  • packages/documents/src/BlockDocumentAi.ts
  • packages/documents/src/BlockDocumentBlockHeaderActions.ts
  • packages/documents/src/BlockDocumentChartRendererContext.tsx
  • packages/documents/src/BlockDocumentCommands.ts
  • packages/documents/src/BlockDocumentEditor/BlockDocumentBlockControls.tsx
  • packages/documents/src/BlockDocumentEditor/extensions/BlockDocumentStatefulBlockNode.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/BlockDocumentsSlice.ts
  • packages/documents/src/createListBlockDocumentBlocksTool.ts
  • packages/documents/src/createMoveBlockDocumentBlockTool.ts
  • packages/documents/src/index.ts
  • packages/documents/src/startBlockScopedChat.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
  • packages/mosaic/src/charts/block-document/ChartBlockRenderer.tsx
  • packages/mosaic/src/dashboard/DefaultMosaicDashboardBlock.tsx
  • packages/mosaic/src/dashboard/MosaicDashboard.tsx
  • packages/mosaic/src/dashboard/MosaicDashboardContext.tsx
  • packages/mosaic/src/dashboard/toolbar/MosaicDashboardToolbar.tsx
  • packages/mosaic/src/data-table-explorer/block-document/DataTableBlockRenderer.tsx
  • packages/mosaic/src/data-table-explorer/block-document/DataTableBlockSettings.tsx
  • packages/pivot/src/PivotBlock.tsx
  • packages/pivot/src/index.ts
  • packages/sql-editor/src/SqlQueryBlock.tsx
💤 Files with no reviewable changes (4)
  • packages/documents/src/BlockDocumentEditor/BlockDocumentBlockControls.tsx
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetSqlQueryBlockRenderer.tsx
  • apps/sqlrooms-cli-ui/src/statefulBlockArtifactConfigs.ts
  • packages/documents/src/BlockDocumentsSlice.ts

Comment thread apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts
Comment on lines +25 to +30
<PivotBlock
blockId={blockInstanceId}
blockType={blockType}
pivotId={blockInstanceId}
defaultTitle="Embedded Pivot Table"
/>

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if PivotBlockProps includes blockType
rg -n 'blockType' packages/pivot/src/PivotBlock.tsx

Repository: sqlrooms/sqlrooms

Length of output: 155


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate PivotBlock implementation and its type definitions/usages.
fd -a 'PivotBlock.tsx|PivotBlock.ts|WorksheetPivotBlockRenderer.tsx|*PivotBlock*' apps packages

# Show concise structure of the pivot component file if found.
if [ -f packages/pivot/src/PivotBlock.tsx ]; then
  wc -l packages/pivot/src/PivotBlock.tsx
  ast-grep outline packages/pivot/src/PivotBlock.tsx --view expanded
fi

# Find usages of PivotBlock with blockType and without it.
rg -n "PivotBlock|blockType" apps packages --glob '!**/dist/**' --glob '!**/build/**'

Repository: sqlrooms/sqlrooms

Length of output: 569


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the exact PivotBlockProps definition and component signature.
if [ -f packages/pivot/src/PivotBlock.tsx ]; then
  nl -ba packages/pivot/src/PivotBlock.tsx | sed -n '1,220p'
fi

# Inspect the caller file around the reported lines.
if [ -f apps/sqlrooms-cli-ui/src/workspace/WorksheetPivotBlockRenderer.tsx ]; then
  nl -ba apps/sqlrooms-cli-ui/src/workspace/WorksheetPivotBlockRenderer.tsx | sed -n '1,120p'
fi

Repository: sqlrooms/sqlrooms

Length of output: 195


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the PivotBlock implementation file and caller file.
fd -a --glob 'PivotBlock.tsx' packages apps
fd -a --glob 'WorksheetPivotBlockRenderer.tsx' apps

# Inspect the implementation and caller with line numbers.
if [ -f packages/pivot/src/PivotBlock.tsx ]; then
  sed -n '1,220p' packages/pivot/src/PivotBlock.tsx | cat -n
fi

if [ -f apps/sqlrooms-cli-ui/src/workspace/WorksheetPivotBlockRenderer.tsx ]; then
  sed -n '1,120p' apps/sqlrooms-cli-ui/src/workspace/WorksheetPivotBlockRenderer.tsx | cat -n
fi

# Search the repo for blockType-related PivotBlock usage and prop definitions.
rg -n "PivotBlockProps|blockType" packages apps --glob '!**/dist/**' --glob '!**/build/**'

Repository: sqlrooms/sqlrooms

Length of output: 49545


Remove the extra blockType prop

packages/pivot/src/PivotBlock.tsx doesn’t declare blockType in PivotBlockProps, so this JSX prop causes a type error. Drop it here unless PivotBlock needs to consume it.

🤖 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/workspace/WorksheetPivotBlockRenderer.tsx` around
lines 25 - 30, The JSX for PivotBlock in WorksheetPivotBlockRenderer is passing
an unsupported blockType prop, which triggers a type error because
PivotBlockProps in PivotBlock does not declare it. Remove the blockType prop
from the PivotBlock usage here, or only reintroduce it if PivotBlock is updated
to accept and use that prop consistently.

Comment on lines +1 to +60
import {z} from 'zod';
import {AiRunContextItemSchema} from './schema/ChatSessionSchema';

/**
* AI run context item schema for a selected block inside a block document.
*
* The item captures the document id, document block id, block type, optional
* backing instance id, and optional panel id so agents can route edits to the
* exact surface the user invoked.
*/
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(),
});

/**
* Context item describing a block-scoped AI request.
*
* Use this when a run starts from an individual worksheet/document block rather
* than from the whole artifact.
*/
export type BlockAiRunContextItem = z.infer<typeof BlockAiRunContextItemSchema>;

/**
* Create and validate a block-scoped AI run context item.
*
* The returned item is parsed through {@link BlockAiRunContextItemSchema} so
* omitted optional fields are normalized consistently with stored chat context.
*/
export function createBlockContextItem(fields: {
id: string;
blockDocumentId: string;
blockId: string;
blockType: string;
blockInstanceId?: string;
panelId?: string;
title: string;
subtitle?: string;
}): BlockAiRunContextItem {
const item = {
kind: 'block',
id: fields.id,
title: fields.title,
type: fields.blockType,
...(fields.subtitle !== undefined ? {subtitle: fields.subtitle} : {}),
blockDocumentId: fields.blockDocumentId,
blockId: fields.blockId,
blockType: fields.blockType,
...(fields.blockInstanceId !== undefined
? {blockInstanceId: fields.blockInstanceId}
: {}),
...(fields.panelId !== undefined ? {panelId: fields.panelId} : {}),
};

return BlockAiRunContextItemSchema.parse(item);
}

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if ai-config README mentions the new exports
rg -n 'createBlockContextItem|BlockAiRunContextItem' packages/ai-config/README.md

Repository: sqlrooms/sqlrooms

Length of output: 155


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== package files =="
git ls-files packages/ai-config | sed 's#^`#-` #'

echo
echo "== README mention check =="
rg -n 'createBlockContextItem|BlockAiRunContextItem|BlockAiRunContextItemSchema' packages/ai-config/README.md || true

echo
echo "== exports check =="
rg -n 'createBlockContextItem|BlockAiRunContextItem|BlockAiRunContextItemSchema' packages/ai-config -g '!packages/ai-config/README.md'

Repository: sqlrooms/sqlrooms

Length of output: 2295


Document the new ai-config exports in packages/ai-config/README.md
BlockAiRunContextItemSchema, BlockAiRunContextItem, and createBlockContextItem are exported from @sqlrooms/ai-config, but the package README doesn’t mention them yet.

🤖 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 - 60, Add
documentation for the new block-scoped AI context APIs exposed from
`@sqlrooms/ai-config`. Update the package README to mention
BlockAiRunContextItemSchema, BlockAiRunContextItem, and createBlockContextItem,
and briefly describe that createBlockContextItem builds and validates a
block-level run context item via BlockAiRunContextItemSchema. Place this
alongside the existing exported symbols so users can discover the new block
context helpers easily.

Source: Coding guidelines

Comment on lines +78 to +81
container
.querySelector<HTMLButtonElement>('button[type="button"]')
?.click();
});

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Fragile button selection by DOM order.

querySelector('button[type="button"]') returns the first matching button ("Close") by DOM order. The "Open" button at lines 86-89 is correctly found by text content. Consider using the same text-content approach for consistency and robustness.

🔧 Suggested fix
       act(() => {
-        container
-          .querySelector<HTMLButtonElement>('button[type="button"]')
-          ?.click();
+        const closeButton = Array.from(
+          container.querySelectorAll<HTMLButtonElement>('button'),
+        ).find((button) => button.textContent === 'Close');
+        closeButton?.click();
       });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
container
.querySelector<HTMLButtonElement>('button[type="button"]')
?.click();
});
act(() => {
const closeButton = Array.from(
container.querySelectorAll<HTMLButtonElement>('button'),
).find((button) => button.textContent === 'Close');
closeButton?.click();
});
🤖 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/__tests__/BlockAiPromptPopover.test.tsx` around lines 78 -
81, The test is clicking the wrong button by selecting the first
button[type="button"] in DOM order, which can hit “Close” instead of “Open.”
Update BlockAiPromptPopover.test.tsx to use a text-based query for the intended
“Open” button, matching the existing approach used later in the test, so the
interaction is explicit and resilient to DOM changes.

Comment thread packages/ai-core/src/components/createAskAiBlockHeaderAction.tsx
Comment thread packages/deck/src/blockDocumentRegistration.ts
Comment thread packages/deck/src/index.ts
Comment on lines +70 to +73

export function useBlockDocumentChartRenderBlockHeaderActions() {
return useContext(BlockDocumentChartRendererContext).renderBlockHeaderActions;
}

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add TSDoc to useBlockDocumentChartRenderBlockHeaderActions.

The exported hook lacks a TSDoc comment. The parallel hook useBlockDocumentRenderBlockHeaderActions in BlockDocumentStatefulBlockRendererContext.tsx has one. As per coding guidelines, exported functions in @sqlrooms/* packages should have TSDoc.

📝 Proposed TSDoc addition
+/** Returns the host-provided renderer for chart block header actions, when configured. */
 export function useBlockDocumentChartRenderBlockHeaderActions() {
   return useContext(BlockDocumentChartRendererContext).renderBlockHeaderActions;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function useBlockDocumentChartRenderBlockHeaderActions() {
return useContext(BlockDocumentChartRendererContext).renderBlockHeaderActions;
}
/** Returns the host-provided renderer for chart block header actions, when configured. */
export function useBlockDocumentChartRenderBlockHeaderActions() {
return useContext(BlockDocumentChartRendererContext).renderBlockHeaderActions;
}
🤖 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/BlockDocumentChartRendererContext.tsx` around lines 70
- 73, The exported hook useBlockDocumentChartRenderBlockHeaderActions is missing
TSDoc, unlike the similar useBlockDocumentRenderBlockHeaderActions in
BlockDocumentStatefulBlockRendererContext.tsx. Add a brief TSDoc comment
directly above useBlockDocumentChartRenderBlockHeaderActions describing that it
returns the renderBlockHeaderActions callback from
BlockDocumentChartRendererContext, and keep the style consistent with other
exported hooks in the `@sqlrooms/`* packages.

Source: Coding guidelines

Comment on lines +84 to +95
const updateResult = blockDocumentAdapter.updateBlock(
blockDocumentId,
blockIdToUpdate,
{
type: 'chart',
id: blockIdToUpdate,
config,
tableName: tableIdentity,
caption,
...(selectionGroupId !== undefined ? {selectionGroupId} : {}),
},
);

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether block-document.update-block replaces or merges block fields.
rg -n "update-block" --type=ts -g '!**/__tests__/**' -A 10 packages/documents/src/BlockDocumentCommands.ts

Repository: sqlrooms/sqlrooms

Length of output: 2007


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect updateBlock implementation and the chart tool call site context.
rg -n "updateBlock\\(" packages -g '!**/__tests__/**' -A 8 -B 4

printf '\n---\n'

# Read the command definition around update-block.
sed -n '430,480p' packages/documents/src/BlockDocumentCommands.ts

printf '\n---\n'

# Inspect the chart tool file around the reported lines.
sed -n '60,110p' packages/mosaic/src/ai/block-document/createBlockDocumentChartTools.ts

Repository: sqlrooms/sqlrooms

Length of output: 12768


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the block type/schema for chart blocks and any `intent` field.
rg -n "\bintent\b" packages/documents packages/mosaic packages -g '!**/__tests__/**' -A 4 -B 4

printf '\n---\n'

# Inspect the block document block schema around relevant definitions.
ast-grep outline packages/documents/src/BlockDocumentsSlice.ts --view expanded

printf '\n---\n'

# Inspect block type/schema definitions if present in documents package.
fd -a "BlockDocument" packages/documents/src

Repository: sqlrooms/sqlrooms

Length of output: 50373


Preserve intent on chart updates.
updateBlock replaces the stored block, so this payload should carry over existingBlock.intent just like selectionGroupId; otherwise chart updates clear the block’s durable objective.

🤖 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/ai/block-document/createBlockDocumentChartTools.ts`
around lines 84 - 95, The chart update payload in createBlockDocumentChartTools
should preserve the existing block’s intent, since updateBlock replaces the
stored block and currently drops that field. In the block update object built
for blockDocumentAdapter.updateBlock, carry over existingBlock.intent the same
way selectionGroupId is conditionally forwarded, so chart edits keep the durable
objective intact.

Comment on lines 18 to 24
export {
PivotBlock,
createPivotBlockDefinition,
type CreatePivotBlockDefinitionOptions,
type PivotBlockProps,
type PivotBlockRenderProps,
} from './PivotBlock';

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if pivot README mentions the new exports
rg -n 'PivotBlock\b|PivotBlockProps' packages/pivot/README.md

Repository: sqlrooms/sqlrooms

Length of output: 155


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n-- packages/pivot/README.md --\n'
wc -l packages/pivot/README.md
cat -n packages/pivot/README.md | sed -n '1,220p'

printf '\n-- packages/pivot/src/index.ts --\n'
cat -n packages/pivot/src/index.ts | sed -n '1,120p'

printf '\n-- package metadata --\n'
cat -n packages/pivot/package.json | sed -n '1,220p'

Repository: sqlrooms/sqlrooms

Length of output: 6417


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n-- packages/pivot/README.md --\n'
wc -l packages/pivot/README.md
cat -n packages/pivot/README.md | sed -n '1,220p'

printf '\n-- packages/pivot/src/index.ts --\n'
cat -n packages/pivot/src/index.ts | sed -n '1,120p'

printf '\n-- packages/pivot/package.json --\n'
cat -n packages/pivot/package.json | sed -n '1,220p'

Repository: sqlrooms/sqlrooms

Length of output: 6428


Add the new public pivot exports to the package README. packages/pivot/README.md still only documents createPivotBlockDefinition; PivotBlock and PivotBlockProps should be added alongside the new @sqlrooms/pivot public API.

🤖 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/pivot/src/index.ts` around lines 18 - 24, The package README is
missing the newly exposed public pivot API, so update packages/pivot/README.md
to document the exports from the package entrypoint in index.ts. Add PivotBlock
and PivotBlockProps alongside createPivotBlockDefinition in the public API
section, using the same naming as the exported symbols so the README matches the
actual `@sqlrooms/pivot` surface.

Source: Coding guidelines

@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: 5ceea58cfc

ℹ️ 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 packages/documents/src/startBlockScopedChat.ts Outdated
Stop onCreateOwnedStatefulBlock from re-ensuring with embeddedTitle
(overwriting command-provided titles). Filter the running-session guard
in startBlockScopedChat to isRunning sessions only so finished chats
can be reused.

Co-authored-by: Cursor <[email protected]>
@ilyabo

ilyabo commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the two new Codex findings:

  1. Preserve command-provided stateful block titles — onCreateOwnedStatefulBlock no longer passes config.embeddedTitle into ensureState (matches main; avoids overwriting titles set by create-stateful-block).
  2. Ask AI running-session guard — startBlockScopedChat now filters to session.isRunning before the “already running” check, so finished block chats can be reused. Added regression tests.

@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: ec02b2103f

ℹ️ 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 (!mapId || !panel) {
return;
}
clearPanelIssue(mapId, panel.id);

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 Do not clear fresh map render errors

When a changed map config still throws during the ErrorBoundary remount, componentDidCatch reports the render-error during commit, then this effect for the same committed render runs afterward and clears that same panel issue. In the inspected Deck map block flow, list_blocks and the block-repair prompt rely on this runtime issue, so broken retry configs can be reported as healthy and the agent can stop repairing them.

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 (3)
packages/documents/__tests__/startBlockScopedChat.test.ts (2)

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

Consider asserting setPrompt and revealAssistant are not called in the blocking path.

The test correctly verifies toastError and that startAnalysisWhenReady is not called, but doesn't assert that setPrompt and revealAssistant were also skipped. Adding those negative assertions would fully lock the early-return contract.

🤖 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/__tests__/startBlockScopedChat.test.ts` around lines 153 -
188, The blocking-path test for startBlockScopedChat should also verify the
early return skips UI updates. In the existing "blocks when a matching session
is already running" case, add negative assertions that setPrompt and
revealAssistant are not called, alongside the current toastError and
startAnalysisWhenReady checks, to fully cover the contract in
startBlockScopedChat.

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

Consider asserting revealAssistant and setSessionDraftContextItemIds in the reuse path.

The test verifies the key side effects (switchSession, setPrompt, startAnalysisWhenReady) but doesn't assert that revealAssistant was called or that setSessionDraftContextItemIds was not called (since the context item id is already present in the draft). Adding these assertions would fully lock the reuse-path contract against regressions.

🤖 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/__tests__/startBlockScopedChat.test.ts` around lines 111 -
151, The reuse-path test for startBlockScopedChat should also cover the missing
side effects. In the existing “reuses a finished session” case, assert that
revealAssistant is called for the reused session and that
setSessionDraftContextItemIds is not called because the draft already contains
the context item. Use the existing startBlockScopedChat setup and the actions
object methods to lock down this contract alongside switchSession, setPrompt,
and startAnalysisWhenReady.
apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts (1)

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

Use STATEFUL_TARGET_BLOCK_TYPES constant instead of inline array in the early guard.

The early guard at line 610 uses ['dashboard', 'html-app', 'map'].includes(...) while validateTargetBlock uses the STATEFUL_TARGET_BLOCK_TYPES Set defined at line 328. If a new stateful block type is added to the Set but not the inline array, the early guard won't catch it, allowing ensureBlockDocument/setCurrentBlockDocument side effects before validateTargetBlock throws.

♻️ Proposed fix
         if (
           targetBlock &&
-          ['dashboard', 'html-app', 'map'].includes(targetBlock.blockType) &&
+          STATEFUL_TARGET_BLOCK_TYPES.has(targetBlock.blockType) &&
           !targetBlock.blockInstanceId
         ) {
🤖 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
608 - 616, The early missing-blockInstanceId guard in
createCliBlockDocumentAgentTool should use the same STATEFUL_TARGET_BLOCK_TYPES
source as validateTargetBlock instead of an inline ['dashboard', 'html-app',
'map'] array. Update the guard to reference the STATEFUL_TARGET_BLOCK_TYPES Set
so any newly added stateful block type is caught consistently before
ensureBlockDocument or setCurrentBlockDocument can run.
🤖 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 `@apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts`:
- Around line 608-616: The early missing-blockInstanceId guard in
createCliBlockDocumentAgentTool should use the same STATEFUL_TARGET_BLOCK_TYPES
source as validateTargetBlock instead of an inline ['dashboard', 'html-app',
'map'] array. Update the guard to reference the STATEFUL_TARGET_BLOCK_TYPES Set
so any newly added stateful block type is caught consistently before
ensureBlockDocument or setCurrentBlockDocument can run.

In `@packages/documents/__tests__/startBlockScopedChat.test.ts`:
- Around line 153-188: The blocking-path test for startBlockScopedChat should
also verify the early return skips UI updates. In the existing "blocks when a
matching session is already running" case, add negative assertions that
setPrompt and revealAssistant are not called, alongside the current toastError
and startAnalysisWhenReady checks, to fully cover the contract in
startBlockScopedChat.
- Around line 111-151: The reuse-path test for startBlockScopedChat should also
cover the missing side effects. In the existing “reuses a finished session”
case, assert that revealAssistant is called for the reused session and that
setSessionDraftContextItemIds is not called because the draft already contains
the context item. Use the existing startBlockScopedChat setup and the actions
object methods to lock down this contract alongside switchSession, setPrompt,
and startAnalysisWhenReady.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 05572963-9903-4f17-aa23-ff327ac59898

📥 Commits

Reviewing files that changed from the base of the PR and between b3e56ce and ec02b21.

📒 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/createCliBlockDocumentCommands.ts
  • apps/sqlrooms-cli-ui/src/store.ts
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsx
  • packages/ai-core/README.md
  • packages/deck/__tests__/createOrUpdateDeckMapBlock.test.ts
  • packages/deck/__tests__/normalizeDeckMapPointConfig.test.ts
  • packages/deck/src/block.tsx
  • packages/deck/src/blockDocumentRegistration.ts
  • packages/deck/src/createOrUpdateDeckMapBlock.ts
  • packages/documents/__tests__/startBlockScopedChat.test.ts
  • packages/documents/src/startBlockScopedChat.ts
  • packages/mosaic/src/dashboard/MosaicDashboard.tsx
✅ Files skipped from review due to trivial changes (1)
  • packages/ai-core/README.md
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/deck/tests/normalizeDeckMapPointConfig.test.ts
  • packages/documents/src/startBlockScopedChat.ts
  • packages/deck/src/block.tsx
  • packages/deck/src/blockDocumentRegistration.ts
  • packages/deck/src/createOrUpdateDeckMapBlock.ts
  • packages/mosaic/src/dashboard/MosaicDashboard.tsx
  • apps/sqlrooms-cli-ui/src/workspace/WorksheetArtifact.tsx
  • apps/sqlrooms-cli-ui/src/createCliBlockDocumentCommands.ts

@ilyabo
ilyabo force-pushed the feat/block-document-sharing-stages-1-5 branch from 10eb74e to ecfaab1 Compare July 9, 2026 15:28

@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: ecfaab1271

ℹ️ 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".

} from './datasetSourceUtils';
export type {DeckMapDatasetSourceConfig} from './datasetSourceUtils';
export {
createOrUpdateDeckMapBlock,

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 Add README docs for deck map APIs

This publishes createOrUpdateDeckMapBlock as a new @sqlrooms/deck public API, alongside the new normalization/dataset/block-registration helpers in this export block, but packages/deck/README.md has no corresponding usage or API entry. The repo AGENTS.md Documentation section requires updating a package README when adding public @sqlrooms/* APIs, and these helpers have non-obvious host-callback/title-preservation behavior that consumers need documented.

Useful? React with 👍 / 👎.

type BlockAiTarget,
} from './BlockAiTarget';
export {
startBlockScopedChat,

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 Add README docs for block-scoped chat

This exports startBlockScopedChat from @sqlrooms/documents, but packages/documents/README.md was not updated to explain the required action adapter and validation callback. The repo AGENTS.md Documentation section requires README updates for new public @sqlrooms/* APIs, and consumers otherwise have to infer the wiring contract from source.

Useful? React with 👍 / 👎.

@ilyabo
ilyabo force-pushed the feat/block-document-sharing-stages-1-5 branch from ecfaab1 to 3ea4f63 Compare July 9, 2026 15:42

@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: 3ea4f633b5

ℹ️ 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 packages/deck/src/mapConfigUtils.ts Outdated
: undefined;
const tableName =
typeof source?.tableName === 'string' ? source.tableName : undefined;
if (!tableName || source?.sqlQuery || source?.transformSql) {

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 explicit geometry columns during normalization

When a valid table-backed map config already declares a dataset geometryColumn (for example a GeoJSON/spatial table using geom) and that table also contains longitude/latitude attributes, this condition still treats it as a lon/lat point dataset and rewrites the source/fit-to-data geometry to __sqlrooms_geom. Hosts using the exported normalizeDeckMapPointConfig(...) on AI-authored configs can therefore break existing geometry or polygon layers; skip datasets with an explicit geometry column, or only apply the transform after confirming a point layer targets the dataset.

Useful? React with 👍 / 👎.

@ilyabo
ilyabo force-pushed the feat/block-document-sharing-stages-1-5 branch from 3ea4f63 to 88943a6 Compare July 9, 2026 16:34

@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/documents/__tests__/startBlockScopedChat.test.ts (1)

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

Solid test structure covering the main session paths.

The ESM mock setup, createActions helper with Map-backed draft context, and the four test cases map well to the implementation's primary control flow: creation, invalid artifact rejection, finished-session reuse, and running-session blocking. The finished-session test correctly asserts that setSessionDraftContextItemIds is not called when the context item id is already present.

Two error paths in the implementation are not covered:

  1. createArtifactScopedSession returns undefined → toast error "Cannot start an AI chat for this block"
  2. startAnalysisWhenReady returns false → toast error "Could not start the AI chat"

Consider adding tests for these branches 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/documents/__tests__/startBlockScopedChat.test.ts` around lines 1 -
37, The current `startBlockScopedChat` test suite covers the happy path and a
few session states, but it misses the two toast-error branches in the
`startBlockScopedChat` flow. Add tests using `createActions` for the cases where
`createArtifactScopedSession` returns `undefined` and where
`startAnalysisWhenReady` resolves to `false`, and assert that `toast.error` is
called with the corresponding messages. Use the existing `startBlockScopedChat`
import and the `toastError` mock to verify these fallback paths.
🤖 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/documents/__tests__/startBlockScopedChat.test.ts`:
- Around line 1-37: The current `startBlockScopedChat` test suite covers the
happy path and a few session states, but it misses the two toast-error branches
in the `startBlockScopedChat` flow. Add tests using `createActions` for the
cases where `createArtifactScopedSession` returns `undefined` and where
`startAnalysisWhenReady` resolves to `false`, and assert that `toast.error` is
called with the corresponding messages. Use the existing `startBlockScopedChat`
import and the `toastError` mock to verify these fallback paths.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 68bdbd17-11ac-4a74-b253-732875570c63

📥 Commits

Reviewing files that changed from the base of the PR and between 10eb74e and 88943a6.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (10)
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts
  • packages/artifacts/package.json
  • packages/deck/README.md
  • packages/deck/__tests__/createOrUpdateDeckMapBlock.test.ts
  • packages/deck/__tests__/normalizeDeckMapPointConfig.test.ts
  • packages/deck/src/block.tsx
  • packages/deck/src/mapConfigUtils.ts
  • packages/documents/README.md
  • packages/documents/__tests__/startBlockScopedChat.test.ts
  • packages/documents/package.json
✅ Files skipped from review due to trivial changes (3)
  • packages/documents/README.md
  • packages/artifacts/package.json
  • packages/deck/README.md
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/documents/package.json
  • apps/sqlrooms-cli-ui/src/ai/createCliBlockDocumentAgentTool.ts
  • packages/deck/tests/createOrUpdateDeckMapBlock.test.ts
  • packages/deck/tests/normalizeDeckMapPointConfig.test.ts
  • packages/deck/src/mapConfigUtils.ts
  • packages/deck/src/block.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: 2da183d77d

ℹ️ 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 packages/deck/src/createOrUpdateDeckMapBlock.ts Outdated
Comment thread packages/deck/src/createOrUpdateDeckMapBlock.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: a1e5130018

ℹ️ 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".

blockId = existingMapBlock.blockId;
resolvedMapId = existingMapBlock.mapId;
host.ensureMapState(resolvedMapId, title);
host.ensureDashboard(resolvedMapId, title);

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 dashboard titles on title-less edits

When updating an existing map and the AI omits title, title is still synthesized from the block caption or panel title and passed to ensureDashboard. The CLI adapter forwards this to mosaicDashboard.ensureDashboard, which renames existing dashboards whenever a non-empty title differs, so a title-less Ask AI config edit can overwrite the backing dashboard/map name even though only the panel config was meant to change. Pass undefined here unless params.title was explicitly provided, while still using the synthesized value for the panel title/caption.

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: 287997de2b

ℹ️ 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 +207 to +209
params.caption ??
existingCaption ??
params.title?.trim() ??

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 Apply explicit map titles to block captions

When an existing map block already has a caption and the update supplies title but no explicit caption, this fallback selects the old existingCaption before considering params.title. Later updateBlockMetadata persists that old caption, and the worksheet map header renders the caption before the panel title, so a rename like {mapId, title: 'Sales map'} updates the panel/dashboard but the visible block caption remains the previous title. Prefer the explicit title before the existing caption when no caption was supplied.

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: 0413dcae1d

ℹ️ 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 +336 to +342
if (
!tableName ||
source?.sqlQuery ||
source?.transformSql ||
(typeof dataset.geometryColumn === 'string' &&
dataset.geometryColumn.trim())
) {

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 inferred geometry datasets during point normalization

When normalizeDeckMapPointConfig(...) is run on a table-backed polygon/line config that relies on SQLRooms' existing geometry auto-detection (for example a GeoJSON table with a geom column) and that table also has lon/lat attribute columns, this guard only skips explicitly declared dataset.geometryColumn. The helper then rewrites the dataset to __sqlrooms_geom, so layers that would have rendered from the inferred native geometry can be converted to point geometry or get incorrect fit-to-data bounds. Fresh evidence after the earlier explicit-geometry fix: the current guard still does not check the resolved table for an inferred geometry column or confirm that a point layer targets this dataset before transforming it.

Useful? React with 👍 / 👎.

Comment on lines 389 to +392
<DeckMapBlockErrorBoundary
key={mapBoundaryKey}
onError={handleMapRenderError}
onRenderSuccess={handleMapRenderSuccess}

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 Clear stale map issues when rendering the empty state

This only clears a prior render issue through onRenderSuccess, but that boundary is not mounted when a repaired/updated map config has no datasets and the block renders DataTableSelectorEmptyState instead. In that case a previous render-error remains in panelIssuesByPanelId, so list_blocks and block-repair prompts can continue reporting the map as broken even though the current panel is just the no-dataset empty state. Fresh evidence after the earlier stale-issue fix: the current clear path is attached only to the success boundary on the hasDatasets branch.

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: 33364754b5

ℹ️ 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 +197 to +200
requireTableNameForSqlOnlyUpdate &&
params.mapId &&
!tableName &&
hasSqlOnlyDatasetSource(params.config)

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 Treat create-mode stale map IDs as creates

When a host opts into missingMapBlockBehavior: 'create' for a stale mapId, this branch still treats the call as an update solely because params.mapId is present. A SQL-only config that is valid when creating a new map without a selected table will throw before the helper reaches created = !existingMapBlock, so the documented soft-recovery path cannot create replacement maps for those configs. Gate this on existingMapBlock/the resolved update path rather than the presence of the stale parameter.

Useful? React with 👍 / 👎.

}

const table = tableName ? host.findTable(tableName) : undefined;
if (requestedTableName && !table) {

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 Validate tables added by prepared configs

If prepareConfig merges or injects a table-backed dataset and the original params did not include a tableName or table-backed source, requestedTableName is undefined, so a missing prepared tableName is silently accepted even though tableName was resolved and findTable returned nothing. The helper then writes a panel that points at a nonexistent table and reports success with no selected table; this check should use the resolved tableName so prepared configs get the same validation as direct configs.

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: a73683cf9a

ℹ️ 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 packages/ai/src/index.ts
Comment on lines +198 to +200
createAskAiBlockHeaderAction,
type AskAiBlockHeaderActionRenderContext,
type CreateAskAiBlockHeaderActionOptions,

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 Document the re-exported Ask AI helpers

This adds createAskAiBlockHeaderAction and its related types to the public @sqlrooms/ai barrel, but packages/ai/README.md is unchanged; only @sqlrooms/ai-core documents the helper. The root AGENTS.md Documentation rule requires updating the package README when adding public @sqlrooms/* APIs, so consumers using the recommended high-level package won't see the new block Ask AI integration contract.

Useful? React with 👍 / 👎.

@ilyabo
ilyabo merged commit 10eaa68 into main Jul 12, 2026
4 checks passed
@ilyabo
ilyabo deleted the feat/block-document-sharing-stages-1-5 branch July 12, 2026 21:38
@coderabbitai coderabbitai Bot mentioned this pull request Aug 4, 2026
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