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