@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 130 lines 4.82 KB
Raw
1 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations";
4 import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7 type AtomCommandResult,
8 } from "@t3tools/client-runtime/state/runtime";
9 import {
10 MessageId,
11 ThreadId,
12 type ModelSelection,
13 type RuntimeMode,
14 type ScopedThreadRef,
15 } from "@t3tools/contracts";
16 import { msg, useGT } from "gt-react-native";
17 import { m } from "../../i18n/messages";
18
19 import * as Dialog from "../../components/ui/Dialog";
20 import { uuidv4 } from "../../lib/uuid";
21 import { appAtomRegistry } from "../../state/atom-registry";
22 import { environmentThreadShells, threadEnvironment } from "../../state/threads";
23 import { useAtomCommand } from "../../state/use-atom-command";
24 import { waitForThreadShell } from "./threadForkNavigation";
25 import { useOpenLinkedThread } from "./useOpenLinkedThread";
26
27 export type SideChatMessage = Pick<
28 StartThreadTurnInput["message"],
29 "text" | "attachments" | "context"
30 > & { readonly titleSeed: string };
31
32 /**
33 * Forks `source` at its latest stable point into a side chat, sends `message` there, and opens
34 * it like any linked thread. Resolves false when the side chat did not start. `settings` are
35 * what the parent's composer would send, which its thread gets only on its next send.
36 */
37 export function useStartSideChat() {
38 const gt = useGT();
39 const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });
40 const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
41 const setRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, { reportFailure: false });
42 const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
43 const openLinkedThread = useOpenLinkedThread();
44
45 const alertFailure = (
46 failure: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
47 fallback: string,
48 ) => {
49 if (isAtomCommandInterrupted(failure)) return;
50 const error = squashAtomCommandFailure(failure);
51 Dialog.alert(gt("Side chat not started"), errorDisplayMessage(error, m) ?? fallback);
52 };
53
54 return async (
55 source: ScopedThreadRef,
56 message: SideChatMessage,
57 settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection },
58 ): Promise<boolean> => {
59 const targetThreadId = ThreadId.make(uuidv4());
60 const fork = await forkSideChat({
61 environmentId: source.environmentId,
62 input: {
63 sourceThreadId: source.threadId,
64 targetThreadId,
65 title: m(msg("Side chat")),
66 creationSource: "mobile",
67 },
68 });
69 if (fork._tag === "Failure") {
70 alertFailure(fork, gt("Could not start a side chat."));
71 return false;
72 }
73 // Drops the empty side chat a failed start leaves behind; one that got its message stays.
74 const discard = () =>
75 void deleteThread({
76 environmentId: source.environmentId,
77 input: { threadId: targetThreadId, onlyIfUnused: true },
78 });
79 const targetRef = scopeThreadRef(source.environmentId, targetThreadId);
80 if (!(await waitForThreadShell(targetRef))) {
81 Dialog.alert(
82 gt("Side chat not started"),
83 gt("The side chat was created, but it did not reach this device."),
84 );
85 discard();
86 return false;
87 }
88 const sideChat = appAtomRegistry.get(environmentThreadShells.threadShellAtom(targetRef));
89 if (sideChat === null) {
90 Dialog.alert(gt("Side chat not started"), gt("The side chat is no longer available."));
91 discard();
92 return false;
93 }
94 if (settings.runtimeMode !== sideChat.runtimeMode) {
95 const mode = await setRuntimeMode({
96 environmentId: source.environmentId,
97 input: {
98 threadId: targetThreadId,
99 runtimeMode: settings.runtimeMode,
100 createdAt: new Date().toISOString(),
101 },
102 });
103 if (mode._tag === "Failure") {
104 alertFailure(mode, gt("Could not set the side chat's permission mode."));
105 discard();
106 return false;
107 }
108 }
109 const { titleSeed, ...content } = message;
110 const turn = await startTurn({
111 environmentId: source.environmentId,
112 input: {
113 threadId: targetThreadId,
114 message: { messageId: MessageId.make(uuidv4()), role: "user", ...content },
115 modelSelection: settings.modelSelection,
116 titleSeed,
117 runtimeMode: settings.runtimeMode,
118 interactionMode: "default",
119 createdAt: new Date().toISOString(),
120 },
121 });
122 if (turn._tag === "Failure") {
123 alertFailure(turn, gt("Could not send the side chat message."));
124 discard();
125 return false;
126 }
127 openLinkedThread({ environmentId: source.environmentId, threadId: targetThreadId });
128 return true;
129 };
130 }