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