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

useSideChat.ts

96 lines4.0 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 { 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 if (!(await waitForThreadShell(scopeThreadRef(threadRef.environmentId, targetThreadId)))) {
59 input.onError("The side chat was created, but it did not reach this client.");
60 discard();
61 return false;
62 }
63 const text = prompt?.trim();
64 // Send before showing the tab: closing a tab whose side chat has no run deletes it.
65 if (text) {
66 // The server asks before edits on a side chat's first turn whatever mode is sent.
67 const turn = await startThreadTurn({
68 environmentId: threadRef.environmentId,
69 input: {
70 threadId: targetThreadId,
71 message: { messageId: newMessageId(), role: "user", text, attachments: [] },
72 titleSeed: deriveThreadTitleSeed({ text, attachments: [] }),
73 runtimeMode: "approval-required",
74 interactionMode: "default",
75 createdAt: new Date().toISOString(),
76 },
77 });
78 if (turn._tag === "Failure") {
79 reportFailure(turn, "Could not send the side chat message.");
80 discard();
81 return false;
82 }
83 }
84 useRightPanelStore.getState().openSideChat(threadRef, targetThreadId);
85 return true;
86 };
87 const open = async (prompt?: string) => {
88 const { threadRef } = input;
89 if (!threadRef || pendingRef.current) return false;
90 pendingRef.current = true;
91 return start(threadRef, prompt).finally(() => {
92 pendingRef.current = false;
93 });
94 };
95 return { available: input.threadRef !== null, open: useStableCallback(open) };