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

useTimelineRewind.ts

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