@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 241 lines 8.44 KB
Raw
1 import { msg } from "gt-react";
2 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3 import { m } from "~/i18n/messages";
4 import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-runtime/state/shell";
5 import type { ComposerThreadTarget } from "../../composerDraftStore";
6 import type { ComposerHandleRef } from "../../composerHandleContext";
7 import type { SessionPhase } from "../../types";
8 import { useStableCallback } from "../../hooks/useStableCallback";
9 import {
10 AuthOrchestrationOperateScope,
11 type EnvironmentId,
12 type MessageId,
13 type ScopedThreadRef,
14 type ThreadId,
15 type RunId,
16 } from "@t3tools/contracts";
17 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
18 import { useNavigate } from "@tanstack/react-router";
19 import {
20 isAtomCommandInterrupted,
21 squashAtomCommandFailure,
22 } from "@t3tools/client-runtime/state/runtime";
23 import { readLocalApi } from "../../localApi";
24 import { findRevertCheckpoint } from "../../session-logic";
25 import { type ChatMessage } from "../../types";
26 import { newThreadId } from "~/lib/utils";
27 import { buildThreadRouteParams } from "../../threadRoutes";
28 import { useComposerDraftStore } from "../../composerDraftStore";
29 import { threadEnvironment } from "../../state/threads";
30 import { waitForThreadShell } from "../../state/entities";
31 import { openRevertConfirm } from "./ChatOverlayHosts";
32 import { assetEnvironment } from "../../state/assets";
33 import { readEnvironmentScope } from "../../state/session";
34 import { useAtomCommand } from "../../state/use-atom-command";
35 import { useOrchestrationCommand } from "../../state/use-orchestration-command";
36 import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
37 import { rewindToMessage } from "./chatViewSend";
38 import { makeThreadErrorSetter } from "../ChatView.logic";
39 interface 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>;
57 }
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 */
63 export 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 createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
85 reportFailure: false,
86 refresh: true,
87 });
88
89 const revertThreadCheckpoint = useOrchestrationCommand(threadEnvironment.revertCheckpoint, {
90 reportFailure: false,
91 });
92 const forkThreadFromRun = useAtomCommand(threadEnvironment.forkFromRun, {
93 reportFailure: false,
94 });
95
96 const onRevertToTurnCount = async (
97 turnCount: number,
98 messageId: MessageId,
99 restoreFiles?: boolean,
100 ) => {
101 const localApi = readLocalApi();
102 if (
103 !localApi ||
104 !activeThread ||
105 isRevertingCheckpoint ||
106 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
107 )
108 return;
109 const message = timelineMessages.find((message) => message.id === messageId);
110 if (!message || message.role !== "user") return;
111
112 if (!supportsConversationRollback) {
113 setThreadError(
114 activeThread.id,
115 m(
116 msg(
117 "This provider does not support reverting conversation history. Start a new thread instead.",
118 ),
119 ),
120 );
121 return;
122 }
123 if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
124 setThreadError(
125 activeThread.id,
126 m(
127 msg("Reconnect {environment} before reverting checkpoints.", {
128 environment: activeEnvironmentUnavailableLabel,
129 }),
130 ),
131 );
132 return;
133 }
134 if (phase === "running" || isSendBusy) {
135 setThreadError(
136 activeThread.id,
137 m(msg("Interrupt the current turn before reverting checkpoints.")),
138 );
139 return;
140 }
141 if (restoreFiles === undefined) {
142 openRevertConfirm(routeThreadKey, { turnCount, messageId });
143 return;
144 }
145
146 useComposerDraftStore.setState((store) => ({
147 rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey),
148 }));
149 setThreadError(activeThread.id, null);
150 const rewind = await rewindToMessage({
151 message,
152 environmentId,
153 routeThreadRef,
154 threadId: activeThread.id,
155 turnCount,
156 restoreFiles,
157 // Keep the live checkpoint identity when command context refetches a bounded window.
158 checkpoint: findRevertCheckpoint(serverProjection?.checkpoints ?? [], turnCount),
159 draftTarget: composerDraftTarget,
160 composerHasPendingAttachments: composerRef.current?.hasPendingAttachments() === true,
161 createAssetUrl: createAttachmentAssetUrl,
162 revertThreadCheckpoint,
163 });
164 useComposerDraftStore.setState((store) => {
165 const remaining = new Set(store.rewindingThreadKeys);
166 remaining.delete(routeThreadKey);
167 return { rewindingThreadKeys: remaining };
168 });
169 if (rewind.error !== null) {
170 setThreadError(activeThread.id, rewind.error);
171 return;
172 }
173 if (currentRouteThreadKeyRef.current === routeThreadKey) {
174 const nextPrompt = rewind.prompt;
175 promptRef.current = nextPrompt;
176 composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length });
177 requestAnimationFrame(() => {
178 if (currentRouteThreadKeyRef.current === routeThreadKey) composerRef.current?.focusAtEnd();
179 });
180 }
181 };
182 const onRevertToTurnCountStable = useStableCallback(onRevertToTurnCount);
183 const onConfirmRevert = (turnCount: number, messageId: MessageId, restoreFiles: boolean) => {
184 void onRevertToTurnCount(turnCount, messageId, restoreFiles);
185 };
186 const onConfirmRevertStable = useStableCallback(onConfirmRevert);
187
188 const onForkFromRun = async (input: {
189 readonly sourceThreadId: ThreadId;
190 readonly runId: RunId;
191 }) => {
192 if (!activeThread || activeEnvironmentUnavailable) return;
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: `${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 await navigate({
227 to: "/$environmentId/$threadId",
228 params: buildThreadRouteParams(targetThreadRef),
229 });
230 };
231 const onForkFromRunStable = useStableCallback(onForkFromRun);
232 const onRevertTimelineTurn = (targetTurnCount: number, messageId: MessageId) => {
233 void onRevertToTurnCountStable(targetTurnCount, messageId);
234 };
235 const onRevertTimelineTurnStable = useStableCallback(onRevertTimelineTurn);
236 return {
237 onConfirmRevertStable,
238 onForkFromRunStable,
239 onRevertTimelineTurnStable,
240 };
241 }