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