Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useComposerResume.ts

165 lines5.9 KB

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