@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
ts 182 lines 7.39 KB
Raw
1 import {
2 AuthOrchestrationOperateScope,
3 AuthPreviewOperateScope,
4 AuthTerminalOperateScope,
5 type ScopedThreadRef,
6 } from "@t3tools/contracts";
7 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
8 import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy";
9 import { agentControlledBrowserCloseConfirmation } from "../components/ChatView.logic";
10 import { closePreviewSession } from "../components/preview/closePreviewSession";
11 import { useThreadTerminalActions } from "../components/terminal/useThreadTerminalActions";
12 import { m } from "../i18n/messages";
13 import { confirmTerminalClose } from "../lib/terminalCloseConfirm";
14 import { focusPanelTerminalAfterClose } from "../lib/terminalFocus";
15 import { readLocalApi } from "../localApi";
16 import { setActivePreviewTab, useThreadPreviewState } from "../previewStateStore";
17 import {
18 selectActiveRightPanelSurface,
19 selectThreadRightPanelState,
20 useRightPanelStore,
21 type RightPanelSurface,
22 } from "../rightPanelStore";
23 import { readThreadShell } from "../state/entities";
24 import { previewEnvironment } from "../state/preview";
25 import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
26 import { threadEnvironment } from "../state/threads";
27 import { useAtomCommand } from "../state/use-atom-command";
28 import { useTerminalUiStateStore } from "../terminalUiStateStore";
29 import { useStableCallback } from "./useStableCallback";
30
31 /**
32 * Closing releases preview and terminal sessions, and deletes a side chat that never ran.
33 * Agent-driven browsers and terminal tabs require confirmation.
34 */
35 export function useRightPanelSurfaceClose(input: {
36 readonly threadRef: ScopedThreadRef | null;
37 readonly terminalLabelsById: ReadonlyMap<string, string>;
38 }) {
39 const { threadRef, terminalLabelsById } = input;
40 const closePreview = useAtomCommand(previewEnvironment.close, "preview close");
41 const deleteThread = useAtomCommand(threadEnvironment.delete, "side chat delete");
42 const canOperatePreview = useEnvironmentScope(
43 threadRef?.environmentId ?? null,
44 AuthPreviewOperateScope,
45 );
46 const previewState = useThreadPreviewState(threadRef);
47 const terminalActions = useThreadTerminalActions(threadRef);
48 const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal);
49 const surfaces = useRightPanelStore(
50 (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,
51 );
52
53 const releaseSurfaceResources = (ref: ScopedThreadRef, surface: RightPanelSurface) => {
54 // Without preview access, server state remains until an authorized close or restart.
55 if (canOperatePreview && surface.kind === "preview" && surface.resourceId) {
56 void closePreviewSession({
57 closePreview,
58 snapshot: previewState.sessions[surface.resourceId] ?? null,
59 tabId: surface.resourceId,
60 threadRef: ref,
61 });
62 }
63 if (
64 surface.kind === "terminal" &&
65 readEnvironmentScope(ref.environmentId, AuthTerminalOperateScope)
66 ) {
67 for (const terminalId of surface.terminalIds) {
68 storeCloseTerminal(ref, terminalId);
69 terminalActions.closeTerminalSession(terminalId, ref);
70 }
71 }
72 if (
73 surface.kind === "thread" &&
74 // Only a side chat the shell still lists is thrown away with its tab; a subagent belongs to
75 // its parent's work, and an unlisted side chat is already deleted.
76 readThreadShell(scopeThreadRef(ref.environmentId, surface.threadId))?.lineage.sideChat ===
77 true &&
78 readEnvironmentScope(ref.environmentId, AuthOrchestrationOperateScope)
79 ) {
80 // The server keeps a side chat with a run or message. Reopen skips one it deleted.
81 void deleteThread({
82 environmentId: ref.environmentId,
83 input: { threadId: surface.threadId, onlyIfUnused: true },
84 });
85 }
86 };
87 const closeAfterAgentBrowserConfirmation = (
88 toClose: readonly RightPanelSurface[],
89 closeSurfaces: () => void,
90 ) => {
91 const message = agentControlledBrowserCloseConfirmation(toClose, previewState.desktopByTabId);
92 if (!message) {
93 closeSurfaces();
94 return;
95 }
96 const localApi = readLocalApi();
97 if (!localApi) return;
98 void localApi.dialogs.confirm(message, { variant: "destructive" }).then(
99 (confirmed) => {
100 if (confirmed) closeSurfaces();
101 },
102 () => undefined,
103 );
104 };
105 // The active surface closes last so the panel does not flash through it.
106 const finishClose = (toClose: readonly RightPanelSurface[]) => {
107 if (!threadRef) return;
108 const store = useRightPanelStore.getState();
109 const activeId = selectThreadRightPanelState(store.byThreadKey, threadRef).activeSurfaceId;
110 const ordered = toClose.toSorted(
111 (left, right) => Number(left.id === activeId) - Number(right.id === activeId),
112 );
113 for (const surface of ordered) {
114 // Releasing a browser drops its session, which prunes the tab automatically; close it
115 // first so the close stays a user action that hides the panel after the last tab.
116 store.closeSurface(threadRef, surface.id);
117 releaseSurfaceResources(threadRef, surface);
118 }
119 const nextActiveSurface = selectActiveRightPanelSurface(
120 useRightPanelStore.getState().byThreadKey,
121 threadRef,
122 );
123 if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {
124 setActivePreviewTab(threadRef, nextActiveSurface.resourceId);
125 }
126 focusPanelTerminalAfterClose(threadRef, activeId);
127 };
128 const labelFor = (terminalId: string) =>
129 terminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId, m);
130 const closeSurfaces = (toClose: readonly RightPanelSurface[]) => {
131 if (!threadRef) return;
132 closeAfterAgentBrowserConfirmation(toClose, () => {
133 const labels = readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)
134 ? toClose.flatMap((surface) =>
135 surface.kind === "terminal" ? surface.terminalIds.map(labelFor) : [],
136 )
137 : [];
138 const [first, ...rest] = labels;
139 if (first === undefined) {
140 finishClose(toClose);
141 return;
142 }
143 void confirmTerminalClose([first, ...rest]).then((confirmed) => {
144 if (confirmed) finishClose(toClose);
145 });
146 });
147 };
148
149 const closeSurface = useStableCallback((surface: RightPanelSurface) => {
150 if (!threadRef) return;
151 if (surface.kind === "preview") {
152 closeSurfaces([surface]);
153 return;
154 }
155 if (
156 surface.kind !== "terminal" ||
157 !readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)
158 ) {
159 finishClose([surface]);
160 return;
161 }
162 const otherLabels = surface.terminalIds
163 .filter((terminalId) => terminalId !== surface.activeTerminalId)
164 .map(labelFor);
165 void confirmTerminalClose([labelFor(surface.activeTerminalId), ...otherLabels]).then(
166 (confirmed) => {
167 if (confirmed) finishClose([surface]);
168 },
169 );
170 });
171 const closeOtherSurfaces = useStableCallback((surface: RightPanelSurface) =>
172 closeSurfaces(surfaces.filter((entry) => entry.id !== surface.id)),
173 );
174 const closeSurfacesToRight = useStableCallback((surface: RightPanelSurface) => {
175 const surfaceIndex = surfaces.findIndex((entry) => entry.id === surface.id);
176 if (surfaceIndex < 0) return;
177 closeSurfaces(surfaces.slice(surfaceIndex + 1));
178 });
179 const closeAllSurfaces = useStableCallback(() => closeSurfaces(surfaces));
180
181 return { closeSurface, closeOtherSurfaces, closeSurfacesToRight, closeAllSurfaces };
182 }