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