The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 08:15 UTC
fix(clients): background work Stop stays pending until the stopped tasks leave (#25002)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>
Srijan Dubey committed
Nov 2, 2026 at 02:26 UTC
41b3b0b1b636c0334d74e72132ceefb1005d4973
5 files changed
+186
-26
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+44
-7
@@ -59,7 +59,11 @@ import {
59
type ApprovalResponder,
60
type ThreadUserInputQuestion,
61
} from "@t3tools/client-runtime/state/thread-requests";
62
+import { useDeadlinePassed } from "../../lib/clock";
63
import {
64
+ BACKGROUND_WORK_STOP_RETRY_AFTER_MS,
65
+ type BackgroundWorkStopRequest,
66
+ isBackgroundWorkStopPending,
67
presentPendingBackgroundWork,
68
presentProviderGoal,
69
} from "@t3tools/client-runtime/state/thread-execution";
@@ -357,15 +361,27 @@ const RECONNECT_ERROR_DELAY_MS = 5_000;
361
// Anchors, the submitted message, follow state and pending scrolls belong to
362
// one thread, so the body remounts when the thread changes.
363
export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
364
+ const [statusRequests, setStatusRequests] = useState<
365
+ Record<string, BackgroundWorkStopRequest | undefined>
366
+ >({});
367
return (
368
<ThreadDetailBody
369
key={scopedThreadKey(props.environmentId, props.selectedThread.id)}
370
{...props}
371
+ statusRequests={statusRequests}
372
+ setStatusRequests={setStatusRequests}
373
/>
374
);
375
}
376
368
-function ThreadDetailBody(props: ThreadDetailScreenProps) {
377
+function ThreadDetailBody(
378
+ props: ThreadDetailScreenProps & {
379
+ statusRequests: Record<string, BackgroundWorkStopRequest | undefined>;
380
+ setStatusRequests: React.Dispatch<
381
+ React.SetStateAction<Record<string, BackgroundWorkStopRequest | undefined>>
382
+ >;
383
+ },
384
+) {
385
const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
386
const { layout } = useAdaptiveWorkspaceLayout();
387
const deviceType = useDeviceType();
@@ -594,8 +610,13 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
610
);
611
}
612
};
597
- const [statusRequest, setStatusRequest] = useState<{ threadKey: string } | null>(null);
598
- const statusPending = statusRequest?.threadKey === selectedThreadKey;
613
+ const statusRequest = props.statusRequests[selectedThreadKey] ?? null;
614
+ const statusPending = isBackgroundWorkStopPending(
615
+ statusRequest,
616
+ selectedThreadKey,
617
+ props.selectedThread.pendingBackgroundTasks,
618
+ useDeadlinePassed(statusRequest?.retryAt ?? null),
619
+ );
620
const [lifecycleNow, setLifecycleNow] = useState(() => new Date().toISOString());
621
useFocusEffect(
622
useCallback(() => {
@@ -627,8 +648,15 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
648
});
649
const runStatusAction = async (action: "stop" | "wake" | "unsettle" | "dismiss") => {
650
if (statusPending || !props.canOperateThread) return;
630
- const request = { threadKey: selectedThreadKey };
631
- setStatusRequest(request);
651
+ const request: BackgroundWorkStopRequest = {
652
+ threadKey: selectedThreadKey,
653
+ taskIds:
654
+ action === "stop"
655
+ ? props.selectedThread.pendingBackgroundTasks.map((task) => task.taskId)
656
+ : [],
657
+ retryAt: null,
658
+ };
659
+ props.setStatusRequests((current) => ({ ...current, [request.threadKey]: request }));
660
const target = {
661
environmentId: props.environmentId,
662
input: { threadId: props.selectedThread.id },
@@ -662,8 +690,17 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
690
...target,
691
input: { ...target.input, visitedAt: wokeAt ?? lifecycleNow },
692
});
665
- // An accepted interrupt can leave tasks running. Release the action for retry.
666
- setStatusRequest((current) => (current === request ? null : current));
693
+ props.setStatusRequests((current) =>
694
+ current[request.threadKey] !== request
695
+ ? current
696
+ : {
697
+ ...current,
698
+ [request.threadKey]:
699
+ action === "stop" && result._tag !== "Failure"
700
+ ? { ...request, retryAt: Date.now() + BACKGROUND_WORK_STOP_RETRY_AFTER_MS }
701
+ : undefined,
702
+ },
703
+ );
704
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
705
const error = squashAtomCommandFailure(result);
706
Dialog.alert(
apps/web/src/components/chat/useThreadLifecycle.browser.test.tsx
+54
-9
@@ -1,3 +1,4 @@
1
+import * as Cause from "effect/Cause";
2
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
3
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4
import { expect, it, vi } from "vite-plus/test";
@@ -20,7 +21,7 @@ vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
21
22
vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({
23
...(await importOriginal()),
23
- useOrchestrationCommand: (() => async () => ({ _tag: "Success", value: undefined })) as never,
24
+ useOrchestrationCommand: (() => (input: unknown) => state.switchRef(input)) as never,
25
}));
26
27
vi.mock(import("../../hooks/useThreadActions"), async (importOriginal) => ({
@@ -77,7 +78,7 @@ function RestoreBranchHarness(props: {
78
serverConfig: null,
79
runtimeMode: "full-access" as never,
80
isWorking: false,
80
- pendingBackgroundTasks: [],
81
+ pendingBackgroundTasks: [{ taskId: "background-command", kind: "command" }] as never,
82
turnItems: [],
83
activePendingApproval: null as never,
84
activePendingUserInput: null as never,
@@ -95,13 +96,16 @@ function RestoreBranchHarness(props: {
96
persistThreadSettingsForNextTurn: async () => ({ _tag: "Success", value: undefined }) as never,
97
});
98
return (
98
- <button
99
- type="button"
100
- disabled={lifecycle.isRestoringThreadBranch}
101
- onClick={lifecycle.handleSwitchCheckoutToThreadStable}
102
- >
103
- {lifecycle.isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
104
- </button>
99
+ <>
100
+ {lifecycle.workNow?.actions}
101
+ <button
102
+ type="button"
103
+ disabled={lifecycle.isRestoringThreadBranch}
104
+ onClick={lifecycle.handleSwitchCheckoutToThreadStable}
105
+ >
106
+ {lifecycle.isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
107
+ </button>
108
+ </>
109
);
110
}
111
@@ -181,3 +185,44 @@ it.each(["a", "b", "navigation"] as const)(
185
expect(focusComposer).toHaveBeenCalledTimes(scenario === "navigation" ? 0 : 1);
186
},
187
);
188
+
189
+it.each(["Success", "Failure"] as const)(
190
+ "keeps background stop requests per thread after %s",
191
+ async (outcome) => {
192
+ setup();
193
+ const completions: Array<(result: unknown) => void> = [];
194
+ state.switchRef = vi.fn(() => new Promise((resolve) => completions.push(resolve)));
195
+ const threadA = threadInput("thread:a", "feature-a");
196
+ const threadB = threadInput("thread:b", "feature-b");
197
+ const currentRouteThreadKeyRef = { current: threadA.routeThreadKey };
198
+ const harness = (thread: ThreadInput) => (
199
+ <RestoreBranchHarness
200
+ thread={thread}
201
+ currentRouteThreadKeyRef={currentRouteThreadKeyRef}
202
+ refreshGitStatus={() => undefined}
203
+ focusComposer={() => undefined}
204
+ />
205
+ );
206
+ await using screen = await render(harness(threadA));
207
+ await page.getByRole("button", { name: "Stop", exact: true }).click();
208
+ await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
209
+ await screen.rerender(harness(threadB));
210
+ await page.getByRole("button", { name: "Stop", exact: true }).click();
211
+ await screen.rerender(harness(threadA));
212
+ await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
213
+ completions[0]!(
214
+ outcome === "Success"
215
+ ? { _tag: "Success", value: undefined }
216
+ : { _tag: "Failure", cause: Cause.fail(new Error("stop failed")) },
217
+ );
218
+ if (outcome === "Success") {
219
+ await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
220
+ } else {
221
+ await expect.element(page.getByRole("button", { name: "Stop", exact: true })).toBeEnabled();
222
+ }
223
+ await screen.rerender(harness(threadB));
224
+ await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
225
+ expect(state.switchRef).toHaveBeenCalledTimes(2);
226
+ completions[1]!({ _tag: "Success", value: undefined });
227
+ },
228
+);
apps/web/src/components/chat/useThreadLifecycle.tsx
+38
-10
@@ -12,7 +12,7 @@ import {
12
makeThreadErrorSetter,
13
} from "../ChatView.logic";
14
import { useStableCallback } from "../../hooks/useStableCallback";
15
-import { useNowAfter } from "../../hooks/useDeadline";
15
+import { useDeadlinePassed, useNowAfter } from "../../hooks/useDeadline";
16
import type { usePendingThreadRequests } from "./usePendingThreadRequests";
17
import {
18
AuthOrchestrationOperateScope,
@@ -28,6 +28,11 @@ import {
28
snoozeWakeLabel,
29
threadWokeAt,
30
} from "@t3tools/client-runtime/state/thread-settled";
31
+import {
32
+ BACKGROUND_WORK_STOP_RETRY_AFTER_MS,
33
+ type BackgroundWorkStopRequest,
34
+ isBackgroundWorkStopPending,
35
+} from "@t3tools/client-runtime/state/thread-execution";
36
import { useAcknowledgeThreadWoke, useThreadActions } from "../../hooks/useThreadActions";
37
import { settleAndAdvance } from "../../settleAndAdvance";
38
import type { ChatShortcutCommands } from "./useChatShortcuts";
@@ -400,21 +405,44 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
405
// The interrupt path also accepts a completed run while its provider still
406
// has background work.
407
const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : [];
403
- const [stoppingBackgroundWorkKey, setStoppingBackgroundWorkKey] = useState<string | null>(null);
404
- const isStoppingBackgroundWork =
405
- stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`;
408
+ const [backgroundWorkStops, setBackgroundWorkStops] = useState<
409
+ Record<string, BackgroundWorkStopRequest | undefined>
410
+ >({});
411
+ const backgroundWorkStop = backgroundWorkStops[`${environmentId}:${activeThreadId}`] ?? null;
412
+ const isStoppingBackgroundWork = isBackgroundWorkStopPending(
413
+ backgroundWorkStop,
414
+ `${environmentId}:${activeThreadId}`,
415
+ pendingBackgroundTasks,
416
+ useDeadlinePassed(backgroundWorkStop?.retryAt ?? null),
417
+ );
418
const handleStopBackgroundWork = async () => {
407
- if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
419
+ if (
420
+ isStoppingBackgroundWork ||
421
+ !activeThread ||
422
+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
423
+ )
424
return;
409
- const requestKey = `${environmentId}:${activeThread.id}`;
410
- setStoppingBackgroundWorkKey(requestKey);
425
+ const request: BackgroundWorkStopRequest = {
426
+ threadKey: `${environmentId}:${activeThread.id}`,
427
+ taskIds: pendingBackgroundTasks.map((task) => task.taskId),
428
+ retryAt: null,
429
+ };
430
+ setBackgroundWorkStops((current) => ({ ...current, [request.threadKey]: request }));
431
const result = await interruptThreadTurn({
432
environmentId,
433
input: { threadId: activeThread.id },
434
});
415
- // Acceptance does not confirm termination. Allow retry while the provider
416
- // finishes stopping the tasks or reports a failure.
417
- setStoppingBackgroundWorkKey((current) => (current === requestKey ? null : current));
435
+ setBackgroundWorkStops((current) =>
436
+ current[request.threadKey] !== request
437
+ ? current
438
+ : {
439
+ ...current,
440
+ [request.threadKey]:
441
+ result._tag === "Failure"
442
+ ? undefined
443
+ : { ...request, retryAt: Date.now() + BACKGROUND_WORK_STOP_RETRY_AFTER_MS },
444
+ },
445
+ );
446
if (result._tag === "Failure") {
447
if (!isAtomCommandInterrupted(result)) {
448
const error = squashAtomCommandFailure(result);
packages/client-runtime/src/state/threadExecution.test.ts
+30
@@ -26,6 +26,7 @@ import {
26
deriveRunlessWorkStartedAt,
27
deriveThreadActivityRun,
28
deriveThreadRuntime,
29
+ isBackgroundWorkStopPending,
30
presentPendingBackgroundWork,
31
presentProviderGoal,
32
presentRunStop,
@@ -472,6 +473,35 @@ describe("provider-reported model selection", () => {
473
});
474
});
475
476
+describe("isBackgroundWorkStopPending", () => {
477
+ const tasks = [{ taskId: "dev-server" }];
478
+ const sent = { threadKey: "env:thread", taskIds: ["dev-server"], retryAt: null };
479
+ const accepted = { ...sent, retryAt: 10_000 };
480
+
481
+ it("stays pending after acceptance while a stopped task is still listed", () => {
482
+ expect(isBackgroundWorkStopPending(sent, "env:thread", tasks, false)).toBe(true);
483
+ expect(isBackgroundWorkStopPending(accepted, "env:thread", tasks, false)).toBe(true);
484
+ });
485
+
486
+ it("ends once the stopped tasks leave, even if new work starts", () => {
487
+ expect(isBackgroundWorkStopPending(accepted, "env:thread", [], false)).toBe(false);
488
+ expect(isBackgroundWorkStopPending(accepted, "env:thread", [{ taskId: "next" }], false)).toBe(
489
+ false,
490
+ );
491
+ });
492
+
493
+ it("allows retry at the deadline even if a stopped task remains", () => {
494
+ const request = { ...accepted, retryAt: 10_000 };
495
+ expect(isBackgroundWorkStopPending(request, "env:thread", tasks, false)).toBe(true);
496
+ expect(isBackgroundWorkStopPending(request, "env:thread", tasks, true)).toBe(false);
497
+ });
498
+
499
+ it("only applies to the thread that sent the Stop", () => {
500
+ expect(isBackgroundWorkStopPending(null, "env:thread", tasks, false)).toBe(false);
501
+ expect(isBackgroundWorkStopPending(sent, "env:other", tasks, false)).toBe(false);
502
+ });
503
+});
504
+
505
describe("presentProviderGoal", () => {
506
it("rolls token counts that round to 1000k over to 1m", () => {
507
const usage = (tokensUsed: number) =>
packages/client-runtime/src/state/threadExecution.ts
+20
@@ -378,6 +378,26 @@ function joinWithAnd(parts: ReadonlyArray<string>): string {
378
return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
379
}
380
381
+// The Claude adapter forces a stuck query closed after 10 seconds.
382
+export const BACKGROUND_WORK_STOP_RETRY_AFTER_MS = 10_000;
383
+
384
+export interface BackgroundWorkStopRequest {
385
+ readonly threadKey: string;
386
+ readonly taskIds: ReadonlyArray<string>;
387
+ readonly retryAt: number | null;
388
+}
389
+
390
+/** Acceptance does not end the tasks, so an accepted Stop stays pending while they are listed. */
391
+export function isBackgroundWorkStopPending(
392
+ request: BackgroundWorkStopRequest | null,
393
+ threadKey: string,
394
+ tasks: ReadonlyArray<Pick<OrchestrationV2PendingBackgroundTask, "taskId">>,
395
+ retryExpired: boolean,
396
+): boolean {
397
+ if (request === null || request.threadKey !== threadKey || retryExpired) return false;
398
+ return request.retryAt === null || tasks.some((task) => request.taskIds.includes(task.taskId));
399
+}
400
+
401
export function presentPendingBackgroundWork(
402
tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
403
): PendingBackgroundWorkPresentation | null {