The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg } from "gt-react"; |
| 2 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { m } from "~/i18n/messages"; |
| 4 | import type { ModelSelection, RuntimeMode, ScopedThreadRef } from "@t3tools/contracts"; |
| 5 | import { scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 6 | import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations"; |
| 7 | import { |
| 8 | type AtomCommandResult, |
| 9 | isAtomCommandInterrupted, |
| 10 | squashAtomCommandFailure, |
| 11 | } from "@t3tools/client-runtime/state/runtime"; |
| 12 | import { useRef } from "react"; |
| 13 | |
| 14 | import { newMessageId, newThreadId } from "~/lib/utils"; |
| 15 | import { useComposerDraftStore } from "../../composerDraftStore"; |
| 16 | import { useStableCallback } from "../../hooks/useStableCallback"; |
| 17 | import { useRightPanelStore } from "../../rightPanelStore"; |
| 18 | import { readThreadShell, waitForThreadShell } from "../../state/entities"; |
| 19 | import { threadEnvironment } from "../../state/threads"; |
| 20 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 21 | import { useOrchestrationCommand } from "../../state/use-orchestration-command"; |
| 22 | |
| 23 | export type SideChatMessage = Pick< |
| 24 | StartThreadTurnInput["message"], |
| 25 | "text" | "attachments" | "context" |
| 26 | > & { readonly titleSeed: string }; |
| 27 | |
| 28 | /** |
| 29 | * Starts side chats from `threadRef`, or offers none when it is null. `open` forks the |
| 30 | * thread's latest stable point, sends `message` there with `readSettings()`, the parent |
| 31 | * composer's settings, and shows the tab. It resolves false when the side chat did not |
| 32 | * start, or another one is still starting. |
| 33 | */ |
| 34 | export function useSideChat(input: { |
| 35 | readonly threadRef: ScopedThreadRef | null; |
| 36 | readonly readSettings: () => { |
| 37 | readonly runtimeMode: RuntimeMode; |
| 38 | readonly modelSelection: ModelSelection | undefined; |
| 39 | }; |
| 40 | readonly onError: (message: string) => void; |
| 41 | }) { |
| 42 | const pendingRef = useRef(false); |
| 43 | const forkSideChat = useAtomCommand(threadEnvironment.forkSideChat, { reportFailure: false }); |
| 44 | const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false }); |
| 45 | const setThreadRuntimeMode = useOrchestrationCommand(threadEnvironment.setRuntimeMode, { |
| 46 | reportFailure: false, |
| 47 | }); |
| 48 | const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, { |
| 49 | reportFailure: false, |
| 50 | }); |
| 51 | const reportFailure = ( |
| 52 | failure: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>, |
| 53 | fallback: string, |
| 54 | ) => { |
| 55 | if (isAtomCommandInterrupted(failure)) return; |
| 56 | const error = squashAtomCommandFailure(failure); |
| 57 | input.onError(thrownErrorMessage(error, m) ?? fallback); |
| 58 | }; |
| 59 | const start = async (threadRef: ScopedThreadRef, message: SideChatMessage | undefined) => { |
| 60 | const { runtimeMode, modelSelection } = input.readSettings(); |
| 61 | const targetThreadId = newThreadId(); |
| 62 | const fork = await forkSideChat({ |
| 63 | environmentId: threadRef.environmentId, |
| 64 | // oxlint-disable-next-line t3code/no-untranslated-copy -- stored on the server as the thread title, shared by every viewer |
| 65 | input: { sourceThreadId: threadRef.threadId, targetThreadId, title: "Side chat" }, |
| 66 | }); |
| 67 | if (fork._tag === "Failure") { |
| 68 | reportFailure(fork, m(msg("Could not start a side chat."))); |
| 69 | return false; |
| 70 | } |
| 71 | // Drops the empty side chat a failed start leaves behind; one that got its message stays. |
| 72 | const discard = () => |
| 73 | void deleteThread({ |
| 74 | environmentId: threadRef.environmentId, |
| 75 | input: { threadId: targetThreadId, onlyIfUnused: true }, |
| 76 | }); |
| 77 | const targetRef = scopeThreadRef(threadRef.environmentId, targetThreadId); |
| 78 | if (!(await waitForThreadShell(targetRef))) { |
| 79 | input.onError(m(msg("The side chat was created, but it did not reach this client."))); |
| 80 | discard(); |
| 81 | return false; |
| 82 | } |
| 83 | const sideChat = readThreadShell(targetRef); |
| 84 | if (sideChat === null) { |
| 85 | input.onError(m(msg("The side chat is no longer available."))); |
| 86 | discard(); |
| 87 | return false; |
| 88 | } |
| 89 | if (runtimeMode !== sideChat.runtimeMode) { |
| 90 | const mode = await setThreadRuntimeMode({ |
| 91 | environmentId: threadRef.environmentId, |
| 92 | input: { threadId: targetThreadId, runtimeMode, createdAt: new Date().toISOString() }, |
| 93 | }); |
| 94 | if (mode._tag === "Failure") { |
| 95 | reportFailure(mode, m(msg("Could not set the side chat's permission mode."))); |
| 96 | discard(); |
| 97 | return false; |
| 98 | } |
| 99 | } |
| 100 | // Send before showing the tab: closing a tab whose side chat has no run deletes it. |
| 101 | if (message) { |
| 102 | const { titleSeed, ...content } = message; |
| 103 | const turn = await startThreadTurn({ |
| 104 | environmentId: threadRef.environmentId, |
| 105 | input: { |
| 106 | threadId: targetThreadId, |
| 107 | message: { messageId: newMessageId(), role: "user", ...content }, |
| 108 | ...(modelSelection === undefined ? {} : { modelSelection }), |
| 109 | titleSeed, |
| 110 | runtimeMode, |
| 111 | interactionMode: "default", |
| 112 | createdAt: new Date().toISOString(), |
| 113 | }, |
| 114 | }); |
| 115 | if (turn._tag === "Failure") { |
| 116 | reportFailure(turn, m(msg("Could not send the side chat message."))); |
| 117 | discard(); |
| 118 | return false; |
| 119 | } |
| 120 | } else if (modelSelection !== undefined) { |
| 121 | useComposerDraftStore.getState().setModelSelection(targetRef, modelSelection); |
| 122 | } |
| 123 | useRightPanelStore.getState().openThread(threadRef, targetThreadId); |
| 124 | return true; |
| 125 | }; |
| 126 | const open = async (message?: SideChatMessage) => { |
| 127 | const { threadRef } = input; |
| 128 | if (!threadRef || pendingRef.current) return false; |
| 129 | pendingRef.current = true; |
| 130 | return start(threadRef, message).finally(() => { |
| 131 | pendingRef.current = false; |
| 132 | }); |
| 133 | }; |
| 134 | return { available: input.threadRef !== null, open: useStableCallback(open) }; |
| 135 | } |