Open History to see the last commit
1import { msg } from "gt-react";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { m } from "~/i18n/messages";
4import {
5 CommandId,
6 type ModelSelection,
7 type RuntimeMode,
8 type ScopedThreadRef,
9} from "@t3tools/contracts";
10import { scopeThreadRef } from "@t3tools/client-runtime/environment";
11import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations";
12import {
13 type AtomCommandResult,
14 isAtomCommandInterrupted,
15 isAtomCommandOutcomeUnknown,
16 squashAtomCommandFailure,
17} from "@t3tools/client-runtime/state/runtime";
18import {
19 makeUnconfirmedSideChatForks,
20 sideChatHasStarted,
21} from "@t3tools/client-runtime/unconfirmed-side-chat-fork";
22import { useRef } from "react";
23
24import { newMessageId, newThreadId, randomUUID } from "~/lib/utils";
25import { useComposerDraftStore } from "../../composerDraftStore";
26import { useStableCallback } from "../../hooks/useStableCallback";
27import { useRightPanelStore } from "../../rightPanelStore";
28import { readThreadShell, waitForThreadShell } from "../../state/entities";
29import { threadEnvironment } from "../../state/threads";
30import { useAtomCommand } from "../../state/use-atom-command";
31import { useOrchestrationCommand } from "../../state/use-orchestration-command";
32
33const unconfirmedForks = makeUnconfirmedSideChatForks(() => window.sessionStorage);
34
35export type SideChatMessage = Pick<
36 StartThreadTurnInput["message"],
37 "text" | "attachments" | "context"
38> & { readonly titleSeed: string };
39
40/**
41 * Starts side chats from `threadRef`, or offers none when it is null. `open` forks the
42 * thread's latest stable point, sends `message` there with `readSettings()`, the parent
43 * composer's settings, and shows the tab. It resolves false when the side chat did not
44 * start, or another one is still starting.
45 */
46export function useSideChat(input: {
47 readonly threadRef: ScopedThreadRef | null;
48 readonly readSettings: () => {
49 readonly runtimeMode: RuntimeMode;
50 readonly modelSelection: ModelSelection | undefined;
51 };
52 readonly onError: (message: string) => void;
53}) {
54 const pendingRef = useRef(false);
55 const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });
56 const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
57 const setThreadRuntimeMode = useOrchestrationCommand(threadEnvironment.setRuntimeMode, {
58 reportFailure: false,
59 });
60 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
61 reportFailure: false,
62 });
63 const reportFailure = (
64 failure: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
65 fallback: string,
66 ) => {
67 if (isAtomCommandInterrupted(failure)) return;
68 const error = squashAtomCommandFailure(failure);
69 input.onError(thrownErrorMessage(error, m) ?? fallback);
70 };
71 const start = async (
72 threadRef: ScopedThreadRef,
73 message: SideChatMessage | undefined,
74 reuseUnconfirmed = true,
75 ): Promise<boolean> => {
76 const { runtimeMode, modelSelection } = input.readSettings();
77 const reused = reuseUnconfirmed
78 ? unconfirmedForks.readReusable(threadRef, (targetThreadId) =>
79 readThreadShell(scopeThreadRef(threadRef.environmentId, targetThreadId)),
80 )
81 : null;
82 const { targetThreadId, commandId } = reused ?? {
83 targetThreadId: newThreadId(),
84 commandId: CommandId.make(randomUUID()),
85 };
86 // Stored before sending so a reload while the fork is in flight still resends it.
87 unconfirmedForks.write(threadRef, { targetThreadId, commandId });
88 const fork = await forkSideChat({
89 environmentId: threadRef.environmentId,
90 input: {
91 commandId,
92 sourceThreadId: threadRef.threadId,
93 targetThreadId,
94 // oxlint-disable-next-line t3code/no-untranslated-copy -- stored on the server as the thread title, shared by every viewer
95 title: "Side chat",
96 },
97 });
98 const outcomeUnknown =
99 fork._tag === "Failure" &&
100 (isAtomCommandOutcomeUnknown(fork) || isAtomCommandInterrupted(fork));
101 if (!outcomeUnknown) unconfirmedForks.write(threadRef, null);
102 if (fork._tag === "Failure") {
103 reportFailure(fork, m(msg("Could not start a side chat.")));
104 return false;
105 }
106 // Drops the empty side chat a failed start leaves behind; one that got its message stays.
107 const discard = () =>
108 void deleteThread({
109 environmentId: threadRef.environmentId,
110 input: { threadId: targetThreadId, onlyIfUnused: true },
111 });
112 const targetRef = scopeThreadRef(threadRef.environmentId, targetThreadId);
113 if (!(await waitForThreadShell(targetRef))) {
114 discard();
115 // The resent fork's side chat was deleted since; start a new one instead.
116 if (reused !== null) return start(threadRef, message, false);
117 input.onError(m(msg("The side chat was created, but it did not reach this client.")));
118 return false;
119 }
120 const sideChat = readThreadShell(targetRef);
121 if (sideChat === null) {
122 input.onError(m(msg("The side chat is no longer available.")));
123 discard();
124 return false;
125 }
126 // A reused side chat not yet loaded at the retry may turn out to have its own run.
127 if (reused !== null && sideChatHasStarted(sideChat)) return start(threadRef, message, false);
128 if (runtimeMode !== sideChat.runtimeMode) {
129 const mode = await setThreadRuntimeMode({
130 environmentId: threadRef.environmentId,
131 input: { threadId: targetThreadId, runtimeMode, createdAt: new Date().toISOString() },
132 });
133 if (mode._tag === "Failure") {
134 reportFailure(mode, m(msg("Could not set the side chat's permission mode.")));
135 discard();
136 return false;
137 }
138 }
139 // Send before showing the tab: closing a tab whose side chat has no run deletes it.
140 if (message) {
141 const { titleSeed, ...content } = message;
142 const turn = await startThreadTurn({
143 environmentId: threadRef.environmentId,
144 input: {
145 threadId: targetThreadId,
146 message: { messageId: newMessageId(), role: "user", ...content },
147 ...(modelSelection === undefined ? {} : { modelSelection }),
148 titleSeed,
149 runtimeMode,
150 interactionMode: "default",
151 createdAt: new Date().toISOString(),
152 },
153 });
154 if (turn._tag === "Failure") {
155 reportFailure(turn, m(msg("Could not send the side chat message.")));
156 discard();
157 return false;
158 }
159 } else if (modelSelection !== undefined) {
160 useComposerDraftStore.getState().setModelSelection(targetRef, modelSelection);
161 }
162 useRightPanelStore.getState().openThread(threadRef, targetThreadId);
163 return true;
164 };
165 const open = async (message?: SideChatMessage) => {
166 const { threadRef } = input;
167 if (!threadRef || pendingRef.current) return false;
168 pendingRef.current = true;
169 return start(threadRef, message).finally(() => {
170 pendingRef.current = false;
171 });
172 };
173 return { available: input.threadRef !== null, open: useStableCallback(open) };
174}