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

SideChatPane.tsx

179 lines7.1 KB

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