TypeScript
fix(server): stop abandoned turns before continuing threads (#23169)
Yash Singh6f6f68ad2d80
diff --git a/apps/mobile/src/features/threads/worktree-setup-card.tsx b/apps/mobile/src/features/threads/worktree-setup-card.tsxindex 45a5bb9404d..7495399edd2 100644--- a/apps/mobile/src/features/threads/worktree-setup-card.tsx+++ b/apps/mobile/src/features/threads/worktree-setup-card.tsx@@ -84,7 +84,7 @@ export function WorktreeSetupCard(props: WorktreeSetupCardProps) {accessibilityRole="button"accessibilityLabel={backgroundSetup- ? `${scriptName} is still running. Show setup progress.`+ ? `Background setup is still running: ${scriptName}. Show setup progress.`: "Worktree setup details"}accessibilityState={{ expanded: detailsOpen }}@@ -116,7 +116,7 @@ export function WorktreeSetupCard(props: WorktreeSetupCardProps) {/>) : null}<Text numberOfLines={1} className="shrink text-2xs text-foreground-secondary">- {backgroundSetup ? scriptName : "Details"}+ {backgroundSetup ? "Background setup" : "Details"}</Text>{!backgroundSetup ? (<SymbolView name="chevron.right" size={10} tintColorClassName="accent-icon-muted" />diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.tsindex 0e7ecfa9f01..8fca16a1017 100644--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts@@ -7,6 +7,7 @@ import {NodeId,ProviderSessionId,ProviderThreadId,+ ProviderTurnId,ProviderDriverKind,ProviderInstanceId,ProviderSetupError,@@ -271,6 +272,14 @@ function makeLocalCommandHarness(input: {readonly interruptRunBeforeOpenFailure?: boolean;readonly writeFailure?: unknown;readonly failReadsAfterRunning?: boolean;+ readonly previousTurn?: {+ readonly runStatus: "failed" | "completed";+ readonly turnStatus: "running" | "completed" | "interrupted";+ readonly differentThread?: boolean;+ readonly liveSession?: boolean;+ readonly interruptFailure?: boolean;+ readonly interruptCurrentRun?: boolean;+ };}) {const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");const threadId = ThreadId.make("thread-native-account-command");@@ -456,6 +465,74 @@ function makeLocalCommandHarness(input: {),};}+ const previousTurnId = ProviderTurnId.make("previous-provider-turn");+ if (input.previousTurn !== undefined) {+ const previousRunId = RunId.make("previous-failed-run");+ const previousAttemptId = RunAttemptId.make("previous-failed-attempt");+ const previousProviderThreadId = input.previousTurn.differentThread+ ? oldProviderThreadId+ : providerThreadId;+ projection = {+ ...projection,+ runs: [+ {+ ...run,+ id: previousRunId,+ ordinal: 1,+ status: input.previousTurn.runStatus,+ rootNodeId: NodeId.make("previous-root"),+ activeAttemptId: previousAttemptId,+ providerThreadId: previousProviderThreadId,+ completedAt: now,+ },+ run,+ ],+ providerThreads: [+ {+ ...providerThread,+ nativeThreadRef: {+ driver: providerThread.driver,+ nativeId: "existing-native-conversation",+ strength: "strong",+ },+ },+ ],+ providerTurns: [+ {+ id: previousTurnId,+ providerThreadId: previousProviderThreadId,+ nodeId: NodeId.make("previous-root"),+ runAttemptId: previousAttemptId,+ ordinal: 1,+ nativeTurnRef: null,+ status: input.previousTurn.turnStatus,+ startedAt: now,+ completedAt: input.previousTurn.turnStatus === "running" ? null : now,+ },+ ],+ };+ }+ let providerBusy =+ input.previousTurn?.runStatus === "failed" &&+ input.previousTurn.turnStatus === "running" &&+ !input.previousTurn.differentThread &&+ input.previousTurn.liveSession !== false;+ const interruptTurn = vi.fn((request: ProviderAdapter.ProviderAdapterV2InterruptInput) =>+ Effect.gen(function* () {+ expect(request.providerTurnId).toBe(previousTurnId);+ expect(request.providerThread.id).toBe(providerThreadId);+ if (input.previousTurn?.interruptFailure) {+ return yield* new ProviderAdapter.ProviderAdapterInterruptError({+ driver: providerThread.driver,+ providerThreadId,+ providerTurnId: request.providerTurnId,+ cause: "provider interrupt failed",+ });+ }+ providerBusy = false;+ if (input.previousTurn?.interruptCurrentRun) interruptRun();+ }),+ );const events: Array<OrchestrationV2DomainEvent> = [];const interruptRun = () => {projection = {@@ -515,7 +592,7 @@ function makeLocalCommandHarness(input: {),),)- : input.failReadsAfterRunning === true+ : input.failReadsAfterRunning === true || input.previousTurn !== undefined? Effect.succeed({driver: providerThread.driver,providerSession: {@@ -531,14 +608,17 @@ function makeLocalCommandHarness(input: {lastError: null,},ensureThread: () => Effect.succeed(providerThread),+ resumeThread: () => Effect.succeed(projection.providerThreads[0]),} as never): Effect.die("A local command must not open a native session."),);const startRootRun = vi.fn<(input: RunExecutionService.RunExecutionServiceV2StartRootRunInput) => Effect.Effect<void>>(() =>- input.failReadsAfterRunning === true- ? Effect.void+ input.failReadsAfterRunning === true || input.previousTurn !== undefined+ ? Effect.suspend(() =>+ providerBusy ? Effect.die("The previous provider turn is still running.") : Effect.void,+ ): Effect.die("A local command must not start a native turn."),);const failReadIfRunning = Effect.suspend(() =>@@ -642,7 +722,19 @@ function makeLocalCommandHarness(input: {}),),}),- Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),+ Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({+ open,+ get: () =>+ Effect.succeed(+ input.previousTurn?.liveSession === false+ ? Option.none()+ : Option.some({+ driver: providerThread.driver,+ providerSessionId,+ interruptTurn,+ } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime),+ ),+ }),Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand }),Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),Layer.mock(RuntimePolicy.RuntimePolicyV2)({@@ -662,6 +754,7 @@ function makeLocalCommandHarness(input: {open,writeIfRunCurrent,startRootRun,+ interruptTurn,tryHandlePromptCommand,events,oldInstanceId,@@ -681,6 +774,106 @@ function makeLocalCommandHarness(input: {};}+effectIt.effect("recovers an abandoned failed turn before continuing its native conversation", () =>+ Effect.gen(function* () {+ const harness = makeLocalCommandHarness({+ text: "Continue",+ previousTurn: { runStatus: "failed", turnStatus: "running" },+ });++ yield* harness.start;++ expect(harness.interruptTurn).toHaveBeenCalledOnce();+ expect(harness.projection().runs.at(-1)?.status).toBe("running");+ expect(harness.projection().providerTurns[0]).toMatchObject({+ status: "interrupted",+ completedAt: expect.anything(),+ });+ expect(harness.startRootRun).toHaveBeenCalledOnce();+ expect(harness.startRootRun.mock.calls[0]?.[0].providerThread.nativeThreadRef?.nativeId).toBe(+ "existing-native-conversation",+ );+ }),+);++effectIt.effect.each([+ { runStatus: "failed", turnStatus: "completed" },+ { runStatus: "completed", turnStatus: "completed" },+ { runStatus: "failed", turnStatus: "running", differentThread: true },+ { runStatus: "failed", turnStatus: "running", liveSession: false },+ { runStatus: "failed", turnStatus: "interrupted", interruptFailure: true },+] as const)("continues without interrupting when recovery does not apply: %j", (previousTurn) =>+ Effect.gen(function* () {+ const harness = makeLocalCommandHarness({ text: "Continue", previousTurn });++ yield* harness.start;++ expect(harness.interruptTurn).not.toHaveBeenCalled();+ expect(harness.projection().runs.at(-1)?.status).toBe("running");+ }),+);++effectIt.effect("does not start another turn when abandoned-turn cleanup fails", () =>+ Effect.gen(function* () {+ const harness = makeLocalCommandHarness({+ text: "Continue",+ previousTurn: { runStatus: "failed", turnStatus: "running", interruptFailure: true },+ });++ yield* harness.start;++ expect(harness.interruptTurn).toHaveBeenCalledOnce();+ expect(harness.startRootRun).not.toHaveBeenCalled();+ expect(harness.projection().runs.at(-1)?.status).toBe("failed");+ }),+);++effectIt.effect("retries abandoned-turn cleanup without failing the continuation early", () =>+ Effect.gen(function* () {+ const harness = makeLocalCommandHarness({+ text: "Continue",+ previousTurn: { runStatus: "failed", turnStatus: "running", interruptFailure: true },+ });++ const error = yield* harness.startWithRetry.pipe(Effect.flip);++ expect(error._tag).toBe("ProviderTurnStartError");+ expect(harness.projection().runs.at(-1)?.status).toBe("starting");+ expect(harness.open).not.toHaveBeenCalled();+ }),+);++effectIt.effect("does not start the continuation if recording recovery fails", () =>+ Effect.gen(function* () {+ const harness = makeLocalCommandHarness({+ text: "Continue",+ previousTurn: { runStatus: "failed", turnStatus: "running" },+ writeFailure: new Error("database unavailable"),+ });++ const error = yield* harness.start.pipe(Effect.flip);++ expect(error._tag).toBe("ProviderTurnStartError");+ expect(harness.projection().runs.at(-1)?.status).toBe("starting");+ expect(harness.projection().providerTurns[0]?.status).toBe("running");+ expect(harness.open).not.toHaveBeenCalled();+ }),+);++effectIt.effect("does not resume a continuation stopped while recovery was in flight", () =>+ Effect.gen(function* () {+ const harness = makeLocalCommandHarness({+ text: "Continue",+ previousTurn: { runStatus: "failed", turnStatus: "running", interruptCurrentRun: true },+ });++ yield* harness.start;++ expect(harness.projection().runs.at(-1)?.status).toBe("interrupted");+ expect(harness.open).not.toHaveBeenCalled();+ }),+);+effectIt.effect.each(["cleanup-first", "startup-first"])("coordinates provider startup with %s",(order) =>diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.tsindex 325c4557636..89ae2cc2c0c 100644--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts@@ -541,26 +541,6 @@ export const layer: Layer.Layer<const existingSessionProjection = projection.providerSessions.find((candidate) => candidate.id === providerSessionId,);- const sessionResult = yield* Effect.result(- providerSessions.open({- threadId: projection.thread.id,- providerSessionId,- modelSelection: run.modelSelection,- runtimePolicy: resolvedRuntimePolicy,- ...(existingSessionProjection === undefined- ? {}- : { resumeFromSession: existingSessionProjection }),- ...(providerThread.nativeThreadRef?.nativeId == null- ? {}- : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),- ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined- ? {}- : {- initialProviderItemIdentityVersion:- providerThread.nativeMetadata.itemIdentityVersion,- }),- }),- );const settleStartFailure = Effect.fn("ProviderTurnStartService.settleStartFailure")(function* (failed: {readonly signal: string;@@ -592,6 +572,91 @@ export const layer: Layer.Layer<});},);+ const failedRuns = new Map(+ projection.runs+ .filter(+ (previous) =>+ previous.ordinal < run.ordinal &&+ previous.providerThreadId === providerThread.id &&+ previous.status === "failed",+ )+ .map((previous) => [previous.activeAttemptId, previous] as const),+ );+ const abandonedTurns = projection.providerTurns.flatMap((turn) => {+ const previous = failedRuns.get(turn.runAttemptId);+ return turn.providerThreadId === providerThread.id &&+ turn.status === "running" &&+ previous !== undefined &&+ turn.nodeId === previous.rootNodeId+ ? [{ turn, run: previous }]+ : [];+ });+ const abandonedTurn = abandonedTurns.at(-1)?.turn;+ if (abandonedTurn !== undefined) {+ const liveSession = yield* providerSessions.get(providerSessionId);+ if (Option.isSome(liveSession)) {+ // Older versions could fail the run without stopping its provider.+ // Recover that exact turn before reusing its native conversation.+ const recovered = yield* Effect.result(+ liveSession.value.interruptTurn({+ providerThread,+ providerTurnId: abandonedTurn.id,+ requestRuntimeRestart: true,+ }),+ );+ if (recovered._tag === "Failure") {+ if (input.willRetry === true) return yield* recovered.failure;+ yield* settleStartFailure({+ signal: "provider-turn-recovery-failure",+ title: "Provider turn recovery failed",+ error: recovered.failure,+ });+ return;+ }+ }+ const completedAt = yield* DateTime.now;+ const repaired = yield* eventSink.writeIfRunCurrent({+ threadId: projection.thread.id,+ runId: run.id,+ activeAttemptId: attempt.id,+ expectedStatus: "starting",+ events: yield* Effect.forEach(abandonedTurns, ({ turn, run: failedRun }) =>+ Effect.gen(function* () {+ return {+ id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),+ type: "provider-turn.updated" as const,+ threadId: projection.thread.id,+ runId: failedRun.id,+ nodeId: turn.nodeId,+ providerInstanceId: failedRun.providerInstanceId,+ occurredAt: completedAt,+ payload: { ...turn, status: "interrupted" as const, completedAt },+ };+ }),+ ),+ });+ if (!repaired.committed) return;+ }+ const sessionResult = yield* Effect.result(+ providerSessions.open({+ threadId: projection.thread.id,+ providerSessionId,+ modelSelection: run.modelSelection,+ runtimePolicy: resolvedRuntimePolicy,+ ...(existingSessionProjection === undefined+ ? {}+ : { resumeFromSession: existingSessionProjection }),+ ...(providerThread.nativeThreadRef?.nativeId == null+ ? {}+ : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),+ ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined+ ? {}+ : {+ initialProviderItemIdentityVersion:+ providerThread.nativeMetadata.itemIdentityVersion,+ }),+ }),+ );if (sessionResult._tag === "Failure") {if (input.willRetry === true) return yield* sessionResult.failure;yield* settleStartFailure({diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.tsindex 4dcfaa069f5..e7937f8a1fc 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts@@ -2487,6 +2487,152 @@ it.effect("refreshes pull requests after a provider stream exits with an error",}),);+it.effect.each(["failure", "defect", "interrupt-failure", "ownership-lost"] as const)(+ "stops the live provider and background work before settling an ingestion %s",+ (failureMode) =>+ Effect.gen(function* () {+ const started = yield* Deferred.make<void>();+ const stopped = yield* Deferred.make<void>();+ const backgroundWorkRunning = yield* Ref.make(true);+ const backgroundWorkAtFinalization = yield* Ref.make<boolean | null>(null);+ const now = yield* DateTime.now;+ const interrupts = yield* Ref.make<+ ReadonlyArray<ProviderAdapter.ProviderAdapterV2InterruptInput>+ >([]);+ const ids = backgroundScenarioIds(`ingestion:${failureMode}`);+ const { observed, finalEvents } = yield* captureRootRunTermination({+ key: `ingestion:${failureMode}`,+ initialProviderTurnId: null,+ rejectTerminalWrite: failureMode === "ownership-lost",+ shouldFinalizeRun: () => Effect.succeed(true),+ startTurn: () =>+ Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(stopped))),+ events: () =>+ Stream.unwrap(+ Deferred.await(started).pipe(+ Effect.as(+ Stream.make({+ type: "provider_turn.updated" as const,+ driver,+ providerTurn: {+ id: ids.rootProviderTurnId,+ providerThreadId: ids.providerThreadId,+ nodeId: ids.rootNodeId,+ runAttemptId: ids.attemptId,+ nativeTurnRef: null,+ ordinal: 1,+ status: "running" as const,+ startedAt: now,+ completedAt: null,+ },+ }),+ ),+ ),+ ),+ ingestNormalized: () => {+ const error = new ProviderEventIngestor.ProviderEventPublishError({+ providerSessionId: ProviderSessionId.make(`session:${failureMode}`),+ eventCount: 1,+ cause: new Error("SQLITE_FULL: database or disk is full"),+ });+ return failureMode === "defect" ? Effect.die(error) : Effect.fail(error);+ },+ interruptTurn: (input) =>+ Ref.update(interrupts, (current) => [...current, input]).pipe(+ Effect.andThen(+ input.requestRuntimeRestart === true && failureMode !== "interrupt-failure"+ ? Ref.set(backgroundWorkRunning, false)+ : Effect.void,+ ),+ Effect.andThen(Deferred.succeed(stopped, undefined)),+ Effect.andThen(+ failureMode === "interrupt-failure"+ ? Effect.fail(+ new ProviderAdapter.ProviderAdapterInterruptError({+ driver,+ providerThreadId: input.providerThread.id,+ providerTurnId: input.providerTurnId,+ cause: "provider already exited",+ }),+ )+ : Effect.void,+ ),+ ),+ beforeTerminalWrite: () =>+ Effect.gen(function* () {+ const calls = yield* Ref.get(interrupts);+ assert.equal(calls.length, 1);+ assert.equal(calls[0]?.providerTurnId, ids.rootProviderTurnId);+ assert.equal(calls[0]?.providerThread.id, ids.providerThreadId);+ yield* Ref.set(backgroundWorkAtFinalization, yield* Ref.get(backgroundWorkRunning));+ return true;+ }),+ });+ if (failureMode === "ownership-lost") {+ assert.deepEqual(finalEvents, []);+ assert.deepEqual(observed, []);+ } else {+ assert.equal(+ yield* Ref.get(backgroundWorkAtFinalization),+ failureMode === "interrupt-failure",+ );+ assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]);+ const repaired = finalEvents.find((event) => event.type === "provider-turn.updated");+ if (failureMode === "interrupt-failure") {+ assert.isUndefined(repaired);+ } else {+ assert.equal(repaired?.payload.id, ids.rootProviderTurnId);+ assert.equal(repaired?.payload.status, "interrupted");+ assert.isNotNull(repaired?.payload.completedAt);+ }+ }+ }),+);++it.effect("does not interrupt an ended provider when its terminal write fails", () =>+ Effect.gen(function* () {+ const interrupts = yield* Ref.make(0);+ const writes = yield* Ref.make(0);+ const { observed } = yield* captureRootRunTermination({+ key: "terminal-write-failure",+ shouldFinalizeRun: () => Effect.succeed(true),+ events: (ids) => Stream.make(rootTerminalEvent(ids, "completed")),+ interruptTurn: () => Ref.update(interrupts, (count) => count + 1),+ beforeTerminalWrite: () =>+ Effect.gen(function* () {+ if ((yield* Ref.updateAndGet(writes, (count) => count + 1)) === 1) {+ return yield* new EventSink.EventSinkWriteError({ eventCount: 1 });+ }+ return true;+ }),+ });+ assert.equal(yield* Ref.get(interrupts), 0);+ assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]);+ }),+);++it.effect("does not interrupt a provider when ingestion fails before the root turn is known", () =>+ Effect.gen(function* () {+ const interrupts = yield* Ref.make(0);+ const { observed } = yield* captureRootRunTermination({+ key: "unknown-turn-stream-error",+ initialProviderTurnId: null,+ shouldFinalizeRun: () => Effect.succeed(true),+ events: () =>+ Stream.fail(+ new ProviderAdapter.ProviderAdapterEventStreamError({+ driver,+ providerSessionId: ProviderSessionId.make("session:unknown-turn"),+ cause: "provider process exited",+ }),+ ),+ interruptTurn: () => Ref.update(interrupts, (count) => count + 1),+ });+ assert.equal(yield* Ref.get(interrupts), 0);+ assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]);+ }),+);+it.effect("fails the run when its event stream ends without a root terminal", () =>Effect.gen(function* () {const { observed, finalEvents } = yield* captureRootRunTermination({@@ -2564,6 +2710,8 @@ function captureRootRunTermination(input: {ProviderAdapter.ProviderAdapterV2Error>;readonly startTurn?: ProviderAdapter.ProviderAdapterV2SessionRuntime["startTurn"];+ readonly interruptTurn?: ProviderAdapter.ProviderAdapterV2SessionRuntime["interruptTurn"];+ readonly initialProviderTurnId?: ProviderTurnId | null;readonly onStartFailure?: (error: RunExecutionService.RunExecutionServiceV2Error,) => Effect.Effect<void>;@@ -2704,6 +2852,7 @@ function captureRootRunTermination(input: {),}),startTurn: input.startTurn ?? (() => Effect.void),+ interruptTurn: input.interruptTurn ?? (() => Effect.void),} as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime,run: {id: ids.runId,@@ -2724,7 +2873,10 @@ function captureRootRunTermination(input: {} as OrchestrationV2ProviderThread,attempt: {id: ids.attemptId,- providerTurnId: ids.rootProviderTurnId,+ providerTurnId:+ input.initialProviderTurnId === undefined+ ? ids.rootProviderTurnId+ : input.initialProviderTurnId,} as OrchestrationV2RunAttempt,attemptId: ids.attemptId,providerTurnOrdinal: 1,diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.tsindex 022b67d9cf4..a2b4f1de5bc 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts@@ -622,6 +622,7 @@ export const layer: Layer.Layer<readonly shouldFinalizeRun?: () => Effect.Effect<boolean, ProjectionStoreV2Error>;readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;+ readonly interruptedProviderTurn?: OrchestrationV2ProviderTurn;readonly terminal: ProviderTerminalEvent;readonly completedAt?: DateTime.Utc;readonly failureItemPersisted: boolean;@@ -743,6 +744,24 @@ export const layer: Layer.Layer<: [],events: [...cascadedSubagentEvents,+ ...(input.interruptedProviderTurn === undefined+ ? []+ : [+ {+ id: yield* allocateEventId(),+ type: "provider-turn.updated" as const,+ threadId: input.run.threadId,+ runId: input.run.id,+ nodeId: input.rootNode.id,+ providerInstanceId: input.run.providerInstanceId,+ occurredAt: completedAt,+ payload: {+ ...input.interruptedProviderTurn,+ status: "interrupted" as const,+ completedAt,+ },+ },+ ]),...(finalizedAttempt === null? []: [@@ -962,6 +981,7 @@ export const layer: Layer.Layer<const terminalEvent = yield* Ref.make<ProviderTerminalEvent | null>(null);const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);const latestProviderThread = yield* Ref.make(input.providerThread);+ const latestRootProviderTurn = yield* Ref.make<OrchestrationV2ProviderTurn | null>(null);const routeIdentity: ProviderEventRouteIdentity = {threadId: input.run.threadId,runId: input.run.id,@@ -1318,6 +1338,13 @@ export const layer: Layer.Layer<Stream.tap(({ event, accepted }) =>Effect.gen(function* () {if (!accepted) return;+ if (+ event.type === "provider_turn.updated" &&+ event.providerTurn.runAttemptId === input.attempt.id &&+ event.providerTurn.providerThreadId === input.providerThread.id+ ) {+ yield* Ref.set(latestRootProviderTurn, event.providerTurn);+ }let storedEventCount = 0;const deliveredEvent = filterAssistantEvent(event,@@ -1436,6 +1463,28 @@ export const layer: Layer.Layer<});if (yield* Ref.get(rootRunFinalized)) return;const providerThread = yield* Ref.get(latestProviderThread);+ const routing = yield* Ref.get(eventRouting);+ // Stop background work too; the failed consumer cannot persist terminal events.+ const interruptedProviderTurn =+ routing.rootProviderTurnId !== null && !routing.rootTurnEnded+ ? yield* input.session+ .interruptTurn({+ providerThread,+ providerTurnId: routing.rootProviderTurnId,+ requestRuntimeRestart: true,+ })+ .pipe(+ Effect.as(yield* Ref.get(latestRootProviderTurn)),+ Effect.catchCauseIf(+ (interruptCause) => !Cause.hasInterruptsOnly(interruptCause),+ (interruptCause) =>+ Effect.logWarning(+ "orchestration V2 failed to interrupt turn after ingestion failure",+ { runId: input.run.id, cause: interruptCause },+ ).pipe(Effect.as(null)),+ ),+ )+ : null;const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal);const openSubagents = yield* Ref.get(openRunOwnedSubagents);let nextRetryWarningAt = completedAt;@@ -1450,6 +1499,7 @@ export const layer: Layer.Layer<expectedStatus: "running",},openRunOwnedSubagents: openSubagents,+ ...(interruptedProviderTurn === null ? {} : { interruptedProviderTurn }),completedAt,terminal: makeFailedTerminalEvent(makeProviderFailure({ cause: Cause.squash(cause), class: "unknown" }),diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsxindex 11b56a19038..07d6164817c 100644--- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx+++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx@@ -330,12 +330,12 @@ function BackgroundWorktreeSetupChip({ snapshot }: { snapshot: WorktreeSetupSnapvariant="ghost-muted"size="micro"className="ml-auto min-w-0 shrink-0"- aria-label={`${scriptName} is still running. Show setup progress.`}+ aria-label={`Background setup is still running: ${scriptName}. Show setup progress.`}/>}><Spinner className="size-3 shrink-0" />- <span className="truncate">{scriptName}</span>+ <span className="truncate">Background setup</span></PopoverTrigger><PopoverPopup side="bottom" align="end" width="lg" padding="compact"><WorktreeSetupCard