Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
3import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
4import {
5 isAtomCommandInterrupted,
6 settlePromise,
7 squashAtomCommandFailure,
8} from "@t3tools/client-runtime/state/runtime";
9import {
10 AuthOrchestrationOperateScope,
11 type ScopedThreadRef,
12 type ThreadId,
13} from "@t3tools/contracts";
14import { T, useGT } from "gt-react";
15import { Trash2Icon, XIcon } from "lucide-react";
16import { useEffect, useState } from "react";
17
18import { useComposerDraftStore } from "../../composerDraftStore";
19import { ComposerHandleContext } from "../../composerHandleContext";
20import { useClientSettings } from "../../hooks/useSettings";
21import { releaseComposerDraftUploads } from "../../lib/composerDraftUploads";
22import type { SideChatParentPanel } from "../../lib/sideChatPane";
23import { readLocalApi } from "../../localApi";
24import { hostRightPanel, useRightPanelStore } from "../../rightPanelStore";
25import { useQuietThreadProjection, useQuietThreadShell } from "../../state/entities";
26import { useEnvironmentScope } from "../../state/session";
27import { useEnvironmentShellHasSnapshot } from "../../state/shell";
28import { threadEnvironment } from "../../state/threads";
29import { useAtomCommand } from "../../state/use-atom-command";
30import ChatView from "../ChatView";
31import { Button } from "../ui/button";
32import { toastManager } from "../ui/toast";
33import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
34import { BackgroundThreadContext } from "./backgroundThread";
35
36/** A side chat tab: its title, Bring back, Delete and Close, over the side chat's own chat. */
37export default function SideChatPane(props: {
38 readonly parentRef: ScopedThreadRef;
39 readonly threadId: ThreadId;
40 readonly parentPanel: SideChatParentPanel;
41 readonly onClose: () => void;
42}) {
43 const { parentRef, threadId } = props;
44 const gt = useGT();
45 const threadRef = scopeThreadRef(parentRef.environmentId, threadId);
46 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the parent panel as host in the panel store
47 useEffect(
48 () => hostRightPanel(scopeThreadRef(parentRef.environmentId, threadId), parentRef),
49 [parentRef, threadId],
50 );
51 const shell = useQuietThreadShell(threadRef);
52 const parent = useQuietThreadShell(parentRef);
53 const snapshotLoaded = useEnvironmentShellHasSnapshot(parentRef.environmentId);
54 const projection = useQuietThreadProjection(shell === null ? null : threadRef)?.projection;
55 const canOperate = useEnvironmentScope(parentRef.environmentId, AuthOrchestrationOperateScope);
56 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, { reportFailure: false });
57 const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
58 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
59 const [bringingBack, setBringingBack] = useState(false);
60 const [deleting, setDeleting] = useState(false);
61 const mergeRun = projection ? resolveLatestMergeBackRun(projection) : null;
62 // A pending merge-back would fail the main thread's queued message, so the server refuses it.
63 const bringBackBlockedReason = !canOperate
64 ? gt("This connection cannot change threads.")
65 : threadRuntimeIsActive(parent?.runtime)
66 ? gt("Available when the main thread is idle.")
67 : mergeRun === null
68 ? gt("Available after a finished reply.")
69 : null;
70
71 const bringBack = async () => {
72 if (bringBackBlockedReason !== null || mergeRun === null || bringingBack) return;
73 setBringingBack(true);
74 const result = await mergeBack({
75 environmentId: parentRef.environmentId,
76 input: { sourceThreadId: threadId, targetThreadId: parentRef.threadId, runId: mergeRun.id },
77 });
78 setBringingBack(false);
79 if (result._tag === "Success") {
80 toastManager.add({
81 type: "success",
82 title: gt("Brought back"),
83 description: gt("The main thread gets this side chat with your next message there."),
84 });
85 } else if (!isAtomCommandInterrupted(result)) {
86 const error = squashAtomCommandFailure(result);
87 toastManager.add({
88 type: "error",
89 title: gt("Could not bring back the side chat"),
90 ...(error instanceof Error ? { description: error.message } : {}),
91 });
92 }
93 };
94
95 const deleteSideChat = async () => {
96 if (!canOperate || shell === null || deleting) return;
97 if (confirmThreadDelete) {
98 const api = readLocalApi();
99 if (!api) return;
100 const confirmed = await settlePromise(() =>
101 api.dialogs.confirm(
102 [
103 gt('Delete side chat "{title}"?', { title: shell.title }),
104 gt("This permanently clears its conversation history."),
105 ].join("\n"),
106 { variant: "destructive" },
107 ),
108 );
109 if (confirmed._tag === "Failure" || !confirmed.value) return;
110 }
111 setDeleting(true);
112 const result = await deleteThread({
113 environmentId: parentRef.environmentId,
114 input: { threadId },
115 });
116 setDeleting(false);
117 if (result._tag === "Success") {
118 releaseComposerDraftUploads(threadRef);
119 useComposerDraftStore.getState().clearDraftThread(threadRef);
120 useRightPanelStore.getState().closeSurface(parentRef, `side-chat:${threadId}`);
121 } else if (!isAtomCommandInterrupted(result)) {
122 const error = squashAtomCommandFailure(result);
123 toastManager.add({
124 type: "error",
125 title: gt("Could not delete the side chat"),
126 ...(error instanceof Error ? { description: error.message } : {}),
127 });
128 }
129 };
130
131 return (
132 <div data-side-chat-pane={threadId} className="flex h-full min-h-0 flex-col">
133 <div className="flex h-9 shrink-0 items-center gap-1 border-b border-border pr-1 pl-3">
134 <span className="min-w-0 flex-1 truncate text-xs font-medium">
135 {shell?.title ?? gt("Side chat")}
136 </span>
137 <Tooltip>
138 <TooltipTrigger
139 render={
140 <Button
141 variant="ghost"
142 size="xs"
143 aria-disabled={bringBackBlockedReason !== null || bringingBack || undefined}
144 onClick={() => void bringBack()}
145 >
146 <T>Bring back</T>
147 </Button>
148 }
149 />
150 <TooltipPopup side="bottom">
151 {bringBackBlockedReason ?? gt("Adds this side chat to the main thread's next message.")}
152 </TooltipPopup>
153 </Tooltip>
154 <Button
155 variant="ghost"
156 size="icon-xs"
157 aria-label={gt("Delete side chat")}
158 disabled={!canOperate || shell === null || deleting}
159 onClick={() => void deleteSideChat()}
160 >
161 <Trash2Icon />
162 </Button>
163 <Button
164 variant="ghost"
165 size="icon-xs"
166 aria-label={gt("Close side chat")}
167 onClick={props.onClose}
168 >
169 <XIcon />
170 </Button>
171 </div>
172 {shell === null ? (
173 snapshotLoaded ? (
174 <p className="p-3 text-xs text-muted-foreground">
175 <T>This side chat was deleted.</T>
176 </p>
177 ) : null
178 ) : (
179 <BackgroundThreadContext value>
180 <ComposerHandleContext value={null}>
181 <ChatView
182 environmentId={parentRef.environmentId}
183 threadId={threadId}
184 routeKind="server"
185 embedded={props.parentPanel}
186 />
187 </ComposerHandleContext>
188 </BackgroundThreadContext>
189 )}
190 </div>
191 );
192}