Repository navigation
feat(host-service): mount chat-v3 runtime — scope_id rename + tRPC/WS routes behind flag - #6203
Conversation
📝 WalkthroughWalkthroughChat v3 adds host-service tRPC and WebSocket mounting with lazy runtime lifecycle management. Chat sessions now use opaque ChangesChat v3 runtime integration
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Greptile SummaryThe PR renames the chat runtime’s local workspace grouping field to
Confidence Score: 4/5The 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
|
| 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
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, |
There was a problem hiding this 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.
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); |
There was a problem hiding this 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.
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.
🧹 Preview Cleanup CompleteThe following preview resources have been cleaned up:
Thank you for your contribution! 🎉 |
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (36)
packages/chat-runtime/README.mdpackages/chat-runtime/src/commands/commands/commands.test.tspackages/chat-runtime/src/commands/commands/commands.tspackages/chat-runtime/src/commands/commands/commandsRecovery.test.tspackages/chat-runtime/src/db/drizzle/0000_natural_wolverine.sqlpackages/chat-runtime/src/db/drizzle/meta/0000_snapshot.jsonpackages/chat-runtime/src/db/drizzle/meta/_journal.jsonpackages/chat-runtime/src/db/schema/schema.tspackages/chat-runtime/src/harness/claude/createClaudeAdapter/createClaudeAdapter.tspackages/chat-runtime/src/harness/claude/createClaudeAdapter/index.tspackages/chat-runtime/src/harness/claude/index.tspackages/chat-runtime/src/harness/claude/translateStream/translateStream.test.tspackages/chat-runtime/src/harness/codex/codexAdapter/codexTimeline.test.tspackages/chat-runtime/src/harness/index.tspackages/chat-runtime/src/journal/epoch/epoch.tspackages/chat-runtime/src/journal/journal/journal.test.tspackages/chat-runtime/src/projection/projection.test.tspackages/chat-runtime/src/projection/projection.tspackages/chat-runtime/src/replay/replay.test.tspackages/chat-runtime/src/replay/replayIntegrity.test.tspackages/chat-runtime/src/replay/replayParity.test.tspackages/chat-runtime/src/router/router/router.tspackages/chat-runtime/src/router/wsSink/wsSink.test.tspackages/chat-runtime/src/sessions/liveSession/liveSession.test.tspackages/chat-runtime/src/sessions/liveSession/liveSession.tspackages/chat-runtime/src/sessions/liveSession/liveSessionFailure.test.tspackages/chat-runtime/src/sessions/registry/registry.test.tspackages/chat-runtime/src/sessions/registry/registry.tspackages/chat-runtime/src/stream/subscriptions/subscriptionResilience.test.tspackages/chat-runtime/src/stream/subscriptions/subscriptions.test.tspackages/host-service/package.jsonpackages/host-service/src/app.tspackages/host-service/src/chat-v3/index.tspackages/host-service/src/chat-v3/mount.tspackages/host-service/src/chat-v3/resolveCwd.tsplans/chat-v3-pane-mount.md
| options.app.use(`${endpoint}/*`, (c, next) => { | ||
| handler ??= trpcServer({ | ||
| endpoint, | ||
| router: createChatRouter(options.mount.runtime(), { resolveCwd }), | ||
| }); | ||
| return handler(c, next); |
There was a problem hiding this comment.
🎯 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/srcRepository: 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/srcRepository: 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) | ||
|
|
||
| ``` |
There was a problem hiding this comment.
📐 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
There was a problem hiding this comment.
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(), |
There was a problem hiding this comment.
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() }); |
There was a problem hiding this comment.
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>
| .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"; | |||
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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) | ||
|
|
||
| ``` |
There was a problem hiding this comment.
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>
| ``` | |
| ```text |
…ates the UI only Claude-Session: https://claude.ai/code/session_01XRFCEPsfmJHu2SenDKYJ2h
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
apps/desktop/src/main/lib/host-service-coordinator.ts (1)
16-16: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse the
main/*path alias for the new import.Replace
./chat-v3-flagwithmain/lib/chat-v3-flag. This matches the existing alias usage inapps/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.jsonwhenever 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
📒 Files selected for processing (6)
apps/desktop/src/main/lib/chat-v3-flag/chat-v3-flag.tsapps/desktop/src/main/lib/chat-v3-flag/index.tsapps/desktop/src/main/lib/host-service-coordinator.tspackages/chat-runtime/README.mdpackages/host-service/src/app.tspackages/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
| // 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" } : {}), |
There was a problem hiding this comment.
🎯 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.
| // 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.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/chat-runtime/README.md (2)
9-10: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winNarrow the data-boundary invariant to caller-owned fields.
Line 9 says every
chat.dbcolumn contains a value passed by the caller. This conflicts with line 5, where the journal assigns cursors, and line 16, whereepoch/mints epochs. Limit the statement to caller-owned values such asscope_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 liftMove 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/. KeepREADME.mdas 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
📒 Files selected for processing (7)
packages/chat-runtime/README.mdpackages/chat-runtime/src/harness/claude/claudeAdapter/claudeAdapter.live.test.tspackages/chat-runtime/src/harness/claude/claudeAdapter/claudeAdapter.test.tspackages/chat-runtime/src/harness/claude/claudeAdapter/claudeAdapter.tspackages/chat-runtime/src/harness/claude/createClaudeAdapter/createClaudeAdapter.tspackages/host-service/src/app.tspackages/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
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-v3runtime inhost-servicewith tRPC and streaming WS routes, and switches the runtime to group sessions byscope_id(router mapsworkspaceId → scopeId). Routes are always registered; the desktop gates the pane with theFEATURE_FLAGS.CHAT_V3flag.New Features
/chat-v3/trpcand stream at/chat-v3/sessions/:sessionId/stream?since=&deltas=, both behindwsAuth.FEATURE_FLAGS.CHAT_V3to show the pane. No host restart needed.chat.dbis untouched until then.resolveCwd(workspaceId)reads the hostworkspacestable; throwsChatWorkspaceNotFoundError."claude-code"and"codex";createClaudeAdapterkeeps the SDK out ofhost-serviceand now derives query input types from the Claude SDK (removes an unsafe cast).Migration
SUPERSET_CHAT_V3_MIGRATIONSto override path if needed.host.dbchanges;chat.dblives besidehost.dband is created lazily.workspaceId; the router maps it toscopeIdinternally (no client changes required).Written for commit 1c8e736. Summary will update on new commits.
Summary by CodeRabbit