Skip to content

feat(host-service): mount chat-v3 runtime — scope_id rename + tRPC/WS routes behind flag - #6203

Merged
saddlepaddle merged 6 commits into
mainfrom
chat-v3-mount
Aug 5, 2026
Merged

saddlepaddle merged 6 commits into
mainfrom
chat-v3-mount

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Chunk A of plans/chat-v3-pane-mount.md (doc included). scope_id rename per §D: the runtime's command layer .omit()s workspaceId and .extend()s scopeId, making workspace vocabulary unrepresentable inside chat-runtime — the mapping exists only at the router binding; migration regenerated in place, generate no-op verified. Mount: packages/host-service/src/chat-v3/ behind SUPERSET_CHAT_V3=1 (ACP gate pattern) — lazy runtime (memoized handler, chat.db untouched until first request), resolveCwd off the workspaces read model, wsAuth reused for both routes, WSContext wraps directly into createWsSink. Also fixes the harness barrel (claude now exported; createClaudeAdapter factory keeps the SDK dep out of host-service). chat-runtime 136 green; host-service 951 green.

https://claude.ai/code/session_01XRFCEPsfmJHu2SenDKYJ2h


Summary by cubic

Mounts the chat-v3 runtime in host-service with tRPC and streaming WS routes, and switches the runtime to group sessions by scope_id (router maps workspaceId → scopeId). Routes are always registered; the desktop gates the pane with the FEATURE_FLAGS.CHAT_V3 flag.

  • New Features

    • Routes: tRPC at /chat-v3/trpc and stream at /chat-v3/sessions/:sessionId/stream?since=&deltas=, both behind wsAuth.
    • Rollout: routes are unconditional; the UI uses FEATURE_FLAGS.CHAT_V3 to show the pane. No host restart needed.
    • Lazy runtime: builds on first request; disposed on shutdown. chat.db is untouched until then.
    • CWD resolution: resolveCwd(workspaceId) reads the host workspaces table; throws ChatWorkspaceNotFoundError.
    • Harnesses: registry with "claude-code" and "codex"; createClaudeAdapter keeps the SDK out of host-service and now derives query input types from the Claude SDK (removes an unsafe cast).
  • Migration

    • Ship the runtime migrations folder; set SUPERSET_CHAT_V3_MIGRATIONS to override path if needed.
    • No host.db changes; chat.db lives beside host.db and is created lazily.
    • External API still uses workspaceId; the router maps it to scopeId internally (no client changes required).

Written for commit 1c8e736. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features
    • Added Chat v3 host-service integration with authenticated chat and streaming routes.
    • Added support for Claude-powered chat sessions.
    • Added live feature-flag control for the rebuilt chat experience without requiring a host restart.
  • Improvements
    • Chat sessions now support scope-based grouping and filtering.
    • Chat runtime and database setup are deferred until the first request to improve startup behavior.
  • Documentation
    • Clarified chat data storage, scope labels, routing, authentication, and rollout behavior.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Chat v3 adds host-service tRPC and WebSocket mounting with lazy runtime lifecycle management. Chat sessions now use opaque scopeId values in storage and commands. The Claude adapter uses SDK-derived types and gains a factory. A live CHAT_V3 feature flag controls renderer visibility.

Changes

Chat v3 runtime integration

Layer / File(s) Summary
Scope-based session contract
packages/chat-runtime/src/db/..., packages/chat-runtime/src/journal/..., packages/chat-runtime/src/projection/..., packages/chat-runtime/README.md
Session storage, indexes, journal initialization, and projection filtering use scopeId. Documentation defines the workspaceId to scopeId router mapping.
Command and session scope propagation
packages/chat-runtime/src/commands/..., packages/chat-runtime/src/router/..., packages/chat-runtime/src/sessions/..., packages/chat-runtime/src/replay/..., packages/chat-runtime/src/stream/..., packages/chat-runtime/src/harness/...
Command schemas require or accept scopeId. Routers map protocol workspace fields to scope fields. Session, replay, stream, and recovery tests use the renamed inputs.
Claude adapter factory and exports
packages/chat-runtime/src/harness/claude/..., packages/chat-runtime/src/harness/index.ts
Claude query and message types derive from the Agent SDK. Tool approval wiring is updated. An SDK-backed adapter factory is publicly exported.
Host-service Chat v3 mount
packages/host-service/src/chat-v3/..., packages/host-service/src/app.ts, packages/host-service/package.json, packages/shared/src/constants.ts, plans/chat-v3-pane-mount.md
The host service mounts authenticated tRPC and WebSocket routes, creates the runtime lazily, resolves workspace worktrees, disposes the runtime on shutdown, and adds the live CHAT_V3 renderer flag.

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HostService
  participant ChatV3Mount
  participant ChatRuntime
  Client->>HostService: Request /chat-v3/* or open stream
  HostService->>ChatV3Mount: Authenticate and route request
  ChatV3Mount->>ChatRuntime: Create or reuse runtime
  ChatRuntime-->>Client: Return tRPC data or session deltas
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.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 identifies the host-service Chat V3 mount and related scope and route changes.
Description check ✅ Passed The description explains the changes and reports test results, but it does not include the required checklist section.
✨ 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 chat-v3-mount

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.

@greptile-apps

greptile-apps Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR renames the chat runtime’s local workspace grouping field to scope_id and mounts lazy chat-v3 tRPC and WebSocket routes in host-service behind SUPERSET_CHAT_V3. It also exports the Claude adapter factory and wires Claude and Codex harnesses into the host runtime.

  • Maps protocol workspaceId values to opaque runtime scopeId values at the router boundary.
  • Regenerates the chat.db schema and migration metadata for scope_id.
  • Adds authenticated, feature-gated tRPC and session-stream routes with lazy runtime initialization.
  • Adds host workspace-to-working-directory resolution and runtime shutdown disposal.

Confidence Score: 4/5

The PR should not merge until existing chat.db schemas are upgraded safely and missing workspaces return a typed NOT_FOUND response.

Rewriting an already-applied initial migration leaves existing databases without scope_id and breaks runtime SQL, while workspace lookup failures currently escape the router’s error mapping as internal server errors.

Files Needing Attention: packages/chat-runtime/src/db/drizzle/0000_natural_wolverine.sql, packages/chat-runtime/src/router/router/router.ts

Important Files Changed

Filename Overview
packages/chat-runtime/src/db/drizzle/0000_natural_wolverine.sql Rewrites migration index 0 for scope_id, leaving existing databases without an upgrade path.
packages/chat-runtime/src/router/router/router.ts Correctly maps workspaceId to scopeId, but resolves missing workspaces outside the typed error boundary.
packages/host-service/src/chat-v3/mount.ts Adds lazy runtime construction plus authenticated tRPC and WebSocket route bindings with cleanup.
packages/host-service/src/chat-v3/resolveCwd.ts Resolves workspace worktree paths and throws a typed error that the router currently fails to map.
packages/host-service/src/app.ts Feature-gates route registration, applies chat-v3 authentication middleware, and disposes the lazy runtime during shutdown.
packages/chat-runtime/src/commands/commands/commands.ts Replaces workspaceId with scopeId in the runtime command layer while preserving protocol-level mapping in the router.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Host as host-service
  participant Router as chat router
  participant HostDB as host.db
  participant Runtime as chat-runtime
  participant ChatDB as chat.db
  Client->>Host: createSession(workspaceId)
  Host->>Router: authenticated tRPC request
  Router->>HostDB: resolveCwd(workspaceId)
  HostDB-->>Router: worktreePath
  Router->>Runtime: "createSession(scopeId=workspaceId, cwd)"
  Runtime->>ChatDB: persist session and journal
  Runtime-->>Client: sessionId and epoch
  Client->>Host: WebSocket /sessions/:id/stream
  Host->>Runtime: subscribe(sessionId, cursor, deltas)
  Runtime-->>Client: replay and live envelopes
Loading
Prompt To Fix All With AI
### Issue 1
packages/chat-runtime/src/db/drizzle/0000_natural_wolverine.sql:12
**Rewritten migration leaves stale schema**

When a `chat.db` initialized by the previous migration is reopened, migration index 0 is already recorded and the rewritten migration is skipped, leaving `workspace_id` in place while the runtime queries `scope_id` and causing SQLite `no such column: scope_id` failures.

### Issue 2
packages/chat-runtime/src/router/router/router.ts:63
**Workspace errors bypass typed mapping**

When `createSession` receives a stale or nonexistent workspace ID, `resolveCwd` throws before `guarded()` is entered, causing an `INTERNAL_SERVER_ERROR` instead of the required typed `NOT_FOUND` response.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "feat(host-service): mount chat-v3 runtim..." | Re-trigger Greptile

CREATE TABLE `chat_sessions_local` (
`session_id` text PRIMARY KEY NOT NULL,
`workspace_id` text NOT NULL,
`scope_id` text NOT NULL,

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.

P1 Rewritten migration leaves stale schema

When a chat.db initialized by the previous migration is reopened, migration index 0 is already recorded and the rewritten migration is skipped, leaving workspace_id in place while the runtime queries scope_id and causing SQLite no such column: scope_id failures.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/chat-runtime/src/db/drizzle/0000_natural_wolverine.sql
Line: 12

Comment:
**Rewritten migration leaves stale schema**

When a `chat.db` initialized by the previous migration is reopened, migration index 0 is already recorded and the rewritten migration is skipped, leaving `workspace_id` in place while the runtime queries `scope_id` and causing SQLite `no such column: scope_id` failures.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

const cwd = await options.resolveCwd(input.workspaceId);
return guarded(() => runtime.commands.createSession({ ...input, cwd }));
const { workspaceId, ...rest } = input;
const cwd = await options.resolveCwd(workspaceId);

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.

P1 Workspace errors bypass typed mapping

When createSession receives a stale or nonexistent workspace ID, resolveCwd throws before guarded() is entered, causing an INTERNAL_SERVER_ERROR instead of the required typed NOT_FOUND response.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/chat-runtime/src/router/router/router.ts
Line: 63

Comment:
**Workspace errors bypass typed mapping**

When `createSession` receives a stale or nonexistent workspace ID, `resolveCwd` throws before `guarded()` is entered, causing an `INTERNAL_SERVER_ERROR` instead of the required typed `NOT_FOUND` response.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ✅ Neon database branch

Thank you for your contribution! 🎉

@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 `@packages/host-service/src/chat-v3/mount.ts`:
- Around line 92-97: Update createSession or the guarded runtime command path so
ChatWorkspaceNotFoundError from options.resolveCwd(workspaceId) is translated to
the tRPC NOT_FOUND response before it reaches the generic error mapping.
Preserve existing handling for other command and session errors.

In `@plans/chat-v3-pane-mount.md`:
- Line 14: Add the text language identifier to the opening fence of both fenced
code blocks in the document, including the block referenced by the additional
location, so each uses a text-tagged fence and satisfies MD040.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b9c9270f-b0b9-4bf1-8949-962c1c0e8391

📥 Commits

Reviewing files that changed from the base of the PR and between b2552e3 and d5dd537.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (36)
  • packages/chat-runtime/README.md
  • packages/chat-runtime/src/commands/commands/commands.test.ts
  • packages/chat-runtime/src/commands/commands/commands.ts
  • packages/chat-runtime/src/commands/commands/commandsRecovery.test.ts
  • packages/chat-runtime/src/db/drizzle/0000_natural_wolverine.sql
  • packages/chat-runtime/src/db/drizzle/meta/0000_snapshot.json
  • packages/chat-runtime/src/db/drizzle/meta/_journal.json
  • packages/chat-runtime/src/db/schema/schema.ts
  • packages/chat-runtime/src/harness/claude/createClaudeAdapter/createClaudeAdapter.ts
  • packages/chat-runtime/src/harness/claude/createClaudeAdapter/index.ts
  • packages/chat-runtime/src/harness/claude/index.ts
  • packages/chat-runtime/src/harness/claude/translateStream/translateStream.test.ts
  • packages/chat-runtime/src/harness/codex/codexAdapter/codexTimeline.test.ts
  • packages/chat-runtime/src/harness/index.ts
  • packages/chat-runtime/src/journal/epoch/epoch.ts
  • packages/chat-runtime/src/journal/journal/journal.test.ts
  • packages/chat-runtime/src/projection/projection.test.ts
  • packages/chat-runtime/src/projection/projection.ts
  • packages/chat-runtime/src/replay/replay.test.ts
  • packages/chat-runtime/src/replay/replayIntegrity.test.ts
  • packages/chat-runtime/src/replay/replayParity.test.ts
  • packages/chat-runtime/src/router/router/router.ts
  • packages/chat-runtime/src/router/wsSink/wsSink.test.ts
  • packages/chat-runtime/src/sessions/liveSession/liveSession.test.ts
  • packages/chat-runtime/src/sessions/liveSession/liveSession.ts
  • packages/chat-runtime/src/sessions/liveSession/liveSessionFailure.test.ts
  • packages/chat-runtime/src/sessions/registry/registry.test.ts
  • packages/chat-runtime/src/sessions/registry/registry.ts
  • packages/chat-runtime/src/stream/subscriptions/subscriptionResilience.test.ts
  • packages/chat-runtime/src/stream/subscriptions/subscriptions.test.ts
  • packages/host-service/package.json
  • packages/host-service/src/app.ts
  • packages/host-service/src/chat-v3/index.ts
  • packages/host-service/src/chat-v3/mount.ts
  • packages/host-service/src/chat-v3/resolveCwd.ts
  • plans/chat-v3-pane-mount.md

Comment on lines +92 to +97
options.app.use(`${endpoint}/*`, (c, next) => {
handler ??= trpcServer({
endpoint,
router: createChatRouter(options.mount.runtime(), { resolveCwd }),
});
return handler(c, next);

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline packages/chat-runtime/src/router/router/router.ts --items all
rg -n -C 8 'guarded|mapCommandError|resolveCwd|createSession' \
  packages/chat-runtime/src/router/router/router.ts
rg -n -C 6 'ChatWorkspaceNotFoundError|mapCommandError' \
  packages/chat-runtime/src packages/host-service/src

Repository: superset-sh/superset

Length of output: 7633


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '20,110p' packages/chat-runtime/src/router/router/router.ts
sed -n '1,30p' packages/host-service/src/chat-v3/resolveCwd.ts
rg -n -C 5 'Workspace not found|resolveCwd\\(' packages/host-service/src packages/chat-runtime/src

Repository: superset-sh/superset

Length of output: 3231


Let ChatWorkspaceNotFoundError become a tRPC NOT_FOUND.

options.resolveCwd(workspaceId) runs before guarded(), and it throws ChatWorkspaceNotFoundError for missing workspaces. Since mapCommandError only handles harness errors and session not-run errors, missing-workspace requests return an internal server error instead of NOT_FOUND. Handle this error inside createSession or move the check into the guarded runtime command path.

🤖 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/host-service/src/chat-v3/mount.ts` around lines 92 - 97, Update
createSession or the guarded runtime command path so ChatWorkspaceNotFoundError
from options.resolveCwd(workspaceId) is translated to the tRPC NOT_FOUND
response before it reaches the generic error mapping. Preserve existing handling
for other command and session errors.


## A. Host-service mount (~1–2 days)

```

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 language identifiers to both fenced code blocks.

Static analysis reports MD040 for both blocks. Use text after each opening fence so lint can pass.

Also applies to: 32-32

🧰 Tools
🪛 markdownlint-cli2 (0.23.2)

[warning] 14-14: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 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 `@plans/chat-v3-pane-mount.md` at line 14, Add the text language identifier to
the opening fence of both fenced code blocks in the document, including the
block referenced by the additional location, so each uses a text-tagged fence
and satisfies MD040.

Sources: Coding guidelines, Linters/SAST tools

@cubic-dev-ai cubic-dev-ai 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.

7 issues found and verified against the latest diff

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="plans/chat-v3-pane-mount.md">

<violation number="1" location="plans/chat-v3-pane-mount.md:14">
P3: This fenced code block (and the one further down in the same doc) has no language identifier, which trips MD040 in markdownlint. Add `text` (or an appropriate language) after the opening fence.</violation>

<violation number="2" location="plans/chat-v3-pane-mount.md:22">
P3: The plan's gate description is inaccurate: the chat-v3 and ACP routes are not gated by the desktop `isInternalBuild()` channel, but by env vars (`SUPERSET_CHAT_V3 === "1"`, `SUPERSET_ACP_SESSIONS === "1"`) checked directly in `host-service/src/app.ts`. Update the parenthetical so implementers of chunks B/C don't wire the flag to the wrong mechanism.</violation>
</file>

<file name="packages/chat-runtime/src/db/schema/schema.ts">

<violation number="1" location="packages/chat-runtime/src/db/schema/schema.ts:29">
P1: Existing `chat.db` files created with the previous `workspace_id` schema will fail when the runtime first reads or writes `chat_sessions_local`, because this schema rename is not represented by a new migration. Adding a migration that renames the column and index while preserving rows would make upgrades safe.</violation>
</file>

<file name="packages/chat-runtime/src/projection/projection.test.ts">

<violation number="1" location="packages/chat-runtime/src/projection/projection.test.ts:31">
P3: The test description still says "filters by workspace" but the test now exercises `listByScope("w2")` with `scopeId` vocabulary after the rename. A future reader grepping for workspace filtering in the projection won't find this test. Update the title to reference scope.</violation>
</file>

<file name="packages/chat-runtime/src/commands/commands/commands.ts">

<violation number="1" location="packages/chat-runtime/src/commands/commands/commands.ts:38">
P2: A legacy `workspaceId` list command is silently turned into an unfiltered list instead of being rejected. Making this command schema strict (or explicitly rejecting `workspaceId`) would preserve the rename without returning sessions outside the requested scope to stale direct callers.</violation>
</file>

<file name="packages/chat-runtime/src/harness/claude/createClaudeAdapter/createClaudeAdapter.ts">

<violation number="1" location="packages/chat-runtime/src/harness/claude/createClaudeAdapter/createClaudeAdapter.ts:1">
P2: The factory is intended to keep the Claude Code SDK dependency out of host-service, but the import is a static top-level import that is reachable at host-service startup: host-service's app.ts imports ./chat-v3 → mount.ts → createClaudeAdapter → `@anthropic-ai/claude-agent-sdk`. Because mounting the claude-code harness pulls the SDK module graph in when host-service boots, the dependency is loaded and bundled into the host-service process even when SUPERSET_CHAT_V3 is disabled - the gate only skips opening chat.db and registering routes. If the goal is runtime isolation, defer the SDK import (e.g. a dynamic `import()` inside `createClaudeAdapter` or a function that lazily requires the module) so the SDK is only touched when the claude-code harness is actually used.</violation>
</file>

<file name="packages/chat-runtime/src/router/router/router.ts">

<violation number="1" location="packages/chat-runtime/src/router/router/router.ts:62">
P2: resolveCwd(workspaceId) is called outside of guarded(), so a missing/stale workspace throws ChatWorkspaceNotFoundError before mapCommandError has a chance to translate it, and the tRPC client receives an INTERNAL_SERVER_ERROR instead of the expected NOT_FOUND. Consider wrapping the resolveCwd call inside guarded() (or mapping ChatWorkspaceNotFoundError to NOT_FOUND explicitly) so callers get a typed not-found response for missing workspaces.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

{
sessionId: text("session_id").primaryKey(),
workspaceId: text("workspace_id").notNull(),
scopeId: text("scope_id").notNull(),

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.

P1: Existing chat.db files created with the previous workspace_id schema will fail when the runtime first reads or writes chat_sessions_local, because this schema rename is not represented by a new migration. Adding a migration that renames the column and index while preserving rows would make upgrades safe.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-runtime/src/db/schema/schema.ts, line 29:

<comment>Existing `chat.db` files created with the previous `workspace_id` schema will fail when the runtime first reads or writes `chat_sessions_local`, because this schema rename is not represented by a new migration. Adding a migration that renames the column and index while preserving rows would make upgrades safe.</comment>

<file context>
@@ -26,7 +26,7 @@ export const chatSessionsLocal = sqliteTable(
 	{
 		sessionId: text("session_id").primaryKey(),
-		workspaceId: text("workspace_id").notNull(),
+		scopeId: text("scope_id").notNull(),
 		harness: text().notNull(),
 		harnessSessionId: text("harness_session_id"),
</file context>


export const listSessionsCommandSchema = listSessionsInputSchema
.omit({ workspaceId: true })
.extend({ scopeId: z.string().min(1).optional() });

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.

P2: A legacy workspaceId list command is silently turned into an unfiltered list instead of being rejected. Making this command schema strict (or explicitly rejecting workspaceId) would preserve the rename without returning sessions outside the requested scope to stale direct callers.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-runtime/src/commands/commands/commands.ts, line 38:

<comment>A legacy `workspaceId` list command is silently turned into an unfiltered list instead of being rejected. Making this command schema strict (or explicitly rejecting `workspaceId`) would preserve the rename without returning sessions outside the requested scope to stale direct callers.</comment>

<file context>
@@ -27,13 +26,20 @@ import type { PageResult } from "../../replay";
 
+export const listSessionsCommandSchema = listSessionsInputSchema
+	.omit({ workspaceId: true })
+	.extend({ scopeId: z.string().min(1).optional() });
+export type ListSessionsCommandInput = z.input<
+	typeof listSessionsCommandSchema
</file context>
Suggested change
.extend({ scopeId: z.string().min(1).optional() });
.extend({ scopeId: z.string().min(1).optional() })
.strict();

@@ -0,0 +1,12 @@
import { query } from "@anthropic-ai/claude-agent-sdk";

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.

P2: The factory is intended to keep the Claude Code SDK dependency out of host-service, but the import is a static top-level import that is reachable at host-service startup: host-service's app.ts imports ./chat-v3 → mount.ts → createClaudeAdapter → @anthropic-ai/claude-agent-sdk. Because mounting the claude-code harness pulls the SDK module graph in when host-service boots, the dependency is loaded and bundled into the host-service process even when SUPERSET_CHAT_V3 is disabled - the gate only skips opening chat.db and registering routes. If the goal is runtime isolation, defer the SDK import (e.g. a dynamic import() inside createClaudeAdapter or a function that lazily requires the module) so the SDK is only touched when the claude-code harness is actually used.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-runtime/src/harness/claude/createClaudeAdapter/createClaudeAdapter.ts, line 1:

<comment>The factory is intended to keep the Claude Code SDK dependency out of host-service, but the import is a static top-level import that is reachable at host-service startup: host-service's app.ts imports ./chat-v3 → mount.ts → createClaudeAdapter → `@anthropic-ai/claude-agent-sdk`. Because mounting the claude-code harness pulls the SDK module graph in when host-service boots, the dependency is loaded and bundled into the host-service process even when SUPERSET_CHAT_V3 is disabled - the gate only skips opening chat.db and registering routes. If the goal is runtime isolation, defer the SDK import (e.g. a dynamic `import()` inside `createClaudeAdapter` or a function that lazily requires the module) so the SDK is only touched when the claude-code harness is actually used.</comment>

<file context>
@@ -0,0 +1,12 @@
+import { query } from "@anthropic-ai/claude-agent-sdk";
+import type { HarnessAdapter } from "../../types";
+import type { ClaudeQuery } from "../claudeAdapter";
</file context>

.mutation(async ({ input }) => {
const cwd = await options.resolveCwd(input.workspaceId);
return guarded(() => runtime.commands.createSession({ ...input, cwd }));
const { workspaceId, ...rest } = input;

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.

P2: resolveCwd(workspaceId) is called outside of guarded(), so a missing/stale workspace throws ChatWorkspaceNotFoundError before mapCommandError has a chance to translate it, and the tRPC client receives an INTERNAL_SERVER_ERROR instead of the expected NOT_FOUND. Consider wrapping the resolveCwd call inside guarded() (or mapping ChatWorkspaceNotFoundError to NOT_FOUND explicitly) so callers get a typed not-found response for missing workspaces.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-runtime/src/router/router/router.ts, line 62:

<comment>resolveCwd(workspaceId) is called outside of guarded(), so a missing/stale workspace throws ChatWorkspaceNotFoundError before mapCommandError has a chance to translate it, and the tRPC client receives an INTERNAL_SERVER_ERROR instead of the expected NOT_FOUND. Consider wrapping the resolveCwd call inside guarded() (or mapping ChatWorkspaceNotFoundError to NOT_FOUND explicitly) so callers get a typed not-found response for missing workspaces.</comment>

<file context>
@@ -59,8 +59,15 @@ export function createChatRouter(
 			.mutation(async ({ input }) => {
-				const cwd = await options.resolveCwd(input.workspaceId);
-				return guarded(() => runtime.commands.createSession({ ...input, cwd }));
+				const { workspaceId, ...rest } = input;
+				const cwd = await options.resolveCwd(workspaceId);
+				return guarded(() =>
</file context>

# not-found (router maps it to NOT_FOUND)
```

- `app.ts` registrations, both gated behind the same internal-build flag pattern as ACP (`isInternalBuild()` env → gate):

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.

P3: The plan's gate description is inaccurate: the chat-v3 and ACP routes are not gated by the desktop isInternalBuild() channel, but by env vars (SUPERSET_CHAT_V3 === "1", SUPERSET_ACP_SESSIONS === "1") checked directly in host-service/src/app.ts. Update the parenthetical so implementers of chunks B/C don't wire the flag to the wrong mechanism.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At plans/chat-v3-pane-mount.md, line 22:

<comment>The plan's gate description is inaccurate: the chat-v3 and ACP routes are not gated by the desktop `isInternalBuild()` channel, but by env vars (`SUPERSET_CHAT_V3 === "1"`, `SUPERSET_ACP_SESSIONS === "1"`) checked directly in `host-service/src/app.ts`. Update the parenthetical so implementers of chunks B/C don't wire the flag to the wrong mechanism.</comment>

<file context>
@@ -0,0 +1,62 @@
+                  #   not-found (router maps it to NOT_FOUND)
+```
+
+- `app.ts` registrations, both gated behind the same internal-build flag pattern as ACP (`isInternalBuild()` env → gate):
+  - tRPC: mount `createChatRouter(runtime, { resolveCwd })` at `POST/GET /chat-v3/trpc/*` via `@trpc/server` fetch adapter on the existing Hono app (second tRPC endpoint — the established per-domain pattern; host auth middleware applied at the route).
+  - Stream: `GET /chat-v3/sessions/:id/stream?since=&deltas=` — upgrade exactly like `/acp-sessions/:id/stream` does today, wrap the socket in `createWsSink`, call `runtime.subscribe(...)`, dispose subscription on close.
</file context>

).toEqual(["s1", "s2"]);
expect(
runtime.sessions.listByWorkspace("w2").map((row) => row.harness),
runtime.sessions.listByScope("w2").map((row) => row.harness),

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.

P3: The test description still says "filters by workspace" but the test now exercises listByScope("w2") with scopeId vocabulary after the rename. A future reader grepping for workspace filtering in the projection won't find this test. Update the title to reference scope.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/chat-runtime/src/projection/projection.test.ts, line 31:

<comment>The test description still says "filters by workspace" but the test now exercises `listByScope("w2")` with `scopeId` vocabulary after the rename. A future reader grepping for workspace filtering in the projection won't find this test. Update the title to reference scope.</comment>

<file context>
@@ -28,7 +28,7 @@ describe("ChatSessionStore", () => {
 		).toEqual(["s1", "s2"]);
 		expect(
-			runtime.sessions.listByWorkspace("w2").map((row) => row.harness),
+			runtime.sessions.listByScope("w2").map((row) => row.harness),
 		).toEqual(["codex"]);
 	});
</file context>


## A. Host-service mount (~1–2 days)

```

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.

P3: This fenced code block (and the one further down in the same doc) has no language identifier, which trips MD040 in markdownlint. Add text (or an appropriate language) after the opening fence.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At plans/chat-v3-pane-mount.md, line 14:

<comment>This fenced code block (and the one further down in the same doc) has no language identifier, which trips MD040 in markdownlint. Add `text` (or an appropriate language) after the opening fence.</comment>

<file context>
@@ -0,0 +1,62 @@
+
+## A. Host-service mount (~1–2 days)
+
+```
+packages/host-service/src/chat-v3/          # thin mount only; "runtime/chat/" name is taken by legacy mastra code
+  mount.ts        # buildChatRuntime(): createChatRuntime({ dataDir, migrationsFolder, harnesses })
</file context>
Suggested change
```
```text

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
apps/desktop/src/main/lib/host-service-coordinator.ts (1)

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

Use the main/* path alias for the new import.

Replace ./chat-v3-flag with main/lib/chat-v3-flag. This matches the existing alias usage in apps/desktop/src/main/lib/chat-v3-flag/chat-v3-flag.ts.

Proposed change
-import { isChatV3Enabled } from "./chat-v3-flag";
+import { isChatV3Enabled } from "main/lib/chat-v3-flag";

As per coding guidelines, use the path aliases defined in tsconfig.json whenever possible.

🤖 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/desktop/src/main/lib/host-service-coordinator.ts` at line 16, Update the
import used by host-service-coordinator to reference the chat-v3-flag module
through the main/* path alias, replacing the relative "./chat-v3-flag" path with
"main/lib/chat-v3-flag" and leaving the imported symbol unchanged.

Source: Coding guidelines

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

Inline comments:
In `@apps/desktop/src/main/lib/host-service-coordinator.ts`:
- Around line 802-805: Update the environment construction in the host-service
coordination flow so SUPERSET_CHAT_V3 is assigned after
getProcessEnvWithShellPath performs its shell-environment merge. Set it to "1"
when chatV3Enabled is true and explicitly remove it when false, ensuring the
final childEnv always matches the flag.

---

Nitpick comments:
In `@apps/desktop/src/main/lib/host-service-coordinator.ts`:
- Line 16: Update the import used by host-service-coordinator to reference the
chat-v3-flag module through the main/* path alias, replacing the relative
"./chat-v3-flag" path with "main/lib/chat-v3-flag" and leaving the imported
symbol unchanged.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 10abaa9b-89d2-4385-a787-754ab35567b0

📥 Commits

Reviewing files that changed from the base of the PR and between d5dd537 and e8d38f5.

📒 Files selected for processing (6)
  • apps/desktop/src/main/lib/chat-v3-flag/chat-v3-flag.ts
  • apps/desktop/src/main/lib/chat-v3-flag/index.ts
  • apps/desktop/src/main/lib/host-service-coordinator.ts
  • packages/chat-runtime/README.md
  • packages/host-service/src/app.ts
  • packages/shared/src/constants.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/chat-runtime/README.md
  • packages/host-service/src/app.ts

Comment on lines +802 to +805
// Chat v3 routes, gated by the `chat-v3` PostHog flag (see
// main/lib/chat-v3-flag). Evaluated per spawn like the relay URL
// below, so a flag flip takes effect on the next host restart.
...(chatV3Enabled ? { SUPERSET_CHAT_V3: "1" } : {}),

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 | 🟠 Major | ⚡ Quick win

Enforce SUPERSET_CHAT_V3 after the shell-environment merge.

getProcessEnvWithShellPath merges the interactive shell environment before the later environment overrides. The conditional at Lines 802-805 does not guarantee that the returned childEnv matches chatV3Enabled.

Set SUPERSET_CHAT_V3 to "1" when enabled. Delete it otherwise.

Proposed change
-			...(chatV3Enabled ? { SUPERSET_CHAT_V3: "1" } : {}),
 			// Namespaced so terminals/agents spawned by the host service don't
 			// inherit a generic SENTRY_DSN — third-party tools with a Sentry SDK
 			// auto-pick it up and report into our project.
@@
 		const effectiveRelayUrl = await getRelayUrl();
+		if (chatV3Enabled) {
+			childEnv.SUPERSET_CHAT_V3 = "1";
+		} else {
+			delete childEnv.SUPERSET_CHAT_V3;
+		}
 		if (exposeViaRelay && effectiveRelayUrl) {
📝 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
// Chat v3 routes, gated by the `chat-v3` PostHog flag (see
// main/lib/chat-v3-flag). Evaluated per spawn like the relay URL
// below, so a flag flip takes effect on the next host restart.
...(chatV3Enabled ? { SUPERSET_CHAT_V3: "1" } : {}),
// Chat v3 routes, gated by the `chat-v3` PostHog flag (see
// main/lib/chat-v3-flag). Evaluated per spawn like the relay URL
// below, so a flag flip takes effect on the next host restart.
// Namespaced so terminals/agents spawned by the host service don't
// inherit a generic SENTRY_DSN — third-party tools with a Sentry SDK
// auto-pick it up and report into our project.
const effectiveRelayUrl = await getRelayUrl();
if (chatV3Enabled) {
childEnv.SUPERSET_CHAT_V3 = "1";
} else {
delete childEnv.SUPERSET_CHAT_V3;
}
if (exposeViaRelay && effectiveRelayUrl) {
🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import * as childProcess from "node:child_process";
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

🤖 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/desktop/src/main/lib/host-service-coordinator.ts` around lines 802 -
805, Update the environment construction in the host-service coordination flow
so SUPERSET_CHAT_V3 is assigned after getProcessEnvWithShellPath performs its
shell-environment merge. Set it to "1" when chatV3Enabled is true and explicitly
remove it when false, ensuring the final childEnv always matches the flag.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (2)
packages/chat-runtime/README.md (2)

9-10: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Narrow the data-boundary invariant to caller-owned fields.

Line 9 says every chat.db column contains a value passed by the caller. This conflicts with line 5, where the journal assigns cursors, and line 16, where epoch/ mints epochs. Limit the statement to caller-owned values such as scope_id, or document runtime-generated metadata separately.

🤖 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/chat-runtime/README.md` around lines 9 - 10, Update the
data-boundary statement in the README to apply only to caller-owned fields,
using scope_id as the example. Remove the claim that every chat.db column must
contain caller-provided values, or explicitly distinguish runtime-generated
metadata such as journal cursors and epoch values.

9-10: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Move the new architecture details under packages/chat-runtime/docs/.

These changes add data-boundary and host-service rollout documentation. The repository rule places architecture and reference documentation in <app>/docs/. Keep README.md as an entry point and link to the detailed documentation.

Also applies to: 57-58

🤖 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/chat-runtime/README.md` around lines 9 - 10, Move the newly added
architecture, data-boundary, and host-service rollout details from
packages/chat-runtime/README.md into documentation files under
packages/chat-runtime/docs/. Keep README.md limited to an entry point and add
links to the relocated documents, preserving the existing content and
references.

Source: Coding guidelines

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

Outside diff comments:
In `@packages/chat-runtime/README.md`:
- Around line 9-10: Update the data-boundary statement in the README to apply
only to caller-owned fields, using scope_id as the example. Remove the claim
that every chat.db column must contain caller-provided values, or explicitly
distinguish runtime-generated metadata such as journal cursors and epoch values.
- Around line 9-10: Move the newly added architecture, data-boundary, and
host-service rollout details from packages/chat-runtime/README.md into
documentation files under packages/chat-runtime/docs/. Keep README.md limited to
an entry point and add links to the relocated documents, preserving the existing
content and references.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b047f5c6-3afb-4e1e-bed9-125ee2df6740

📥 Commits

Reviewing files that changed from the base of the PR and between e8d38f5 and 1c8e736.

📒 Files selected for processing (7)
  • packages/chat-runtime/README.md
  • packages/chat-runtime/src/harness/claude/claudeAdapter/claudeAdapter.live.test.ts
  • packages/chat-runtime/src/harness/claude/claudeAdapter/claudeAdapter.test.ts
  • packages/chat-runtime/src/harness/claude/claudeAdapter/claudeAdapter.ts
  • packages/chat-runtime/src/harness/claude/createClaudeAdapter/createClaudeAdapter.ts
  • packages/host-service/src/app.ts
  • packages/shared/src/constants.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/host-service/src/app.ts
  • packages/chat-runtime/src/harness/claude/createClaudeAdapter/createClaudeAdapter.ts

This branch was previously deployed

1 inactive deployment
preview — 1c8e736f Deployed Aug 5, 2026 by saddlepaddle via Deploy Web #7169
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