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