Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat: claude code added #82

Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromtheo/claudeopened View on GitHub

agent sdk with claude binary I think (idk i didn't read the fucking code)


Open with Devin

Summary by CodeRabbit

  • New Features

    • Introduced Claude Code as a new coding provider alongside Codex
    • Added provider selector to switch between providers
    • Model options now vary by selected provider
    • Enabled permission handling for Claude-based operations
  • Style

    • Refined ring color theme variables for visual consistency
  • Chores

    • Added Claude Code SDK dependency
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Walkthrough

      Introduces Claude Code integration via the Claude Agent SDK alongside existing Codex support. Adds ClaudeCodeManager backend, provider-aware routing in ProviderManager, extended contracts for Claude models and session parameters, and frontend updates for provider selection, model options, and state management.

      Changes

      Cohort / File(s)Summary
      Claude Backend Implementation
      apps/server/src/claudeCodeManager.ts, apps/server/src/claudeCodeManager.test.ts, apps/server/package.json
      Introduces ClaudeCodeManager class with session lifecycle, turn management, message streaming, tool/permission handling, and event emission. Adds Claude Agent SDK dependency and comprehensive test suite covering session start, streaming behavior, and tool request routing.
      Provider Routing & Management
      apps/server/src/providerManager.ts, apps/server/src/providerManager.test.ts
      Extends ProviderManager to support both Codex and Claude backends. Implements provider-aware routing for session start, turn handling, and thread operations. Adds new tests verifying Claude session routing.
      Type System & Contracts
      packages/contracts/src/model.ts, packages/contracts/src/model.test.ts, packages/contracts/src/provider.ts, packages/contracts/src/provider.test.ts
      Introduces Claude model definitions (CLAUDE_MODEL_OPTIONS, ClaudeModelSlug), normalization functions, and extends providerSessionStartInputSchema with Claude-specific fields (claudeSessionId, claudeBinaryPath, permissionMode, maxThinkingTokens). Adds ProviderModelOption schema.
      Frontend Model Resolution
      apps/web/src/model-logic.ts, apps/web/src/model-logic.test.ts
      Adds provider-aware model selection utilities: modelOptionsForProvider, resolveModelSlugForProvider, defaultModelForProvider. Exports Claude model options and introduces SupportedModelSlug type for provider-specific model handling.
      Frontend Chat & Session UI
      apps/web/src/ChatView.tsx, apps/web/src/session-logic.ts, apps/web/src/session-logic.test.ts
      Updates ChatView with ProviderPicker component and provider-aware model selection. Enables Claude Code provider option. Extends session-logic to handle Claude permission modes and derives work-log entries for assistant thinking and tool operations.
      Frontend State & Persistence
      apps/web/src/store.ts, apps/web/src/store.test.ts, apps/web/src/persistenceSchema.ts, apps/web/src/persistenceSchema.test.ts, apps/web/src/threadFactory.ts, apps/web/src/types.ts
      Introduces provider tracking per thread with SET_THREAD_PROVIDER action. Persists provider in thread state with default "codex". Updates thread factory and types to include provider field. Modifies state rebinding logic to handle provider-specific thread identity placeholders.
      Documentation & Styling
      .plans/claude-agent-sdk.md, TODO.md, apps/web/src/index.css
      Adds implementation plan for Claude integration. Includes new task in TODO. Adjusts CSS ring color chroma (oklch 0.217 → 0.13) in light and dark theme variants.

      Estimated code review effort

      🎯 4 (Complex) | ⏱️ ~50 minutes

      🚥 Pre-merge checks | ✅ 2 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 3.85% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (2 passed)
      Check nameStatusExplanation
      Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      Title check✅ PassedThe title accurately describes the main change: adding Claude Code integration as a new provider alongside the existing Codex provider.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing Touches
      • 📝 Generate docstrings
        🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `theo/claude`

      Tip

      Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Add Claude Code provider support and route sessions, turns, and checkpoints via unified ProviderManager using ClaudeCodeManager and provider-aware web UI

      Introduce ClaudeCodeManager and wire it into ProviderManager for session lifecycle, turn streaming, interrupts, approvals, thread reads/rollbacks, and checkpointing across Codex and Claude; update contracts for provider-specific models and start inputs; add provider-aware model resolution and selection in the web UI with a new ProviderPicker; adjust store, persistence, and work log logic to handle Claude events and thread rebinding; add tests across server, web, and contracts; add @anthropic-ai/claude-agent-sdk.

      📍Where to Start

      Start with the routing and event unification in ProviderManager in providerManager.ts, then review the Claude backend in claudeCodeManager.ts.


      📊 Macroscope summarized 0f1c8ea. 12 files reviewed, 21 issues evaluated, 0 issues filtered, 6 comments posted. View details

    3. Greptile Summary

      Adds Claude Code as a second provider alongside the existing Codex integration. The implementation follows the architecture pattern established by Codex, creating a parallel ClaudeCodeManager that wraps @anthropic-ai/claude-agent-sdk and routes through the unified ProviderManager.

      Major changes:

      • New ClaudeCodeManager (1054 lines) handles Claude SDK lifecycle, multi-turn message queuing, permission callbacks, and event normalization
      • ProviderManager routing logic dispatches to Codex or Claude based on session provider
      • Contract schemas extended with Claude-specific parameters (claudeSessionId, permissionMode, maxThinkingTokens)
      • Web app updated with provider picker UI, Claude model options, and event rendering for Claude-specific events (assistant/thinking, tool_use/start)
      • Comprehensive test coverage added across all layers

      Issue found:

      • claudeCodeManager.ts:265-278 - duplicate image attachment parsing loop stores incomplete image data without source details (first loop only stores {type: "image"}, second loop at 297-313 correctly includes base64 data)

      Confidence Score: 4/5

      • Safe to merge with one logic issue that should be addressed
      • Score reflects solid architecture and comprehensive test coverage, but reduced by one critical logic bug in image attachment handling that could cause runtime issues when users send images. The rest of the integration follows established patterns correctly.
      • apps/server/src/claudeCodeManager.ts - fix duplicate image parsing logic before merge

      Important Files Changed

      FilenameOverview
      apps/server/src/claudeCodeManager.tsNew Claude Code manager with image attachment parsing duplication issue
      apps/server/src/providerManager.tsRouting logic added to support both Codex and Claude Code providers
      packages/contracts/src/provider.tsSchema extended with Claude-specific session parameters
      packages/contracts/src/model.tsClaude model options and resolution logic added
      apps/web/src/store.tsState management updated for multi-provider support with thread identity rebinding
      apps/web/src/session-logic.tsClaude Code enabled and event rendering extended for tool use and thinking events

      Flowchart

      %%{init: {'theme': 'neutral'}}%%
      flowchart TD
          Start[User starts session] --> ProviderChoice{Provider?}
          
          ProviderChoice -->|Codex| CodexManager[CodexAppServerManager]
          ProviderChoice -->|Claude Code| ClaudeManager[ClaudeCodeManager]
          
          CodexManager --> CodexSpawn[Spawn codex app-server<br/>JSON-RPC over stdio]
          ClaudeManager --> ClaudeSDK[claude-agent-sdk<br/>spawns claude binary]
          
          CodexSpawn --> CodexEvents[Codex Events:<br/>thread/start, turn/start,<br/>agentMessage/delta]
          ClaudeSDK --> ClaudeEvents[Claude Events:<br/>assistant/text,<br/>tool_use/start,<br/>assistant/thinking]
          
          CodexEvents --> ProviderManager[ProviderManager<br/>Routes by provider]
          ClaudeEvents --> ProviderManager
          
          ProviderManager --> Normalize[Normalize to<br/>ProviderEvent schema]
          Normalize --> WebSocket[WebSocket push<br/>to web client]
          
          WebSocket --> WebStore[Web Store<br/>applyEventToMessages]
          WebStore --> Render[Render Chat UI<br/>Provider-aware model picker]
          
          ClaudeManager -.->|Permission request| CanUseTool[canUseTool callback]
          CanUseTool --> ApprovalFlow[Emit approval request<br/>Wait for user decision]
          ApprovalFlow -.->|allow/deny| ClaudeManager
      Last reviewed commit: 0f1c8ea
    4. 24 files reviewed, 1 comment [Edit Code Review Agent Settings](https://app.greptile.com/review/github) | [Greptile](https://greptile.com?utm_source=greptile_expert&utm_medium=github&utm_campaign=code_reviews)
      @@ -0,0 +258,21 @@
      258+
      259+ if (input.input) {
      260+ userContent.push({
      261+ type: "text",
      262+ text: input.input,
      263+ });
      264+ }
      265+ for (const attachment of input.attachments ?? []) {
      266+ if (attachment.type !== "image") {
      267+ continue;
      268+ }
      269+
      270+ const parsed = parseDataUrl(attachment.dataUrl);
      271+ if (!parsed) {
      272+ throw new Error(`Attachment '${attachment.name}' is not a valid base64 data URL.`);
      273+ }
      274+
      275+ userContent.push({
      276+ type: "image",
      277+ });
      278+ }
      greptile-apps[bot](GitHub profile, opens in a new tab)commented

      duplicate image attachment parsing - first loop stores incomplete image data without source details

      The first loop (lines 265-278) only pushes {type: "image"} to userContent without the actual image source data, while the second loop (lines 297-313) correctly builds the full image objects with source.data. The first loop appears redundant since userContent is only used to store in context.currentTurn but isn't sent to Claude.

      Suggested change
      265- for (const attachment of input.attachments ?? []) {
      266- if (attachment.type !== "image") {
      267- continue;
      268- }
      269-
      270- const parsed = parseDataUrl(attachment.dataUrl);
      271- if (!parsed) {
      272- throw new Error(`Attachment '${attachment.name}' is not a valid base64 data URL.`);
      273- }
      274-
      275- userContent.push({
      276- type: "image",
      277- });
      278- }
      265+ // userContent stores a simplified version for turn tracking
      266+ for (const attachment of input.attachments ?? []) {
      267+ if (attachment.type !== "image") {
      268+ continue;
      269+ }
      270+
      271+ const parsed = parseDataUrl(attachment.dataUrl);
      272+ if (!parsed) {
      273+ throw new Error(`Attachment '${attachment.name}' is not a valid base64 data URL.`);
      274+ }
      275+
      276+ userContent.push({
      277+ type: "image",
      278+ name: attachment.name,
      279+ });
      280+ }
    5. @@ -0,0 +234,21 @@
      234+ });
      235+ this.emitLifecycleEvent(
      236+ context,
      237+ "session/ready",
      238+ `Connected to session ${context.session.threadId ?? context.session.sessionId}`,
      239+ );
      240+ return { ...context.session };
      241+ } catch (error) {
      242+ const message = error instanceof Error ? error.message : "Failed to start Claude session.";
      243+ this.updateSession(context, {
      244+ status: "error",
      245+ lastError: message,
      246+ });
      247+ this.emitErrorEvent(context, "session/startFailed", message);
      248+ this.stopSession(sessionId);
      249+ throw new Error(message, { cause: error });
      250+ }
      251+ }
      252+
      253+ async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
      254+ const context = this.requireSession(input.sessionId);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      src/claudeCodeManager.ts:254 Concurrent sendTurn calls can overwrite context.currentTurn and mix streamed data across turns. Suggest guarding against an active turn (e.g., check context.currentTurn or session.status === 'running') and fail fast.

      -    const context = this.requireSession(input.sessionId);
      +    const context = this.requireSession(input.sessionId);
      +    if (context.session.status === "running") {
      +      throw new Error("A turn is already in progress.");
      +    }

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/server/src/claudeCodeManager.ts around line 254:
      
      Concurrent `sendTurn` calls can overwrite `context.currentTurn` and mix streamed data across turns. Suggest guarding against an active turn (e.g., check `context.currentTurn` or `session.status === 'running'`) and fail fast.
      
      Evidence trail:
      Viewed `apps/server/src/claudeCodeManager.ts` around `sendTurn` assignment of `context.currentTurn` and session status updates (`0f1c8ea`, lines ~300-360). Viewed `handleStreamEvent`, `handleAssistantMessage`, `appendAssistantDelta`, and related emit methods using `context.currentTurn` (`0f1c8ea`, lines ~560-820).
      @@ -0,0 +362,21 @@
      362+ }
      363+
      364+ async readThread(sessionId: string): Promise<CodexThreadSnapshot> {
      365+ const context = this.requireSession(sessionId);
      366+ return {
      367+ threadId: context.session.threadId ?? context.session.sessionId,
      368+ turns: context.turns.map((turn) => ({
      369+ id: turn.id,
      370+ items: [...turn.items],
      371+ })),
      372+ };
      373+ }
      374+
      375+ async rollbackThread(sessionId: string, numTurns: number): Promise<CodexThreadSnapshot> {
      376+ const context = this.requireSession(sessionId);
      377+ if (!Number.isInteger(numTurns) || numTurns < 1) {
      378+ throw new Error("numTurns must be an integer >= 1.");
      379+ }
      380+
      381+ const nextLength = Math.max(0, context.turns.length - numTurns);
      382+ context.turns = context.turns.slice(0, nextLength);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/claudeCodeManager.ts:376 rollbackThread doesn't terminate the active generation stream before resetting state. If called during a running turn, the background consumeMessages loop continues processing, and subsequent stream events will corrupt currentTurn data—either mixing into a newly started turn or creating phantom history entries. Consider interrupting the query and clearing currentTurn before modifying state.

      -  async rollbackThread(sessionId: string, numTurns: number): Promise<CodexThreadSnapshot> {
      -    const context = this.requireSession(sessionId);
      -    if (!Number.isInteger(numTurns) || numTurns < 1) {
      -      throw new Error("numTurns must be an integer >= 1.");
      -    }
      -
      -    const nextLength = Math.max(0, context.turns.length - numTurns);
      +  async rollbackThread(sessionId: string, numTurns: number): Promise<CodexThreadSnapshot> {
      +    const context = this.requireSession(sessionId);
      +    if (!Number.isInteger(numTurns) || numTurns < 1) {
      +      throw new Error("numTurns must be an integer >= 1.");
      +    }
      +
      +    if (context.currentTurn) {
      +      await context.query.interrupt();
      +      context.currentTurn = null;
      +    }
      +
      +    const nextLength = Math.max(0, context.turns.length - numTurns);

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/server/src/claudeCodeManager.ts around lines 376-382:
      
      `rollbackThread` doesn't terminate the active generation stream before resetting state. If called during a running turn, the background `consumeMessages` loop continues processing, and subsequent stream events will corrupt `currentTurn` data—either mixing into a newly started turn or creating phantom history entries. Consider interrupting the query and clearing `currentTurn` before modifying state.
      
      Evidence trail:
      Viewed `apps/server/src/claudeCodeManager.ts` lines ~350-410 (rollbackThread) and ~483-540 (consumeMessages) and ~720-920 (appendAssistantDelta/completeTurn/currentTurn handling) at commit `0f1c8ea` using https://github.com/pingdotgg/codething-mvp/tree/0f1c8eaa7e13f1fbcf1aec80d4694658ccd7eb2c.
      @@ -0,0 +452,21 @@
      452+ hasSession(sessionId: string): boolean {
      453+ return this.sessions.has(sessionId);
      454+ }
      455+
      456+ stopAll(): void {
      457+ for (const sessionId of this.sessions.keys()) {
      458+ this.stopSession(sessionId);
      459+ }
      460+ }
      461+
      462+ private resolvePermissionMode(input: ProviderSessionStartInput): PermissionMode {
      463+ if (input.permissionMode) {
      464+ return input.permissionMode;
      465+ }
      466+ return input.approvalPolicy === "never" ? "bypassPermissions" : "default";
      467+ }
      468+
      469+ private assertClaudeAvailable(binaryPath: string): void {
      470+ if (binaryPath !== "claude" && !fs.existsSync(binaryPath)) {
      471+ throw new Error(`Claude Code binary not found at '${binaryPath}'.`);
      472+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/claudeCodeManager.ts:470 The fs.existsSync check fails for binaries resolvable via PATH (e.g., claude-code, claude-nightly). Consider removing the existence check entirely since spawnSync already validates the binary works.

      Suggested change
      470- if (binaryPath !== "claude" && !fs.existsSync(binaryPath)) {
      471- throw new Error(`Claude Code binary not found at '${binaryPath}'.`);
      472- }
      470+ private assertClaudeAvailable(binaryPath: string): void {

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/server/src/claudeCodeManager.ts around lines 470-472:
      
      The `fs.existsSync` check fails for binaries resolvable via `PATH` (e.g., `claude-code`, `claude-nightly`). Consider removing the existence check entirely since `spawnSync` already validates the binary works.
      
      Evidence trail:
      Viewed `apps/server/src/claudeCodeManager.ts:456-473` at `0f1c8ea`.
      @@ -39,0 +59,21 @@
      59+ "claude-opus-4-6": "opus",
      60+ "opus-4-5": "opus",
      61+ "claude-opus-4-5": "opus",
      62+ "opus-4-1": "opus",
      63+ "claude-opus-4-1": "opus",
      64+ haiku: "haiku",
      65+ "haiku-4-5": "haiku",
      66+ "claude-haiku-4-5": "haiku",
      67+};
      68+
      69+export function normalizeClaudeModelSlug(model: string | null | undefined): ClaudeModelSlug | null {
      70+ if (typeof model !== "string") {
      71+ return null;
      72+ }
      73+
      74+ const trimmed = model.trim();
      75+ if (!trimmed) {
      76+ return null;
      77+ }
      78+
      79+ return CLAUDE_MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ClaudeModelSlug);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/model.ts:79 Indexing CLAUDE_MODEL_SLUG_ALIASES without an own‑key check can hit inherited keys (e.g., toString/constructor), returning non‑strings and breaking the function’s return type. Suggest guarding with Object.hasOwn (or using a null‑prototype object/Map) before lookup.

      Suggested change
      79- return CLAUDE_MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ClaudeModelSlug);
      79+ return Object.hasOwn(CLAUDE_MODEL_SLUG_ALIASES, trimmed) ? CLAUDE_MODEL_SLUG_ALIASES[trimmed] : (trimmed as ClaudeModelSlug);

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file packages/contracts/src/model.ts around line 79:
      
      Indexing `CLAUDE_MODEL_SLUG_ALIASES` without an own‑key check can hit inherited keys (e.g., `toString`/`constructor`), returning non‑strings and breaking the function’s return type. Suggest guarding with `Object.hasOwn` (or using a null‑prototype object/`Map`) before lookup.
      
      Evidence trail:
      Viewed `packages/contracts/src/model.ts` lines 55-88 at commit `0f1c8ea` (URL: https://github.com/pingdotgg/codething-mvp/tree/0f1c8eaa7e13f1fbcf1aec80d4694658ccd7eb2c).
      @@ -0,0 +936,21 @@
      936+ turnId: context.currentTurn?.turnId,
      937+ requestId,
      938+ requestKind,
      939+ payload: {
      940+ toolName,
      941+ input: toolInput,
      942+ toolUseId: options.toolUseID,
      943+ blockedPath: options.blockedPath,
      944+ reason: options.decisionReason,
      945+ },
      946+ });
      947+
      948+ const onAbort = () => {
      949+ if (settled) {
      950+ return;
      951+ }
      952+ settled = true;
      953+ context.pendingApprovals.delete(requestId);
      954+ reject(new Error("Permission request was cancelled."));
      955+ };
      956+ options.signal.addEventListener("abort", onAbort, { once: true });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/claudeCodeManager.ts:956 If options.signal is already aborted when handleCanUseTool is called, the abort listener won't fire and the promise will hang forever. Consider checking options.signal.aborted before adding the listener and rejecting immediately if true.

      -      options.signal.addEventListener("abort", onAbort, { once: true });
      +      options.signal.addEventListener("abort", onAbort, { once: true });
      +      if (options.signal.aborted) {
      +        onAbort();
      +      }

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/server/src/claudeCodeManager.ts around line 956:
      
      If `options.signal` is already aborted when `handleCanUseTool` is called, the `abort` listener won't fire and the promise will hang forever. Consider checking `options.signal.aborted` before adding the listener and rejecting immediately if true.
      
      Evidence trail:
      Viewed `apps/server/src/claudeCodeManager.ts` around `handleCanUseTool` in commit `0f1c8ea`: lines ~880-970 show the Promise setup and only `options.signal.addEventListener("abort", onAbort, { once: true })` without an `options.signal.aborted` check. URL: https://github.com/pingdotgg/codething-mvp/tree/0f1c8eaa7e13f1fbcf1aec80d4694658ccd7eb2c/apps/server/src/claudeCodeManager.ts
      @@ -0,0 +456,21 @@
      456+ stopAll(): void {
      457+ for (const sessionId of this.sessions.keys()) {
      458+ this.stopSession(sessionId);
      459+ }
      460+ }
      461+
      462+ private resolvePermissionMode(input: ProviderSessionStartInput): PermissionMode {
      463+ if (input.permissionMode) {
      464+ return input.permissionMode;
      465+ }
      466+ return input.approvalPolicy === "never" ? "bypassPermissions" : "default";
      467+ }
      468+
      469+ private assertClaudeAvailable(binaryPath: string): void {
      470+ if (binaryPath !== "claude" && !fs.existsSync(binaryPath)) {
      471+ throw new Error(`Claude Code binary not found at '${binaryPath}'.`);
      472+ }
      473+
      474+ const probe = spawnSync(binaryPath, ["--version"], {
      475+ stdio: "ignore",
      476+ });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      src/claudeCodeManager.ts:474 spawnSync without a timeout option can block the event loop indefinitely if the binary hangs. Consider adding a reasonable timeout (e.g., timeout: 5000).

      Suggested change
      474- const probe = spawnSync(binaryPath, ["--version"], {
      475- stdio: "ignore",
      476- });
      474+ const probe = spawnSync(binaryPath, ["--version"], {
      475+ stdio: "ignore",
      476+ timeout: 5000,
      477+ });

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/server/src/claudeCodeManager.ts around lines 474-476:
      
      `spawnSync` without a `timeout` option can block the event loop indefinitely if the binary hangs. Consider adding a reasonable timeout (e.g., `timeout: 5000`).
      
      Evidence trail:
      Viewed `apps/server/src/claudeCodeManager.ts` lines 466-482 at commit `0f1c8ea` using repository URL `https://github.com/pingdotgg/codething-mvp/tree/0f1c8eaa7e13f1fbcf1aec80d4694658ccd7eb2c`.
    6. Actionable comments posted: 6

      Caution

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

      ⚠️ Outside diff range comments (1)
      apps/web/src/threadFactory.ts (1)

      14-23: ⚠️ Potential issue | 🟠 Major

      Use provider-aware default model when provider is Claude. DEFAULT_MODEL is Codex-specific; if callers omit options.model for a claudeCode thread, the thread will start with an invalid Codex slug. Please default based on provider.

      🛠️ Proposed fix
      -import { DEFAULT_MODEL } from "./model-logic";
      +import { defaultModelForProvider } from "./model-logic";
      
       export function createThread(projectId: string, options: CreateThreadOptions = {}): Thread {
         const createdAt = options.createdAt ?? new Date().toISOString();
      +  const provider = options.provider ?? "codex";
      +  const model = options.model ?? defaultModelForProvider(provider);
      
         return {
           id: crypto.randomUUID(),
           codexThreadId: null,
      -    provider: options.provider ?? "codex",
      +    provider,
           projectId,
           title: options.title ?? "New thread",
      -    model: options.model ?? DEFAULT_MODEL,
      +    model,
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@apps/web/src/threadFactory.ts` around lines 14 - 23, createThread currently
      always falls back to DEFAULT_MODEL even when the provider is set to Claude;
      update the defaulting logic so that if options.model is undefined you choose the
      model based on the provider (e.g., when provider === "claudeCode" use the Claude
      default model constant instead of DEFAULT_MODEL, otherwise use DEFAULT_MODEL).
      Modify the model assignment in createThread to consult options.provider (or the
      resolved provider value) and pick the appropriate provider-aware default model
      constant.
      🧹 Nitpick comments (2)
      packages/contracts/src/model.ts (2)

      82-88: resolveClaudeModelSlug doesn't validate against CLAUDE_MODEL_OPTIONS.

      Unlike resolveModelSlug (line 38), this function returns any non-empty normalized string without checking if it's a supported slug. Unknown models will pass through instead of defaulting.

      If validation is desired:

      ♻️ Proposed fix to validate against known options
       export function resolveClaudeModelSlug(model: string | null | undefined): ClaudeModelSlug {
         const normalized = normalizeClaudeModelSlug(model);
         if (!normalized) {
           return DEFAULT_CLAUDE_MODEL;
         }
      
      -  return normalized;
      +  return CLAUDE_MODEL_OPTIONS.some((option) => option.slug === normalized)
      +    ? normalized
      +    : DEFAULT_CLAUDE_MODEL;
       }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/contracts/src/model.ts` around lines 82 - 88, resolveClaudeModelSlug
      currently returns any non-empty normalized slug; update it to validate the
      normalized value against the allowed set (CLAUDE_MODEL_OPTIONS or an
      isClaudeModelSlug helper) and fall back to DEFAULT_CLAUDE_MODEL when the
      normalized value is not one of the supported slugs. Locate
      resolveClaudeModelSlug and replace the unconditional return of normalized with a
      membership check (e.g., CLAUDE_MODEL_OPTIONS.includes(normalized) or call
      isClaudeModelSlug(normalized)) and return DEFAULT_CLAUDE_MODEL when the check
      fails.

      47-47: Consider constraining ClaudeModelSlug to known options.

      ClaudeModelSlug is defined as string, whereas ModelSlug is derived from MODEL_OPTIONS. This allows arbitrary strings to pass through resolveClaudeModelSlug without validation against CLAUDE_MODEL_OPTIONS.

      If this permissiveness is intentional (e.g., to support dynamic/unknown Claude models), consider adding a clarifying comment. Otherwise, consider aligning with the pattern used for Codex models:

      -export type ClaudeModelSlug = string;
      +export type ClaudeModelSlug = (typeof CLAUDE_MODEL_OPTIONS)[number]["slug"];

      And updating resolveClaudeModelSlug to validate against the options array.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/contracts/src/model.ts` at line 47, ClaudeModelSlug is currently
      typed as string which lets arbitrary values bypass validation; change it to a
      union of known options (mirror pattern used for ModelSlug/MODEL_OPTIONS) or add
      a clarifying comment if dynamic values are intended. Update the type alias
      ClaudeModelSlug to derive from CLAUDE_MODEL_OPTIONS (or create a Claude-specific
      constant similar to MODEL_OPTIONS) and modify resolveClaudeModelSlug to validate
      the input against CLAUDE_MODEL_OPTIONS, returning a typed slug or
      throwing/handling invalid values accordingly; reference ClaudeModelSlug,
      CLAUDE_MODEL_OPTIONS, and resolveClaudeModelSlug when making the changes.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Inline comments:
      In @.plans/claude-agent-sdk.md:
      - Around line 123-133: The fenced code blocks in the document are missing
      language identifiers (causing markdownlint MD040); update every triple-backtick
      fence (for example the block showing the startSession/sendTurn pseudocode) to
      include an appropriate language tag such as ```ts or ```text to silence the lint
      and improve readability; scan the file for all occurrences of ```...``` and add
      language identifiers consistent with the block contents (use "ts" for
      TypeScript-like pseudocode and "text" for plain lists).
      
      In `@apps/server/src/claudeCodeManager.ts`:
      - Around line 259-313: The turn history is losing image payloads because
      userContent is pushed with only { type: "image" } while messageContent includes
      the parsed base64 payload; update the userContent construction to mirror
      messageContent for images: when iterating attachments in the userContent block
      (where parseDataUrl is called), add the parsed data (media_type and base64 data)
      under a source object (or equivalent shape used by readThread) instead of just {
      type: "image" } so readThread/turn history can render attachments; use the same
      parseDataUrl/parsed.mimeType and parsed.base64Data fields you already use for
      messageContent to keep both representations consistent.
      - Around line 253-327: sendTurn currently overwrites context.currentTurn even
      when a previous turn is still streaming; add an early guard in sendTurn (after
      const context = this.requireSession(...)) that checks context.currentTurn (or
      context.status === "running"/context.activeTurnId) and rejects/throws an error
      like "A turn is already in progress" to prevent starting a second overlapping
      turn; ensure callers will clear context.currentTurn (or updateSession to set
      status/activeTurnId to null) when a turn finishes so new turns can proceed.
      - Around line 483-509: The consumeMessages error and normal-exit paths remove
      the session but do not abort the stream controller or resolve/reject pending
      approvals/queued promises, which leaks callers; add a single cleanup helper
      (e.g., cleanupSession or finalizeSession) and call it from both the catch block
      and the normal termination branch in consumeMessages to: abort the controller
      (context.controller.abort()), drain/clear any context.queue or internal message
      queue, iterate pending approvals/requests in context.pendingApprovals (or
      similar) and resolve/reject them with a clear error or cancellation result,
      clear those collections, then perform the existing updateSession/emits and
      this.sessions.delete(context.session.sessionId). Reference consumeMessages,
      context.query, context.controller, context.pendingApprovals (or the actual
      approval/queue symbols in the file), updateSession, emitErrorEvent,
      emitLifecycleEvent and this.sessions.delete when implementing.
      - Around line 1028-1030: The emitEvent method currently emits ad-hoc
      ProviderEvent payloads without runtime validation; import the
      providerEventSchema (from the provider contracts module) into this file and call
      providerEventSchema.parse(event) at the start of emitEvent (before
      this.emit("event", event)) to validate the payload; decide whether to let the
      parse error bubble (fail-fast) or catch it to log and drop the event, but ensure
      validation runs at the emission boundary so malformed ProviderEvent objects are
      caught.
      
      In `@apps/server/src/providerManager.ts`:
      - Around line 239-254: The stopSession method currently returns early when
      hasSession(input.sessionId) is false, which leaves local state
      (sessionThreadIds, pendingEventsBySession, sessionCheckpointCwds,
      filesystemLocks) stale; change stopSession so it always deletes those maps for
      input.sessionId regardless of hasSession, and only call
      resolveBackend/claude.stopSession or codex.stopSession if the backend/session
      exists; specifically, in stopSession (using
      providerStopSessionInputSchema.parse, hasSession, resolveBackend,
      claude.stopSession, codex.stopSession) perform the local cleanup deletes
      unconditionally and then conditionally invoke remote backend stop logic.
      
      ---
      
      Outside diff comments:
      In `@apps/web/src/threadFactory.ts`:
      - Around line 14-23: createThread currently always falls back to DEFAULT_MODEL
      even when the provider is set to Claude; update the defaulting logic so that if
      options.model is undefined you choose the model based on the provider (e.g.,
      when provider === "claudeCode" use the Claude default model constant instead of
      DEFAULT_MODEL, otherwise use DEFAULT_MODEL). Modify the model assignment in
      createThread to consult options.provider (or the resolved provider value) and
      pick the appropriate provider-aware default model constant.
      
      ---
      
      Nitpick comments:
      In `@packages/contracts/src/model.ts`:
      - Around line 82-88: resolveClaudeModelSlug currently returns any non-empty
      normalized slug; update it to validate the normalized value against the allowed
      set (CLAUDE_MODEL_OPTIONS or an isClaudeModelSlug helper) and fall back to
      DEFAULT_CLAUDE_MODEL when the normalized value is not one of the supported
      slugs. Locate resolveClaudeModelSlug and replace the unconditional return of
      normalized with a membership check (e.g.,
      CLAUDE_MODEL_OPTIONS.includes(normalized) or call isClaudeModelSlug(normalized))
      and return DEFAULT_CLAUDE_MODEL when the check fails.
      - Line 47: ClaudeModelSlug is currently typed as string which lets arbitrary
      values bypass validation; change it to a union of known options (mirror pattern
      used for ModelSlug/MODEL_OPTIONS) or add a clarifying comment if dynamic values
      are intended. Update the type alias ClaudeModelSlug to derive from
      CLAUDE_MODEL_OPTIONS (or create a Claude-specific constant similar to
      MODEL_OPTIONS) and modify resolveClaudeModelSlug to validate the input against
      CLAUDE_MODEL_OPTIONS, returning a typed slug or throwing/handling invalid values
      accordingly; reference ClaudeModelSlug, CLAUDE_MODEL_OPTIONS, and
      resolveClaudeModelSlug when making the changes.
      @@ -0,0 +113,21 @@
      113+ abortController: AbortController;
      114+ currentModel: string | undefined;
      115+}
      116+
      117+export class ClaudeCodeManager extends EventEmitter<ClaudeCodeManagerEvents> {
      118+ private sessions = new Map<string, ClaudeSessionContext>();
      119+```
      120+
      121+**Session lifecycle:**
      122+
      123+```
      124+startSession(input)
      125+ 1. Resolve claude binary path (bundled or system `claude`)
      126+ 2. Validate claude is available: execSync(`claude -v`)
      127+ 3. Create AbortController
      128+ 4. Set up async generator for multi-turn messages
      129+ 5. Call claudeQuery({ prompt: asyncGenerator, options: { ... } })
      130+ 6. Start consuming the async iterable in background, emitting ProviderEvents
      131+ 7. Return ProviderSession with status "ready"
      132+
      133+sendTurn(input)
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟡 Minor

      Add language identifiers to fenced code blocks. markdownlint MD040 flags unlabeled fences; adding language tags improves linting and readability. Please apply across the document.

      💡 Example fix
      -```
      +```ts
       startSession(input)
         1. Resolve claude binary path (bundled or system `claude`)
         2. Validate claude is available: execSync(`claude -v`)
         3. Create AbortController
         4. Set up async generator for multi-turn messages
         5. Call claudeQuery({ prompt: asyncGenerator, options: { ... } })
         6. Start consuming the async iterable in background, emitting ProviderEvents
         7. Return ProviderSession with status "ready"
      -```
      +```
      🧰 Tools
      🪛 markdownlint-cli2 (0.21.0)

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

      (MD040, fenced-code-language)

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In @.plans/claude-agent-sdk.md around lines 123 - 133, The fenced code blocks in
      the document are missing language identifiers (causing markdownlint MD040);
      update every triple-backtick fence (for example the block showing the
      startSession/sendTurn pseudocode) to include an appropriate language tag such as
      ```ts or ```text to silence the lint and improve readability; scan the file for
      all occurrences of ```...``` and add language identifiers consistent with the
      block contents (use "ts" for TypeScript-like pseudocode and "text" for plain
      lists).
      @@ -0,0 +307,21 @@
      307+ source: {
      308+ type: "base64",
      309+ media_type: parsed.mimeType,
      310+ data: parsed.base64Data,
      311+ },
      312+ });
      313+ }
      314+
      315+ context.currentTurn = {
      316+ turnId,
      317+ assistantItemId,
      318+ userContent,
      319+ assistantText: "",
      320+ assistantStarted: false,
      321+ };
      322+
      323+ this.updateSession(context, {
      324+ status: "running",
      325+ activeTurnId: turnId,
      326+ });
      327+ this.emitEvent({
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟠 Major

      Prevent overlapping turns from clobbering currentTurn. sendTurn overwrites currentTurn even if a prior turn is still streaming, which can mis-attribute deltas and corrupt turn history under concurrent calls.

      🔧 Suggested guard
       async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
         const context = this.requireSession(input.sessionId);
      +  if (context.currentTurn || context.session.status === "running") {
      +    throw new Error("A turn is already running for this session.");
      +  }
         const turnId = randomUUID();
      📝 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
      253+ async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
      254+ const context = this.requireSession(input.sessionId);
      255+ if (context.currentTurn || context.session.status === "running") {
      256+ throw new Error("A turn is already running for this session.");
      257+ }
      258+ const turnId = randomUUID();
      259+ const assistantItemId = randomUUID();
      260+ const userContent: unknown[] = [];
      261+
      262+ if (input.input) {
      263+ userContent.push({
      264+ type: "text",
      265+ text: input.input,
      266+ });
      267+ }
      268+ for (const attachment of input.attachments ?? []) {
      269+ if (attachment.type !== "image") {
      270+ continue;
      271+ }
      272+
      273+ const parsed = parseDataUrl(attachment.dataUrl);
      274+ if (!parsed) {
      275+ throw new Error(`Attachment '${attachment.name}' is not a valid base64 data URL.`);
      276+ }
      277+
      278+ userContent.push({
      279+ type: "image",
      280+ });
      281+ }
      282+
      283+ if (userContent.length === 0) {
      284+ throw new Error("Turn input must include text or attachments.");
      285+ }
      286+
      287+ if (input.model) {
      288+ const model = resolveClaudeModelSlug(input.model);
      289+ await context.query.setModel(model);
      290+ this.updateSession(context, { model });
      291+ }
      292+
      293+ const messageContent: Array<Record<string, unknown>> = [];
      294+ if (input.input) {
      295+ messageContent.push({
      296+ type: "text",
      297+ text: input.input,
      298+ });
      299+ }
      300+ for (const attachment of input.attachments ?? []) {
      301+ if (attachment.type !== "image") {
      302+ continue;
      303+ }
      304+ const parsed = parseDataUrl(attachment.dataUrl);
      305+ if (!parsed) {
      306+ throw new Error(`Attachment '${attachment.name}' is not a valid base64 data URL.`);
      307+ }
      308+ messageContent.push({
      309+ type: "image",
      310+ source: {
      311+ type: "base64",
      312+ media_type: parsed.mimeType,
      313+ data: parsed.base64Data,
      314+ },
      315+ });
      316+ }
      317+
      318+ context.currentTurn = {
      319+ turnId,
      320+ assistantItemId,
      321+ userContent,
      322+ assistantText: "",
      323+ assistantStarted: false,
      324+ };
      325+
      326+ this.updateSession(context, {
      327+ status: "running",
      328+ activeTurnId: turnId,
      329+ });
      330+ this.emitEvent({
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@apps/server/src/claudeCodeManager.ts` around lines 253 - 327, sendTurn
      currently overwrites context.currentTurn even when a previous turn is still
      streaming; add an early guard in sendTurn (after const context =
      this.requireSession(...)) that checks context.currentTurn (or context.status ===
      "running"/context.activeTurnId) and rejects/throws an error like "A turn is
      already in progress" to prevent starting a second overlapping turn; ensure
      callers will clear context.currentTurn (or updateSession to set
      status/activeTurnId to null) when a turn finishes so new turns can proceed.
      @@ -0,0 +293,21 @@
      293+ type: "text",
      294+ text: input.input,
      295+ });
      296+ }
      297+ for (const attachment of input.attachments ?? []) {
      298+ if (attachment.type !== "image") {
      299+ continue;
      300+ }
      301+ const parsed = parseDataUrl(attachment.dataUrl);
      302+ if (!parsed) {
      303+ throw new Error(`Attachment '${attachment.name}' is not a valid base64 data URL.`);
      304+ }
      305+ messageContent.push({
      306+ type: "image",
      307+ source: {
      308+ type: "base64",
      309+ media_type: parsed.mimeType,
      310+ data: parsed.base64Data,
      311+ },
      312+ });
      313+ }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟡 Minor

      User message snapshot drops image payloads. userContent only records { type: "image" }, so readThread/turn history can’t render attachments even though the Claude request includes them.

      🧩 Include image data in `userContent`
             const parsed = parseDataUrl(attachment.dataUrl);
             if (!parsed) {
               throw new Error(`Attachment '${attachment.name}' is not a valid base64 data URL.`);
             }
       
             userContent.push({
               type: "image",
      +        source: {
      +          type: "base64",
      +          media_type: parsed.mimeType,
      +          data: parsed.base64Data,
      +        },
             });
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@apps/server/src/claudeCodeManager.ts` around lines 259 - 313, The turn
      history is losing image payloads because userContent is pushed with only { type:
      "image" } while messageContent includes the parsed base64 payload; update the
      userContent construction to mirror messageContent for images: when iterating
      attachments in the userContent block (where parseDataUrl is called), add the
      parsed data (media_type and base64 data) under a source object (or equivalent
      shape used by readThread) instead of just { type: "image" } so readThread/turn
      history can render attachments; use the same parseDataUrl/parsed.mimeType and
      parsed.base64Data fields you already use for messageContent to keep both
      representations consistent.
      @@ -0,0 +489,21 @@
      489+ if (context.stopping) {
      490+ return;
      491+ }
      492+ const message = error instanceof Error ? error.message : "Claude session crashed.";
      493+ this.updateSession(context, {
      494+ status: "error",
      495+ lastError: message,
      496+ });
      497+ this.emitErrorEvent(context, "session/exited", message);
      498+ this.sessions.delete(context.session.sessionId);
      499+ return;
      500+ }
      501+
      502+ if (!context.stopping && this.sessions.has(context.session.sessionId)) {
      503+ this.updateSession(context, {
      504+ status: "closed",
      505+ activeTurnId: undefined,
      506+ });
      507+ this.emitLifecycleEvent(context, "session/exited", "Claude session ended.");
      508+ this.sessions.delete(context.session.sessionId);
      509+ }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟠 Major

      Clean up approvals/queue on stream failure or exit. On error (or normal stream termination), the session is removed without terminating the queue, aborting the controller, or resolving pending approvals. This can leak pending promises and leave callers hanging after failures.

      🧹 Minimal cleanup in failure/exit paths
         } catch (error) {
           if (context.stopping) {
             return;
           }
           const message = error instanceof Error ? error.message : "Claude session crashed.";
           this.updateSession(context, {
             status: "error",
             lastError: message,
           });
           this.emitErrorEvent(context, "session/exited", message);
      +    for (const pending of context.pendingApprovals.values()) {
      +      pending.resolve("cancel");
      +    }
      +    context.pendingApprovals.clear();
      +    context.queue.terminate();
      +    context.abortController.abort();
      +    context.query.close();
           this.sessions.delete(context.session.sessionId);
           return;
         }
       
         if (!context.stopping && this.sessions.has(context.session.sessionId)) {
           this.updateSession(context, {
             status: "closed",
             activeTurnId: undefined,
           });
           this.emitLifecycleEvent(context, "session/exited", "Claude session ended.");
      +    for (const pending of context.pendingApprovals.values()) {
      +      pending.resolve("cancel");
      +    }
      +    context.pendingApprovals.clear();
      +    context.queue.terminate();
      +    context.abortController.abort();
      +    context.query.close();
           this.sessions.delete(context.session.sessionId);
         }
      As per coding guidelines: "apps/server/src/**/*.{ts,js}: Maintain predictable behavior under load and during failures (session restarts, reconnects, partial streams)".
      📝 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
      483+ private async consumeMessages(context: ClaudeSessionContext): Promise<void> {
      484+ try {
      485+ for await (const message of context.query) {
      486+ this.handleMessage(context, message);
      487+ }
      488+ } catch (error) {
      489+ if (context.stopping) {
      490+ return;
      491+ }
      492+ const message = error instanceof Error ? error.message : "Claude session crashed.";
      493+ this.updateSession(context, {
      494+ status: "error",
      495+ lastError: message,
      496+ });
      497+ this.emitErrorEvent(context, "session/exited", message);
      498+ for (const pending of context.pendingApprovals.values()) {
      499+ pending.resolve("cancel");
      500+ }
      501+ context.pendingApprovals.clear();
      502+ context.queue.terminate();
      503+ context.abortController.abort();
      504+ context.query.close();
      505+ this.sessions.delete(context.session.sessionId);
      506+ return;
      507+ }
      508+
      509+ if (!context.stopping && this.sessions.has(context.session.sessionId)) {
      510+ this.updateSession(context, {
      511+ status: "closed",
      512+ activeTurnId: undefined,
      513+ });
      514+ this.emitLifecycleEvent(context, "session/exited", "Claude session ended.");
      515+ for (const pending of context.pendingApprovals.values()) {
      516+ pending.resolve("cancel");
      517+ }
      518+ context.pendingApprovals.clear();
      519+ context.queue.terminate();
      520+ context.abortController.abort();
      521+ context.query.close();
      522+ this.sessions.delete(context.session.sessionId);
      523+ }
      524+ }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@apps/server/src/claudeCodeManager.ts` around lines 483 - 509, The
      consumeMessages error and normal-exit paths remove the session but do not abort
      the stream controller or resolve/reject pending approvals/queued promises, which
      leaks callers; add a single cleanup helper (e.g., cleanupSession or
      finalizeSession) and call it from both the catch block and the normal
      termination branch in consumeMessages to: abort the controller
      (context.controller.abort()), drain/clear any context.queue or internal message
      queue, iterate pending approvals/requests in context.pendingApprovals (or
      similar) and resolve/reject them with a clear error or cancellation result,
      clear those collections, then perform the existing updateSession/emits and
      this.sessions.delete(context.session.sessionId). Reference consumeMessages,
      context.query, context.controller, context.pendingApprovals (or the actual
      approval/queue symbols in the file), updateSession, emitErrorEvent,
      emitLifecycleEvent and this.sessions.delete when implementing.
      @@ -0,0 +1010,21 @@
      1010+ message,
      1011+ threadId: context.session.threadId,
      1012+ });
      1013+ }
      1014+
      1015+ private emitErrorEvent(context: ClaudeSessionContext, method: string, message: string): void {
      1016+ this.emitEvent({
      1017+ id: randomUUID(),
      1018+ kind: "error",
      1019+ provider: "claudeCode",
      1020+ sessionId: context.session.sessionId,
      1021+ createdAt: new Date().toISOString(),
      1022+ method,
      1023+ message,
      1024+ threadId: context.session.threadId,
      1025+ });
      1026+ }
      1027+
      1028+ private emitEvent(event: ProviderEvent): void {
      1029+ this.emit("event", event);
      1030+ }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟠 Major

      🧩 Analysis chain

      🏁 Script executed:

      # Find ProviderEvent Zod schema and contract definitions
      rg -n "ProviderEvent" packages/contracts --type ts --type tsx

      Repository: pingdotgg/codething-mvp

      Length of output: 94


      🏁 Script executed:

      # Check the structure of packages/contracts
      fd -t f . packages/contracts | head -20

      Repository: pingdotgg/codething-mvp

      Length of output: 759


      🏁 Script executed:

      # Examine the emitEvent method and surrounding context in claudeCodeManager.ts
      rg -n "emitEvent|ProviderEvent" apps/server/src/claudeCodeManager.ts -B 2 -A 10

      Repository: pingdotgg/codething-mvp

      Length of output: 8980


      🏁 Script executed:

      # Check the ProviderEvent definition in packages/contracts
      cat -n packages/contracts/src/provider.ts

      Repository: pingdotgg/codething-mvp

      Length of output: 10298


      🏁 Script executed:

      # Check if there's a Zod schema exported from packages/contracts
      rg -n "ProviderEvent" packages/contracts/src/provider.ts -A 5 -B 2

      Repository: pingdotgg/codething-mvp

      Length of output: 418


      Validate ProviderEvent payloads with Zod schema at the emit boundary.

      The providerEventSchema exists in packages/contracts/src/provider.ts but is not being used for runtime validation. Events are constructed ad-hoc throughout this file (16+ call sites); without validation, malformed payloads will silently propagate to consumers. Add providerEventSchema.parse(event) in the emitEvent method to enforce the contract at emission time.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@apps/server/src/claudeCodeManager.ts` around lines 1028 - 1030, The emitEvent
      method currently emits ad-hoc ProviderEvent payloads without runtime validation;
      import the providerEventSchema (from the provider contracts module) into this
      file and call providerEventSchema.parse(event) at the start of emitEvent (before
      this.emit("event", event)) to validate the payload; decide whether to let the
      parse error bubble (fail-fast) or catch it to log and drop the event, but ensure
      validation runs at the emission boundary so malformed ProviderEvent objects are
      caught.
      @@ -235,12 +235,20 @@
      235235
      236236 await this.codex.respondToRequest(input.sessionId, input.requestId, input.decision);
      237237 }
      238238
      239239 stopSession(raw: ProviderStopSessionInput): void {
      240240 const input = providerStopSessionInputSchema.parse(raw);
      241- this.codex.stopSession(input.sessionId);
      241+ if (!this.hasSession(input.sessionId)) {
      242+ return;
      243+ }
      244+ const backend = this.resolveBackend(input.sessionId);
      245+ if (backend === "claudeCode") {
      246+ this.claude.stopSession(input.sessionId);
      247+ } else {
      248+ this.codex.stopSession(input.sessionId);
      249+ }
      242250 this.sessionThreadIds.delete(input.sessionId);
      243251 this.pendingEventsBySession.delete(input.sessionId);
      244252 this.sessionCheckpointCwds.delete(input.sessionId);
      245253 this.filesystemLocks.delete(input.sessionId);
      246254 }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟡 Minor

      Don’t skip local cleanup when the backend session is already gone. The early return leaves sessionThreadIds, pendingEventsBySession, and checkpoint/lock maps populated if a session disappears before this call, which can accumulate stale state.

      🔧 Suggested adjustment
         stopSession(raw: ProviderStopSessionInput): void {
           const input = providerStopSessionInputSchema.parse(raw);
      -    if (!this.hasSession(input.sessionId)) {
      -      return;
      -    }
      -    const backend = this.resolveBackend(input.sessionId);
      -    if (backend === "claudeCode") {
      -      this.claude.stopSession(input.sessionId);
      -    } else {
      -      this.codex.stopSession(input.sessionId);
      -    }
      +    const hasSession = this.hasSession(input.sessionId);
      +    if (hasSession) {
      +      const backend = this.resolveBackend(input.sessionId);
      +      if (backend === "claudeCode") {
      +        this.claude.stopSession(input.sessionId);
      +      } else {
      +        this.codex.stopSession(input.sessionId);
      +      }
      +    }
           this.sessionThreadIds.delete(input.sessionId);
           this.pendingEventsBySession.delete(input.sessionId);
           this.sessionCheckpointCwds.delete(input.sessionId);
           this.filesystemLocks.delete(input.sessionId);
         }
      As per coding guidelines "apps/server/src/**/*.{ts,js}: Maintain predictable behavior under load and during failures (session restarts, reconnects, partial streams)".
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@apps/server/src/providerManager.ts` around lines 239 - 254, The stopSession
      method currently returns early when hasSession(input.sessionId) is false, which
      leaves local state (sessionThreadIds, pendingEventsBySession,
      sessionCheckpointCwds, filesystemLocks) stale; change stopSession so it always
      deletes those maps for input.sessionId regardless of hasSession, and only call
      resolveBackend/claude.stopSession or codex.stopSession if the backend/session
      exists; specifically, in stopSession (using
      providerStopSessionInputSchema.parse, hasSession, resolveBackend,
      claude.stopSession, codex.stopSession) perform the local cleanup deletes
      unconditionally and then conditionally invoke remote backend stop logic.
    7. juliusmarminge closed this

Sign in to join this conversation.