Skip to content

Commit ef18f8e

Browse files
Srijan-Dclaude
andcommitted
fix(clients): background work Stop stays pending until the stopped tasks leave
Fixes #24993. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b3b2c55 commit ef18f8e

4 files changed

Lines changed: 105 additions & 13 deletions

File tree

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

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ import {
6161
type ThreadUserInputQuestion,
6262
} from "@t3tools/client-runtime/state/thread-requests";
6363
import {
64+
BACKGROUND_WORK_STOP_RETRY_AFTER_MS,
65+
type BackgroundWorkStopRequest,
66+
isBackgroundWorkStopPending,
6467
presentPendingBackgroundWork,
6568
presentProviderGoal,
6669
} from "@t3tools/client-runtime/state/thread-execution";
@@ -669,8 +672,19 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
669672
const unsettleThread = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
670673
const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });
671674
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
672-
const [statusRequest, setStatusRequest] = useState<{ threadKey: string } | null>(null);
673-
const statusPending = statusRequest?.threadKey === selectedThreadKey;
675+
const [statusRequest, setStatusRequest] = useState<BackgroundWorkStopRequest | null>(null);
676+
const statusPending = isBackgroundWorkStopPending(
677+
statusRequest,
678+
selectedThreadKey,
679+
props.selectedThread.pendingBackgroundTasks,
680+
);
681+
useEffect(() => {
682+
if (statusRequest?.accepted !== true) return;
683+
const timer = setTimeout(() => {
684+
setStatusRequest((current) => (current === statusRequest ? null : current));
685+
}, BACKGROUND_WORK_STOP_RETRY_AFTER_MS);
686+
return () => clearTimeout(timer);
687+
}, [statusRequest]);
674688
const [lifecycleNow, setLifecycleNow] = useState(() => new Date().toISOString());
675689
useFocusEffect(
676690
useCallback(() => {
@@ -707,7 +721,14 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
707721
});
708722
const runStatusAction = async (action: "stop" | "wake" | "unsettle" | "dismiss") => {
709723
if (statusPending || !props.canOperateThread) return;
710-
const request = { threadKey: selectedThreadKey };
724+
const request: BackgroundWorkStopRequest = {
725+
threadKey: selectedThreadKey,
726+
taskIds:
727+
action === "stop"
728+
? props.selectedThread.pendingBackgroundTasks.map((task) => task.taskId)
729+
: [],
730+
accepted: false,
731+
};
711732
setStatusRequest(request);
712733
const target = {
713734
environmentId: props.environmentId,
@@ -742,8 +763,13 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
742763
...target,
743764
input: { ...target.input, visitedAt: wokeAt ?? lifecycleNow },
744765
});
745-
// An accepted interrupt can leave tasks running. Release the action for retry.
746-
setStatusRequest((current) => (current === request ? null : current));
766+
setStatusRequest((current) =>
767+
current !== request
768+
? current
769+
: action === "stop" && result._tag !== "Failure"
770+
? { ...request, accepted: true }
771+
: null,
772+
);
747773
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
748774
const error = squashAtomCommandFailure(result);
749775
Dialog.alert(

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

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ import {
2323
RuntimeMode,
2424
} from "@t3tools/contracts";
2525
import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
26+
import {
27+
BACKGROUND_WORK_STOP_RETRY_AFTER_MS,
28+
type BackgroundWorkStopRequest,
29+
isBackgroundWorkStopPending,
30+
} from "@t3tools/client-runtime/state/thread-execution";
2631
import { useAcknowledgeThreadWoke, useThreadActions } from "../../hooks/useThreadActions";
2732
import { settleAndAdvance } from "../../settleAndAdvance";
2833
import type { ChatShortcutCommands } from "./useChatShortcuts";
@@ -386,21 +391,41 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
386391
// The interrupt path also accepts a completed run while its provider still
387392
// has background work.
388393
const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : [];
389-
const [stoppingBackgroundWorkKey, setStoppingBackgroundWorkKey] = useState<string | null>(null);
390-
const isStoppingBackgroundWork =
391-
stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`;
394+
const [backgroundWorkStop, setBackgroundWorkStop] = useState<BackgroundWorkStopRequest | null>(
395+
null,
396+
);
397+
const isStoppingBackgroundWork = isBackgroundWorkStopPending(
398+
backgroundWorkStop,
399+
`${environmentId}:${activeThreadId}`,
400+
pendingBackgroundTasks,
401+
);
402+
useEffect(() => {
403+
if (backgroundWorkStop?.accepted !== true) return;
404+
const timer = setTimeout(() => {
405+
setBackgroundWorkStop((current) => (current === backgroundWorkStop ? null : current));
406+
}, BACKGROUND_WORK_STOP_RETRY_AFTER_MS);
407+
return () => clearTimeout(timer);
408+
}, [backgroundWorkStop]);
392409
const handleStopBackgroundWork = async () => {
393410
if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
394411
return;
395-
const requestKey = `${environmentId}:${activeThread.id}`;
396-
setStoppingBackgroundWorkKey(requestKey);
412+
const request: BackgroundWorkStopRequest = {
413+
threadKey: `${environmentId}:${activeThread.id}`,
414+
taskIds: pendingBackgroundTasks.map((task) => task.taskId),
415+
accepted: false,
416+
};
417+
setBackgroundWorkStop(request);
397418
const result = await interruptThreadTurn({
398419
environmentId,
399420
input: { threadId: activeThread.id },
400421
});
401-
// Acceptance does not confirm termination. Allow retry while the provider
402-
// finishes stopping the tasks or reports a failure.
403-
setStoppingBackgroundWorkKey((current) => (current === requestKey ? null : current));
422+
setBackgroundWorkStop((current) =>
423+
current !== request
424+
? current
425+
: result._tag === "Failure"
426+
? null
427+
: { ...request, accepted: true },
428+
);
404429
if (result._tag === "Failure") {
405430
if (!isAtomCommandInterrupted(result)) {
406431
const error = squashAtomCommandFailure(result);

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
deriveRunlessWorkStartedAt,
2626
deriveThreadActivityRun,
2727
deriveThreadRuntime,
28+
isBackgroundWorkStopPending,
2829
threadRuntimeHasInterruptibleRun,
2930
} from "./threadExecution.ts";
3031

@@ -393,3 +394,24 @@ describe("provider-reported model selection", () => {
393394
).toBeNull();
394395
});
395396
});
397+
398+
describe("isBackgroundWorkStopPending", () => {
399+
const tasks = [{ taskId: "dev-server" }];
400+
const sent = { threadKey: "env:thread", taskIds: ["dev-server"], accepted: false };
401+
const accepted = { ...sent, accepted: true };
402+
403+
it("stays pending after acceptance while a stopped task is still listed", () => {
404+
expect(isBackgroundWorkStopPending(sent, "env:thread", tasks)).toBe(true);
405+
expect(isBackgroundWorkStopPending(accepted, "env:thread", tasks)).toBe(true);
406+
});
407+
408+
it("ends once the stopped tasks leave, even if new work starts", () => {
409+
expect(isBackgroundWorkStopPending(accepted, "env:thread", [])).toBe(false);
410+
expect(isBackgroundWorkStopPending(accepted, "env:thread", [{ taskId: "next" }])).toBe(false);
411+
});
412+
413+
it("only applies to the thread that sent the Stop", () => {
414+
expect(isBackgroundWorkStopPending(null, "env:thread", tasks)).toBe(false);
415+
expect(isBackgroundWorkStopPending(sent, "env:other", tasks)).toBe(false);
416+
});
417+
});

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,25 @@ function joinWithAnd(parts: ReadonlyArray<string>): string {
311311
return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
312312
}
313313

314+
// The Claude adapter forces a stuck query closed after 10 seconds.
315+
export const BACKGROUND_WORK_STOP_RETRY_AFTER_MS = 10_000;
316+
317+
export interface BackgroundWorkStopRequest {
318+
readonly threadKey: string;
319+
readonly taskIds: ReadonlyArray<string>;
320+
readonly accepted: boolean;
321+
}
322+
323+
/** Acceptance does not end the tasks, so an accepted Stop stays pending while they are listed. */
324+
export function isBackgroundWorkStopPending(
325+
request: BackgroundWorkStopRequest | null,
326+
threadKey: string,
327+
tasks: ReadonlyArray<Pick<OrchestrationV2PendingBackgroundTask, "taskId">>,
328+
): boolean {
329+
if (request === null || request.threadKey !== threadKey) return false;
330+
return !request.accepted || tasks.some((task) => request.taskIds.includes(task.taskId));
331+
}
332+
314333
export function presentPendingBackgroundWork(
315334
tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
316335
): PendingBackgroundWorkPresentation | null {

0 commit comments

Comments
 (0)