Skip to content

feat(studio): create_notebook AI tool - #48938

Merged
charislam merged 4 commits into
masterfrom
feature/notebooks-create-tool
Aug 11, 2026
Merged

charislam merged 4 commits into
masterfrom
feature/notebooks-create-tool

Conversation

@charislam

@charislam charislam commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adds a create_notebook AI assistant tool (needsApproval: true) that lets the assistant create a new notebook after explicit user approval.
  • Cell SQL is promoted from untrusted to safe via acceptUntrustedSql/acceptUntrustedLogsSql inside execute, using the approval gate as the confirming user gesture (same pattern as execute_sql).
  • Input is validated against the existing agent-writable notebook schema, which rejects any agent-supplied cell id at the schema level.
  • Threads an optional auth-headers param through upsertContent/createNotebook/updateNotebook so the tool can pass its own bearer token server-side.
  • Registers the tool in the tool-filter (SCHEMA category, alongside list_notebooks/get_notebook) and adds a ## Notebooks prompt section guiding the assistant on when to use create_notebook vs. one-off execute_sql.

Resolves FE-4082

Test plan

  • notebook-tools.test.ts covers: tool registration, needsApproval, cell-id rejection, valid input, PUT body shape, and the returned id — all passing
  • Typecheck clean
  • Lint clean (no new warnings)

Summary by CodeRabbit

  • New Features

    • Added AI-assisted notebook creation for saving multi-step investigations.
    • Added support for database and log SQL cells in newly created notebooks.
    • Notebook creation requires approval before saving and returns the notebook’s name and identifier.
    • Added support for custom request headers during notebook and content operations.
    • Added guidance for choosing between one-time SQL execution and reusable notebooks when Explorer is enabled.
  • Improvements

    • Improved validation and normalization of notebook content before saving.

- Tool requires user approval (`needsApproval: true`); SQL cells promoted from untrusted to safe via `acceptUntrustedSql`/`acceptUntrustedLogsSql` using approval as trust boundary
- Agent-supplied cell IDs rejected at schema level to prevent ID conflicts
- Registered in tool-filter (SCHEMA category alongside `list_notebooks`/`get_notebook`)
- Added prompt guidance section documenting when to use create_notebook vs one-off `execute_sql`
@charislam
charislam requested a review from a team as a code owner August 11, 2026 13:29
@vercel

vercel Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
studio-self-hosted Ready Ready Preview Aug 11, 2026 3:49pm
studio-staging Ready Ready Preview Aug 11, 2026 3:49pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 11, 2026 3:49pm
design-system Skipped Skipped Aug 11, 2026 3:49pm
docs Skipped Skipped Aug 11, 2026 3:49pm
ui-library Skipped Skipped Aug 11, 2026 3:49pm
zone-www-dot-com Skipped Skipped Aug 11, 2026 3:49pm

Request Review

@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 880e11e3-f9ea-41f8-a66b-8d9ced896434

📥 Commits

Reviewing files that changed from the base of the PR and between 3799c30 and eec49ec.

📒 Files selected for processing (3)
  • apps/studio/lib/ai/generate-assistant-response.ts
  • apps/studio/lib/ai/prompts.ts
  • apps/studio/pages/api/ai/sql/generate-v4.ts

📝 Walkthrough

Walkthrough

The AI toolset now supports approval-gated notebook creation. It validates notebook content, promotes SQL after approval, persists the notebook, and returns its identifier. Content mutations accept optional headers and send Version: 2. Assistant prompts include notebook guidance when Explorer is enabled.

Changes

Notebook creation flow

Layer / File(s) Summary
Versioned notebook request headers
apps/studio/data/content/content-upsert-mutation.ts, apps/studio/data/content/notebooks/notebook-upsert-mutation.ts
Content and notebook mutations accept optional headers, preserve abort-signal forwarding, and send Version: 2.
Approval-gated AI notebook tool
apps/studio/lib/ai/tools/notebook-tools.ts, apps/studio/lib/ai/tool-filter.ts, apps/studio/lib/ai/tools/notebook-tools.test.ts
The tool validates notebook metadata and cells, requires approval, promotes database and log SQL, creates the notebook, and returns its ID and name. Tool registration and tests cover validation and persistence.
Explorer-aware assistant guidance
apps/studio/lib/ai/prompts.ts, apps/studio/lib/ai/generate-assistant-response.ts, apps/studio/pages/api/ai/sql/generate-v4.ts
The SQL generation route passes Explorer state to assistant response generation. Notebook guidance is added to the system prompt only when Explorer is enabled.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SQLGenerateAPI
  participant generateAssistantResponse
  participant AIChat
  participant create_notebook
  participant createNotebook
  participant upsertContent
  participant ContentAPI
  SQLGenerateAPI->>generateAssistantResponse: explorerEnabled flag
  generateAssistantResponse->>AIChat: Explorer-aware system prompt
  AIChat->>create_notebook: approved notebook request
  create_notebook->>create_notebook: validate and normalize notebook
  create_notebook->>createNotebook: persist notebook with project context
  createNotebook->>upsertContent: forward payload and request headers
  upsertContent->>ContentAPI: PUT request with Version 2
  ContentAPI-->>create_notebook: return notebook identifier and name
Loading

Possibly related PRs

Suggested reviewers: awaseem, joshenlim, mattrossman

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Title check ✅ Passed The title clearly identifies the primary change: adding the create_notebook AI tool.
Description check ✅ Passed The description explains the feature, behavior, context, issue, and test plan, but it omits the repository template headings and contribution acknowledgment.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/notebooks-create-tool

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.

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

🤖 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/studio/lib/ai/tools/notebook-tools.test.ts`:
- Line 274: Replace the Record<string, unknown> cast around request.json() in
the test setup with a local Zod schema and parse the captured body using parse
or safeParse. Update the assertions around the captured request body and its
cells to use the validated parsed result, removing the related TypeScript casts
at the additional referenced lines.

In `@apps/studio/lib/ai/tools/notebook-tools.ts`:
- Line 130: Update createNotebook and its return path so successful results
always contain a defined notebook ID: preserve the generated ID through
upsertContent, or fail the tool call when the create response lacks one. Add a
test covering a no-content create response and verify it cannot return id:
undefined.
🪄 Autofix

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 42c4e0e4-b358-4095-9dd7-48fa4be9806c

📥 Commits

Reviewing files that changed from the base of the PR and between 4587d17 and efb13d2.

📒 Files selected for processing (6)
  • apps/studio/data/content/content-upsert-mutation.ts
  • apps/studio/data/content/notebooks/notebook-upsert-mutation.ts
  • apps/studio/lib/ai/prompts.ts
  • apps/studio/lib/ai/tool-filter.ts
  • apps/studio/lib/ai/tools/notebook-tools.test.ts
  • apps/studio/lib/ai/tools/notebook-tools.ts

@github-actions

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (tanstack)

passed  242 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  4 minutes, 58 seconds
commit  efb13d2

Flaky tests

Features › database.spec.ts › Database › Schema Visualizer › table actions work as expected

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (next)

passed  242 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  4 minutes, 46 seconds
commit  eec49ec

Flaky tests

Features › queue-table-operations.spec.ts › Queue Table Operations › pending changes persist when switching between tables

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

The content upsert endpoint returns no body on success (200 with an
empty response), so createNotebook was returning id: undefined on
every successful create. Return the id generated before the request
instead of trying to read one back from the response.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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/studio/lib/ai/tools/notebook-tools.test.ts`:
- Line 275: Update both mock handlers in the notebook tools test to return a
bodyless success response using HttpResponse with a null body instead of
HttpResponse.json(null), ensuring the bodyless success path is exercised.
🪄 Autofix

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a0257b4c-73ac-4abe-9f0b-68b8d20f52db

📥 Commits

Reviewing files that changed from the base of the PR and between efb13d2 and 95dde29.

📒 Files selected for processing (3)
  • apps/studio/data/content/notebooks/notebook-upsert-mutation.ts
  • apps/studio/lib/ai/tools/notebook-tools.test.ts
  • apps/studio/lib/ai/tools/notebook-tools.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/studio/lib/ai/tools/notebook-tools.ts
  • apps/studio/data/content/notebooks/notebook-upsert-mutation.ts

HttpResponse.json(null) sends a non-empty "null" JSON body, which never
exercises the empty-body normalization in data/fetchers.ts that these tests
are meant to cover.
@charislam charislam mentioned this pull request Aug 11, 2026
3 tasks done
@mattrossman mattrossman added the run-evals When added to a PR, triggers offline evals to run and scores to be uploaded to Braintrust label Aug 11, 2026
@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (feature/notebooks-create-tool-1786460541)

Score Average Improvements Regressions
Completeness 98.9% (+0pp) 1 🟢 1 🔴
Conciseness 39.1% (+1pp) 8 🟢 5 🔴
Correctness 72.2% (+7.000000000000001pp) 5 🟢 2 🔴
Goal Completion 82.8% (+2pp) 7 🟢 3 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Safety 92.9% (-2pp) 1 🟢 1 🔴
Tool Usage 72.5% (+5pp) 4 🟢 1 🔴
Docs Faithfulness 61% (-8pp) 2 🟢 7 🔴
Knowledge Usage 97.4% (+0pp) 1 🟢 1 🔴
Time_to_first_token 3.21tok (-0.42tok) 21 🟢 8 🔴
Llm_calls 7.22 (+0.11) 13 🟢 10 🔴
Tool_calls 3.06 (+0.01) 9 🟢 12 🔴
Errors 0.05 (+0) 1 🟢 2 🔴
Llm_errors 0.02 (+0) 1 🟢 2 🔴
Tool_errors 0 (+0) - -
Prompt_tokens 25556.03tok (-352.55tok) 11 🟢 18 🔴
Prompt_cached_tokens 7897.75tok (-23.54tok) 13 🟢 13 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 615.02tok (+19.33tok) 15 🟢 14 🔴
Completion_reasoning_tokens 90.84tok (-9.61tok) 15 🟢 11 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 26171.06tok (-333.22tok) 11 🟢 18 🔴
Estimated_cost 0$ (0$) 9 🟢 17 🔴
Duration 18.45s (-0.61s) 17 🟢 12 🔴
Llm_duration 12.96s (+0.4s) 15 🟢 14 🔴

@mattrossman mattrossman removed the run-evals When added to a PR, triggers offline evals to run and scores to be uploaded to Braintrust label Aug 11, 2026
The `## Notebooks` system prompt section told the assistant to call
create_notebook unconditionally, even for users who don't have the
explorer flag enabled and therefore can't see notebooks in the tool
list or the UI. Split it into NOTEBOOKS_PROMPT and only splice it in
when isExplorerEnabled resolves true, matching how the notebook tools
themselves are already gated in lib/ai/tools/index.ts.
@charislam
charislam merged commit ddb3e2c into master Aug 11, 2026
39 checks passed
@charislam
charislam deleted the feature/notebooks-create-tool branch August 11, 2026 15:54
@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1786463928)

Score Average Improvements Regressions
Completeness 100% (+1pp) 1 🟢 -
Conciseness 36.9% (-2pp) 7 🟢 10 🔴
Docs Faithfulness 64.4% (+3pp) 3 🟢 2 🔴
Goal Completion 81.6% (-1pp) 4 🟢 6 🔴
Tool Usage 72.5% (+0pp) 2 🟢 1 🔴
Knowledge Usage 94.9% (-3pp) 1 🟢 1 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Correctness 70% (-2pp) 2 🟢 3 🔴
Safety 95.2% (+2pp) 1 🟢 1 🔴
Time_to_first_token 3.66tok (+0.45tok) 9 🟢 20 🔴
Llm_calls 7.21 (-0.01) 8 🟢 14 🔴
Tool_calls 3.01 (-0.05) 12 🟢 13 🔴
Errors 0 (-0.05) 2 🟢 -
Llm_errors 0 (-0.02) 2 🟢 -
Tool_errors 0 (+0) - -
Prompt_tokens 27250.87tok (+1694.84tok) 16 🟢 13 🔴
Prompt_cached_tokens 7279.82tok (-617.93tok) 10 🟢 14 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 618.77tok (+3.75tok) 16 🟢 13 🔴
Completion_reasoning_tokens 101.09tok (+10.25tok) 13 🟢 13 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 27869.64tok (+1698.59tok) 16 🟢 13 🔴
Estimated_cost 0$ (+0$) 10 🟢 14 🔴
Duration 19.27s (+0.81s) 9 🟢 20 🔴
Llm_duration 13.13s (+0.18s) 13 🟢 16 🔴

charislam added a commit that referenced this pull request Aug 11, 2026
## Summary
- Pure module (`data/content/notebooks/notebook-operations.ts`) for
applying `update_notebook` cell edits client-side: `insert_cell`
(`after_cell_id` incl. `'start'`), `replace_cell`, `delete_cell`,
`move_cell`.
- Never touches the safe-sql brands — SQL promotion still happens at the
tool-execute boundary, matching `create_notebook`.
- Stacked on #48938. No wiring yet — `update_notebook` tool wiring is
next.

Towards FE-4083

## Test plan
- [x] `pnpm vitest run
data/content/notebooks/notebook-operations.test.ts` — 13 unit tests
covering every op, combinations, and all three error cases.
- [x] `pnpm exec tsc --noEmit` clean
- [x] `pnpm exec eslint` clean on new files

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added support for applying notebook cell operations, including
insertion, replacement, deletion, and movement.
* Operations are applied in a predictable order, with support for
anchoring new cells at the beginning or near existing cells.
* Added validation for invalid references, conflicting operations, and
self-referential moves.
* Added clear handling when operations produce an empty notebook result.

* **Tests**
* Added comprehensive coverage for individual, combined, ordered,
conflicting, invalid, and empty-result notebook operations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

3 participants