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

useStartSideChat.ts

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