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

useStartSideChat.ts

125 lines4.5 KB

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