Open History to see the last commit
1import {
2 type EnvironmentId,
3 type ProviderInteractionMode,
4 type RunId,
5 type RuntimeMode,
6} from "@t3tools/contracts";
7import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
8import {
9 isAtomCommandInterrupted,
10 squashAtomCommandFailure,
11 type AtomCommandResult,
12} from "@t3tools/client-runtime/state/runtime";
13import { useState } from "react";
14import { newMessageId } from "~/lib/utils";
15import type { ComposerHandleRef } from "../../composerHandleContext";
16import { threadEnvironment } from "../../state/threads";
17import { useOrchestrationCommand } from "../../state/use-orchestration-command";
18import type { makeThreadErrorSetter } from "../ChatView.logic";
19import { draftSendState } from "./chatViewSend";
20import type { useTimelineFollow } from "./useTimelineFollow";
21import type { useUsageLimitsPanel } from "./useUsageLimitsPanel";
22
23interface ComposerResumeInput {
24 readonly environmentId: EnvironmentId;
25 readonly routeThreadKey: string;
26 readonly currentRouteThreadKeyRef: { readonly current: string | null };
27 readonly activeThread: EnvironmentThreadShell | undefined;
28 readonly resumableRunId: RunId | null;
29 readonly hasHeldQueuedRuns: boolean;
30 readonly isSendBusy: boolean;
31 readonly isConnecting: boolean;
32 readonly isRevertingCheckpoint: boolean;
33 readonly threadDetailLoading: boolean;
34 readonly activeEnvironmentUnavailable: boolean;
35 readonly runtimeMode: RuntimeMode;
36 readonly interactionMode: ProviderInteractionMode;
37 readonly localCheckoutBranchMismatch: { readonly currentBranch: string } | null;
38 readonly composerRef: ComposerHandleRef;
39 readonly persistThreadSettingsForNextTurn: (input: {
40 threadId: EnvironmentThreadShell["id"];
41 createdAt: string;
42 branch?: string;
43 runtimeMode: RuntimeMode;
44 interactionMode: ProviderInteractionMode;
45 }) => Promise<AtomCommandResult<void, unknown>>;
46 readonly clearUsageLimitsFor: ReturnType<typeof useUsageLimitsPanel>["clearFor"];
47 readonly scrollToEnd: ReturnType<typeof useTimelineFollow>["scrollToEnd"];
48 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
49}
50
51/**
52 * Resumes an interrupted run ("Continue where you left off.") and/or releases the turns held
53 * in its queue. Shares the per-route send lock with the composer's send paths.
54 */
55export function useComposerResume(input: ComposerResumeInput) {
56 const {
57 environmentId,
58 routeThreadKey,
59 currentRouteThreadKeyRef,
60 activeThread,
61 resumableRunId,
62 hasHeldQueuedRuns,
63 isSendBusy,
64 isConnecting,
65 isRevertingCheckpoint,
66 threadDetailLoading,
67 activeEnvironmentUnavailable,
68 runtimeMode,
69 interactionMode,
70 localCheckoutBranchMismatch,
71 composerRef,
72 persistThreadSettingsForNextTurn,
73 clearUsageLimitsFor,
74 scrollToEnd,
75 setThreadError,
76 } = input;
77 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
78 reportFailure: false,
79 });
80 const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, {
81 reportFailure: false,
82 });
83 const [resumingThreadKeys, setResumingThreadKeys] = useState<ReadonlySet<string>>(
84 () => new Set(),
85 );
86 const isResuming = resumingThreadKeys.has(routeThreadKey);
87 const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
88
89 const onResume = async () => {
90 if (
91 !activeThread ||
92 (resumableRunId === null && !hasHeldQueuedRuns) ||
93 isSendBusy ||
94 isResuming ||
95 isConnecting ||
96 isRevertingCheckpoint ||
97 threadDetailLoading ||
98 activeEnvironmentUnavailable ||
99 sendInFlightRef.current
100 ) {
101 return;
102 }
103 const threadId = activeThread.id;
104 sendInFlightRef.current = true;
105 setResumingThreadKeys((current) => new Set(current).add(routeThreadKey));
106 setThreadError(threadId, null);
107 // Commands settle into a result, so this always runs.
108 const resume = async () => {
109 if (resumableRunId === null) {
110 return resumeThreadQueue({ environmentId, input: { threadId } });
111 }
112 const createdAt = new Date().toISOString();
113 const settingsResult = await persistThreadSettingsForNextTurn({
114 threadId,
115 createdAt,
116 ...(localCheckoutBranchMismatch
117 ? { branch: localCheckoutBranchMismatch.currentBranch }
118 : {}),
119 runtimeMode,
120 interactionMode,
121 });
122 if (settingsResult._tag === "Failure") return settingsResult;
123 const modelSelection = composerRef.current?.getSendContext().selectedModelSelection;
124 const turnResult = await startThreadTurn({
125 environmentId,
126 input: {
127 threadId,
128 manualContinuationOfRunId: resumableRunId,
129 ...(modelSelection ? { modelSelection } : {}),
130 message: {
131 messageId: newMessageId(),
132 role: "user",
133 text: "Continue where you left off.",
134 attachments: [],
135 },
136 runtimeMode,
137 interactionMode,
138 dispatchMode: "start",
139 },
140 });
141 if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult;
142 clearUsageLimitsFor(routeThreadKey);
143 return resumeThreadQueue({ environmentId, input: { threadId } });
144 };
145 const result = await resume();
146 if (result._tag === "Failure") {
147 if (!isAtomCommandInterrupted(result)) {
148 const error = squashAtomCommandFailure(result);
149 setThreadError(
150 threadId,
151 error instanceof Error ? error.message : "Could not resume thread.",
152 );
153 }
154 } else {
155 clearUsageLimitsFor(routeThreadKey);
156 if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd();
157 }
158 sendInFlightRef.current = false;
159 setResumingThreadKeys((current) => {
160 const next = new Set(current);
161 next.delete(routeThreadKey);
162 return next;
163 });
164 };
165
166 return { onResume, isResuming };
167}