Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat: add Claude Code adapter #179

Mergedjuliusmarmingemerged 39 commits intomain fromcodething/648ca884-claudemerged by juliusmarminge View on GitHub

juliusmarmingecommented

Summary

This PR adds the Claude Code adapter on top of the core orchestration branch in #103.

It includes:

  • the Claude Code provider adapter and service layer
  • provider registry/server-layer wiring for Claude Code
  • Claude Code availability in the provider/session UI surface needed for this stack

Stack

  • Base PR: #103
  • Base branch: codething/648ca884

Validation

  • bun lint
  • bun typecheck
  • cd apps/server && bun run test -- --run src/provider/Layers/ProviderAdapterRegistry.test.ts
  • cd apps/web && bun run test -- --run src/session-logic.test.ts

Note

High Risk Adds a new claudeAgent provider with session lifecycle, resume, approvals/user-input bridging, and rollback behavior, plus changes to provider/session validation and restart rules; mistakes could break turn execution, approval gating, or checkpoint reverts across providers.

Overview Adds first-class support for the claudeAgent provider end-to-end, including a new ClaudeAdapterLive backed by @anthropic-ai/claude-agent-sdk that streams canonical ProviderRuntimeEvents, supports interrupts, approvals/user-input requests, resume cursors, and thread rollback.

Updates orchestration/provider plumbing to be provider-aware: ProviderKind and model catalogs now include Claude models and options, ProviderCommandReactor enforces provider/model compatibility, restarts Claude sessions when Claude modelOptions change, and surfaces turn-start failures as thread activities instead of crashing.

Extends ingestion and checkpointing tests/behavior for Claude events (turn lifecycle, task progress summaries, checkpoint capture/revert), and adds new integration coverage for first-turn Claude selection, stopAll recovery via persisted resume state, approval response forwarding, and interrupt forwarding. Also refreshes docs/README to reflect Claude as supported.

Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit a75a9b427fa044588d50a95e57571db20653dba5. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).

Note

Add Claude ('claudeAgent') provider adapter with full session management, model options, and UI integration

  • Adds a new claudeAgent provider adapter (ClaudeAdapter.ts) wrapping the @anthropic-ai/claude-agent-sdk, supporting streaming, approvals, user-input flows, thinking tokens, resume state, and NDJSON event logging.
  • Registers claudeAgent in the provider registry, health service (CLI availability + auth status checks), and session directory; provider selection, model inference, and legacy mappings are all updated to recognize claudeAgent.
  • Extends shared contracts (orchestration.ts, model.ts) with ClaudeProviderStartOptions, ClaudeModelOptions (effort, thinking, fastMode), CLAUDE_CODE_EFFORT_OPTIONS including 'ultrathink', and Claude model slugs/aliases.
  • Adds composer draft store support for per-provider modelOptions (versioned v2 schema with migration), a ClaudeTraitsPicker UI component, and CodexTraitsPicker refactor to read/write from the store.
  • Routes claudeAgent child conversation notifications to their parent turn in CodexAppServerManager, suppressing lifecycle noise and rewriting turn IDs.
  • Surfaces sourceProposedPlan through projection pipeline, snapshot query, and persistence layers so the sidebar can prefer the in-flight turn's source plan.
  • Adds 'ultrathink' visual treatment in the composer (animated gradient frame, chroma icon effect) and prefixes outgoing prompts when ultrathink effort is selected.
  • Risk: composer draft storage format bumps to v2; existing persisted drafts are migrated on load but legacy effort/codexFastMode fields are removed.
Macroscope summarized bc812e9.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: 28bfb09d-843d-4e79-91f1-1ca466bbaf04

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `codething/648ca884-claude`
      📝 Coding Plan
      • Generate coding plan for human review comments

      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: SDK stream fiber is detached and unmanaged
        • Replaced Effect.runFork with Effect.forkChild to keep the fiber in the managed runtime, stored the fiber reference in session context, and added explicit Fiber.interrupt in stopSessionInternal before queue teardown to eliminate the race window.
      • ✅ Fixed: Identity function adds unnecessary indirection
        • Removed the no-op asCanonicalTurnId identity function and inlined the TurnId value directly at all 10 call sites.

      Create PR

      Or push these changes by commenting:

      @cursor push 2efc9d6c0c
      Preview (pingdotgg/t3code@2efc9d6c0c)
      diff --git a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      --- a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      +++ b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      @@ -34,7 +34,7 @@
         ThreadId,
         TurnId,
       } from "@t3tools/contracts";
      -import { Cause, DateTime, Deferred, Effect, Layer, Queue, Random, Ref, Stream } from "effect";
      +import { Cause, DateTime, Deferred, Effect, Fiber, Layer, Queue, Random, Ref, Stream } from "effect";
       
       import {
         ProviderAdapterProcessError,
      @@ -106,6 +106,7 @@
         lastAssistantUuid: string | undefined;
         lastThreadStartedId: string | undefined;
         stopped: boolean;
      +  streamFiber: Fiber.Fiber<void, never> | undefined;
       }
       
       interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
      @@ -144,10 +145,6 @@
         return RuntimeItemId.makeUnsafe(value);
       }
       
      -function asCanonicalTurnId(value: TurnId): TurnId {
      -  return value;
      -}
      -
       function asRuntimeRequestId(value: ApprovalRequestId): RuntimeRequestId {
         return RuntimeRequestId.makeUnsafe(value);
       }
      @@ -505,7 +502,7 @@
                       ...(typeof message.session_id === "string"
                         ? { providerThreadId: message.session_id }
                         : {}),
      -                ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
      +                ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
                       ...(itemId ? { itemId: ProviderItemId.makeUnsafe(itemId) } : {}),
                       payload: message,
                     },
      @@ -613,7 +610,7 @@
                 provider: PROVIDER,
                 createdAt: stamp.createdAt,
                 threadId: context.session.threadId,
      -          ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),
      +          ...(turnState ? { turnId: turnState.turnId } : {}),
                 payload: {
                   message,
                   class: "provider_error",
      @@ -640,7 +637,7 @@
                 provider: PROVIDER,
                 createdAt: stamp.createdAt,
                 threadId: context.session.threadId,
      -          ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),
      +          ...(turnState ? { turnId: turnState.turnId } : {}),
                 payload: {
                   message,
                   ...(detail !== undefined ? { detail } : {}),
      @@ -855,7 +852,7 @@
                   provider: PROVIDER,
                     createdAt: stamp.createdAt,
                   threadId: context.session.threadId,
      -            ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
      +            ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
                   itemId: asRuntimeItemId(tool.itemId),
                   payload: {
                     itemType: tool.itemType,
      @@ -896,7 +893,7 @@
                   provider: PROVIDER,
                     createdAt: stamp.createdAt,
                   threadId: context.session.threadId,
      -            ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
      +            ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
                   itemId: asRuntimeItemId(tool.itemId),
                   payload: {
                     itemType: tool.itemType,
      @@ -1006,7 +1003,7 @@
                 provider: PROVIDER,
                 createdAt: stamp.createdAt,
                 threadId: context.session.threadId,
      -          ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
      +          ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
                 providerRefs: {
                   ...providerThreadRef(context),
                   ...(context.turnState ? { providerTurnId: context.turnState.turnId } : {}),
      @@ -1165,7 +1162,7 @@
                 provider: PROVIDER,
                 createdAt: stamp.createdAt,
                 threadId: context.session.threadId,
      -          ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
      +          ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
                 providerRefs: {
                   ...providerThreadRef(context),
                   ...(context.turnState ? { providerTurnId: context.turnState.turnId } : {}),
      @@ -1295,6 +1292,11 @@
       
               context.stopped = true;
       
      +        if (context.streamFiber) {
      +          yield* Fiber.interrupt(context.streamFiber);
      +          context.streamFiber = undefined;
      +        }
      +
               for (const [requestId, pending] of context.pendingApprovals) {
                 yield* Deferred.succeed(pending.decision, "cancel");
                 const stamp = yield* makeEventStamp();
      @@ -1304,7 +1306,7 @@
                   provider: PROVIDER,
                     createdAt: stamp.createdAt,
                   threadId: context.session.threadId,
      -            ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
      +            ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
                   requestId: asRuntimeRequestId(requestId),
                   payload: {
                     requestType: pending.requestType,
      @@ -1442,7 +1444,7 @@
                       provider: PROVIDER,
                             createdAt: requestedStamp.createdAt,
                       threadId: context.session.threadId,
      -                ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
      +                ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
                       requestId: asRuntimeRequestId(requestId),
                       payload: {
                         requestType,
      @@ -1494,7 +1496,7 @@
                       provider: PROVIDER,
                             createdAt: resolvedStamp.createdAt,
                       threadId: context.session.threadId,
      -                ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
      +                ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
                       requestId: asRuntimeRequestId(requestId),
                       payload: {
                         requestType,
      @@ -1610,6 +1612,7 @@
                 lastAssistantUuid: resumeState?.resumeSessionAt,
                 lastThreadStartedId: undefined,
                 stopped: false,
      +          streamFiber: undefined,
               };
               yield* Ref.set(contextRef, context);
               sessions.set(threadId, context);
      @@ -1658,7 +1661,7 @@
                 providerRefs: {},
               });
       
      -        Effect.runFork(runSdkStream(context));
      +        context.streamFiber = yield* Effect.forkChild(runSdkStream(context));
       
               return {
                 ...session,
    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/ClaudeCodeAdapter.ts:358

      toSessionError matches any error containing "not found" substring, so errors like "Model not found" or "File not found" are misclassified as ProviderAdapterSessionNotFoundError instead of the correct ProviderAdapterRequestError. This masks the actual root cause. Consider using a more specific pattern like "unknown session" or matching against expected error types rather than substrings.

      No longer relevant as of ff34d2c708e00945ae542e1484739754dd4e9286

    4. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Native event logger missing threadId in event payload
        • Added threadId: context.session.threadId to the event object and passed context.session.threadId instead of null as the second argument to nativeEventLogger.write(), enabling per-thread log routing consistent with the Codex adapter.

      Create PR

      Or push these changes by commenting:

      @cursor push 8489584240
      Preview (pingdotgg/t3code@8489584240)
      diff --git a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      --- a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      +++ b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      @@ -502,6 +502,7 @@
                       provider: PROVIDER,
                       createdAt: observedAt,
                       method: sdkNativeMethod(message),
      +                threadId: context.session.threadId,
                       ...(typeof message.session_id === "string"
                         ? { providerThreadId: message.session_id }
                         : {}),
      @@ -510,7 +511,7 @@
                       payload: message,
                     },
                   },
      -            null,
      +            context.session.threadId,
                 );
             });
    5. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Redundant duplicate threadId assignment in session construction
        • Removed the redundant ...(threadId ? { threadId } : {}) spread at line 1587 since threadId is already set directly at line 1581 and is always defined.

      Create PR

      Or push these changes by commenting:

      @cursor push 1970102289
      Preview (pingdotgg/t3code@1970102289)
      diff --git a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      --- a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      +++ b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      @@ -1584,7 +1584,6 @@
                 runtimeMode: input.runtimeMode,
                 ...(input.cwd ? { cwd: input.cwd } : {}),
                 ...(input.model ? { model: input.model } : {}),
      -          ...(threadId ? { threadId } : {}),
                 resumeCursor: {
                   ...(threadId ? { threadId } : {}),
                   ...(resumeState?.resume ? { resume: resumeState.resume } : {}),
    6. @@ -173,7 +417,12 @@
      173417 }
      174418
      175419 export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
      176- private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
      420+ private readonly sessions = new Map<ThreadId, CodexSessionContext>();
      177421
      178- async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
      179- const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
      422+ private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
      423+ constructor(services?: ServiceMap.ServiceMap<never>) {
      424+ super();
      425+ this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
      426+ }
      427+
      428+ async startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High src/codexAppServerManager.ts:428

      startSession overwrites this.sessions.set(threadId, context) without checking if a session already exists for that threadId. This orphans the previous process (which keeps running) and leaves its exit handler active. When the orphaned process later exits, that handler calls this.sessions.delete(threadId), which removes the new session from the map. Subsequent calls like sendTurn then fail with "Unknown session" because the entry was deleted by the stale handler.

      Also found in 1 other location(s)

      apps/server/src/provider/Layers/CodexAdapter.ts:1262

      The nativeEventLogger created when options.nativeEventLogPath is provided is never closed. While manager is wrapped in Effect.acquireRelease for cleanup, nativeEventLogger is instantiated separately and its close() method is never called. This causes file handles opened by the logger to leak every time the CodexAdapter layer is released (e.g., during configuration reloads or tests).

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/codexAppServerManager.ts around line 428:
      
      `startSession` overwrites `this.sessions.set(threadId, context)` without checking if a session already exists for that `threadId`. This orphans the previous process (which keeps running) and leaves its `exit` handler active. When the orphaned process later exits, that handler calls `this.sessions.delete(threadId)`, which removes the *new* session from the map. Subsequent calls like `sendTurn` then fail with "Unknown session" because the entry was deleted by the stale handler.
      
      Evidence trail:
      apps/server/src/codexAppServerManager.ts: lines 428-471 show `startSession` calls `this.sessions.set(threadId, context)` without checking for existing session; line 943 shows exit handler calls `this.sessions.delete(context.session.threadId)` where `context` is captured in closure; lines 890-893 show `requireSession` throws 'Unknown session' when entry not in map; lines 606-607 show `sendTurn` uses `requireSession`.
      
      Also found in 1 other location(s):
      - apps/server/src/provider/Layers/CodexAdapter.ts:1262 -- The `nativeEventLogger` created when `options.nativeEventLogPath` is provided is never closed. While `manager` is wrapped in `Effect.acquireRelease` for cleanup, `nativeEventLogger` is instantiated separately and its `close()` method is never called. This causes file handles opened by the logger to leak every time the `CodexAdapter` layer is released (e.g., during configuration reloads or tests).
      
      @@ -144,0 +321,21 @@
      321+ result="effect1_foregroundBlur_69_17998"
      322+ stdDeviation="32"
      323+ />
      324+ </filter>
      325+ </defs>
      326+ </svg>
      327+);
      328+
      329+export const OpenCodeIcon: Icon = (props) => (
      330+ <svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
      331+ <g clipPath="url(#opencode__clip0_1311_94969)">
      332+ <path d="M24 32H8V16H24V32Z" fill="#BCBBBB" />
      333+ <path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill="#211E1E" />
      334+ </g>
      335+ <defs>
      336+ <clipPath id="opencode__clip0_1311_94969">
      337+ <rect width="32" height="40" fill="white" />
      338+ </clipPath>
      339+ </defs>
      340+ </svg>
      341+);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low components/Icons.tsx:329

      The OpenCodeIcon component uses hardcoded fill attributes (#211E1E and #BCBBBB) on its SVG paths. In dark mode, the #211E1E dark grey fill renders the icon nearly invisible due to low contrast against dark backgrounds. Unlike GitHubIcon and OpenAI, which use currentColor to inherit the surrounding text color, this icon fails to adapt to the theme.

      -  <svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
      +  <svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
           <g clipPath="url(#opencode__clip0_1311_94969)">
      -      <path d="M24 32H8V16H24V32Z" fill="#BCBBBB" />
      -      <path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill="#211E1E" />
      +      <path d="M24 32H8V16H24V32Z" fill="currentColor" />
      +      <path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill="currentColor" />
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/web/src/components/Icons.tsx around lines 329-341:
      
      The `OpenCodeIcon` component uses hardcoded `fill` attributes (`#211E1E` and `#BCBBBB`) on its SVG paths. In dark mode, the `#211E1E` dark grey fill renders the icon nearly invisible due to low contrast against dark backgrounds. Unlike `GitHubIcon` and `OpenAI`, which use `currentColor` to inherit the surrounding text color, this icon fails to adapt to the theme.
      
      Evidence trail:
      apps/web/src/components/Icons.tsx lines 329-342 (OpenCodeIcon with hardcoded fills #211E1E and #BCBBBB), lines 5-15 (GitHubIcon with fill="currentColor" at line 12), lines 146-150 (OpenAI with fill="currentColor" at line 147). Verified at commit REVIEWED_COMMIT.
    7. @bcherny @ThariqS mind giving this an approval so we know we can ship it safely? Would hate for our users to get banned 😭

    8. I prepared a CI fix PR targeting this branch: #243\n\nIt updates stale ClaudeCodeAdapter test expectations for thread identity/providerThreadId behavior and aligns with current adapter semantics.

    9. maria-rcks closed this

    10. maria-rcks reopened this

    11. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    12. any update? Really want this!

    13. Can't wait to try this out.

    14. Are we just waiting for official approval? I don't have Codex so holding my breath here.

    15. I am working on making this branch compatible with the newer versions since this is very out of date at this point.

    16. I am working on making this branch compatible with the newer versions since this is very out of date at this point.

      Please double check with @juliusmarminge, as it’s currently unclear what the status with Anthropic is.

    17. @akarabach I am mainly updating it because i need it as well.

    18. But of course would love if we finally get some input from Anthropic or Theo and his team.

    19. Almost done. Trying to get the teams feature to work correctly.

      I even implemented Ultrathink: Screenshot 2026-03-15 at 20 51 41

    20. If anyone has some ideas how to represent a team, I would welcome it. This is what I got so far:

      Screenshot 2026-03-15 at 22 06 22

      I will remove the lead as it is the thread you are interacting with, and use the names for each agent that claude gives it. You can click into every agent to see what its doing.

    21. Almost done. Trying to get the teams feature to work correctly.

      I even implemented Ultrathink: Screenshot 2026-03-15 at 20 51 41

      @JustYannicc would you make this available in your fork?

    22. @Ben-Taarit I will file a PR for this branch, so you can use it. I am still trying to make the teams feature work.

    23. Would supporting Claude Code via AWS Bedrock make sense as a separate provider? It's the way we are provided Claude Code in my workplace, and it avoids the legal issues with Claude Code subs?

    24. AWS Bedrock

      I think the idea of building the app around native agents like Claude, Codex, and Gemini makes sense. Each of them is designed to work best with its own model, so leveraging them natively could provide better performance and capabilities.

    25. For anyone that wants to try it already use my branch https://github.com/JustYannicc/t3code/tree/codex/pr-179-refresh

      THE TEAMS FEATURE DOES NOT WORK FULLY YET. Everything else should be fine.

    26. AWS Bedrock

      I think the idea of building the app around native agents like Claude, Codex, and Gemini makes sense. Each of them is designed to work best with its own model, so leveraging them natively could provide better performance and capabilities.

      AWS Bedrock is just an auth provider here, it will still use the same claude code cli/sdk

    27. @JustYannicc picking this up rn, do you have a commit that is just this PR but refreshed on latest main? i don't think we'll ship the teams support (atleast for v1) but can definitely use your rebased one as a start if you have it

    28. maria-rcks assignedJustYannicc

    29. juliusmarminge assignedjuliusmarminge

    30. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      There are 6 total unresolved issues (including 4 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared a fix for 1 of the 2 issues found in the latest run.

      • ✅ Fixed: Claude Code filtered out from available provider options
        • Removed the leftover option.value !== "claudeCode" guard from isAvailableProviderOption so that Claude Code (now marked available: true) is included in AVAILABLE_PROVIDER_OPTIONS and visible in the UI.

      Create PR

      Or push these changes by commenting:

      @cursor push e2ac73d4e9
      Preview (pingdotgg/t3code@e2ac73d4e9)
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      @@ -206,8 +206,7 @@
       
           const desiredRuntimeMode = thread.runtimeMode;
           const currentProvider: ProviderKind | undefined =
      -      thread.session?.providerName === "codex" ||
      -      thread.session?.providerName === "claudeCode"
      +      thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
               ? thread.session.providerName
               : undefined;
           const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
      
      diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx
      --- a/apps/web/src/components/chat/ProviderModelPicker.tsx
      +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx
      @@ -25,7 +25,7 @@
         label: string;
         available: true;
       } {
      -  return option.available && option.value !== "claudeCode";
      +  return option.available;
       }
       
       function resolveModelForProviderPicker(
      
      diff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.ts
      --- a/packages/shared/src/model.test.ts
      +++ b/packages/shared/src/model.test.ts
      @@ -44,9 +44,7 @@
         it("uses provider-specific aliases", () => {
           expect(normalizeModelSlug("sonnet", "claudeCode")).toBe("claude-sonnet-4-6");
           expect(normalizeModelSlug("opus-4.6", "claudeCode")).toBe("claude-opus-4-6");
      -    expect(normalizeModelSlug("claude-haiku-4-5-20251001", "claudeCode")).toBe(
      -      "claude-haiku-4-5",
      -    );
      +    expect(normalizeModelSlug("claude-haiku-4-5-20251001", "claudeCode")).toBe("claude-haiku-4-5");
         });
       });
    31. Cursor Bugbot has reviewed your changes and found 3 potential issues.

      There are 5 total unresolved issues (including 2 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared fixes for all 3 issues found in the latest run.

      • ✅ Fixed: Map mutation during iteration in stopAll and finalizer
        • Snapshot the sessions Map with Array.from(sessions) before iterating in both stopAll and the finalizer to prevent entries being skipped when stopSessionInternal deletes during iteration.
      • ✅ Fixed: Custom model slugs resolve to built-in aliases unexpectedly
        • Changed normalizeCustomModelSlugs to trim and check the raw slug literally against built-ins instead of resolving aliases first, so dated model versions like claude-sonnet-4-6-20251117 are no longer silently dropped.
      • ✅ Fixed: Test asserts wrong model for claudeCode provider start
        • Removed the incorrect model: "gpt-5-codex" assertion from the claudeCode provider selection test since it was a copy-paste artifact and the test validates provider selection, not model resolution.

      Create PR

      Or push these changes by commenting:

      @cursor push 0cebffe67a
      Preview (pingdotgg/t3code@0cebffe67a)
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      @@ -416,7 +416,6 @@
           expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
             provider: "claudeCode",
             cwd: "/tmp/provider-project",
      -      model: "gpt-5-codex",
             runtimeMode: "approval-required",
           });
       
      
      diff --git a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      --- a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      +++ b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      @@ -1816,7 +1816,7 @@
       
           const stopAll: ClaudeCodeAdapterShape["stopAll"] = () =>
             Effect.forEach(
      -        sessions,
      +        Array.from(sessions),
               ([, context]) =>
                 stopSessionInternal(context, {
                   emitExitEvent: true,
      @@ -1826,7 +1826,7 @@
       
           yield* Effect.addFinalizer(() =>
             Effect.forEach(
      -        sessions,
      +        Array.from(sessions),
               ([, context]) =>
                 stopSessionInternal(context, {
                   emitExitEvent: false,
      
      diff --git a/apps/web/src/appSettings.test.ts b/apps/web/src/appSettings.test.ts
      --- a/apps/web/src/appSettings.test.ts
      +++ b/apps/web/src/appSettings.test.ts
      @@ -8,12 +8,11 @@
       } from "./appSettings";
       
       describe("normalizeCustomModelSlugs", () => {
      -  it("normalizes aliases, removes built-ins, and deduplicates values", () => {
      +  it("removes literal built-ins, trims whitespace, and deduplicates values", () => {
           expect(
             normalizeCustomModelSlugs([
               " custom/internal-model ",
               "gpt-5.3-codex",
      -        "5.3",
               "custom/internal-model",
               "",
               null,
      @@ -21,8 +20,10 @@
           ).toEqual(["custom/internal-model"]);
         });
       
      -  it("normalizes provider-specific aliases for claude", () => {
      -    expect(normalizeCustomModelSlugs(["sonnet"], "claudeCode")).toEqual([]);
      +  it("preserves aliases and dated versions as custom models", () => {
      +    expect(normalizeCustomModelSlugs(["claude-sonnet-4-6-20251117"], "claudeCode")).toEqual([
      +      "claude-sonnet-4-6-20251117",
      +    ]);
           expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeCode")).toEqual([
             "claude/custom-sonnet",
           ]);
      
      diff --git a/apps/web/src/appSettings.ts b/apps/web/src/appSettings.ts
      --- a/apps/web/src/appSettings.ts
      +++ b/apps/web/src/appSettings.ts
      @@ -57,18 +57,19 @@
         const builtInModelSlugs = BUILT_IN_MODEL_SLUGS_BY_PROVIDER[provider];
       
         for (const candidate of models) {
      -    const normalized = normalizeModelSlug(candidate, provider);
      +    if (typeof candidate !== "string") continue;
      +    const trimmed = candidate.trim();
           if (
      -      !normalized ||
      -      normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
      -      builtInModelSlugs.has(normalized) ||
      -      seen.has(normalized)
      +      !trimmed ||
      +      trimmed.length > MAX_CUSTOM_MODEL_LENGTH ||
      +      builtInModelSlugs.has(trimmed) ||
      +      seen.has(trimmed)
           ) {
             continue;
           }
       
      -    seen.add(normalized);
      -    normalizedModels.push(normalized);
      +    seen.add(trimmed);
      +    normalizedModels.push(trimmed);
           if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
             break;
           }
      @@ -0,0 +1805,21 @@
      1805+ });
      1806+ });
      1807+
      1808+ const listSessions: ClaudeCodeAdapterShape["listSessions"] = () =>
      1809+ Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session })));
      1810+
      1811+ const hasSession: ClaudeCodeAdapterShape["hasSession"] = (threadId) =>
      1812+ Effect.sync(() => {
      1813+ const context = sessions.get(threadId);
      1814+ return context !== undefined && !context.stopped;
      1815+ });
      1816+
      1817+ const stopAll: ClaudeCodeAdapterShape["stopAll"] = () =>
      1818+ Effect.forEach(
      1819+ sessions,
      1820+ ([, context]) =>
      1821+ stopSessionInternal(context, {
      1822+ emitExitEvent: true,
      1823+ }),
      1824+ { discard: true },
      1825+ );

      Map mutation during iteration in stopAll and finalizer

      Medium Severity

      stopAll and the finalizer iterate over the sessions Map using Effect.forEach, but stopSessionInternal calls sessions.delete(context.session.threadId) on line 1352 during iteration. Mutating a Map while iterating over it can cause entries to be skipped, leading to sessions not being properly cleaned up. The iteration collection needs to be snapshot (e.g., Array.from(sessions)) before iterating.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      @@ -73,3 +77,4 @@
      7377 return normalizedModels;
      7478 }
      7579
      80+function normalizeAppSettings(settings: AppSettings): AppSettings {

      Custom model slugs resolve to built-in aliases unexpectedly

      Medium Severity

      normalizeCustomModelSlugs calls normalizeModelSlug which resolves aliases (e.g., "sonnet" → "claude-sonnet-4-6"). Since the built-in slug set check then matches, user-entered aliases like "sonnet" get silently dropped instead of being stored as custom models. This is correct behavior per the test, but normalizeModelSlug for Claude also means any short alias input (like "opus") will resolve to a built-in slug and get rejected — the user can never add an alias as a custom model. However, a real custom slug like "claude-sonnet-4-6-20251117" would also be resolved to "claude-sonnet-4-6" (a built-in) and silently dropped, preventing users from pinning dated model versions.

      Fix in Cursor Fix in Web
    32. @@ -0,0 +241,21 @@
      241+ }
      242+ if (normalized.includes("websearch") || normalized.includes("web search")) {
      243+ return "web_search";
      244+ }
      245+ if (normalized.includes("image")) {
      246+ return "image_view";
      247+ }
      248+ return "dynamic_tool_call";
      249+}
      250+
      251+function isReadOnlyToolName(toolName: string): boolean {
      252+ const normalized = toolName.toLowerCase();
      253+ return (
      254+ normalized === "read" ||
      255+ normalized.includes("read file") ||
      256+ normalized.includes("view") ||
      257+ normalized.includes("grep") ||
      258+ normalized.includes("glob") ||
      259+ normalized.includes("search")
      260+ );
      261+}

      isReadOnlyToolName misclassifies web search tools as read-only

      Medium Severity

      isReadOnlyToolName uses normalized.includes("search") which matches tool names like "WebSearch" or "web search". Since classifyRequestType checks isReadOnlyToolName first and short-circuits, any tool containing "search" gets classified as file_read_approval instead of being routed through classifyToolItemType which would correctly identify it as web_search. This causes web search tools to get the wrong approval request type.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      @@ -0,0 +1900,21 @@
      1900+ toPermissionMode(providerOptions?.permissionMode) ??
      1901+ (input.runtimeMode === "full-access" ? "bypassPermissions" : undefined);
      1902+
      1903+ const queryOptions: ClaudeQueryOptions = {
      1904+ ...(input.cwd ? { cwd: input.cwd } : {}),
      1905+ ...(input.model ? { model: input.model } : {}),
      1906+ ...(providerOptions?.binaryPath
      1907+ ? { pathToClaudeCodeExecutable: providerOptions.binaryPath }
      1908+ : {}),
      1909+ ...(permissionMode ? { permissionMode } : {}),
      1910+ ...(permissionMode === "bypassPermissions"
      1911+ ? { allowDangerouslySkipPermissions: true }
      1912+ : {}),
      1913+ ...(providerOptions?.maxThinkingTokens !== undefined
      1914+ ? { maxThinkingTokens: providerOptions.maxThinkingTokens }
      1915+ : {}),
      1916+ ...(resumeState?.resume ? { resume: resumeState.resume } : {}),
      1917+ ...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}),
      1918+ includePartialMessages: true,
      1919+ canUseTool,
      1920+ env: process.env,

      Entire process.env passed to Claude query options

      Medium Severity

      The Claude query options pass env: process.env directly, forwarding the server's entire environment (including secrets, API keys, and internal configuration) to the Claude Code subprocess. This could expose sensitive server-side environment variables to the Claude runtime and any tools it invokes.

      Fix in Cursor Fix in Web
      @@ -392,0 +472,21 @@
      472+ if (parsedAuth.attemptedJsonParse) {
      473+ return {
      474+ status: "warning",
      475+ authStatus: "unknown",
      476+ message:
      477+ "Could not verify Claude Code authentication status from JSON output (missing auth marker).",
      478+ };
      479+ }
      480+ if (result.code === 0) {
      481+ return { status: "ready", authStatus: "authenticated" };
      482+ }
      483+
      484+ const detail = detailFromResult(result);
      485+ return {
      486+ status: "warning",
      487+ authStatus: "unknown",
      488+ message: detail
      489+ ? `Could not verify Claude Code authentication status. ${detail}`
      490+ : "Could not verify Claude Code authentication status.",
      491+ };
      492+}

      parseClaudeAuthStatusFromOutput duplicates parseAuthStatusFromOutput logic entirely

      Low Severity

      parseClaudeAuthStatusFromOutput is a near-exact copy of parseAuthStatusFromOutput, with only minor string differences in user-facing messages. Similarly, runClaudeCommand duplicates runCodexCommand with only the binary name changed. A shared parameterized function would reduce maintenance burden and risk of inconsistent fixes.

      Additional Locations (1)
      Fix in Cursor Fix in Web
    33. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 8 total unresolved issues (including 7 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Empty content_block_stop handler does nothing with retrieved tool
        • The content_block_stop handler now finalizes accumulated partial JSON input, updates the tool in inFlightTools, and emits an item.updated event with the complete tool state, following the same pattern as nearby handlers.

      Create PR

      Or push these changes by commenting:

      @cursor push f5a4bbcb1c
      Preview (pingdotgg/t3code@f5a4bbcb1c)
      diff --git a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      --- a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      +++ b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      @@ -1148,6 +1148,52 @@
                 if (!tool) {
                   return;
                 }
      +
      +          let finalTool = tool;
      +          if (tool.partialInputJson.length > 0) {
      +            const parsedInput = tryParseJsonRecord(tool.partialInputJson);
      +            if (parsedInput) {
      +              const detail = summarizeToolRequest(tool.toolName, parsedInput);
      +              finalTool = {
      +                ...tool,
      +                input: parsedInput,
      +                ...(detail ? { detail } : {}),
      +              };
      +              context.inFlightTools.set(index, finalTool);
      +            }
      +          }
      +
      +          const stamp = yield* makeEventStamp();
      +          yield* offerRuntimeEvent({
      +            type: "item.updated",
      +            eventId: stamp.eventId,
      +            provider: PROVIDER,
      +            createdAt: stamp.createdAt,
      +            threadId: context.session.threadId,
      +            ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
      +            itemId: asRuntimeItemId(finalTool.itemId),
      +            payload: {
      +              itemType: finalTool.itemType,
      +              status: "inProgress",
      +              title: finalTool.title,
      +              ...(finalTool.detail ? { detail: finalTool.detail } : {}),
      +              data: {
      +                toolName: finalTool.toolName,
      +                input: finalTool.input,
      +              },
      +            },
      +            providerRefs: {
      +              ...providerThreadRef(context),
      +              ...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}),
      +              providerItemId: ProviderItemId.makeUnsafe(finalTool.itemId),
      +            },
      +            raw: {
      +              source: "claude.sdk.message",
      +              method: "claude/stream_event/content_block_stop",
      +              payload: message,
      +            },
      +          });
      +          return;
               }
             });
      @@ -0,0 +1131,21 @@
      1131+ providerRefs: {
      1132+ ...providerThreadRef(context),
      1133+ ...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}),
      1134+ providerItemId: ProviderItemId.makeUnsafe(tool.itemId),
      1135+ },
      1136+ raw: {
      1137+ source: "claude.sdk.message",
      1138+ method: "claude/stream_event/content_block_start",
      1139+ payload: message,
      1140+ },
      1141+ });
      1142+ return;
      1143+ }
      1144+
      1145+ if (event.type === "content_block_stop") {
      1146+ const { index } = event;
      1147+ const tool = context.inFlightTools.get(index);
      1148+ if (!tool) {
      1149+ return;
      1150+ }
      1151+ }

      Empty content_block_stop handler does nothing with retrieved tool

      Medium Severity

      The content_block_stop handler retrieves a tool from context.inFlightTools but does absolutely nothing with it — no event emission, no state update, no cleanup. After the if (!tool) return; guard, the code just falls through to the end of the enclosing function. This looks like an incomplete implementation where item.completed or some finalization was intended. Currently, in-flight tools are only cleaned up via handleUserMessage (on tool results) or completeTurn (flush at turn end), making this block dead code.

      Fix in Cursor Fix in Web
    34. Bugbot Autofix prepared fixes for all 3 issues found in the latest run.

      • ✅ Fixed: isReadOnlyToolName misclassifies web search tools as read-only
        • Added && !normalized.includes("web") to the search substring check in isReadOnlyToolName so web search tools are no longer short-circuited as read-only and instead flow through classifyToolItemType.
      • ✅ Fixed: parseClaudeAuthStatusFromOutput duplicates parseAuthStatusFromOutput logic entirely
        • Extracted shared parseAuthStatusWithLabels (parameterized by provider-specific labels) and runCliCommand (parameterized by binary name) to eliminate the duplicated functions while preserving the public API.
      • ✅ Fixed: Entire process.env passed to Claude query options
        • Replaced env: process.env with env: createClaudeSpawnEnv(process.env) which filters out T3CODE_* and VITE_* prefixed variables before forwarding to the Claude subprocess.

      Create PR

      Or push these changes by commenting:

      @cursor push b8b3926669
      Preview (pingdotgg/t3code@b8b3926669)
      diff --git a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      --- a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      +++ b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts
      @@ -134,6 +134,19 @@
         readonly nativeEventLogger?: EventNdjsonLogger;
       }
       
      +const CLAUDE_ENV_PREFIX_BLOCKLIST = ["T3CODE_", "VITE_"];
      +
      +function createClaudeSpawnEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
      +  const filtered: NodeJS.ProcessEnv = {};
      +  for (const [key, value] of Object.entries(baseEnv)) {
      +    if (value === undefined) continue;
      +    const upper = key.toUpperCase();
      +    if (CLAUDE_ENV_PREFIX_BLOCKLIST.some((prefix) => upper.startsWith(prefix))) continue;
      +    filtered[key] = value;
      +  }
      +  return filtered;
      +}
      +
       function isUuid(value: string): boolean {
         return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
       }
      @@ -256,7 +269,7 @@
           normalized.includes("view") ||
           normalized.includes("grep") ||
           normalized.includes("glob") ||
      -    normalized.includes("search")
      +    (normalized.includes("search") && !normalized.includes("web"))
         );
       }
       
      @@ -1917,7 +1930,7 @@
                 ...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}),
                 includePartialMessages: true,
                 canUseTool,
      -          env: process.env,
      +          env: createClaudeSpawnEnv(process.env),
                 ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
               };
       
      
      diff --git a/apps/server/src/provider/Layers/ProviderHealth.ts b/apps/server/src/provider/Layers/ProviderHealth.ts
      --- a/apps/server/src/provider/Layers/ProviderHealth.ts
      +++ b/apps/server/src/provider/Layers/ProviderHealth.ts
      @@ -84,7 +84,39 @@
         return undefined;
       }
       
      -export function parseAuthStatusFromOutput(result: CommandResult): {
      +interface ProviderAuthLabels {
      +  readonly unknownCommandMessage: string;
      +  readonly unauthenticatedMessage: string;
      +  readonly jsonParseWarning: string;
      +  readonly verifyFailurePrefix: string;
      +  readonly loginHints: ReadonlyArray<string>;
      +}
      +
      +const CODEX_AUTH_LABELS: ProviderAuthLabels = {
      +  unknownCommandMessage:
      +    "Codex CLI authentication status command is unavailable in this Codex version.",
      +  unauthenticatedMessage: "Codex CLI is not authenticated. Run `codex login` and try again.",
      +  jsonParseWarning:
      +    "Could not verify Codex authentication status from JSON output (missing auth marker).",
      +  verifyFailurePrefix: "Could not verify Codex authentication status",
      +  loginHints: ["run `codex login`", "run codex login"],
      +};
      +
      +const CLAUDE_AUTH_LABELS: ProviderAuthLabels = {
      +  unknownCommandMessage:
      +    "Claude Code authentication status command is unavailable in this version of Claude Code.",
      +  unauthenticatedMessage:
      +    "Claude Code is not authenticated. Run `claude auth login` and try again.",
      +  jsonParseWarning:
      +    "Could not verify Claude Code authentication status from JSON output (missing auth marker).",
      +  verifyFailurePrefix: "Could not verify Claude Code authentication status",
      +  loginHints: ["run `claude login`", "run claude login"],
      +};
      +
      +function parseAuthStatusWithLabels(
      +  result: CommandResult,
      +  labels: ProviderAuthLabels,
      +): {
         readonly status: ServerProviderStatusState;
         readonly authStatus: ServerProviderAuthStatus;
         readonly message?: string;
      @@ -99,7 +131,7 @@
           return {
             status: "warning",
             authStatus: "unknown",
      -      message: "Codex CLI authentication status command is unavailable in this Codex version.",
      +      message: labels.unknownCommandMessage,
           };
         }
       
      @@ -107,13 +139,12 @@
           lowerOutput.includes("not logged in") ||
           lowerOutput.includes("login required") ||
           lowerOutput.includes("authentication required") ||
      -    lowerOutput.includes("run `codex login`") ||
      -    lowerOutput.includes("run codex login")
      +    labels.loginHints.some((hint) => lowerOutput.includes(hint))
         ) {
           return {
             status: "error",
             authStatus: "unauthenticated",
      -      message: "Codex CLI is not authenticated. Run `codex login` and try again.",
      +      message: labels.unauthenticatedMessage,
           };
         }
       
      @@ -139,15 +170,14 @@
           return {
             status: "error",
             authStatus: "unauthenticated",
      -      message: "Codex CLI is not authenticated. Run `codex login` and try again.",
      +      message: labels.unauthenticatedMessage,
           };
         }
         if (parsedAuth.attemptedJsonParse) {
           return {
             status: "warning",
             authStatus: "unknown",
      -      message:
      -        "Could not verify Codex authentication status from JSON output (missing auth marker).",
      +      message: labels.jsonParseWarning,
           };
         }
         if (result.code === 0) {
      @@ -158,12 +188,14 @@
         return {
           status: "warning",
           authStatus: "unknown",
      -    message: detail
      -      ? `Could not verify Codex authentication status. ${detail}`
      -      : "Could not verify Codex authentication status.",
      +    message: detail ? `${labels.verifyFailurePrefix}. ${detail}` : `${labels.verifyFailurePrefix}.`,
         };
       }
       
      +export function parseAuthStatusFromOutput(result: CommandResult) {
      +  return parseAuthStatusWithLabels(result, CODEX_AUTH_LABELS);
      +}
      +
       // ── Codex CLI config detection ──────────────────────────────────────
       
       /**
      @@ -239,10 +271,10 @@
           (acc, chunk) => acc + new TextDecoder().decode(chunk),
         );
       
      -const runCodexCommand = (args: ReadonlyArray<string>) =>
      +const runCliCommand = (binary: string, args: ReadonlyArray<string>) =>
         Effect.gen(function* () {
           const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
      -    const command = ChildProcess.make("codex", [...args], {
      +    const command = ChildProcess.make(binary, [...args], {
             shell: process.platform === "win32",
           });
       
      @@ -260,27 +292,10 @@
           return { stdout, stderr, code: exitCode } satisfies CommandResult;
         }).pipe(Effect.scoped);
       
      -const runClaudeCommand = (args: ReadonlyArray<string>) =>
      -  Effect.gen(function* () {
      -    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
      -    const command = ChildProcess.make("claude", [...args], {
      -      shell: process.platform === "win32",
      -    });
      +const runCodexCommand = (args: ReadonlyArray<string>) => runCliCommand("codex", args);
       
      -    const child = yield* spawner.spawn(command);
      +const runClaudeCommand = (args: ReadonlyArray<string>) => runCliCommand("claude", args);
       
      -    const [stdout, stderr, exitCode] = yield* Effect.all(
      -      [
      -        collectStreamAsString(child.stdout),
      -        collectStreamAsString(child.stderr),
      -        child.exitCode.pipe(Effect.map(Number)),
      -      ],
      -      { concurrency: "unbounded" },
      -    );
      -
      -    return { stdout, stderr, code: exitCode } satisfies CommandResult;
      -  }).pipe(Effect.scoped);
      -
       // ── Health check ────────────────────────────────────────────────────
       
       export const checkCodexProviderStatus: Effect.Effect<
      @@ -409,86 +424,8 @@
       
       // ── Claude Code health check ────────────────────────────────────────
       
      -export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
      -  readonly status: ServerProviderStatusState;
      -  readonly authStatus: ServerProviderAuthStatus;
      -  readonly message?: string;
      -} {
      -  const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
      -
      -  if (
      -    lowerOutput.includes("unknown command") ||
      -    lowerOutput.includes("unrecognized command") ||
      -    lowerOutput.includes("unexpected argument")
      -  ) {
      -    return {
      -      status: "warning",
      -      authStatus: "unknown",
      -      message:
      -        "Claude Code authentication status command is unavailable in this version of Claude Code.",
      -    };
      -  }
      -
      -  if (
      -    lowerOutput.includes("not logged in") ||
      -    lowerOutput.includes("login required") ||
      -    lowerOutput.includes("authentication required") ||
      -    lowerOutput.includes("run `claude login`") ||
      -    lowerOutput.includes("run claude login")
      -  ) {
      -    return {
      -      status: "error",
      -      authStatus: "unauthenticated",
      -      message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
      -    };
      -  }
      -
      -  // `claude auth status` returns JSON with a `loggedIn` boolean.
      -  const parsedAuth = (() => {
      -    const trimmed = result.stdout.trim();
      -    if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
      -      return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
      -    }
      -    try {
      -      return {
      -        attemptedJsonParse: true as const,
      -        auth: extractAuthBoolean(JSON.parse(trimmed)),
      -      };
      -    } catch {
      -      return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
      -    }
      -  })();
      -
      -  if (parsedAuth.auth === true) {
      -    return { status: "ready", authStatus: "authenticated" };
      -  }
      -  if (parsedAuth.auth === false) {
      -    return {
      -      status: "error",
      -      authStatus: "unauthenticated",
      -      message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
      -    };
      -  }
      -  if (parsedAuth.attemptedJsonParse) {
      -    return {
      -      status: "warning",
      -      authStatus: "unknown",
      -      message:
      -        "Could not verify Claude Code authentication status from JSON output (missing auth marker).",
      -    };
      -  }
      -  if (result.code === 0) {
      -    return { status: "ready", authStatus: "authenticated" };
      -  }
      -
      -  const detail = detailFromResult(result);
      -  return {
      -    status: "warning",
      -    authStatus: "unknown",
      -    message: detail
      -      ? `Could not verify Claude Code authentication status. ${detail}`
      -      : "Could not verify Claude Code authentication status.",
      -  };
      +export function parseClaudeAuthStatusFromOutput(result: CommandResult) {
      +  return parseAuthStatusWithLabels(result, CLAUDE_AUTH_LABELS);
       }
       
       export const checkClaudeCodeProviderStatus: Effect.Effect<
    35. @juliusmarminge i can strip out and put it in a sperate branch. give me a sec

    36. i did a lot of work making ti compatible with all the reverse engineered docs that are available.

    37. @juliusmarminge So I filled PR #1146 targeting this branch, excluding the Teams feature which is now in a seperate branch #1145 in drafts targeting main. Will update and fix the teams feature tmr.

    38. @@ -0,0 +1360,21 @@
      1360+ },
      1361+ });
      1362+ return;
      1363+ }
      1364+
      1365+ if (event.type === "content_block_stop") {
      1366+ const { index } = event;
      1367+ const assistantBlock = context.turnState?.assistantTextBlocks.get(index);
      1368+ if (assistantBlock) {
      1369+ assistantBlock.streamClosed = true;
      1370+ yield* completeAssistantTextBlock(context, index, {
      1371+ rawMethod: "claude/stream_event/content_block_stop",
      1372+ rawPayload: message,
      1373+ });
      1374+ return;
      1375+ }
      1376+ const tool = context.inFlightTools.get(index);
      1377+ if (!tool) {
      1378+ return;
      1379+ }
      1380+ }

      Dead code in tool content_block_stop handler

      Low Severity

      In handleStreamEvent, when a content_block_stop event fires for a tool-use block (not an assistant text block), the code looks up the tool via context.inFlightTools.get(index) but does absolutely nothing with the result. The if (!tool) { return; } guard exits early if the tool is missing, but when the tool IS found, execution falls through to the end of the function with no tool-specific action taken. This dead branch is confusing and suggests missing logic for handling tool stream closure.

      Fix in Cursor Fix in Web
    39. @@ -0,0 +2392,21 @@
      2392+
      2393+ const turnStartedStamp = yield* makeEventStamp();
      2394+ yield* offerRuntimeEvent({
      2395+ type: "turn.started",
      2396+ eventId: turnStartedStamp.eventId,
      2397+ provider: PROVIDER,
      2398+ createdAt: turnStartedStamp.createdAt,
      2399+ threadId: context.session.threadId,
      2400+ turnId,
      2401+ payload: input.model ? { model: input.model } : {},
      2402+ providerRefs: {
      2403+ providerTurnId: String(turnId),
      2404+ },
      2405+ });
      2406+
      2407+ const message = buildUserMessage(input);
      2408+
      2409+ yield* Queue.offer(context.promptQueue, {
      2410+ type: "message",
      2411+ message,
      2412+ }).pipe(Effect.mapError((cause) => toRequestError(input.threadId, "turn/start", cause)));
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/ClaudeAdapter.ts:2409

      Queue.offer returns Effect<boolean> where false means the queue was shutdown. The current code ignores this boolean and only maps the error channel, so when the session is stopping and the queue is shutdown, the message is silently dropped but sendTurn still returns a successful ProviderTurnStartResult. The caller believes the turn started when the message was never queued. Consider checking the boolean result and failing with an appropriate error when the queue is shutdown.

      -        yield* Queue.offer(context.promptQueue, {
      -          type: "message",
      -          message,
      -        }).pipe(Effect.mapError((cause) => toRequestError(input.threadId, "turn/start", cause)));
      +        const offered = yield* Queue.offer(context.promptQueue, {
      +          type: "message",
      +          message,
      +        });
      +        if (!offered) {
      +          return yield* new ProviderAdapterRequestError({
      +            provider: PROVIDER,
      +            method: "turn/start",
      +            detail: "Failed to queue message: prompt queue is shutdown.",
      +          });
      +        }
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/ClaudeAdapter.ts around lines 2409-2412:
      
      `Queue.offer` returns `Effect<boolean>` where `false` means the queue was shutdown. The current code ignores this boolean and only maps the error channel, so when the session is stopping and the queue is shutdown, the message is silently dropped but `sendTurn` still returns a successful `ProviderTurnStartResult`. The caller believes the turn started when the message was never queued. Consider checking the boolean result and failing with an appropriate error when the queue is shutdown.
      
      Evidence trail:
      - Reviewed code: `apps/server/src/provider/Layers/ClaudeAdapter.ts` lines 2409-2420 (REVIEWED_COMMIT)
      - Same codebase pattern for handling Queue.offer boolean: `packages/shared/src/DrainableWorker.ts` lines 90-93 - shows `const accepted = yield* Queue.offer(queue, item); if (!accepted) { ... }`
      - Effect-TS Queue.offer behavior is confirmed by the codebase's own usage pattern which captures and checks the boolean return value
    40. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 7 total unresolved issues (including 6 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Approval events use orchestration ID as provider thread ID
        • Replaced four direct uses of context.session.threadId as providerThreadId with the providerThreadRef(context) helper, consistent with all other event emissions in the file.

      Create PR

      Or push these changes by commenting:

      @cursor push 241180f045
      Preview (pingdotgg/t3code@241180f045)
      diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts
      --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts
      +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts
      @@ -1995,7 +1995,7 @@
                     requestId: asRuntimeRequestId(requestId),
                     payload: { questions },
                     providerRefs: {
      -                ...(context.session.threadId ? { providerThreadId: context.session.threadId } : {}),
      +                ...providerThreadRef(context),
                       ...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}),
                       providerRequestId: requestId,
                     },
      @@ -2034,7 +2034,7 @@
                     requestId: asRuntimeRequestId(requestId),
                     payload: { answers },
                     providerRefs: {
      -                ...(context.session.threadId ? { providerThreadId: context.session.threadId } : {}),
      +                ...providerThreadRef(context),
                       ...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}),
                       providerRequestId: requestId,
                     },
      @@ -2116,9 +2116,7 @@
                         },
                       },
                       providerRefs: {
      -                  ...(context.session.threadId
      -                    ? { providerThreadId: context.session.threadId }
      -                    : {}),
      +                  ...providerThreadRef(context),
                         ...(context.turnState
                           ? { providerTurnId: String(context.turnState.turnId) }
                           : {}),
      @@ -2167,9 +2165,7 @@
                         decision,
                       },
                       providerRefs: {
      -                  ...(context.session.threadId
      -                    ? { providerThreadId: context.session.threadId }
      -                    : {}),
      +                  ...providerThreadRef(context),
                         ...(context.turnState
                           ? { providerTurnId: String(context.turnState.turnId) }
                           : {}),
      apps/server/src/provider/Layers/ClaudeAdapter.ts line 1998OutdatedResolvedby juliusmarminge
    41. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 7 total unresolved issues (including 6 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Codex model name passed to Claude on provider switch
        • When a provider is explicitly requested and differs from the current provider (or no session exists), the code now falls back to DEFAULT_MODEL_BY_PROVIDER for the target provider instead of carrying over the thread's existing model slug.

      Create PR

      Or push these changes by commenting:

      @cursor push 5b9f3fb2e9
      Preview (pingdotgg/t3code@5b9f3fb2e9)
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      @@ -416,7 +416,7 @@
           expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
             provider: "claudeAgent",
             cwd: "/tmp/provider-project",
      -      model: "gpt-5-codex",
      +      model: "claude-sonnet-4-6",
             runtimeMode: "approval-required",
           });
       
      
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      @@ -1,6 +1,7 @@
       import {
         type ChatAttachment,
         CommandId,
      +  DEFAULT_MODEL_BY_PROVIDER,
         EventId,
         type OrchestrationEvent,
         type ProviderModelOptions,
      @@ -211,7 +212,11 @@
             ? thread.session.providerName
             : undefined;
           const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
      -    const desiredModel = options?.model ?? thread.model;
      +    const providerIsChanging =
      +      options?.provider !== undefined && options.provider !== currentProvider;
      +    const desiredModel =
      +      options?.model ??
      +      (providerIsChanging ? DEFAULT_MODEL_BY_PROVIDER[options.provider!] : thread.model);
           const effectiveCwd = resolveThreadWorkspaceCwd({
             thread,
             projects: readModel.projects,
    42. @@ -0,0 +1775,21 @@
      1775+ Effect.gen(function* () {
      1776+ if (Cause.hasInterruptsOnly(cause) || context.stopped) {
      1777+ return;
      1778+ }
      1779+ const message = toMessage(Cause.squash(cause), "Claude runtime stream failed.");
      1780+ yield* emitRuntimeError(context, message, cause);
      1781+ yield* completeTurn(context, "failed", message);
      1782+ }),
      1783+ ),
      1784+ );
      1785+
      1786+ const stopSessionInternal = (
      1787+ context: ClaudeSessionContext,
      1788+ options?: { readonly emitExitEvent?: boolean },
      1789+ ): Effect.Effect<void> =>
      1790+ Effect.gen(function* () {
      1791+ if (context.stopped) return;
      1792+
      1793+ context.stopped = true;
      1794+
      1795+ for (const [requestId, pending] of context.pendingApprovals) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/ClaudeAdapter.ts:1795

      In stopSessionInternal, pendingApprovals are resolved and cleaned up (lines 1795-1813), but pendingUserInputs is not handled. If a session is stopped while handleAskUserQuestion is waiting for user input, and the SDK's abort signal does not fire, the Deferred.await(answersDeferred) at line 1969 will never resolve, causing the fiber inside Effect.runPromise (line 2005) to hang indefinitely.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/ClaudeAdapter.ts around line 1795:
      
      In `stopSessionInternal`, `pendingApprovals` are resolved and cleaned up (lines 1795-1813), but `pendingUserInputs` is not handled. If a session is stopped while `handleAskUserQuestion` is waiting for user input, and the SDK's abort signal does not fire, the `Deferred.await(answersDeferred)` at line 1969 will never resolve, causing the fiber inside `Effect.runPromise` (line 2005) to hang indefinitely.
      
      Evidence trail:
      apps/server/src/provider/Layers/ClaudeAdapter.ts lines 1785-1848 (`stopSessionInternal` function showing `pendingApprovals` cleanup at 1794-1813 but no `pendingUserInputs` handling); lines 120-130 (context type definition showing both `pendingApprovals` and `pendingUserInputs`); lines 1920-1975 (`handleAskUserQuestion` showing `Deferred.await(answersDeferred)` at line 1969 and abort signal handler at lines 1959-1966)
    43. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 6 total unresolved issues (including 5 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: preferredProvider fallback chain contains dead code path
        • Removed the dead options?.provider operand from the nullish coalescing chain, simplifying it to currentProvider ?? threadProvider which is behaviorally identical.

      Create PR

      Or push these changes by commenting:

      @cursor push a98a939d9b
      Preview (pingdotgg/t3code@a98a939d9b)
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      @@ -229,7 +229,7 @@
               detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
             });
           }
      -    const preferredProvider: ProviderKind = currentProvider ?? options?.provider ?? threadProvider;
      +    const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
           const desiredModel = options?.model ?? thread.model;
           const effectiveCwd = resolveThreadWorkspaceCwd({
             thread,
    44. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 6 total unresolved issues (including 5 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Turn start error handler catches interrupts as failures
        • Added a Cause.hasInterruptsOnly check in the inner catchCause handler to re-propagate interrupt causes instead of converting them into spurious provider.turn.start.failed activities.

      Create PR

      Or push these changes by commenting:

      @cursor push ae48a85907
      Preview (pingdotgg/t3code@ae48a85907)
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      @@ -498,16 +498,19 @@
             interactionMode: event.payload.interactionMode,
             createdAt: event.payload.createdAt,
           }).pipe(
      -      Effect.catchCause((cause) =>
      -        appendProviderFailureActivity({
      +      Effect.catchCause((cause) => {
      +        if (Cause.hasInterruptsOnly(cause)) {
      +          return Effect.failCause(cause);
      +        }
      +        return appendProviderFailureActivity({
                 threadId: event.payload.threadId,
                 kind: "provider.turn.start.failed",
                 summary: "Provider turn start failed",
                 detail: Cause.pretty(cause),
                 turnId: null,
                 createdAt: event.payload.createdAt,
      -        }),
      -      ),
      +        });
      +      }),
           );
         });
      @@ -475,4 +497,15 @@
      475497 : {}),
      476498 interactionMode: event.payload.interactionMode,
      477499 createdAt: event.payload.createdAt,
      478- });
      500+ }).pipe(
      501+ Effect.catchCause((cause) =>
      502+ appendProviderFailureActivity({
      503+ threadId: event.payload.threadId,
      504+ kind: "provider.turn.start.failed",
      505+ summary: "Provider turn start failed",
      506+ detail: Cause.pretty(cause),
      507+ turnId: null,
      508+ createdAt: event.payload.createdAt,
      509+ }),
      510+ ),
      511+ );

      Turn start error handler catches interrupts as failures

      Low Severity

      The new Effect.catchCause wrapper around sendTurnForThread catches all causes including interrupts. When a fiber is interrupted (e.g., during shutdown), this creates a spurious provider.turn.start.failed activity instead of allowing the interrupt to propagate. The outer processDomainEventSafely handler already filters interrupts via Cause.hasInterruptsOnly, but this inner handler runs first and swallows them.

      Fix in Cursor Fix in Web
    45. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 6 total unresolved issues (including 5 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Redundant variable always equals existing value
        • Removed the redundant preferredProvider variable and replaced its two usages with threadProvider, which is always equal.

      Create PR

      Or push these changes by commenting:

      @cursor push 7b50561688
      Preview (pingdotgg/t3code@7b50561688)
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      @@ -229,7 +229,6 @@
               detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
             });
           }
      -    const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
           const desiredModel = options?.model ?? thread.model;
           const effectiveCwd = resolveThreadWorkspaceCwd({
             thread,
      @@ -247,8 +246,8 @@
           }) =>
             providerService.startSession(threadId, {
               threadId,
      -        ...((input?.provider ?? preferredProvider)
      -          ? { provider: input?.provider ?? preferredProvider }
      +        ...((input?.provider ?? threadProvider)
      +          ? { provider: input?.provider ?? threadProvider }
                 : {}),
               ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
               ...(desiredModel ? { model: desiredModel } : {}),
    46. @JustYannicc should the ultrathink UI trigger here?

      CleanShot 2026-03-17 at 13 26 13@2x
    47. @@ -0,0 +2491,21 @@
      2491+
      2492+ const stopAll: ClaudeAdapterShape["stopAll"] = () =>
      2493+ Effect.forEach(
      2494+ sessions,
      2495+ ([, context]) =>
      2496+ stopSessionInternal(context, {
      2497+ emitExitEvent: true,
      2498+ }),
      2499+ { discard: true },
      2500+ );
      2501+
      2502+ yield* Effect.addFinalizer(() =>
      2503+ Effect.forEach(
      2504+ sessions,
      2505+ ([, context]) =>
      2506+ stopSessionInternal(context, {
      2507+ emitExitEvent: false,
      2508+ }),
      2509+ { discard: true },
      2510+ ).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))),
      2511+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/ClaudeAdapter.ts:2502

      When nativeEventLogPath is provided, makeClaudeAdapter creates an EventNdjsonLogger internally at line 644, but the finalizer (lines 2502-2511) never calls nativeEventLogger.close(). This leaves file handles held by the logger's thread writers open until process exit. Consider calling nativeEventLogger.close() in the finalizer when the logger was created internally.

          yield* Effect.addFinalizer(() =>
            Effect.forEach(
              sessions,
              ([, context]) =>
                stopSessionInternal(context, {
                  emitExitEvent: false,
                }),
              { discard: true },
      -      ).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))),
      +      ).pipe(
      +        Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
      +        Effect.tap(() =>
      +          nativeEventLogger ? nativeEventLogger.close() : Effect.void
      +        )
      +      ),
          );
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/ClaudeAdapter.ts around lines 2502-2511:
      
      When `nativeEventLogPath` is provided, `makeClaudeAdapter` creates an `EventNdjsonLogger` internally at line 644, but the finalizer (lines 2502-2511) never calls `nativeEventLogger.close()`. This leaves file handles held by the logger's thread writers open until process exit. Consider calling `nativeEventLogger.close()` in the finalizer when the logger was created internally.
      
      Evidence trail:
      - apps/server/src/provider/Layers/ClaudeAdapter.ts lines 641-646 (REVIEWED_COMMIT): Shows `nativeEventLogger` is created internally via `makeEventNdjsonLogger` when `nativeEventLogPath` is provided
      - apps/server/src/provider/Layers/ClaudeAdapter.ts lines 2502-2511 (REVIEWED_COMMIT): Finalizer only stops sessions and shuts down queue, no `nativeEventLogger.close()` call
      - apps/server/src/provider/Layers/EventNdjsonLogger.ts lines 25-29, 188-195 (REVIEWED_COMMIT): Shows `EventNdjsonLogger` interface has a `close()` method that closes all thread writers
      - git_grep for `nativeEventLogger.close` in ClaudeAdapter.ts: No results, confirming `close()` is never called
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      https://github.com/pingdotgg/t3code/blob/e6254a8451699c02ecdb0f96ccf240b638e3e429/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts#L595

      The if (!isUnknownPendingApprovalRequestError(cause)) return; statement at line 596 is dead code — there are no subsequent statements in the generator, so the return has no effect and the generator completes with void either way. This appears to be incomplete logic where additional handling was intended for the unknown pending approval request case.

      No longer relevant as of e41830f5dfb7201a5f5e5f2e7bae0e9b8d3e997d

      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/e6254a8451699c02ecdb0f96ccf240b638e3e429/apps/server/src/provider/Layers/ProviderService.ts#L247

      In recoverSessionForThread, upsertSessionBinding is called at line 247 without passing persistedModelOptions and persistedProviderOptions, even though these values were extracted and used to start the session. After recovery, the runtime payload drops these options, so subsequent operations that read the persisted binding won't see the original model/provider configuration.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/ProviderService.ts around line 247:
      
      In `recoverSessionForThread`, `upsertSessionBinding` is called at line 247 without passing `persistedModelOptions` and `persistedProviderOptions`, even though these values were extracted and used to start the session. After recovery, the runtime payload drops these options, so subsequent operations that read the persisted binding won't see the original model/provider configuration.
      
      Evidence trail:
      apps/server/src/provider/Layers/ProviderService.ts lines 229-230 (extraction of persistedModelOptions and persistedProviderOptions), lines 234-235 (passing them to startSession), line 247 (upsertSessionBinding called without extra parameter), lines 162-177 (upsertSessionBinding signature showing optional extra parameter), lines 88-99 (toRuntimePayloadFromSession showing options only included if extra is provided), lines 308-311 (startSession correctly passing options to upsertSessionBinding)
    48. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 10 total unresolved issues (including 9 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: New Claude unit tests broken by their own provider validation
        • Each Claude test now creates a dedicated thread with model "claude-sonnet-4-6" so that inferProviderForModel returns "claudeAgent" and the provider validation passes, allowing sessions to start correctly.

      Create PR

      Or push these changes by commenting:

      @cursor push cda0e97dae
      Preview (pingdotgg/t3code@cda0e97dae)
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      @@ -357,9 +357,25 @@
       
           await Effect.runPromise(
             harness.engine.dispatch({
      +        type: "thread.create",
      +        commandId: CommandId.makeUnsafe("cmd-thread-create-claude"),
      +        threadId: ThreadId.makeUnsafe("thread-claude"),
      +        projectId: asProjectId("project-1"),
      +        title: "Claude Thread",
      +        model: "claude-sonnet-4-6",
      +        interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
      +        runtimeMode: "approval-required",
      +        branch: null,
      +        worktreePath: null,
      +        createdAt: now,
      +      }),
      +    );
      +
      +    await Effect.runPromise(
      +      harness.engine.dispatch({
               type: "thread.turn.start",
               commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
      -        threadId: ThreadId.makeUnsafe("thread-1"),
      +        threadId: ThreadId.makeUnsafe("thread-claude"),
               message: {
                 messageId: asMessageId("user-message-claude-effort"),
                 role: "user",
      @@ -391,7 +407,7 @@
             },
           });
           expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
      -      threadId: ThreadId.makeUnsafe("thread-1"),
      +      threadId: ThreadId.makeUnsafe("thread-claude"),
             model: "claude-sonnet-4-6",
             modelOptions: {
               claudeAgent: {
      @@ -587,9 +603,25 @@
       
           await Effect.runPromise(
             harness.engine.dispatch({
      +        type: "thread.create",
      +        commandId: CommandId.makeUnsafe("cmd-thread-create-claude-restart"),
      +        threadId: ThreadId.makeUnsafe("thread-claude-restart"),
      +        projectId: asProjectId("project-1"),
      +        title: "Claude Restart Thread",
      +        model: "claude-sonnet-4-6",
      +        interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
      +        runtimeMode: "approval-required",
      +        branch: null,
      +        worktreePath: null,
      +        createdAt: now,
      +      }),
      +    );
      +
      +    await Effect.runPromise(
      +      harness.engine.dispatch({
               type: "thread.turn.start",
               commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
      -        threadId: ThreadId.makeUnsafe("thread-1"),
      +        threadId: ThreadId.makeUnsafe("thread-claude-restart"),
               message: {
                 messageId: asMessageId("user-message-claude-effort-1"),
                 role: "user",
      @@ -616,7 +648,7 @@
             harness.engine.dispatch({
               type: "thread.turn.start",
               commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"),
      -        threadId: ThreadId.makeUnsafe("thread-1"),
      +        threadId: ThreadId.makeUnsafe("thread-claude-restart"),
               message: {
                 messageId: asMessageId("user-message-claude-effort-2"),
                 role: "user",

Sign in to join this conversation.