@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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