Skip to content

Commit 41b3b0b

Browse files
Srijan-Dclaudemaria-rcks
authored
fix(clients): background work Stop stays pending until the stopped tasks leave (#25002)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent cf4514d commit 41b3b0b

5 files changed

Lines changed: 186 additions & 26 deletions

File tree

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,11 @@ import {
5959
type ApprovalResponder,
6060
type ThreadUserInputQuestion,
6161
} from "@t3tools/client-runtime/state/thread-requests";
62+
import { useDeadlinePassed } from "../../lib/clock";
6263
import {
64+
BACKGROUND_WORK_STOP_RETRY_AFTER_MS,
65+
type BackgroundWorkStopRequest,
66+
isBackgroundWorkStopPending,
6367
presentPendingBackgroundWork,
6468
presentProviderGoal,
6569
} from "@t3tools/client-runtime/state/thread-execution";
@@ -357,15 +361,27 @@ const RECONNECT_ERROR_DELAY_MS = 5_000;
357361
// Anchors, the submitted message, follow state and pending scrolls belong to
358362
// one thread, so the body remounts when the thread changes.
359363
export function ThreadDetailScreen(props: ThreadDetailScreenProps) {
364+
const [statusRequests, setStatusRequests] = useState<
365+
Record<string, BackgroundWorkStopRequest | undefined>
366+
>({});
360367
return (
361368
<ThreadDetailBody
362369
key={scopedThreadKey(props.environmentId, props.selectedThread.id)}
363370
{...props}
371+
statusRequests={statusRequests}
372+
setStatusRequests={setStatusRequests}
364373
/>
365374
);
366375
}
367376

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+
) {
369385
const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
370386
const { layout } = useAdaptiveWorkspaceLayout();
371387
const deviceType = useDeviceType();
@@ -594,8 +610,13 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
594610
);
595611
}
596612
};
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+
);
599620
const [lifecycleNow, setLifecycleNow] = useState(() => new Date().toISOString());
600621
useFocusEffect(
601622
useCallback(() => {
@@ -627,8 +648,15 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
627648
});
628649
const runStatusAction = async (action: "stop" | "wake" | "unsettle" | "dismiss") => {
629650
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 }));
632660
const target = {
633661
environmentId: props.environmentId,
634662
input: { threadId: props.selectedThread.id },
@@ -662,8 +690,17 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
662690
...target,
663691
input: { ...target.input, visitedAt: wokeAt ?? lifecycleNow },
664692
});
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+
);
667704
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
668705
const error = squashAtomCommandFailure(result);
669706
Dialog.alert(

‎apps/web/src/components/chat/useThreadLifecycle.browser.test.tsx‎

Lines changed: 54 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as Cause from "effect/Cause";
12
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
23
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
34
import { expect, it, vi } from "vite-plus/test";
@@ -20,7 +21,7 @@ vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
2021

2122
vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({
2223
...(await importOriginal()),
23-
useOrchestrationCommand: (() => async () => ({ _tag: "Success", value: undefined })) as never,
24+
useOrchestrationCommand: (() => (input: unknown) => state.switchRef(input)) as never,
2425
}));
2526

2627
vi.mock(import("../../hooks/useThreadActions"), async (importOriginal) => ({
@@ -77,7 +78,7 @@ function RestoreBranchHarness(props: {
7778
serverConfig: null,
7879
runtimeMode: "full-access" as never,
7980
isWorking: false,
80-
pendingBackgroundTasks: [],
81+
pendingBackgroundTasks: [{ taskId: "background-command", kind: "command" }] as never,
8182
turnItems: [],
8283
activePendingApproval: null as never,
8384
activePendingUserInput: null as never,
@@ -95,13 +96,16 @@ function RestoreBranchHarness(props: {
9596
persistThreadSettingsForNextTurn: async () => ({ _tag: "Success", value: undefined }) as never,
9697
});
9798
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+
</>
105109
);
106110
}
107111

@@ -181,3 +185,44 @@ it.each(["a", "b", "navigation"] as const)(
181185
expect(focusComposer).toHaveBeenCalledTimes(scenario === "navigation" ? 0 : 1);
182186
},
183187
);
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‎

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
makeThreadErrorSetter,
1313
} from "../ChatView.logic";
1414
import { useStableCallback } from "../../hooks/useStableCallback";
15-
import { useNowAfter } from "../../hooks/useDeadline";
15+
import { useDeadlinePassed, useNowAfter } from "../../hooks/useDeadline";
1616
import type { usePendingThreadRequests } from "./usePendingThreadRequests";
1717
import {
1818
AuthOrchestrationOperateScope,
@@ -28,6 +28,11 @@ import {
2828
snoozeWakeLabel,
2929
threadWokeAt,
3030
} 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";
3136
import { useAcknowledgeThreadWoke, useThreadActions } from "../../hooks/useThreadActions";
3237
import { settleAndAdvance } from "../../settleAndAdvance";
3338
import type { ChatShortcutCommands } from "./useChatShortcuts";
@@ -400,21 +405,44 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
400405
// The interrupt path also accepts a completed run while its provider still
401406
// has background work.
402407
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+
);
406418
const handleStopBackgroundWork = async () => {
407-
if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
419+
if (
420+
isStoppingBackgroundWork ||
421+
!activeThread ||
422+
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
423+
)
408424
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 }));
411431
const result = await interruptThreadTurn({
412432
environmentId,
413433
input: { threadId: activeThread.id },
414434
});
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+
);
418446
if (result._tag === "Failure") {
419447
if (!isAtomCommandInterrupted(result)) {
420448
const error = squashAtomCommandFailure(result);

‎packages/client-runtime/src/state/threadExecution.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
deriveRunlessWorkStartedAt,
2727
deriveThreadActivityRun,
2828
deriveThreadRuntime,
29+
isBackgroundWorkStopPending,
2930
presentPendingBackgroundWork,
3031
presentProviderGoal,
3132
presentRunStop,
@@ -472,6 +473,35 @@ describe("provider-reported model selection", () => {
472473
});
473474
});
474475

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+
475505
describe("presentProviderGoal", () => {
476506
it("rolls token counts that round to 1000k over to 1m", () => {
477507
const usage = (tokensUsed: number) =>

‎packages/client-runtime/src/state/threadExecution.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,26 @@ function joinWithAnd(parts: ReadonlyArray<string>): string {
378378
return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
379379
}
380380

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+
381401
export function presentPendingBackgroundWork(
382402
tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
383403
): PendingBackgroundWorkPresentation | null {

0 commit comments

Comments
 (0)