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

useSideChat.ts

102 lines4.1 KB

1import type { ScopedThreadRef } from "@t3tools/contracts";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
4import {
5 type AtomCommandResult,
6 isAtomCommandInterrupted,
7 squashAtomCommandFailure,
8} from "@t3tools/client-runtime/state/runtime";
9import { useRef } from "react";
10​
11import { newMessageId, newThreadId } from "~/lib/utils";
12import { useStableCallback } from "../../hooks/useStableCallback";
13import { useRightPanelStore } from "../../rightPanelStore";
14import { readThreadShell, waitForThreadShell } from "../../state/entities";
15import { threadEnvironment } from "../../state/threads";
16import { useAtomCommand } from "../../state/use-atom-command";
17import { useOrchestrationCommand } from "../../state/use-orchestration-command";
18​
19/**
20 * Starts side chats from `threadRef`, or offers none when it is null. `open` forks the
21 * thread's latest stable point, sends `prompt` there, and shows the side chat's tab. It
22 * resolves false when the side chat did not start, or another one is still starting.
23 */
24export function useSideChat(input: {
25 readonly threadRef: ScopedThreadRef | null;
26 readonly onError: (message: string) => void;
27}) {
28 const pendingRef = useRef(false);
29 const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false });
30 const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
31 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
32 reportFailure: false,
33 });
34 const reportFailure = (
35 failure: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
36 fallback: string,
37 ) => {
38 if (isAtomCommandInterrupted(failure)) return;
39 const error = squashAtomCommandFailure(failure);
40 input.onError(error instanceof Error ? error.message : fallback);
41 };
42 const start = async (threadRef: ScopedThreadRef, prompt: string | undefined) => {
43 const targetThreadId = newThreadId();
44 const fork = await forkSideChat({
45 environmentId: threadRef.environmentId,
46 input: { sourceThreadId: threadRef.threadId, targetThreadId, title: "Side chat" },
47 });
48 if (fork._tag === "Failure") {
49 reportFailure(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: threadRef.environmentId,
56 input: { threadId: targetThreadId, onlyIfUnused: true },
57 });
58 const targetRef = scopeThreadRef(threadRef.environmentId, targetThreadId);
59 if (!(await waitForThreadShell(targetRef))) {
60 input.onError("The side chat was created, but it did not reach this client.");
61 discard();
62 return false;
63 }
64 const sideChat = readThreadShell(targetRef);
65 if (sideChat === null) {
66 input.onError("The side chat is no longer available.");
67 discard();
68 return false;
69 }
70 const text = prompt?.trim();
71 // Send before showing the tab: closing a tab whose side chat has no run deletes it.
72 if (text) {
73 const turn = await startThreadTurn({
74 environmentId: threadRef.environmentId,
75 input: {
76 threadId: targetThreadId,
77 message: { messageId: newMessageId(), role: "user", text, attachments: [] },
78 titleSeed: deriveThreadTitleSeed({ text, attachments: [] }),
79 runtimeMode: sideChat.runtimeMode,
80 interactionMode: "default",
81 createdAt: new Date().toISOString(),
82 },
83 });
84 if (turn._tag === "Failure") {
85 reportFailure(turn, "Could not send the side chat message.");
86 discard();
87 return false;
88 }
89 }
90 useRightPanelStore.getState().openSideChat(threadRef, targetThreadId);
91 return true;
92 };
93 const open = async (prompt?: string) => {
94 const { threadRef } = input;
95 if (!threadRef || pendingRef.current) return false;
96 pendingRef.current = true;
97 return start(threadRef, prompt).finally(() => {
98 pendingRef.current = false;
99 });
100 };
101 return { available: input.threadRef !== null, open: useStableCallback(open) };