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

useTimelineRewind.ts

284 lines10.3 KB

1import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-runtime/state/shell";
2import type { ComposerThreadTarget } from "../../composerDraftStore";
3import type { ComposerHandleRef } from "../../composerHandleContext";
4import type { SessionPhase } from "../../types";
5import { useStableCallback } from "../../hooks/useStableCallback";
6import {
7 AuthOrchestrationOperateScope,
8 type EnvironmentId,
9 type MessageId,
10 type ScopedThreadRef,
11 type ThreadId,
12 type RunId,
13} from "@t3tools/contracts";
14import { scopeThreadRef } from "@t3tools/client-runtime/environment";
15import { useNavigate } from "@tanstack/react-router";
16import {
17 isAtomCommandInterrupted,
18 squashAtomCommandFailure,
19} from "@t3tools/client-runtime/state/runtime";
20import { readLocalApi } from "../../localApi";
21import { findRevertCheckpoint } from "../../session-logic";
22import { type ChatMessage } from "../../types";
23import { newThreadId } from "~/lib/utils";
24import { buildThreadRouteParams } from "../../threadRoutes";
25import { useComposerDraftStore } from "../../composerDraftStore";
26import { threadEnvironment } from "../../state/threads";
27import { waitForThreadShell } from "../../state/entities";
28import { openRevertConfirm } from "./ChatOverlayHosts";
29import { assetEnvironment } from "../../state/assets";
30import { readEnvironmentScope } from "../../state/session";
31import { useAtomCommand } from "../../state/use-atom-command";
32import { useOrchestrationCommand } from "../../state/use-orchestration-command";
33import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
34import { rewindToMessage } from "./chatViewSend";
35import { makeThreadErrorSetter } from "../ChatView.logic";
36interface TimelineRewindInput {
37 readonly environmentId: EnvironmentId;
38 readonly routeThreadRef: ScopedThreadRef;
39 readonly routeThreadKey: string;
40 readonly currentRouteThreadKeyRef: { readonly current: string | null };
41 readonly serverProjection: ThreadStructure | null;
42 readonly activeThread: EnvironmentThreadShell | undefined;
43 readonly timelineMessages: ReadonlyArray<ChatMessage>;
44 readonly phase: SessionPhase;
45 readonly isConnecting: boolean;
46 readonly isSendBusy: boolean;
47 readonly isRevertingCheckpoint: boolean;
48 readonly supportsConversationRollback: boolean;
49 readonly activeEnvironmentUnavailable: boolean;
50 readonly activeEnvironmentUnavailableLabel: string | null;
51 readonly promptRef: { current: string };
52 readonly composerRef: ComposerHandleRef;
53 readonly composerDraftTarget: ComposerThreadTarget;
54 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
56​
57/**
58 * Going back in a thread's timeline: reverting to an earlier turn (restoring that message into
59 * the composer), rolling back a provider checkpoint, and forking a new thread from a run.
60 */
61export function useTimelineRewind(input: TimelineRewindInput) {
62 const {
63 environmentId,
64 routeThreadRef,
65 routeThreadKey,
66 currentRouteThreadKeyRef,
67 serverProjection,
68 activeThread,
69 timelineMessages,
70 phase,
71 isConnecting,
72 isSendBusy,
73 isRevertingCheckpoint,
74 supportsConversationRollback,
75 activeEnvironmentUnavailable,
76 activeEnvironmentUnavailableLabel,
77 promptRef,
78 composerRef,
79 composerDraftTarget,
80 setThreadError,
81 } = input;
82 const navigate = useNavigate();
83 const createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
84 reportFailure: false,
85 refresh: true,
86 });
87​
88 const revertThreadCheckpoint = useOrchestrationCommand(threadEnvironment.revertCheckpoint, {
89 reportFailure: false,
90 });
91 const forkThreadFromRun = useAtomCommand(threadEnvironment.forkFromRun, {
92 reportFailure: false,
93 });
94​
95 const onRevertToTurnCount = async (
96 turnCount: number,
97 messageId: MessageId,
98 restoreFiles?: boolean,
99 ) => {
100 const localApi = readLocalApi();
101 if (
102 !localApi ||
103 !activeThread ||
104 isRevertingCheckpoint ||
105 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
106 )
107 return;
108 const message = timelineMessages.find((message) => message.id === messageId);
109 if (!message || message.role !== "user") return;
110​
111 if (!supportsConversationRollback) {
112 setThreadError(
113 activeThread.id,
114 "This provider does not support reverting conversation history. Start a new thread instead.",
115 );
116 return;
117 }
118 if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
119 setThreadError(
120 activeThread.id,
121 `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,
122 );
123 return;
124 }
125 if (phase === "running" || isSendBusy || isConnecting) {
126 setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
127 return;
128 }
129 if (restoreFiles === undefined) {
130 openRevertConfirm(routeThreadKey, { turnCount, messageId });
131 return;
132 }
133​
134 useComposerDraftStore.setState((store) => ({
135 rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey),
136 }));
137 setThreadError(activeThread.id, null);
138 const rewind = await rewindToMessage({
139 message,
140 environmentId,
141 routeThreadRef,
142 threadId: activeThread.id,
143 turnCount,
144 restoreFiles,
145 // Keep the live checkpoint identity when command context refetches a bounded window.
146 checkpoint: findRevertCheckpoint(serverProjection?.checkpoints ?? [], turnCount),
147 draftTarget: composerDraftTarget,
148 composerHasPendingAttachments: composerRef.current?.hasPendingAttachments() === true,
149 createAssetUrl: createAttachmentAssetUrl,
150 revertThreadCheckpoint,
151 });
152 useComposerDraftStore.setState((store) => {
153 const remaining = new Set(store.rewindingThreadKeys);
154 remaining.delete(routeThreadKey);
155 return { rewindingThreadKeys: remaining };
156 });
157 if (rewind.error !== null) {
158 setThreadError(activeThread.id, rewind.error);
159 return;
160 }
161 if (currentRouteThreadKeyRef.current === routeThreadKey) {
162 const nextPrompt = rewind.prompt;
163 promptRef.current = nextPrompt;
164 composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length });
165 requestAnimationFrame(() => {
166 if (currentRouteThreadKeyRef.current === routeThreadKey) composerRef.current?.focusAtEnd();
167 });
168 }
169 };
170 const onRevertToTurnCountStable = useStableCallback(onRevertToTurnCount);
171 const onConfirmRevert = (turnCount: number, messageId: MessageId, restoreFiles: boolean) => {
172 void onRevertToTurnCount(turnCount, messageId, restoreFiles);
173 };
174 const onConfirmRevertStable = useStableCallback(onConfirmRevert);
175​
176 const onRollbackCheckpoint = async (input: {
177 readonly checkpointId: string;
178 readonly scopeId: string;
179 }) => {
180 if (!activeThread || isRevertingCheckpoint) return;
181 if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
182 setThreadError(
183 activeThread.id,
184 `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,
185 );
186 return;
187 }
188 if (phase === "running" || isSendBusy || isConnecting) {
189 setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
190 return;
191 }
192 const localApi = readLocalApi();
193 const confirmed =
194 localApi == null
195 ? window.confirm("Roll back this thread to the selected checkpoint?")
196 : await localApi.dialogs.confirm(
197 "Roll back this thread to the selected checkpoint?\nThis action cannot be undone.",
198 );
199 if (!confirmed) return;
200​
201 useComposerDraftStore.setState((store) => ({
202 rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey),
203 }));
204 setThreadError(activeThread.id, null);
205 const result = await revertThreadCheckpoint({
206 environmentId,
207 input: {
208 threadId: activeThread.id,
209 checkpointId: input.checkpointId,
210 scopeId: input.scopeId,
211 },
212 });
213 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
214 const error = squashAtomCommandFailure(result);
215 setThreadError(
216 activeThread.id,
217 error instanceof Error ? error.message : "Failed to revert thread state.",
218 );
219 }
220 useComposerDraftStore.setState((store) => {
221 const remaining = new Set(store.rewindingThreadKeys);
222 remaining.delete(routeThreadKey);
223 return { rewindingThreadKeys: remaining };
224 });
225 };
226​
227 const onForkFromRun = async (input: {
228 readonly sourceThreadId: ThreadId;
229 readonly runId: RunId;
230 }) => {
231 if (!activeThread || activeEnvironmentUnavailable) return;
232 const targetThreadId = newThreadId();
233 const targetThreadRef = scopeThreadRef(environmentId, targetThreadId);
234 const result = await forkThreadFromRun({
235 environmentId,
236 input: {
237 sourceThreadId: input.sourceThreadId,
238 targetThreadId,
239 runId: input.runId,
240 title: `${activeThread.title} fork`,
241 },
242 });
243 if (result._tag === "Failure") {
244 if (!isAtomCommandInterrupted(result)) {
245 const error = squashAtomCommandFailure(result);
246 setThreadError(
247 activeThread.id,
248 error instanceof Error ? error.message : "Failed to fork this response.",
249 );
250 }
251 return;
252 }
253 const targetThreadReady = await waitForThreadShell(targetThreadRef);
254 if (!targetThreadReady) {
255 setThreadError(
256 activeThread.id,
257 "The fork was created, but its thread data did not reach this client. Reconnect and try opening it from the sidebar.",
258 );
259 return;
260 }
261 await navigate({
262 to: "/$environmentId/$threadId",
263 params: buildThreadRouteParams(targetThreadRef),
264 });
265 };
266 const onForkFromRunStable = useStableCallback(onForkFromRun);
267 const onTimelineRollbackCheckpoint = (input: {
268 readonly checkpointId: string;
269 readonly scopeId: string;
270 }) => {
271 void onRollbackCheckpoint(input);
272 };
273 const onTimelineRollbackCheckpointStable = useStableCallback(onTimelineRollbackCheckpoint);
274 const onRevertTimelineTurn = (targetTurnCount: number, messageId: MessageId) => {
275 void onRevertToTurnCountStable(targetTurnCount, messageId);
276 };
277 const onRevertTimelineTurnStable = useStableCallback(onRevertTimelineTurn);
278 return {
279 onConfirmRevertStable,
280 onForkFromRunStable,
281 onRevertTimelineTurnStable,
282 onTimelineRollbackCheckpointStable,
283 };