Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat: add Cursor adapter #178

Closedjuliusmarmingewants to merge 73 commits intomain fromcodething/648ca884-cursoropened View on GitHub

juliusmarmingecommented

Summary

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

It includes:

  • the Cursor provider adapter and service layer
  • provider registry/server-layer wiring for Cursor
  • Cursor 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 provider that spawns and controls an external agent acp process, including permission/approval handling and session persistence, and touches orchestration routing/model switching logic. Failures or mismapped events/approvals could affect turn lifecycle, security posture (auto-approval in full-access), and session recovery across providers.

Overview Adds a first-class cursor provider backed by Cursor ACP (agent acp): introduces CursorAdapterLive to spawn the ACP subprocess, perform initialize/authenticate, create or session/load sessions for resume, translate ACP session/update + permission requests into canonical ProviderRuntimeEvents, and handle approvals via respondToRequest (with auto-approval in full-access).

Wires Cursor through server + contracts + orchestration + web: registers cursor in ProviderKind, provider registry and session directory persistence, and server layer composition; updates ProviderCommandReactor to honor an explicit provider on turn start and to treat Cursor model switching as unsupported (no restart). Web UI gains Cursor availability, Cursor model family + trait selection (reasoning/fast/thinking), provider-specific custom model storage, and disables Cursor model changes after a thread starts.

Adds/updates tests across adapter schemas, adapter behavior (resume + permissions), orchestration/provider routing, and updates docs/scripts for ACP probing.

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

Note

Add Cursor ACP provider adapter and migrate provider runtime to thread-scoped IDs with runtime/interaction modes across server, web, and contracts

Introduce a new CursorAdapter with JSON-RPC stdio transport, register it in the provider registry, and refactor provider/session APIs to key by threadId with runtimeMode/interactionMode; canonicalize runtime events and schemas, add proposed plan projections, and update web UI to support provider-aware model selection (codex/claudeCode/cursor), plan mode, and structured user-input responses.

📍Where to Start

Start with the adapter entry point makeCursorAdapterLive in CursorAdapter.ts, then follow runtime ingestion in ProviderRuntimeIngestion.ts and orchestration command handling in decider.ts.

Macroscope summarized 05f4cb2.
    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: cbc2e528-7f64-461f-a2fa-bbe17861ba0f

      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
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `codething/648ca884-cursor`

      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: Native event logger always writes to global segment
        • Changed the second argument of nativeEventLogger.write() from null to context.session.threadId so native events are routed to per-thread log files.
      • ✅ Fixed: Unexpected process exit leaves pending requests hanging
        • Added pending request draining (clear timeouts and reject promises) in the child process exit handler, matching the pattern already used in stopSessionInternal.

      Create PR

      Or push these changes by commenting:

      @cursor push 68b256ee89
      Preview (pingdotgg/t3code@68b256ee89)
      diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts
      --- a/apps/server/src/provider/Layers/CursorAdapter.ts
      +++ b/apps/server/src/provider/Layers/CursorAdapter.ts
      @@ -830,7 +830,7 @@
                           payload: message,
                         },
                       },
      -                null,
      +                context.session.threadId,
                     ),
                 );
               } catch {
      @@ -1063,6 +1063,12 @@
                 }
                 Effect.runFork(
                   Effect.gen(function* () {
      +              for (const pending of context.pending.values()) {
      +                clearTimeout(pending.timeout);
      +                pending.reject(new Error("Cursor ACP process exited unexpectedly."));
      +              }
      +              context.pending.clear();
      +
                     if (context.turnState) {
                       yield* completeTurn(
                         context,
    3. @@ -0,0 +201,21 @@
      201+ return "file_change_approval";
      202+ }
      203+ return "unknown";
      204+}
      205+
      206+function selectCursorPermissionOption(
      207+ options: ReadonlyArray<{ optionId: string }>,
      208+ decision: "acceptForSession" | "accept" | "decline" | "cancel",
      209+): string | undefined {
      210+ const allowAlways = options.find((option) => option.optionId === "allow-always");
      211+ const allowOnce = options.find((option) => option.optionId === "allow-once");
      212+ const rejectOnce = options.find((option) => option.optionId === "reject-once");
      213+
      214+ if (decision === "acceptForSession") {
      215+ return allowAlways?.optionId ?? allowOnce?.optionId;
      216+ }
      217+ if (decision === "accept") {
      218+ return allowOnce?.optionId ?? allowAlways?.optionId;
      219+ }
      220+ return rejectOnce?.optionId ?? options[0]?.optionId;
      221+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/CursorAdapter.ts:206

      In selectCursorPermissionOption, when decision is "decline" or "cancel", the function falls back to options[0]?.optionId if no "reject-once" option exists. If the provider only sends approval options (e.g., ["allow-once"]), this returns an approval option for a rejection decision, silently inverting the user's intent and potentially authorizing unwanted tool execution. Consider validating that the selected option ID actually corresponds to the intended decision, and fail the request if no appropriate option is available.

      -function selectCursorPermissionOption(
      -  options: ReadonlyArray<{ optionId: string }>,
      -  decision: "acceptForSession" | "accept" | "decline" | "cancel",
      -): string | undefined {
      -  const allowAlways = options.find((option) => option.optionId === "allow-always");
      -  const allowOnce = options.find((option) => option.optionId === "allow-once");
      -  const rejectOnce = options.find((option) => option.optionId === "reject-once");
      -
      -  if (decision === "acceptForSession") {
      -    return allowAlways?.optionId ?? allowOnce?.optionId;
      -  }
      -  if (decision === "accept") {
      -    return allowOnce?.optionId ?? allowAlways?.optionId;
      -  }
      -  return rejectOnce?.optionId ?? options[0]?.optionId;
      -}
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/CursorAdapter.ts around lines 206-221:
      
      In `selectCursorPermissionOption`, when `decision` is `"decline"` or `"cancel"`, the function falls back to `options[0]?.optionId` if no `"reject-once"` option exists. If the provider only sends approval options (e.g., `["allow-once"]`), this returns an approval option for a rejection decision, silently inverting the user's intent and potentially authorizing unwanted tool execution. Consider validating that the selected option ID actually corresponds to the intended decision, and fail the request if no appropriate option is available.
      
      Evidence trail:
      apps/server/src/provider/Layers/CursorAdapter.ts lines 206-221 (function definition with fallback logic at line 220), lines 1437-1454 (usage of the function where optionId is sent to Cursor without validation that it semantically matches the user's decision).
      @@ -0,0 +959,21 @@
      959+ }
      960+ return Effect.succeed(context);
      961+ };
      962+
      963+ const startSession: CursorAdapterShape["startSession"] = (input) =>
      964+ Effect.gen(function* () {
      965+ if (input.provider !== undefined && input.provider !== PROVIDER) {
      966+ return yield* new ProviderAdapterValidationError({
      967+ provider: PROVIDER,
      968+ operation: "startSession",
      969+ issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
      970+ });
      971+ }
      972+
      973+ const startedAt = yield* nowIso;
      974+ const cwd = input.cwd ?? process.cwd();
      975+ const cursorOptions = input.providerOptions?.cursor as { binaryPath?: string } | undefined;
      976+ const binaryPath = cursorOptions?.binaryPath ?? "agent";
      977+ const resumeState = readCursorResumeState(input.resumeCursor);
      978+
      979+ const child = yield* Effect.try({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/CursorAdapter.ts:979

      In startSession, if initialize, authenticate, or session/new throws, the spawned child process is never killed and sessions retains a partially initialized entry. Retrying the same threadId then overwrites the stale entry without stopping its process, leaking zombie processes. Consider wrapping the initialization sequence in a try/finally or using Effect.acquireRelease to ensure stopSessionInternal runs on failure.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/CursorAdapter.ts around line 979:
      
      In `startSession`, if `initialize`, `authenticate`, or `session/new` throws, the spawned child process is never killed and `sessions` retains a partially initialized entry. Retrying the same `threadId` then overwrites the stale entry without stopping its process, leaking zombie processes. Consider wrapping the initialization sequence in a try/finally or using `Effect.acquireRelease` to ensure `stopSessionInternal` runs on failure.
      
      Evidence trail:
      apps/server/src/provider/Layers/CursorAdapter.ts lines 979-995 (child process spawned), line 1092 (session stored before initialization), lines 1094-1220 (initialization sequence that can fail), lines 892-938 (stopSessionInternal that would clean up but is never called on failure). Commit: REVIEWED_COMMIT
    4. @@ -0,0 +70,21 @@
      70+ this.#child = spawn("agent", ["acp"], {
      71+ stdio: ["pipe", "pipe", "pipe"],
      72+ env: {
      73+ ...process.env,
      74+ NO_COLOR: "1",
      75+ },
      76+ });
      77+
      78+ this.#stdoutRl = readline.createInterface({ input: this.#child.stdout });
      79+ this.#stderrRl = readline.createInterface({ input: this.#child.stderr });
      80+
      81+ this.#stdoutRl.on("line", (line) => this.#handleStdoutLine(line));
      82+ this.#stderrRl.on("line", (line) => {
      83+ this.#onMessage({
      84+ ts: nowIso(),
      85+ channel: "stderr",
      86+ line,
      87+ });
      88+ });
      89+
      90+ this.#child.once("exit", (code, signal) => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low scripts/cursor-acp-probe.mjs:90

      spawn("agent", ...) at line 70 can emit an error event (e.g., ENOENT if the command is not found), but AcpProbeClient registers no error handler on this.#child. An unhandled error event on a child process throws an uncaught exception that crashes the process.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file scripts/cursor-acp-probe.mjs around line 90:
      
      `spawn("agent", ...)` at line 70 can emit an `error` event (e.g., `ENOENT` if the command is not found), but `AcpProbeClient` registers no `error` handler on `this.#child`. An unhandled `error` event on a child process throws an uncaught exception that crashes the process.
      
      Evidence trail:
      scripts/cursor-acp-probe.mjs lines 70-103 (REVIEWED_COMMIT) - spawn() call at lines 70-76, handlers registered for readline 'line' and child 'exit' events, but no 'error' handler on this.#child. git_grep for 'on(.*error' in the file returned no results, confirming no error handler exists.
    5. Cursor Bugbot has reviewed your changes and found 3 potential issues.

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

      • ✅ Fixed: Claude Code vanishes from provider picker menu
        • Added Claude Code to COMING_SOON_PROVIDER_OPTIONS so it renders in the picker with a 'Coming soon' badge, since it has available: false and was excluded from AVAILABLE_PROVIDER_OPTIONS.
      • ✅ Fixed: sendTurn overwrites completeTurn's session error status
        • Removed the redundant session status/activeTurnId/updatedAt overwrite after completeTurn, keeping only the resumeCursor addition that was the block's unique contribution.
      • ✅ Fixed: summarizeToolOutput called twice redundantly on same input
        • Cached the result of summarizeToolOutput(update.rawOutput) in a local variable before using it in the conditional spread.

      Create PR

      Or push these changes by commenting:

      @cursor push 7ffed19c49
      Preview (pingdotgg/t3code@7ffed19c49)
      diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts
      --- a/apps/server/src/provider/Layers/CursorAdapter.ts
      +++ b/apps/server/src/provider/Layers/CursorAdapter.ts
      @@ -752,6 +752,7 @@
                   const title = trackedTool?.title ?? titleForItemType(itemType);
                   const stamp = yield* makeEventStamp();
                   const eventType = update.status === "completed" ? "item.completed" : "item.updated";
      +            const toolSummary = summarizeToolOutput(update.rawOutput);
                   yield* offerRuntimeEvent({
                     ...base,
                     type: eventType,
      @@ -763,9 +764,7 @@
                       itemType,
                       status,
                       title,
      -                ...(summarizeToolOutput(update.rawOutput)
      -                  ? { detail: summarizeToolOutput(update.rawOutput) }
      -                  : {}),
      +                ...(toolSummary ? { detail: toolSummary } : {}),
                       ...(update.rawOutput !== undefined ? { data: update.rawOutput } : {}),
                     },
                   });
      @@ -1351,9 +1350,6 @@
       
               context.session = {
                 ...context.session,
      -          status: "ready",
      -          activeTurnId: undefined,
      -          updatedAt: yield* nowIso,
                 resumeCursor: {
                   acpSessionId: context.acpSessionId,
                 },
      
      diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
      --- a/apps/web/src/components/ChatView.tsx
      +++ b/apps/web/src/components/ChatView.tsx
      @@ -5280,6 +5280,7 @@
       
       const AVAILABLE_PROVIDER_OPTIONS = PROVIDER_OPTIONS.filter((option) => option.available);
       const COMING_SOON_PROVIDER_OPTIONS = [
      +  { id: "claudeCode", label: "Claude Code", icon: ClaudeAI },
         { id: "opencode", label: "OpenCode", icon: OpenCodeIcon },
         { id: "gemini", label: "Gemini", icon: Gemini },
       ] as const;
      @@ -5285,20 +5443 @@
      5285- {UNAVAILABLE_PROVIDER_OPTIONS.length > 0 && <MenuDivider />}
      5286- {UNAVAILABLE_PROVIDER_OPTIONS.map((option) => {
      5287- const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
      5288- return (
      5289- <MenuItem key={option.value} disabled>
      5290- <OptionIcon
      5291- aria-hidden="true"
      5292- className={cn(
      5293- "size-4 shrink-0 opacity-80",
      5294- option.value === "claudeCode" ? "" : "text-muted-foreground/85",
      5295- )}
      5296- />
      5297- <span>{option.label}</span>
      5298- <span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
      5299- Coming soon
      5300- </span>
      5301- </MenuItem>
      5302- );
      5303- })}
      5304- {UNAVAILABLE_PROVIDER_OPTIONS.length === 0 && <MenuDivider />}
      5443+ <MenuDivider />

      Claude Code vanishes from provider picker menu

      Medium Severity

      The old code rendered UNAVAILABLE_PROVIDER_OPTIONS (including Claude Code with available: false) in the picker with a "Coming soon" badge. That entire rendering block was removed. Claude Code is not in AVAILABLE_PROVIDER_OPTIONS (filtered by option.available) and is not in COMING_SOON_PROVIDER_OPTIONS (only OpenCode and Gemini). So Claude Code completely disappears from the picker, contradicting the test title that says "keeping Claude Code as coming soon."

      Additional Locations (1)

      Fix in Cursor Fix in Web

      @@ -0,0 +1340,21 @@
      1340+ issue: "Cursor session/prompt response did not match expected schema.",
      1341+ cause,
      1342+ }),
      1343+ });
      1344+ const turnStateValue = mapStopReasonToTurnState(promptResult.stopReason);
      1345+ yield* completeTurn(
      1346+ context,
      1347+ turnStateValue,
      1348+ turnStateValue === "failed" ? "Cursor prompt failed." : undefined,
      1349+ promptResult.stopReason,
      1350+ );
      1351+
      1352+ context.session = {
      1353+ ...context.session,
      1354+ status: "ready",
      1355+ activeTurnId: undefined,
      1356+ updatedAt: yield* nowIso,
      1357+ resumeCursor: {
      1358+ acpSessionId: context.acpSessionId,
      1359+ },
      1360+ };

      sendTurn overwrites completeTurn's session error status

      Medium Severity

      After completeTurn sets context.session.status based on the turn outcome (including "error" for failed turns), sendTurn unconditionally overwrites context.session with status: "ready". This masks any error status that completeTurn may have set, making the session appear healthy when the turn actually failed.

      Additional Locations (1)

      Fix in Cursor Fix in Web

      @@ -0,0 +748,21 @@
      748+ if (!context.turnState) return;
      749+ const status = update.status === "completed" ? "completed" : "inProgress";
      750+ const trackedTool = context.turnState.toolCalls.get(update.toolCallId);
      751+ const itemType = trackedTool?.itemType ?? "dynamic_tool_call";
      752+ const title = trackedTool?.title ?? titleForItemType(itemType);
      753+ const stamp = yield* makeEventStamp();
      754+ const eventType = update.status === "completed" ? "item.completed" : "item.updated";
      755+ yield* offerRuntimeEvent({
      756+ ...base,
      757+ type: eventType,
      758+ eventId: stamp.eventId,
      759+ createdAt: stamp.createdAt,
      760+ turnId: context.turnState.turnId,
      761+ itemId: asRuntimeItemId(update.toolCallId),
      762+ payload: {
      763+ itemType,
      764+ status,
      765+ title,
      766+ ...(summarizeToolOutput(update.rawOutput)
      767+ ? { detail: summarizeToolOutput(update.rawOutput) }
      768+ : {}),

      summarizeToolOutput called twice redundantly on same input

      Low Severity

      summarizeToolOutput(update.rawOutput) is invoked twice — once to check truthiness and once to get the value for detail. This duplicates the string processing and JSON serialization work in summarizeToolOutput. The result could be computed once and reused.

      Fix in Cursor Fix in Web

    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

      🟢 Low 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.

      🚀 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`.
      @@ -428,7 +1241,21 @@
      1241+ ? [
      1242+ {
      1243+ type: "runtime.warning" as const,
      1244+ ...runtimeEventBase(event, canonicalThreadId),
      1245+ payload: {
      1246+ message: failureMessage,
      1247+ ...(event.payload !== undefined ? { detail: event.payload } : {}),
      1248+ },
      1249+ },
      1250+ ]
      1251+ : []),
      1252+ ];
      1253+ }
      1254+
      4281255 return [];
      4291256 }
      4301257
      4311258 const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
      4321259 Effect.gen(function* () {
      4331260 const fileSystem = yield* FileSystem.FileSystem;
      4341261 const serverConfig = yield* Effect.service(ServerConfig);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low Layers/CodexAdapter.ts:1261

      When options.nativeEventLogPath is provided, the created nativeEventLogger is never closed. Unlike manager, which is wrapped in Effect.acquireRelease, the logger's close() method is never invoked, so file handles leak every time the CodexAdapter layer is released.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/CodexAdapter.ts around line 1261:
      
      When `options.nativeEventLogPath` is provided, the created `nativeEventLogger` is never closed. Unlike `manager`, which is wrapped in `Effect.acquireRelease`, the logger's `close()` method is never invoked, so file handles leak every time the `CodexAdapter` layer is released.
      
      Evidence trail:
      apps/server/src/provider/Layers/CodexAdapter.ts lines 1258-1286 (REVIEWED_COMMIT) - shows `nativeEventLogger` creation and `manager` wrapped in `acquireRelease` but no cleanup for `nativeEventLogger`. apps/server/src/provider/Layers/EventNdjsonLogger.ts lines 24-28 (interface with `close()` method), lines 136-164 (thread writer creates `Scope` and `RotatingFileSink`), lines 236-242 (`close()` implementation that closes all writers). git_grep for `nativeEventLogger.*close` returns no results, confirming `close()` is never called.
      @@ -232,3 +235,4 @@
      232235 projectId: ProjectId,
      233236 title: TrimmedNonEmptyString,
      234237 model: TrimmedNonEmptyString,
      238+ runtimeMode: RuntimeMode,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/orchestration.ts:238

      OrchestrationThread adds runtimeMode as a required field without a default, so deserializing existing threads that lack this field fails validation. Consider adding Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE) to match the pattern used for interactionMode.

      -  runtimeMode: RuntimeMode,
      +  runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file packages/contracts/src/orchestration.ts around line 238:
      
      `OrchestrationThread` adds `runtimeMode` as a required field without a default, so deserializing existing threads that lack this field fails validation. Consider adding `Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)` to match the pattern used for `interactionMode`.
      
      Evidence trail:
      packages/contracts/src/orchestration.ts lines 234-241 (OrchestrationThread struct with runtimeMode: RuntimeMode without default, vs interactionMode with Schema.withDecodingDefault), line 35 (DEFAULT_RUNTIME_MODE constant exists), line 166 (OrchestrationSession uses RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE))). git_grep results showing DEFAULT_RUNTIME_MODE is used with withDecodingDefault pattern at lines 154, 339, 629 for other schemas.
      @@ -195,3 +294,21 @@
      294+
      295+function toUserInputQuestions(payload: Record<string, unknown> | undefined) {
      296+ const questions = asArray(payload?.questions);
      297+ if (!questions) {
      195298 return undefined;
      196299 }
      197300
      301+ const parsedQuestions = questions
      302+ .map((entry) => {
      303+ const question = asObject(entry);
      304+ if (!question) return undefined;
      305+ const options = asArray(question.options)
      306+ ?.map((option) => {
      307+ const optionRecord = asObject(option);
      308+ if (!optionRecord) return undefined;
      309+ const label = asString(optionRecord.label)?.trim();
      310+ const description = asString(optionRecord.description)?.trim();
      311+ if (!label || !description) {
      312+ return undefined;
      313+ }
      314+ return { label, description };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low Layers/CodexAdapter.ts:309

      toUserInputQuestions requires every option to have a description, so simple yes/no choices or file lists without descriptions are discarded. When all options are filtered out, the entire question becomes undefined and mapToRuntimeEvents drops the user-input.requested event, leaving the thread stuck waiting for input that the frontend never receives. Consider making description optional so valid options without descriptions are preserved.

      -          const label = asString(optionRecord.label)?.trim();
      -          const description = asString(optionRecord.description)?.trim();
      -          if (!label || !description) {
      -            return undefined;
      -          }
      -          return { label, description };
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/CodexAdapter.ts around lines 309-314:
      
      `toUserInputQuestions` requires every option to have a `description`, so simple yes/no choices or file lists without descriptions are discarded. When all options are filtered out, the entire question becomes `undefined` and `mapToRuntimeEvents` drops the `user-input.requested` event, leaving the thread stuck waiting for input that the frontend never receives. Consider making `description` optional so valid options without descriptions are preserved.
      
      Evidence trail:
      apps/server/src/provider/Layers/CodexAdapter.ts lines 309-311 (description required check), line 320 (options.length === 0 check), line 339 (returns undefined if no valid questions), lines 545-548 (returns empty array when questions undefined, dropping the event). Commit: REVIEWED_COMMIT
      @@ -159,3 +413,19 @@
      159413 });
      160414 }
      161415
      416+function compareActivitiesByOrder(
      417+ left: OrchestrationThreadActivity,
      418+ right: OrchestrationThreadActivity,
      419+): number {
      420+ if (left.sequence !== undefined && right.sequence !== undefined) {
      421+ if (left.sequence !== right.sequence) {
      422+ return left.sequence - right.sequence;
      423+ }
      424+ } else if (left.sequence !== undefined) {
      425+ return 1;
      426+ } else if (right.sequence !== undefined) {
      427+ return -1;
      428+ }
      429+
      430+ return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
      431+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/session-logic.ts:416

      compareActivitiesByOrder sorts all activities with a sequence property after activities without one, regardless of createdAt. When a sequenced user-input.requested is followed by an unsequenced user-input.resolved, the resolution is processed first and discarded, leaving the request stuck in pending state. Consider treating missing sequence as Infinity so unsequenced activities sort after sequenced ones when timestamps are equal, or use timestamp as the primary sort key.

      +function compareActivitiesByOrder(
      +  left: OrchestrationThreadActivity,
      +  right: OrchestrationThreadActivity,
      +): number {
      +  const leftSeq = left.sequence ?? Infinity;
      +  const rightSeq = right.sequence ?? Infinity;
      +  if (leftSeq !== rightSeq) {
      +    return leftSeq - rightSeq;
      +  }
      +  return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
      +}
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/web/src/session-logic.ts around lines 416-431:
      
      `compareActivitiesByOrder` sorts all activities with a `sequence` property after activities without one, regardless of `createdAt`. When a sequenced `user-input.requested` is followed by an unsequenced `user-input.resolved`, the resolution is processed first and discarded, leaving the request stuck in pending state. Consider treating missing `sequence` as `Infinity` so unsequenced activities sort after sequenced ones when timestamps are equal, or use timestamp as the primary sort key.
      
      Evidence trail:
      apps/web/src/session-logic.ts lines 416-428 (compareActivitiesByOrder function) - verifies sorting puts unsequenced before sequenced via return 1/-1 logic. apps/web/src/session-logic.ts lines 247-284 (derivePendingUserInputs function) - shows the function processes sorted activities sequentially, adding requests to map on 'user-input.requested' and deleting on 'user-input.resolved', confirming the out-of-order processing consequence.
      @@ -475,5 +804,17 @@
      475804 });
      476805 }
      477806
      478- stopSession(sessionId: ProviderSessionId): void {
      479- const context = this.sessions.get(sessionId);
      807+ async respondToUserInput(
      808+ threadId: ThreadId,
      809+ requestId: ApprovalRequestId,
      810+ answers: ProviderUserInputAnswers,
      811+ ): Promise<void> {
      812+ const context = this.requireSession(threadId);
      813+ const pendingRequest = context.pendingUserInputs.get(requestId);
      814+ if (!pendingRequest) {
      815+ throw new Error(`Unknown pending user input request: ${requestId}`);
      816+ }
      817+
      818+ context.pendingUserInputs.delete(requestId);
      819+ const codexAnswers = toCodexUserInputAnswers(answers);
      820+ this.writeMessage(context, {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/codexAppServerManager.ts:807

      In respondToUserInput, context.pendingUserInputs.delete(requestId) is called before validating answers via toCodexUserInputAnswers. If conversion throws, the request record is permanently lost but no response reaches the provider, leaving the session corrupted and blocking retries. Move the deletion after successful validation and conversion.

         async respondToUserInput(
           threadId: ThreadId,
           requestId: ApprovalRequestId,
           answers: ProviderUserInputAnswers,
         ): Promise<void> {
           const context = this.requireSession(threadId);
           const pendingRequest = context.pendingUserInputs.get(requestId);
           if (!pendingRequest) {
             throw new Error(`Unknown pending user input request: ${requestId}`);
           }
       
      -    context.pendingUserInputs.delete(requestId);
           const codexAnswers = toCodexUserInputAnswers(answers);
      +    context.pendingUserInputs.delete(requestId);
           this.writeMessage(context, {
             id: pendingRequest.jsonRpcId,
             result: {
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/codexAppServerManager.ts around lines 807-820:
      
      In `respondToUserInput`, `context.pendingUserInputs.delete(requestId)` is called before validating `answers` via `toCodexUserInputAnswers`. If conversion throws, the request record is permanently lost but no response reaches the provider, leaving the session corrupted and blocking retries. Move the deletion after successful validation and conversion.
      
      Evidence trail:
      apps/server/src/codexAppServerManager.ts lines 807-825 (REVIEWED_COMMIT): `respondToUserInput` method showing delete at line 818, conversion at line 819
      apps/server/src/codexAppServerManager.ts lines 358-381 (REVIEWED_COMMIT): `toCodexUserInputAnswer` function that throws Error at line 370, and `toCodexUserInputAnswers` that calls it
      Line 818: `context.pendingUserInputs.delete(requestId);`
      Line 819: `const codexAnswers = toCodexUserInputAnswers(answers);`
      Line 370: `throw new Error("User input answers must be strings or arrays of strings.");`
    7. I prepared a CI fix PR targeting this branch: #242\n\nIt updates stale rollback assertions in CheckpointReactor.test.ts to include threadId and matches current rollback payload shape.

    8. maria-rcks closed this

    9. maria-rcks reopened this

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

    11. Is there anything we can do to help this get in soon?

    12. I added auto commit message generation for users of the Cursor adapter. Branch: https://github.com/lasangainc/t3code/tree/codething/648ca884-cursor Commit: 7c4bad84

    13. Is there anything we can do to help this get in soon?

      I would like to know too.

    14. juliusmarminge closed this

Sign in to join this conversation.