From bc812e9b2d900c1b82562c0a348c32a7bb5fa8c7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Mar 2026 19:52:12 -0700 Subject: [PATCH] Handle Claude stream interruption and collapse duplicate work log update - close Claude sessions cleanly when the runtime stream aborts mid-turn - normalize interrupted stream exits into a completed interrupted turn - collapse repeated tool lifecycle updates into a single work log entry --- .../src/provider/Layers/ClaudeAdapter.test.ts | 112 +++++++++- .../src/provider/Layers/ClaudeAdapter.ts | 121 +++++++++-- apps/web/src/session-logic.test.ts | 152 +++++++++++++ apps/web/src/session-logic.ts | 204 ++++++++++++++---- 4 files changed, 525 insertions(+), 64 deletions(-) diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index 3a463d01b4..fe9889fe9f 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -10,7 +10,12 @@ import type { SDKMessage, SDKUserMessage, } from "@anthropic-ai/claude-agent-sdk"; -import { ApprovalRequestId, ProviderItemId, ThreadId } from "@t3tools/contracts"; +import { + ApprovalRequestId, + ProviderItemId, + ProviderRuntimeEvent, + ThreadId, +} from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; import { Effect, Fiber, Layer, Random, Stream } from "effect"; @@ -22,8 +27,12 @@ import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAd class FakeClaudeQuery implements AsyncIterable { private readonly queue: Array = []; - private readonly resolvers: Array<(value: IteratorResult) => void> = []; + private readonly waiters: Array<{ + readonly resolve: (value: IteratorResult) => void; + readonly reject: (reason: unknown) => void; + }> = []; private done = false; + private failure: unknown | undefined; public readonly interruptCalls: Array = []; public readonly setModelCalls: Array = []; @@ -35,21 +44,33 @@ class FakeClaudeQuery implements AsyncIterable { if (this.done) { return; } - const resolver = this.resolvers.shift(); - if (resolver) { - resolver({ done: false, value: message }); + const waiter = this.waiters.shift(); + if (waiter) { + waiter.resolve({ done: false, value: message }); return; } this.queue.push(message); } + fail(cause: unknown): void { + if (this.done) { + return; + } + this.done = true; + this.failure = cause; + for (const waiter of this.waiters.splice(0)) { + waiter.reject(cause); + } + } + finish(): void { if (this.done) { return; } this.done = true; - for (const resolver of this.resolvers.splice(0)) { - resolver({ done: true, value: undefined }); + this.failure = undefined; + for (const waiter of this.waiters.splice(0)) { + waiter.resolve({ done: true, value: undefined }); } } @@ -86,14 +107,22 @@ class FakeClaudeQuery implements AsyncIterable { }); } } + if (this.failure !== undefined) { + const failure = this.failure; + this.failure = undefined; + return Promise.reject(failure); + } if (this.done) { return Promise.resolve({ done: true, value: undefined, }); } - return new Promise((resolve) => { - this.resolvers.push(resolve); + return new Promise((resolve, reject) => { + this.waiters.push({ + resolve, + reject, + }); }); }, }; @@ -1037,6 +1066,71 @@ describe("ClaudeAdapterLive", () => { ); }); + it.effect("closes the session when the Claude stream aborts after a turn starts", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + const runtimeEvents: Array = []; + + const runtimeEventsFiber = Effect.runFork( + Stream.runForEach(adapter.streamEvents, (event) => + Effect.sync(() => { + runtimeEvents.push(event); + }), + ), + ); + + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId: THREAD_ID, + input: "hello", + attachments: [], + }); + + harness.query.fail(new Error("All fibers interrupted without error")); + + yield* Effect.yieldNow; + yield* Effect.yieldNow; + yield* Effect.yieldNow; + runtimeEventsFiber.interruptUnsafe(); + assert.deepEqual( + runtimeEvents.map((event) => event.type), + [ + "session.started", + "session.configured", + "session.state.changed", + "turn.started", + "turn.completed", + "session.exited", + ], + ); + + const turnCompleted = runtimeEvents[4]; + assert.equal(turnCompleted?.type, "turn.completed"); + if (turnCompleted?.type === "turn.completed") { + assert.equal(String(turnCompleted.turnId), String(turn.turnId)); + assert.equal(turnCompleted.payload.state, "interrupted"); + assert.equal(turnCompleted.payload.errorMessage, "Claude runtime interrupted."); + } + + const sessionExited = runtimeEvents[5]; + assert.equal(sessionExited?.type, "session.exited"); + + assert.equal(yield* adapter.hasSession(THREAD_ID), false); + const sessions = yield* adapter.listSessions(); + assert.equal(sessions.length, 0); + assert.equal(harness.query.closeCalls, 1); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + it.effect("forwards Claude task progress summaries for subagent updates", () => { const harness = makeHarness(); return Effect.gen(function* () { diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 34298a773e..43adc70f1a 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -51,7 +51,9 @@ import { DateTime, Deferred, Effect, + Exit, FileSystem, + Fiber, Layer, Queue, Random, @@ -141,6 +143,7 @@ interface ClaudeSessionContext { session: ProviderSession; readonly promptQueue: Queue.Queue; readonly query: ClaudeQueryRuntime; + streamFiber: Fiber.Fiber | undefined; readonly startedAt: string; readonly basePermissionMode: PermissionMode | undefined; resumeSessionId: string | undefined; @@ -189,6 +192,47 @@ function toMessage(cause: unknown, fallback: string): string { return fallback; } +function toError(cause: unknown, fallback: string): Error { + return cause instanceof Error ? cause : new Error(toMessage(cause, fallback)); +} + +function normalizeClaudeStreamMessages(cause: Cause.Cause): ReadonlyArray { + const errors = Cause.prettyErrors(cause) + .map((error) => error.message.trim()) + .filter((message) => message.length > 0); + if (errors.length > 0) { + return errors; + } + + const squashed = toMessage(Cause.squash(cause), "").trim(); + return squashed.length > 0 ? [squashed] : []; +} + +function isClaudeInterruptedMessage(message: string): boolean { + const normalized = message.toLowerCase(); + return ( + normalized.includes("all fibers interrupted without error") || + normalized.includes("request was aborted") || + normalized.includes("interrupted by user") + ); +} + +function isClaudeInterruptedCause(cause: Cause.Cause): boolean { + return ( + Cause.hasInterruptsOnly(cause) || + normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage) + ); +} + +function messageFromClaudeStreamCause(cause: Cause.Cause, fallback: string): string { + return normalizeClaudeStreamMessages(cause)[0] ?? fallback; +} + +function interruptionMessageFromClaudeCause(cause: Cause.Cause): string { + const message = messageFromClaudeStreamCause(cause, "Claude runtime interrupted."); + return isClaudeInterruptedMessage(message) ? "Claude runtime interrupted." : message; +} + function resultErrorsText(result: SDKResultMessage): string { return "errors" in result && Array.isArray(result.errors) ? result.errors.join(" ").toLowerCase() @@ -2045,22 +2089,49 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { } }); - const runSdkStream = (context: ClaudeSessionContext): Effect.Effect => - Stream.fromAsyncIterable(context.query, (cause) => cause).pipe( + const runSdkStream = (context: ClaudeSessionContext): Effect.Effect => + Stream.fromAsyncIterable(context.query, (cause) => + toError(cause, "Claude runtime stream failed."), + ).pipe( Stream.takeWhile(() => !context.stopped), Stream.runForEach((message) => handleSdkMessage(context, message)), - Effect.catchCause((cause) => - Effect.gen(function* () { - if (Cause.hasInterruptsOnly(cause) || context.stopped) { - return; - } - const message = toMessage(Cause.squash(cause), "Claude runtime stream failed."); - yield* emitRuntimeError(context, message, cause); - yield* completeTurn(context, "failed", message); - }), - ), ); + const handleStreamExit = ( + context: ClaudeSessionContext, + exit: Exit.Exit, + ): Effect.Effect => + Effect.gen(function* () { + if (context.stopped) { + return; + } + + if (Exit.isFailure(exit)) { + if (isClaudeInterruptedCause(exit.cause)) { + if (context.turnState) { + yield* completeTurn( + context, + "interrupted", + interruptionMessageFromClaudeCause(exit.cause), + ); + } + } else { + const message = messageFromClaudeStreamCause( + exit.cause, + "Claude runtime stream failed.", + ); + yield* emitRuntimeError(context, message, Cause.pretty(exit.cause)); + yield* completeTurn(context, "failed", message); + } + } else if (context.turnState) { + yield* completeTurn(context, "interrupted", "Claude runtime stream ended."); + } + + yield* stopSessionInternal(context, { + emitExitEvent: true, + }); + }); + const stopSessionInternal = ( context: ClaudeSessionContext, options?: { readonly emitExitEvent?: boolean }, @@ -2096,7 +2167,18 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { yield* Queue.shutdown(context.promptQueue); - context.query.close(); + const streamFiber = context.streamFiber; + context.streamFiber = undefined; + if (streamFiber && streamFiber.pollUnsafe() === undefined) { + yield* Fiber.interrupt(streamFiber); + } + + // @effect-diagnostics-next-line tryCatchInEffectGen:off + try { + context.query.close(); + } catch (cause) { + yield* emitRuntimeError(context, "Failed to close Claude runtime query.", cause); + } const updatedAt = yield* nowIso; context.session = { @@ -2536,6 +2618,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { session, promptQueue, query: queryRuntime, + streamFiber: undefined, startedAt, basePermissionMode: permissionMode, resumeSessionId: sessionId, @@ -2597,7 +2680,17 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { providerRefs: {}, }); - Effect.runFork(runSdkStream(context)); + const streamFiber = Effect.runFork(runSdkStream(context)); + context.streamFiber = streamFiber; + streamFiber.addObserver((exit) => { + if (context.stopped) { + return; + } + if (context.streamFiber === streamFiber) { + context.streamFiber = undefined; + } + Effect.runFork(handleStreamExit(context, exit)); + }); return { ...session, diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index edca8b5727..4a113adebe 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -767,6 +767,158 @@ describe("deriveWorkLogEntries", () => { "apps/web/src/session-logic.ts", ]); }); + + it("collapses repeated lifecycle updates for the same tool call into one entry", () => { + const activities: OrchestrationThreadActivity[] = [ + makeActivity({ + id: "tool-update-1", + createdAt: "2026-02-23T00:00:01.000Z", + kind: "tool.updated", + summary: "Tool call", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + }, + }), + makeActivity({ + id: "tool-update-2", + createdAt: "2026-02-23T00:00:02.000Z", + kind: "tool.updated", + summary: "Tool call", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + data: { + item: { + command: ["sed", "-n", "1,40p", "/tmp/app.ts"], + }, + }, + }, + }), + makeActivity({ + id: "tool-complete", + createdAt: "2026-02-23T00:00:03.000Z", + kind: "tool.completed", + summary: "Tool call completed", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + }, + }), + ]; + + const entries = deriveWorkLogEntries(activities, undefined); + + expect(entries).toHaveLength(1); + expect(entries[0]).toMatchObject({ + id: "tool-complete", + createdAt: "2026-02-23T00:00:03.000Z", + label: "Tool call completed", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + command: "sed -n 1,40p /tmp/app.ts", + itemType: "dynamic_tool_call", + toolTitle: "Tool call", + }); + }); + + it("keeps separate tool entries when an identical call starts after the prior one completed", () => { + const activities: OrchestrationThreadActivity[] = [ + makeActivity({ + id: "tool-1-update", + createdAt: "2026-02-23T00:00:01.000Z", + kind: "tool.updated", + summary: "Tool call", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + }, + }), + makeActivity({ + id: "tool-1-complete", + createdAt: "2026-02-23T00:00:02.000Z", + kind: "tool.completed", + summary: "Tool call completed", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + }, + }), + makeActivity({ + id: "tool-2-update", + createdAt: "2026-02-23T00:00:03.000Z", + kind: "tool.updated", + summary: "Tool call", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + }, + }), + makeActivity({ + id: "tool-2-complete", + createdAt: "2026-02-23T00:00:04.000Z", + kind: "tool.completed", + summary: "Tool call completed", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + }, + }), + ]; + + const entries = deriveWorkLogEntries(activities, undefined); + + expect(entries.map((entry) => entry.id)).toEqual(["tool-1-complete", "tool-2-complete"]); + }); + + it("collapses same-timestamp lifecycle rows even when completed sorts before updated by id", () => { + const activities: OrchestrationThreadActivity[] = [ + makeActivity({ + id: "z-update-earlier", + createdAt: "2026-02-23T00:00:01.000Z", + kind: "tool.updated", + summary: "Tool call", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + }, + }), + makeActivity({ + id: "a-complete-same-timestamp", + createdAt: "2026-02-23T00:00:02.000Z", + kind: "tool.completed", + summary: "Tool call", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + }, + }), + makeActivity({ + id: "z-update-same-timestamp", + createdAt: "2026-02-23T00:00:02.000Z", + kind: "tool.updated", + summary: "Tool call", + payload: { + itemType: "dynamic_tool_call", + title: "Tool call", + detail: 'Read: {"file_path":"/tmp/app.ts"}', + }, + }), + ]; + + const entries = deriveWorkLogEntries(activities, undefined); + + expect(entries).toHaveLength(1); + expect(entries[0]?.id).toBe("a-complete-same-timestamp"); + }); }); describe("deriveTimelineEntries", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index adbc94f735..7c3ea96e65 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -45,6 +45,11 @@ export interface WorkLogEntry { requestKind?: PendingApproval["requestKind"]; } +interface DerivedWorkLogEntry extends WorkLogEntry { + activityKind: OrchestrationThreadActivity["kind"]; + collapseKey?: string; +} + export interface PendingApproval { requestId: ApprovalRequestId; requestKind: "command" | "file-read" | "file-change"; @@ -454,51 +459,16 @@ export function deriveWorkLogEntries( latestTurnId: TurnId | undefined, ): WorkLogEntry[] { const ordered = [...activities].toSorted(compareActivitiesByOrder); - return ordered + const entries = ordered .filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true)) .filter((activity) => activity.kind !== "tool.started") .filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed") .filter((activity) => activity.summary !== "Checkpoint captured") .filter((activity) => !isPlanBoundaryToolActivity(activity)) - .map((activity) => { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - const command = extractToolCommand(payload); - const changedFiles = extractChangedFiles(payload); - const title = extractToolTitle(payload); - const entry: WorkLogEntry = { - id: activity.id, - createdAt: activity.createdAt, - label: activity.summary, - tone: activity.tone === "approval" ? "info" : activity.tone, - }; - const itemType = extractWorkLogItemType(payload); - const requestKind = extractWorkLogRequestKind(payload); - if (payload && typeof payload.detail === "string" && payload.detail.length > 0) { - const detail = stripTrailingExitCode(payload.detail).output; - if (detail) { - entry.detail = detail; - } - } - if (command) { - entry.command = command; - } - if (changedFiles.length > 0) { - entry.changedFiles = changedFiles; - } - if (title) { - entry.toolTitle = title; - } - if (itemType) { - entry.itemType = itemType; - } - if (requestKind) { - entry.requestKind = requestKind; - } - return entry; - }); + .map(toDerivedWorkLogEntry); + return collapseDerivedWorkLogEntries(entries).map( + ({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry, + ); } function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean { @@ -513,6 +483,134 @@ function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): bool return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:"); } +function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry { + const payload = + activity.payload && typeof activity.payload === "object" + ? (activity.payload as Record) + : null; + const command = extractToolCommand(payload); + const changedFiles = extractChangedFiles(payload); + const title = extractToolTitle(payload); + const entry: DerivedWorkLogEntry = { + id: activity.id, + createdAt: activity.createdAt, + label: activity.summary, + tone: activity.tone === "approval" ? "info" : activity.tone, + activityKind: activity.kind, + }; + const itemType = extractWorkLogItemType(payload); + const requestKind = extractWorkLogRequestKind(payload); + if (payload && typeof payload.detail === "string" && payload.detail.length > 0) { + const detail = stripTrailingExitCode(payload.detail).output; + if (detail) { + entry.detail = detail; + } + } + if (command) { + entry.command = command; + } + if (changedFiles.length > 0) { + entry.changedFiles = changedFiles; + } + if (title) { + entry.toolTitle = title; + } + if (itemType) { + entry.itemType = itemType; + } + if (requestKind) { + entry.requestKind = requestKind; + } + const collapseKey = deriveToolLifecycleCollapseKey(entry); + if (collapseKey) { + entry.collapseKey = collapseKey; + } + return entry; +} + +function collapseDerivedWorkLogEntries( + entries: ReadonlyArray, +): DerivedWorkLogEntry[] { + const collapsed: DerivedWorkLogEntry[] = []; + for (const entry of entries) { + const previous = collapsed.at(-1); + if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) { + collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry); + continue; + } + collapsed.push(entry); + } + return collapsed; +} + +function shouldCollapseToolLifecycleEntries( + previous: DerivedWorkLogEntry, + next: DerivedWorkLogEntry, +): boolean { + if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") { + return false; + } + if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") { + return false; + } + if (previous.activityKind === "tool.completed") { + return false; + } + return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey; +} + +function mergeDerivedWorkLogEntries( + previous: DerivedWorkLogEntry, + next: DerivedWorkLogEntry, +): DerivedWorkLogEntry { + const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles); + const detail = next.detail ?? previous.detail; + const command = next.command ?? previous.command; + const toolTitle = next.toolTitle ?? previous.toolTitle; + const itemType = next.itemType ?? previous.itemType; + const requestKind = next.requestKind ?? previous.requestKind; + const collapseKey = next.collapseKey ?? previous.collapseKey; + return { + ...previous, + ...next, + ...(detail ? { detail } : {}), + ...(command ? { command } : {}), + ...(changedFiles.length > 0 ? { changedFiles } : {}), + ...(toolTitle ? { toolTitle } : {}), + ...(itemType ? { itemType } : {}), + ...(requestKind ? { requestKind } : {}), + ...(collapseKey ? { collapseKey } : {}), + }; +} + +function mergeChangedFiles( + previous: ReadonlyArray | undefined, + next: ReadonlyArray | undefined, +): string[] { + const merged = [...(previous ?? []), ...(next ?? [])]; + if (merged.length === 0) { + return []; + } + return [...new Set(merged)]; +} + +function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined { + if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") { + return undefined; + } + const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label); + const detail = entry.detail?.trim() ?? ""; + const itemType = entry.itemType ?? ""; + if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) { + return undefined; + } + return [itemType, normalizedLabel, detail].join("\u001f"); +} + +function normalizeCompactToolLabel(value: string): string { + return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim(); +} + function toLatestProposedPlanState(proposedPlan: ProposedPlan): LatestProposedPlanState { return { id: proposedPlan.id, @@ -690,7 +788,31 @@ function compareActivitiesByOrder( return -1; } - return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id); + const createdAtComparison = left.createdAt.localeCompare(right.createdAt); + if (createdAtComparison !== 0) { + return createdAtComparison; + } + + const lifecycleRankComparison = + compareActivityLifecycleRank(left.kind) - compareActivityLifecycleRank(right.kind); + if (lifecycleRankComparison !== 0) { + return lifecycleRankComparison; + } + + return left.id.localeCompare(right.id); +} + +function compareActivityLifecycleRank(kind: string): number { + if (kind.endsWith(".started") || kind === "tool.started") { + return 0; + } + if (kind.endsWith(".progress") || kind.endsWith(".updated")) { + return 1; + } + if (kind.endsWith(".completed") || kind.endsWith(".resolved")) { + return 2; + } + return 1; } export function hasToolActivityForTurn(