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

SideThreadPane.tsx

223 lines8.6 KB

1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { sideThreadKindOf } from "@t3tools/client-runtime/side-thread";
3import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display";
4import {
5 isAtomCommandInterrupted,
6 settlePromise,
7 squashAtomCommandFailure,
8} from "@t3tools/client-runtime/state/runtime";
9import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts";
10import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
11import { T, useGT } from "gt-react";
12import { Trash2Icon, XIcon } from "lucide-react";
13import { useEffect, useState } from "react";
14​
15import { useComposerDraftStore } from "../../composerDraftStore";
16import { ComposerHandleContext } from "../../composerHandleContext";
17import { useClientSettings } from "../../hooks/useSettings";
18import { releaseComposerDraftUploads } from "../../lib/composerDraftUploads";
19import type { SideChatParentPanel } from "../../lib/sideChatPane";
20import { readLocalApi } from "../../localApi";
21import {
22 hostRightPanel,
23 rightPanelHostRef,
24 type ThreadSurface,
25 useRightPanelStore,
26} from "../../rightPanelStore";
27import { useQuietThreadProjection, useQuietThreadShell } from "../../state/entities";
28import { useEnvironmentScope } from "../../state/session";
29import { useEnvironmentShellStatus } from "../../state/shell";
30import { threadEnvironment, useEnvironmentThread } from "../../state/threads";
31import {
32 isThreadRouteSnapshotAuthoritative,
33 resolveThreadRouteRenderState,
34} from "../../threadRoutes";
35import { useOpenThreadFamily } from "../ThreadRouteView";
36import { useAtomCommand } from "../../state/use-atom-command";
37import ChatView from "../ChatView";
38import { Button } from "../ui/button";
39import { toastManager } from "../ui/toast";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
41import { BackgroundThreadContext } from "./backgroundThread";
42import { closeThreadFindIn } from "./threadFindStore";
43​
44/**
45 * A side chat or a subagent as a tab: the thread's own chat, which decides its bottom, the
46 * composer or the read-only bar, as it does on the main screen. The tab names it and closes it,
47 * so only a side chat, which has actions of its own, gets a header.
48 */
49export default function SideThreadPane(props: {
50 /** The thread whose panel shows the tab. */
51 readonly parentRef: ScopedThreadRef;
52 readonly surface: ThreadSurface;
53 readonly parentPanel: SideChatParentPanel;
54 readonly onClose: () => void;
55}) {
56 const { parentRef, surface } = props;
57 const { threadId } = surface;
58 const gt = useGT();
59 const threadRef = scopeThreadRef(parentRef.environmentId, threadId);
60 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the parent panel as host in the panel store, and closes this side chat's find with its pane
61 useEffect(() => {
62 const ref = scopeThreadRef(parentRef.environmentId, threadId);
63 const unhost = hostRightPanel(ref, parentRef);
64 return () => {
65 unhost();
66 // Crossing the sheet breakpoint remounts the pane in the same commit, which re-hosts it.
67 queueMicrotask(() => {
68 if (rightPanelHostRef(ref) === ref) closeThreadFindIn(scopedThreadKey(ref));
69 });
70 };
71 }, [parentRef, threadId]);
72 const shell = useQuietThreadShell(threadRef);
73 const bootstrapComplete = isThreadRouteSnapshotAuthoritative(
74 useEnvironmentShellStatus(parentRef.environmentId),
75 );
76 // The shell can leave an idle subagent out, so its own detail says whether it still exists.
77 const unlistedDetail = useEnvironmentThread(
78 shell === null ? parentRef.environmentId : null,
79 shell === null ? threadId : null,
80 );
81 useOpenThreadFamily(threadRef, bootstrapComplete && shell === null);
82 const renderState = resolveThreadRouteRenderState({
83 bootstrapComplete,
84 serverThreadExists: shell !== null,
85 serverThreadDeleted: shell?.deletedAt != null,
86 unlistedThreadDetail: unlistedDetail,
87 draftThreadExists: false,
88 });
89 const projection = useQuietThreadProjection(threadRef)?.projection;
90 const thread = shell ?? projection?.thread ?? null;
91 // A tab opens for side chats and subagents only, so an unloaded one is still one of them.
92 const kind = sideThreadKindOf(thread) ?? "subagent";
93 const isSideChat = kind === "side-chat";
94 const canOperate = useEnvironmentScope(parentRef.environmentId, AuthOrchestrationOperateScope);
95 const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
96 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
97 const [deleting, setDeleting] = useState(false);
98 // Closing an unused side chat deletes it, which would leave the link unreadable.
99 const canAddToChat = shell !== null && shell.latestUserMessageAt !== null;
100 const addToChat = () => {
101 if (!canAddToChat) return;
102 useComposerDraftStore
103 .getState()
104 .addThreadContexts(parentRef, [threadContextRecord(threadRef, shell.title)], {
105 insertAtCaret: false,
106 });
107 };
108​
109 const deleteSideChat = async () => {
110 if (!canOperate || shell === null || deleting) return;
111 if (confirmThreadDelete) {
112 const api = readLocalApi();
113 if (!api) return;
114 const confirmed = await settlePromise(() =>
115 api.dialogs.confirm(
116 [
117 gt('Delete side chat "{title}"?', { title: shell.title }),
118 gt("This permanently clears its conversation history."),
119 ].join("\n"),
120 { variant: "destructive" },
121 ),
122 );
123 if (confirmed._tag === "Failure" || !confirmed.value) return;
124 }
125 setDeleting(true);
126 const result = await deleteThread({
127 environmentId: parentRef.environmentId,
128 input: { threadId },
129 });
130 setDeleting(false);
131 if (result._tag === "Success") {
132 releaseComposerDraftUploads(threadRef);
133 useComposerDraftStore.getState().clearDraftThread(threadRef);
134 useRightPanelStore.getState().closeSurface(parentRef, surface.id);
135 } else if (!isAtomCommandInterrupted(result)) {
136 const error = squashAtomCommandFailure(result);
137 toastManager.add({
138 type: "error",
139 title: gt("Could not delete the side chat"),
140 ...(error instanceof Error ? { description: error.message } : {}),
141 });
142 }
143 };
144​
145 const title =
146 thread === null
147 ? isSideChat
148 ? gt("Side chat")
149 : gt("Subagent")
150 : isSideChat
151 ? thread.title
152 : formatSubagentDisplayTitle(thread.title);
153​
154 return (
155 <div
156 data-side-chat-pane={threadId}
157 data-testid="side-thread-pane"
158 className="flex h-full min-h-0 flex-col"
159 >
160 {isSideChat ? (
161 <div className="flex h-9 shrink-0 items-center gap-1 border-b border-border pr-1 pl-3">
162 <h2 className="min-w-0 flex-1 truncate text-xs font-medium">{title}</h2>
163 <Tooltip>
164 <TooltipTrigger
165 render={
166 <Button
167 variant="ghost"
168 size="xs"
169 aria-disabled={!canAddToChat || undefined}
170 onClick={addToChat}
171 >
172 <T>Add to chat</T>
173 </Button>
174 }
175 />
176 <TooltipPopup side="bottom">
177 {canAddToChat
178 ? gt("Adds this side chat to the main thread's next message.")
179 : gt("Available after the first message.")}
180 </TooltipPopup>
181 </Tooltip>
182 <Button
183 variant="ghost"
184 size="icon-xs"
185 aria-label={gt("Delete side chat")}
186 disabled={!canOperate || shell === null || deleting}
187 onClick={() => void deleteSideChat()}
188 >
189 <Trash2Icon />
190 </Button>
191 <Button
192 variant="ghost"
193 size="icon-xs"
194 aria-label={gt("Close side chat")}
195 onClick={props.onClose}
196 >
197 <XIcon />
198 </Button>
199 </div>
200 ) : null}
201 {renderState === "missing" ? (
202 <p className="p-3 text-xs text-muted-foreground">
203 {isSideChat ? (
204 <T>This side chat was deleted.</T>
205 ) : (
206 <T>This thread is no longer available.</T>
207 )}
208 </p>
209 ) : renderState === "loading" && thread === null ? null : (
210 <BackgroundThreadContext value>
211 <ComposerHandleContext value={null}>
212 <ChatView
213 environmentId={parentRef.environmentId}
214 threadId={threadId}
215 routeKind="server"
216 embedded={props.parentPanel}
217 />
218 </ComposerHandleContext>
219 </BackgroundThreadContext>
220 )}
221 </div>
222 );