Skip to content

refactor: decouple assistant chat surfaces - #48973

Merged
SaxonF merged 2 commits into
masterfrom
chore/assistant-chat-foundation
Aug 13, 2026
Merged

SaxonF merged 2 commits into
masterfrom
chore/assistant-chat-foundation

Conversation

@SaxonF

@SaxonF SaxonF commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • extract the reusable assistant conversation body from the sidebar interface
  • drive shared chat rendering and mutations with an explicit chat ID
  • keep sidebar selection, shortcuts, SQL-editor context, and header controls in the sidebar wrapper
  • add selection-free chat creation and branching primitives while preserving existing sidebar helpers
  • add store tests for cross-surface selection and mutation isolation

This is PR 1 of 3. Review this foundation first, then #49031 for the routed Explorer chat lifecycle, followed by #49032 for discovery and cross-surface entry points.

Supersedes #48970 after renaming the branch to use the repository's chore/ convention.

Test plan

  • mise exec node@22 -- pnpm --dir apps/studio exec tsc --noEmit
  • mise exec node@22 -- pnpm --dir apps/studio exec vitest run state/ai-assistant-state.test.ts
  • ESLint on changed files
  • Prettier on changed files

@vercel

vercel Bot commented Aug 12, 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 13, 2026 4:07am
studio-staging Ready Ready Preview Aug 13, 2026 4:07am
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 13, 2026 4:07am
design-system Skipped Skipped Aug 13, 2026 4:07am
docs Skipped Skipped Aug 13, 2026 4:07am
ui-library Skipped Skipped Aug 13, 2026 4:07am
zone-www-dot-com Skipped Skipped Aug 13, 2026 4:07am

Request Review

@coderabbitai

coderabbitai Bot commented Aug 12, 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: 45557ebb-a6dd-42a3-8f6e-5120ff6961a3

📥 Commits

Reviewing files that changed from the base of the PR and between 00e219b and cae676a.

📒 Files selected for processing (4)
  • apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
  • apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx
  • apps/studio/state/ai-assistant-state.test.ts
  • apps/studio/state/ai-assistant-state.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/studio/state/ai-assistant-state.test.ts
  • apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
  • apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx
  • apps/studio/state/ai-assistant-state.tsx

📝 Walkthrough

Walkthrough

The AI assistant chat logic moved into AssistantChat. The sidebar wrapper now manages activation, shortcuts, and SQL snippet synchronization. Chat state supports targeted creation, branching, initialization, and message mutations.

Changes

AI assistant chat architecture

Layer / File(s) Summary
Chat state API
apps/studio/state/ai-assistant-state.tsx, apps/studio/state/ai-assistant-state.test.ts
Chat creation, branching, lazy initialization, and message mutations now support explicit chat IDs. Tests cover inactive-chat operations without changing sidebar selection.
AssistantChat orchestration
apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx
AssistantChat now owns chat requests, model selection, approvals, message actions, SQL metadata, errors, onboarding, support flows, telemetry, and form rendering.
Message branching contract
apps/studio/components/ui/AIAssistantPanel/Message.Context.tsx, apps/studio/components/ui/AIAssistantPanel/Message.tsx
Message branching uses the action context and receives an explicit onBranch callback.
Sidebar wrapper and shortcuts
apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx, apps/studio/components/ui/AIAssistantPanel/AIAssistantChatSelector.tsx, apps/studio/components/ui/AIAssistantPanel/AIAssistantHeader.tsx
AIAssistant manages sidebar activation, new-chat shortcuts, and SQL snippet synchronization before delegating rendering to AssistantChat. Header and history shortcuts honor shortcutsEnabled.

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

Sequence Diagram(s)

sequenceDiagram
  participant AIAssistant
  participant AssistantChat
  participant AssistantChatForm
  participant useChat
  AIAssistant->>AssistantChat: render active chat
  AssistantChat->>AssistantChatForm: provide chat state and actions
  AssistantChatForm->>AssistantChat: submit prompt
  AssistantChat->>useChat: send prompt and context
  useChat-->>AssistantChat: stream response or approval request
Loading

Possibly related PRs

🚥 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
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.
Title check ✅ Passed The title clearly and concisely describes the main refactor: separating reusable assistant chat surfaces from sidebar-specific behavior.
Description check ✅ Passed The description provides a detailed summary, context, and test plan, although it does not use all template headings or confirm CONTRIBUTING.md review.
✨ 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 chore/assistant-chat-foundation

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.

@supabase

supabase Bot commented Aug 12, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@SaxonF
SaxonF force-pushed the chore/assistant-chat-foundation branch from 15ab2dd to 00e219b Compare August 12, 2026 07:04
@SaxonF
SaxonF marked this pull request as ready for review August 12, 2026 07:06
@SaxonF
SaxonF requested a review from a team as a code owner August 12, 2026 07:06

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

Caution

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

⚠️ Outside diff range comments (1)
apps/studio/state/ai-assistant-state.tsx (1)

547-589: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

state.chats and state.chatInstances can diverge for a chat that is not rendered. The PR makes chat mutation and chat rendering target an explicit chat id, but nothing keeps the stored Chat instance aligned with state.chats[chatId]. ensureChatInstance only creates a missing instance; it never refreshes an existing one, and no render path calls it.

  • apps/studio/state/ai-assistant-state.tsx#L547-L589: in clearMessages, deleteMessagesAfter, and updateMessage, either drop state.chatInstances[chatId] so it is rebuilt lazily, or call setMessages on the stored instance.
  • apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx#L197-L202: call state.ensureChatInstance(chatId) before useChat, so a rendered chat id never falls back to an internal chat without the onFinish state sync.
  • apps/studio/state/ai-assistant-state.test.ts#L78-L94: assert that state.chatInstances[explorerChatId] reflects the cleared messages, so the divergence is covered by a test.
🤖 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/studio/state/ai-assistant-state.tsx` around lines 547 - 589, Keep
state.chats and state.chatInstances synchronized by invalidating or updating the
stored instance in clearMessages, deleteMessagesAfter, and updateMessage within
apps/studio/state/ai-assistant-state.tsx:547-589; call
ensureChatInstance(chatId) before useChat in
apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx:197-202; and add
coverage in apps/studio/state/ai-assistant-state.test.ts:78-94 asserting the
explorer chat instance reflects cleared messages.
🧹 Nitpick comments (10)
apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx (2)

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

Rename the sidebar-activity flag and keep the shortcut prop separate.

Line 29 computes whether the assistant sidebar is the active sidebar. The name shortcutsEnabled describes only one of its uses. Line 45 reuses the same value to gate SQL snippet synchronization, which is not a shortcut concern. Rename the derived value to state the condition, then pass it to the shortcutsEnabled props.

Coding guidelines require boolean names that begin with is, has, can, or should.

♻️ Proposed rename
-  const shortcutsEnabled = activeSidebar?.id === SIDEBAR_KEYS.AI_ASSISTANT
+  const isAssistantSidebarActive = activeSidebar?.id === SIDEBAR_KEYS.AI_ASSISTANT
 
   const handleNewChat = () => state.newChat()
 
   useShortcut(SHORTCUT_IDS.AI_ASSISTANT_NEW_CHAT, handleNewChat, {
-    enabled: shortcutsEnabled,
+    enabled: isAssistantSidebarActive,
   })
@@
   useEffect(() => {
-    if (shortcutsEnabled && isInSQLEditor && !!snippetContent) {
+    if (isAssistantSidebarActive && isInSQLEditor && !!snippetContent) {
       state.setSqlSnippets([
         { label: 'Current Query', content: snippetContent, source: openSnippetSource },
       ])
     }
-  }, [shortcutsEnabled, isInSQLEditor, snippetContent, openSnippetSource, state])
+  }, [isAssistantSidebarActive, isInSQLEditor, snippetContent, openSnippetSource, state])

Then pass shortcutsEnabled={isAssistantSidebarActive} to AssistantChat and AIAssistantHeader.

Also applies to: 44-50

🤖 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/studio/components/ui/AIAssistantPanel/AIAssistant.tsx` at line 29,
Rename the derived sidebar-activity flag in AIAssistant from shortcutsEnabled to
isAssistantSidebarActive, preserving its active-sidebar condition. Use
isAssistantSidebarActive for SQL snippet synchronization and pass it explicitly
as shortcutsEnabled to AssistantChat and AIAssistantHeader.

Source: Coding guidelines


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

Replace the as cast on snap.sqlSnippets.

Line 64 casts a Valtio snapshot value with as SqlSnippet[] | undefined. The coding guidelines require avoiding TypeScript as casts. The snapshot type is DeepReadonly, so widen the composerContext prop type to accept a readonly array instead of casting at the call site.

🤖 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/studio/components/ui/AIAssistantPanel/AIAssistant.tsx` around lines 62 -
73, Remove the `as SqlSnippet[] | undefined` cast from `snap.sqlSnippets` in the
`composerContext` passed by `AIAssistant`. Update the `composerContext`
prop/type definition to accept a readonly `SqlSnippet` array, preserving
compatibility with Valtio’s `DeepReadonly` snapshot value.

Source: Coding guidelines

apps/studio/state/ai-assistant-state.tsx (1)

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

Reuse ensureChatInstance in loadPersistedState.

loadPersistedState still inlines the same "create instance if missing" logic for the active chat. Call state.ensureChatInstance(state.activeChatId) there instead, so instance creation has one definition.

🤖 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/studio/state/ai-assistant-state.tsx` around lines 508 - 515, Update
loadPersistedState to call state.ensureChatInstance(state.activeChatId) instead
of duplicating the chat-instance creation logic. Remove the inline
ref/createChatInstance block there, while preserving the existing active-chat
loading behavior.
apps/studio/components/ui/AIAssistantPanel/Message.tsx (1)

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

Add satisfies MessageActions to messageActions.

messageInfo on line 135 uses satisfies MessageInfo. messageActions has no annotation. Adding satisfies MessageActions catches a missing or misspelled action at the definition site rather than at the provider.

🔧 Proposed change
     onCancelEdit: props.onCancelEdit,
     onRate: props.onRate,
-  }
+  } satisfies MessageActions
🤖 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/studio/components/ui/AIAssistantPanel/Message.tsx` at line 141, Update
the messageActions definition near onBranch to use the MessageActions type with
satisfies, matching the existing messageInfo pattern. Keep the current action
implementations unchanged while ensuring missing or misspelled actions are
validated at definition time.
apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx (5)

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

Flatten the nested ternaries.

Two places nest ternaries. Line 669-679 nests four levels for placeholder. Lines 496-502 nest two levels for the error prop. Extract each into a small function with early returns.

🔧 Proposed change for the placeholder
+  const getPlaceholder = () => {
+    if (hasMessages) {
+      return isSupportChat
+        ? 'Share details so the assistant can help with your support request...'
+        : 'Ask a follow up question...'
+    }
+    if ((composerContext?.sqlSnippets ?? []).length > 0) {
+      return 'Ask a question or make a change...'
+    }
+    return isSupportChat ? 'Describe your support issue...' : 'Chat to Postgres...'
+  }
-            placeholder={
-              hasMessages
-                ? isSupportChat
-                  ? 'Share details so the assistant can help with your support request...'
-                  : 'Ask a follow up question...'
-                : (composerContext?.sqlSnippets ?? []).length > 0
-                  ? 'Ask a question or make a change...'
-                  : isSupportChat
-                    ? 'Describe your support issue...'
-                    : 'Chat to Postgres...'
-            }
+            placeholder={getPlaceholder()}

As per coding guidelines: "Do not nest ternaries. Use a single ternary only for binary choices; flatten larger conditional rendering with early returns or sibling && blocks."

🤖 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/studio/components/ui/AIAssistantPanel/AssistantChat.tsx` around lines
669 - 679, Replace the nested ternary used by the AssistantChat placeholder prop
with a small helper function using early returns, preserving the existing
hasMessages, isSupportChat, and sqlSnippets.length outcomes. Apply the same
approach to the nested ternary in the error prop around the existing
error-rendering logic, extracting a helper with early returns and keeping all
current behavior unchanged.

Source: Coding guidelines


462-481: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Split AssistantChat into smaller components.

The component body spans roughly 625 lines and holds several distinct UI sections: the conversation list, the error block, the edit banner, the support actions, the admonitions, and the composer. Extract the edit banner and the composer block, at minimum.

As per coding guidelines: "Split components at approximately 200–300 lines or earlier when they contain multiple distinct UI sections, tangled conditionals, or unrelated state clusters."

🤖 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/studio/components/ui/AIAssistantPanel/AssistantChat.tsx` around lines
462 - 481, Refactor AssistantChat into smaller focused components, extracting at
minimum the edit banner and composer block from the main component. Keep the
conversation list, error block, support actions, and admonitions behavior
unchanged while passing only the required state, handlers, and values through
clear props.

Source: Coding guidelines


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

Derive selectedModel during render without useMemo.

selectedModel is a string. The computation is three comparisons. The memo adds no referential stability and no measured saving. Compute it inline.

As per coding guidelines: "Do not use useMemo or useCallback by default; use them only for measured expense or referential stability required by a memoized child."

🤖 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/studio/components/ui/AIAssistantPanel/AssistantChat.tsx` around lines
112 - 127, Remove the useMemo wrapper around selectedModel and derive the value
directly during render using the existing entitlement, model validation, and
access checks. Preserve the current fallback behavior and remove the
now-unneeded memo dependency array and import if applicable.

Source: Coding guidelines


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

Remove the unused lastUserMessageRef

lastUserMessageRef is only assigned and never read. Remove the ref and both assignments.

🤖 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/studio/components/ui/AIAssistantPanel/AssistantChat.tsx` at line 404,
Remove the unused lastUserMessageRef declaration from AssistantChat and delete
both assignments to lastUserMessageRef.current, including the assignment near
payload handling, without changing the surrounding chat behavior.

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

Remove the as MessageType cast and createdAt field.

UIMessage in @ai-sdk/react 3.0.118 does not define top-level createdAt. Declare payload as MessageType so TypeScript checks the object shape. Move the timestamp to metadata only if the metadata schema is extended.

🤖 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/studio/components/ui/AIAssistantPanel/AssistantChat.tsx` around lines
395 - 401, Update the payload declaration in AssistantChat by removing the
createdAt property and the `as MessageType` assertion; explicitly declare the
object as MessageType so TypeScript validates its shape. Preserve the timestamp
only through metadata if the existing metadata schema supports it, otherwise do
not add it.

Source: Coding guidelines

apps/studio/state/ai-assistant-state.test.ts (1)

78-94: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add an assertion for the stored Chat instance.

This test proves that state.chats is isolated. It does not prove that state.chatInstances[explorerChatId] was also cleared. That gap is the failure mode described in the ai-assistant-state.tsx comment on clearMessages. Add an assertion on the instance messages once the mutation behavior is settled.

🤖 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/studio/state/ai-assistant-state.test.ts` around lines 78 - 94, Add an
assertion to the clearMessages test for
state.chatInstances[explorerChatId].messages, verifying the stored Chat instance
is also empty after mutating the explicit explorer chat. Keep the existing
assertions for activeChatId and state.chats unchanged.
🤖 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/components/ui/AIAssistantPanel/AIAssistant.tsx`:
- Around line 44-50: Update the useEffect managing the Current Query attachment
to remove or relinquish that attachment when shortcutsEnabled, isInSQLEditor, or
snippetContent no longer applies. Use a targeted clear or ownership check that
preserves sqlSnippets supplied by non-SQL flows, rather than unconditionally
calling clearSqlSnippets(); keep setting the current SQL snippet unchanged for
valid SQL editor context.

In `@apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx`:
- Around line 178-184: Update the useEffect dependency in AssistantChat so it
uses the reactive organization slug value rather than
selectedOrganizationRef.current?.slug. Ensure organization changes re-run
state.setContext and remove the unverifiable ref-member dependency so
exhaustive-deps passes.
- Line 61: Update the aiOptInLevel prop type used by renderHeader to reuse the
return/source type from useOrgAiOptInLevel instead of declaring the redundant
literal-or-string union. Preserve the existing optional/undefined behavior while
allowing consumers to receive the source type’s intended narrowing.

---

Outside diff comments:
In `@apps/studio/state/ai-assistant-state.tsx`:
- Around line 547-589: Keep state.chats and state.chatInstances synchronized by
invalidating or updating the stored instance in clearMessages,
deleteMessagesAfter, and updateMessage within
apps/studio/state/ai-assistant-state.tsx:547-589; call
ensureChatInstance(chatId) before useChat in
apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx:197-202; and add
coverage in apps/studio/state/ai-assistant-state.test.ts:78-94 asserting the
explorer chat instance reflects cleared messages.

---

Nitpick comments:
In `@apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx`:
- Line 29: Rename the derived sidebar-activity flag in AIAssistant from
shortcutsEnabled to isAssistantSidebarActive, preserving its active-sidebar
condition. Use isAssistantSidebarActive for SQL snippet synchronization and pass
it explicitly as shortcutsEnabled to AssistantChat and AIAssistantHeader.
- Around line 62-73: Remove the `as SqlSnippet[] | undefined` cast from
`snap.sqlSnippets` in the `composerContext` passed by `AIAssistant`. Update the
`composerContext` prop/type definition to accept a readonly `SqlSnippet` array,
preserving compatibility with Valtio’s `DeepReadonly` snapshot value.

In `@apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx`:
- Around line 669-679: Replace the nested ternary used by the AssistantChat
placeholder prop with a small helper function using early returns, preserving
the existing hasMessages, isSupportChat, and sqlSnippets.length outcomes. Apply
the same approach to the nested ternary in the error prop around the existing
error-rendering logic, extracting a helper with early returns and keeping all
current behavior unchanged.
- Around line 462-481: Refactor AssistantChat into smaller focused components,
extracting at minimum the edit banner and composer block from the main
component. Keep the conversation list, error block, support actions, and
admonitions behavior unchanged while passing only the required state, handlers,
and values through clear props.
- Around line 112-127: Remove the useMemo wrapper around selectedModel and
derive the value directly during render using the existing entitlement, model
validation, and access checks. Preserve the current fallback behavior and remove
the now-unneeded memo dependency array and import if applicable.
- Line 404: Remove the unused lastUserMessageRef declaration from AssistantChat
and delete both assignments to lastUserMessageRef.current, including the
assignment near payload handling, without changing the surrounding chat
behavior.
- Around line 395-401: Update the payload declaration in AssistantChat by
removing the createdAt property and the `as MessageType` assertion; explicitly
declare the object as MessageType so TypeScript validates its shape. Preserve
the timestamp only through metadata if the existing metadata schema supports it,
otherwise do not add it.

In `@apps/studio/components/ui/AIAssistantPanel/Message.tsx`:
- Line 141: Update the messageActions definition near onBranch to use the
MessageActions type with satisfies, matching the existing messageInfo pattern.
Keep the current action implementations unchanged while ensuring missing or
misspelled actions are validated at definition time.

In `@apps/studio/state/ai-assistant-state.test.ts`:
- Around line 78-94: Add an assertion to the clearMessages test for
state.chatInstances[explorerChatId].messages, verifying the stored Chat instance
is also empty after mutating the explicit explorer chat. Keep the existing
assertions for activeChatId and state.chats unchanged.

In `@apps/studio/state/ai-assistant-state.tsx`:
- Around line 508-515: Update loadPersistedState to call
state.ensureChatInstance(state.activeChatId) instead of duplicating the
chat-instance creation logic. Remove the inline ref/createChatInstance block
there, while preserving the existing active-chat loading behavior.
🪄 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: 90bfce1b-cb4f-42cc-924a-09c850777103

📥 Commits

Reviewing files that changed from the base of the PR and between b5462a9 and 00e219b.

📒 Files selected for processing (8)
  • apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
  • apps/studio/components/ui/AIAssistantPanel/AIAssistantChatSelector.tsx
  • apps/studio/components/ui/AIAssistantPanel/AIAssistantHeader.tsx
  • apps/studio/components/ui/AIAssistantPanel/AssistantChat.tsx
  • apps/studio/components/ui/AIAssistantPanel/Message.Context.tsx
  • apps/studio/components/ui/AIAssistantPanel/Message.tsx
  • apps/studio/state/ai-assistant-state.test.ts
  • apps/studio/state/ai-assistant-state.tsx

@github-actions

github-actions Bot commented Aug 12, 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  6 minutes, 58 seconds
commit  c33e988

Flaky tests

Features › queue-table-operations.spec.ts › Queue Table Operations - queue identity fixes › deleting a newly inserted row removes it from pending changes

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

@SaxonF
SaxonF force-pushed the chore/assistant-chat-foundation branch from cae676a to 53e92d1 Compare August 13, 2026 00:48

@joshenlim joshenlim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Preview test — ✅ all pass

Ran a regression sweep on the AI Assistant sidebar since this PR is a refactor (no explicit "To test" section, and the listed test plan was all local commands — out of scope here). Reused an existing project on studio-staging.

# Test Result
1 Send a message in the AI Assistant ✅ Sent "list my tables", assistant ran list_tables and returned the correct tables plus an RLS advisory. Chat auto-titled itself.
2 Edit a sent message ✅ Edited message resubmitted cleanly, thread updated with no duplication or corruption.
3 Delete a message ✅ Deleted a message + its response via the confirmation dialog; earlier messages stayed intact.
4 Rate an assistant response ✅ Thumbs-up call succeeded (200), button state persisted.
5 Branch a message into a new chat ✅ "Branch in new chat" created a new chat with copied history and an independent response; original chat verified untouched.
6 New chat + switch back (active-conversation isolation) ✅ No message leakage between chats, no unexpected active-conversation changes — this is the specific class of bug the PR calls out as fixed. One minor nuance below.
7 SQL Editor → Assistant context sync ✅ A "Current Query" context chip picked up the exact SQL from the editor; asking the assistant to explain it worked correctly.
8 Keyboard shortcut (⌘I) across states ✅ Toggled open/closed correctly from both a blank state and while focus was in the SQL Monaco editor — no duplicate panels or no-ops.

Notes:

  • Skipped support escalation testing (external write, not authorized for this run) and all local commands from the PR's test plan (tsc, vitest, ESLint, Prettier) — out of scope for preview testing.
  • Small nuance on #6, not a clear bug but worth a glance given the PR explicitly targets this bug class: clicking "Ask Assistant" from the Security Advisor opens an unsent draft chat as the active panel, but the History dropdown's selected marker still shows the prior chat until the draft's first message is sent. Reads as intentional (drafts aren't in history until sent), flagging for awareness.
  • Left a few test chats in the reused project (edited/branched/deleted-message threads) — no side effects worth cleaning up, no SQL was executed against the DB, no projects created or deleted.
  • No screenshots — no failures or visual claims to verify.

@joshenlim joshenlim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Code changes generally LGTM!

@SaxonF
SaxonF merged commit 2f8181b into master Aug 13, 2026
40 checks passed
@SaxonF
SaxonF deleted the chore/assistant-chat-foundation branch August 13, 2026 06:00
@github-actions

github-actions Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1786601069)

Score Average Improvements Regressions
Completeness 98.9% (-1pp) - 1 🔴
Conciseness 45.7% (+5pp) 9 🟢 4 🔴
Correctness 72.4% (+2pp) 3 🟢 3 🔴
Goal Completion 83.2% (+0pp) 4 🟢 3 🔴
Knowledge Usage 92.3% (+3pp) 1 🟢 -
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 95% (-5pp) - 1 🔴
Tool Usage 75% (-4pp) 1 🟢 2 🔴
Docs Faithfulness 65.2% (-1pp) 5 🟢 3 🔴
URL Validity 100% - -
Safety 81% (-14.000000000000002pp) - 2 🔴
Time_to_first_token 3.5tok (-2.29tok) 32 🟢 -
Llm_calls 6.81 (+0.04) 11 🟢 13 🔴
Tool_calls 2.6 (-0.05) 11 🟢 12 🔴
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 24640.52tok (-1755.85tok) 11 🟢 16 🔴
Prompt_cached_tokens 8656tok (+117.33tok) 13 🟢 14 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 554.78tok (-15.48tok) 12 🟢 20 🔴
Completion_reasoning_tokens 88.07tok (-3.79tok) 15 🟢 13 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 25195.3tok (-1771.33tok) 13 🟢 19 🔴
Estimated_cost 0$ (0$) 18 🟢 11 🔴
Duration 16.15s (-7.32s) 31 🟢 1 🔴
Llm_duration 11.68s (-3.88s) 30 🟢 2 🔴

SaxonF added a commit that referenced this pull request Aug 14, 2026
<img width="1695" height="1042" alt="image"
src="https://github.com/user-attachments/assets/b02e64ff-32ac-4aee-bda5-00b56f3a29e5"
/>


## Summary

- add routed Explorer chat pages backed by explicit assistant chat IDs
- wait for persisted assistant state before creating chats so cold-load
creation is not overwritten
- register chat tabs and keep tab labels, navigation, close behavior,
and missing-chat cleanup in sync
- create and branch Explorer chats without changing the assistant
sidebar selection
- support both Next.js and TanStack Router paths

This is PR 2 of 3 and is stacked on #48973. Review and merge #48973
first. The Explorer discovery, toolbar, and cross-surface entry points
follow in #49032. This PR focuses purely on setting up chat tab types,
routes and assistant conversation.

## To Test
- Create a new assistant chat via the assistant sidebar, send a message
etc
- Copy the chat id
- Visit /explorer/chat/[id]
- Verify chat shows up, you can send more messages, chat is synced
across tab and sidebar
- Close the tab

## Test plan

- `mise exec node@22 -- pnpm --dir apps/studio exec tsc --noEmit`
- focused Vitest suite: 4 files / 30 tests covering assistant hydration,
chat creation, routed chat rendering, and tab lifecycle
- ESLint on changed TypeScript files
- Prettier check on changed source files


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

* **New Features**
* Added Explorer chat pages with support for opening, selecting, and
branching chats.
* Added chat tabs, stable navigation, chat icons, and fallback behavior
when tabs are closed.
* Added chat creation that waits for assistant state to finish loading.
* **Bug Fixes**
  * Removed tabs for deleted or unavailable chats.
  * Improved editor tab navigation and history clearing behavior.
* **Tests**
* Added coverage for chat routing, tab management, chat creation, and
assistant-state loading.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 <[email protected]>
SaxonF added a commit that referenced this pull request Aug 14, 2026
<img width="1693" height="1038" alt="image"
src="https://github.com/user-attachments/assets/9ef52446-c517-4ea9-ada6-ac6dc57c8af4"
/>


## Summary

- add an Explorer-specific chat toolbar with rename, chat ID,
permission, and branching controls
- list searchable non-support chats in Explorer with reactive updates
and safe rehydrated-date sorting
- add chat creation entry points to Explorer home and navigation menus
- route chat recent items correctly and show chat icons across shared
tab surfaces
- make the assistant sidebar expand action open the active chat in
Explorer

This is PR 3 of 3 and is stacked on #49031. Review #48973 first, then
#49031, then this PR. Compared with its base, this PR contains only
discovery, toolbar, and cross-surface integration work.

## To Test
- visit /explorer
- Create a new chat either via home tab chat input OR the chats sidebar
- Validate chats show up in sidebar
- Validate chat conversation works
- Close the chat tab and open a chat via sidebar
- Change permission settings via the chat tab toolbar and verify it
persists


## Test plan

- `mise exec node@22 -- pnpm --dir apps/studio exec tsc --noEmit`
- focused Vitest suite: 4 files / 5 tests covering reactive chat lists,
navigation filtering and sorting, recent-item routing, and sidebar
handoff
- ESLint on changed TypeScript files
- Prettier check on changed source files


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

## Summary by CodeRabbit

- **New Features**
- Added chat creation from the Explorer home, navigation, and new-tab
menu.
- Added an Explorer chat toolbar with editable names, ID copying,
permissions, shortcuts, and metadata warnings.
- Added searchable chat history with sorting, active-chat highlighting,
and clear empty states.
  - Chats can now open directly in Explorer from the AI Assistant panel.
  - Recent items now link correctly to chats and notebooks.

- **Bug Fixes**
- Improved chat list updates after creation, deletion, and restored
sessions.
  - Added safer handling for chats without update timestamps.

- **Tests**
- Expanded coverage for chat navigation, creation, metadata warnings,
shortcuts, and recent-item links.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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.

2 participants