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

useTimelineRewind.ts

243 lines8.7 KB

1import { msg } from "gt-react";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { m } from "~/i18n/messages";
4import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-runtime/state/shell";
5import type { ComposerThreadTarget } from "../../composerDraftStore";
6import type { ComposerHandleRef } from "../../composerHandleContext";
7import type { SessionPhase } from "../../types";
8import { useStableCallback } from "../../hooks/useStableCallback";
9import {
10 AuthOrchestrationOperateScope,
11 type EnvironmentId,
12 type MessageId,
13 type ScopedThreadRef,
14 type ThreadId,
15 type RunId,
16} from "@t3tools/contracts";
17import { scopeThreadRef } from "@t3tools/client-runtime/environment";
18import { useNavigate, useRouter } from "@tanstack/react-router";
19import {
20 isAtomCommandInterrupted,
21 squashAtomCommandFailure,
22} from "@t3tools/client-runtime/state/runtime";
23import { readLocalApi } from "../../localApi";
24import { findRevertCheckpoint } from "../../session-logic";
25import { type ChatMessage } from "../../types";
26import { newThreadId } from "~/lib/utils";
27import { buildThreadRouteParams } from "../../threadRoutes";
28import { useComposerDraftStore } from "../../composerDraftStore";
29import { threadEnvironment } from "../../state/threads";
30import { waitForThreadShell } from "../../state/entities";
31import { openRevertConfirm } from "./ChatOverlayHosts";
32import { assetEnvironment } from "../../state/assets";
33import { readEnvironmentScope } from "../../state/session";
34import { useAtomCommand } from "../../state/use-atom-command";
35import { useOrchestrationCommand } from "../../state/use-orchestration-command";
36import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
37import { rewindToMessage } from "./chatViewSend";
38import { makeThreadErrorSetter } from "../ChatView.logic";
39interface TimelineRewindInput {
40 readonly environmentId: EnvironmentId;
41 readonly routeThreadRef: ScopedThreadRef;
42 readonly routeThreadKey: string;
43 readonly currentRouteThreadKeyRef: { readonly current: string | null };
44 readonly serverProjection: ThreadStructure | null;
45 readonly activeThread: EnvironmentThreadShell | undefined;
46 readonly timelineMessages: ReadonlyArray<ChatMessage>;
47 readonly phase: SessionPhase;
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>;
58​
59/**
60 * Going back in a thread's timeline: reverting to an earlier turn (restoring that message into
61 * the composer) 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 phase,
73 isSendBusy,
74 isRevertingCheckpoint,
75 supportsConversationRollback,
76 activeEnvironmentUnavailable,
77 activeEnvironmentUnavailableLabel,
78 promptRef,
79 composerRef,
80 composerDraftTarget,
81 setThreadError,
82 } = input;
83 const navigate = useNavigate();
84 const router = useRouter();
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 m(
117 msg(
118 "This provider does not support reverting conversation history. Start a new thread instead.",
119 ),
120 ),
121 );
122 return;
123 }
124 if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
125 setThreadError(
126 activeThread.id,
127 m(
128 msg`Reconnect ${{ environment: activeEnvironmentUnavailableLabel }} before reverting checkpoints.`,
129 ),
130 );
131 return;
132 }
133 if (phase === "running" || isSendBusy) {
134 setThreadError(
135 activeThread.id,
136 m(msg("Interrupt the current turn before reverting checkpoints.")),
137 );
138 return;
139 }
140 if (restoreFiles === undefined) {
141 openRevertConfirm(routeThreadKey, { turnCount, messageId });
142 return;
143 }
144​
145 useComposerDraftStore.setState((store) => ({
146 rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey),
147 }));
148 setThreadError(activeThread.id, null);
149 const rewind = await rewindToMessage({
150 message,
151 environmentId,
152 routeThreadRef,
153 threadId: activeThread.id,
154 turnCount,
155 restoreFiles,
156 // Keep the live checkpoint identity when command context refetches a bounded window.
157 checkpoint: findRevertCheckpoint(serverProjection, turnCount),
158 draftTarget: composerDraftTarget,
159 composerHasPendingAttachments: composerRef.current?.hasPendingAttachments() === true,
160 createAssetUrl: createAttachmentAssetUrl,
161 revertThreadCheckpoint,
162 });
163 useComposerDraftStore.setState((store) => {
164 const remaining = new Set(store.rewindingThreadKeys);
165 remaining.delete(routeThreadKey);
166 return { rewindingThreadKeys: remaining };
167 });
168 if (rewind.error !== null) {
169 setThreadError(activeThread.id, rewind.error);
170 return;
171 }
172 if (currentRouteThreadKeyRef.current === routeThreadKey) {
173 const nextPrompt = rewind.prompt;
174 promptRef.current = nextPrompt;
175 composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length });
176 requestAnimationFrame(() => {
177 if (currentRouteThreadKeyRef.current === routeThreadKey) composerRef.current?.focusAtEnd();
178 });
179 }
180 };
181 const onRevertToTurnCountStable = useStableCallback(onRevertToTurnCount);
182 const onConfirmRevert = (turnCount: number, messageId: MessageId, restoreFiles: boolean) => {
183 void onRevertToTurnCount(turnCount, messageId, restoreFiles);
184 };
185 const onConfirmRevertStable = useStableCallback(onConfirmRevert);
186​
187 const onForkFromRun = async (input: {
188 readonly sourceThreadId: ThreadId;
189 readonly runId: RunId;
190 }) => {
191 if (!activeThread || activeEnvironmentUnavailable) return;
192 const sourcePathname = (router.state.resolvedLocation ?? router.state.location).pathname;
193 const targetThreadId = newThreadId();
194 const targetThreadRef = scopeThreadRef(environmentId, targetThreadId);
195 const result = await forkThreadFromRun({
196 environmentId,
197 input: {
198 sourceThreadId: input.sourceThreadId,
199 targetThreadId,
200 runId: input.runId,
201 title: m(msg`${{ title: activeThread.title }} fork`),
202 },
203 });
204 if (result._tag === "Failure") {
205 if (!isAtomCommandInterrupted(result)) {
206 const error = squashAtomCommandFailure(result);
207 setThreadError(
208 activeThread.id,
209 thrownErrorMessage(error, m) ?? m(msg("Failed to fork this response.")),
210 );
211 }
212 return;
213 }
214 const targetThreadReady = await waitForThreadShell(targetThreadRef);
215 if (!targetThreadReady) {
216 setThreadError(
217 activeThread.id,
218 m(
219 msg(
220 "The fork was created, but its thread data did not reach this client. Reconnect and try opening it from the sidebar.",
221 ),
222 ),
223 );
224 return;
225 }
226 // The source is the chat on screen; latestLocation also holds a pending navigation away from it.
227 if (router.latestLocation.pathname !== sourcePathname) return;
228 await navigate({
229 to: "/$environmentId/$threadId",
230 params: buildThreadRouteParams(targetThreadRef),
231 });
232 };
233 const onForkFromRunStable = useStableCallback(onForkFromRun);
234 const onRevertTimelineTurn = (targetTurnCount: number, messageId: MessageId) => {
235 void onRevertToTurnCountStable(targetTurnCount, messageId);
236 };
237 const onRevertTimelineTurnStable = useStableCallback(onRevertTimelineTurn);
238 return {
239 onConfirmRevertStable,
240 onForkFromRunStable,
241 onRevertTimelineTurnStable,
242 };