Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations";
4import {
5 isAtomCommandInterrupted,
6 isAtomCommandOutcomeUnknown,
7 squashAtomCommandFailure,
8 type AtomCommandResult,
9} from "@t3tools/client-runtime/state/runtime";
10import {
11 makeUnconfirmedSideChatForks,
12 sideChatHasStarted,
13} from "@t3tools/client-runtime/unconfirmed-side-chat-fork";
14import {
15 CommandId,
16 MessageId,
17 ThreadId,
18 type ModelSelection,
19 type RuntimeMode,
20 type ScopedThreadRef,
21} from "@t3tools/contracts";
22import * as SecureStore from "expo-secure-store";
23import { msg, useGT } from "gt-react-native";
24import { m } from "../../i18n/messages";
25
26import * as Dialog from "../../components/ui/Dialog";
27import { uuidv4 } from "../../lib/uuid";
28import { appAtomRegistry } from "../../state/atom-registry";
29import { environmentThreadShells, threadEnvironment } from "../../state/threads";
30import { useAtomCommand } from "../../state/use-atom-command";
31import { waitForThreadShell } from "./threadForkNavigation";
32import { useOpenLinkedThread } from "./useOpenLinkedThread";
33
34const deviceOnly = { keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY };
35// Secure store keys allow only letters, digits, ".", "-" and "_".
36const secureKey = (key: string) => key.replace(/[^\w.-]/g, "_");
37const unconfirmedForks = makeUnconfirmedSideChatForks(() => ({
38 getItem: (key) => SecureStore.getItem(secureKey(key), deviceOnly),
39 setItem: (key, value) => SecureStore.setItem(secureKey(key), value, deviceOnly),
40 removeItem: (key) => void SecureStore.deleteItemAsync(secureKey(key), deviceOnly),
41}));
42
43export type SideChatMessage = Pick<
44 StartThreadTurnInput["message"],
45 "text" | "attachments" | "context"
46> & { readonly titleSeed: string };
47
48/**
49 * Forks `source` at its latest stable point into a side chat, sends `message` there, and opens
50 * it like any linked thread. Resolves false when the side chat did not start. `settings` are
51 * what the parent's composer would send, which its thread gets only on its next send.
52 */
53export function useStartSideChat() {
54 const gt = useGT();
55 const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });
56 const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
57 const setRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, { reportFailure: false });
58 const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
59 const openLinkedThread = useOpenLinkedThread();
60
61 const alertFailure = (
62 failure: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
63 fallback: string,
64 ) => {
65 if (isAtomCommandInterrupted(failure)) return;
66 const error = squashAtomCommandFailure(failure);
67 Dialog.alert(gt`Side chat not started`, errorDisplayMessage(error, m) ?? fallback);
68 };
69
70 const start = async (
71 source: ScopedThreadRef,
72 message: SideChatMessage,
73 settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection },
74 reuseUnconfirmed = true,
75 ): Promise<boolean> => {
76 const readShell = (threadId: ThreadId) =>
77 appAtomRegistry.get(
78 environmentThreadShells.threadShellAtom(scopeThreadRef(source.environmentId, threadId)),
79 );
80 const reused = reuseUnconfirmed ? unconfirmedForks.readReusable(source, readShell) : null;
81 const { targetThreadId, commandId } = reused ?? {
82 targetThreadId: ThreadId.make(uuidv4()),
83 commandId: CommandId.make(uuidv4()),
84 };
85 // Stored before sending so an app restart while the fork is in flight still resends it.
86 unconfirmedForks.write(source, { targetThreadId, commandId });
87 const fork = await forkSideChat({
88 environmentId: source.environmentId,
89 input: {
90 commandId,
91 sourceThreadId: source.threadId,
92 targetThreadId,
93 title: m(msg("Side chat")),
94 creationSource: "mobile",
95 },
96 });
97 const outcomeUnknown =
98 fork._tag === "Failure" &&
99 (isAtomCommandOutcomeUnknown(fork) || isAtomCommandInterrupted(fork));
100 if (!outcomeUnknown) unconfirmedForks.write(source, null);
101 if (fork._tag === "Failure") {
102 alertFailure(fork, gt`Could not start a side chat.`);
103 return false;
104 }
105 // Drops the empty side chat a failed start leaves behind; one that got its message stays.
106 const discard = () =>
107 void deleteThread({
108 environmentId: source.environmentId,
109 input: { threadId: targetThreadId, onlyIfUnused: true },
110 });
111 const targetRef = scopeThreadRef(source.environmentId, targetThreadId);
112 if (!(await waitForThreadShell(targetRef))) {
113 discard();
114 // The resent fork's side chat was deleted since; start a new one instead.
115 if (reused !== null) return start(source, message, settings, false);
116 Dialog.alert(
117 gt`Side chat not started`,
118 gt`The side chat was created, but it did not reach this device.`,
119 );
120 return false;
121 }
122 const sideChat = readShell(targetThreadId);
123 if (sideChat === null) {
124 Dialog.alert(gt`Side chat not started`, gt`The side chat is no longer available.`);
125 discard();
126 return false;
127 }
128 // A reused side chat not yet loaded at the retry may turn out to have its own run.
129 if (reused !== null && sideChatHasStarted(sideChat)) {
130 return start(source, message, settings, false);
131 }
132 if (settings.runtimeMode !== sideChat.runtimeMode) {
133 const mode = await setRuntimeMode({
134 environmentId: source.environmentId,
135 input: {
136 threadId: targetThreadId,
137 runtimeMode: settings.runtimeMode,
138 createdAt: new Date().toISOString(),
139 },
140 });
141 if (mode._tag === "Failure") {
142 alertFailure(mode, gt`Could not set the side chat's permission mode.`);
143 discard();
144 return false;
145 }
146 }
147 const { titleSeed, ...content } = message;
148 const turn = await startTurn({
149 environmentId: source.environmentId,
150 input: {
151 threadId: targetThreadId,
152 message: { messageId: MessageId.make(uuidv4()), role: "user", ...content },
153 modelSelection: settings.modelSelection,
154 titleSeed,
155 runtimeMode: settings.runtimeMode,
156 interactionMode: "default",
157 createdAt: new Date().toISOString(),
158 // The server confirms a resent command id from its receipt, so a lost reply cannot
159 // restore a question it already accepted.
160 resendUntilAnswered: true,
161 },
162 });
163 if (turn._tag === "Failure") {
164 alertFailure(turn, gt`Could not send the side chat message.`);
165 discard();
166 return false;
167 }
168 openLinkedThread({ environmentId: source.environmentId, threadId: targetThreadId });
169 return true;
170 };
171 return (
172 source: ScopedThreadRef,
173 message: SideChatMessage,
174 settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection },
175 ) => start(source, message, settings);
176}