Open History to see the last commit
1import type {
2 EnvironmentProject,
3 EnvironmentThreadShell,
4} from "@t3tools/client-runtime/state/shell";
5import type { Dispatch } from "react";
6import type { ComposerHandleRef } from "../../composerHandleContext";
7import type { selectThreadTerminalUiState } from "../../terminalUiStateStore";
8import { useStableCallback } from "../../hooks/useStableCallback";
9import { useThreadTerminalActions } from "../terminal/useThreadTerminalActions";
10import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
11import {
12 AuthTerminalReadScope,
13 AuthTerminalOperateScope,
14 type EnvironmentId,
15 type ProjectScript,
16 type ScopedThreadRef,
17 type ThreadId,
18} from "@t3tools/contracts";
19import { projectScriptTerminalInput } from "@t3tools/shared/projectScripts";
20import { type SetStateAction } from "react";
21import {
22 isAtomCommandInterrupted,
23 squashAtomCommandFailure,
24} from "@t3tools/client-runtime/state/runtime";
25import { MAX_TERMINALS_PER_GROUP } from "../../types";
26import {
27 selectThreadRightPanelState,
28 type RightPanelSurface,
29 useRightPanelStore,
30} from "../../rightPanelStore";
31import { openUrlInPreview } from "../../browser/openFileInPreview";
32import { isPreviewAvailableFor } from "../../browser/previewRuntime";
33import { resolveDiscoveredServerUrl } from "../../browser/browserTargetResolver";
34import { stackedThreadToast, toastManager } from "../ui/toast";
35import { confirmTerminalClose } from "../../lib/terminalCloseConfirm";
36import { findReusableProjectScriptTerminal } from "../../lib/projectScriptTerminal";
37import { closingTerminalIds } from "../terminal/closingTerminals";
38import { type TerminalContextSelection } from "../../lib/terminalContext";
39import {
40 focusActiveDrawerTerminal,
41 focusActivePanelTerminal,
42 focusTerminal,
43} from "../../lib/terminalFocus";
44import { useTerminalUiStateStore } from "../../terminalUiStateStore";
45import {
46 LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
47 LastInvokedScriptByProjectSchema,
48 makeThreadErrorSetter,
49} from "../ChatView.logic";
50import { useLocalStorage } from "~/hooks/useLocalStorage";
51import { previewEnvironment } from "../../state/preview";
52import { readEnvironmentScope } from "../../state/session";
53import { useAtomCommand } from "../../state/use-atom-command";
54import type { ChatShortcutCommands } from "./useChatShortcuts";
55const SCRIPT_TERMINAL_COLS = 120;
56const SCRIPT_TERMINAL_ROWS = 30;
57
58export interface TerminalLaunchContext {
59 threadId: ThreadId;
60 cwd: string;
61 worktreePath: string | null;
62}
63
64interface ChatTerminalActionsInput {
65 readonly environmentId: EnvironmentId;
66 readonly composerRef: ComposerHandleRef;
67 readonly terminalUiState: ReturnType<typeof selectThreadTerminalUiState>;
68 readonly activeThread: EnvironmentThreadShell | undefined;
69 readonly activeThreadId: ThreadId | null;
70 readonly activeThreadRef: ScopedThreadRef | null;
71 readonly activeProject: EnvironmentProject | null;
72 readonly activeRightPanelSurface: RightPanelSurface | null;
73 readonly runningTerminalIds: ReadonlyArray<string>;
74 readonly activeServerOrderedTerminalIds: ReadonlyArray<string>;
75 readonly activeTerminalLabelsById: ReadonlyMap<string, string>;
76 readonly panelTerminalIds: ReadonlySet<string>;
77 readonly canReuseTerminal: boolean;
78 readonly gitCwd: string | null;
79 readonly setTerminalUiLaunchContext: Dispatch<SetStateAction<TerminalLaunchContext | null>>;
80 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
81}
82
83/**
84 * The thread's terminals: the drawer's and the right panel's, and project scripts and chat
85 * code blocks, which run in a reused or new drawer terminal.
86 */
87export function useChatTerminalActions(input: ChatTerminalActionsInput) {
88 const {
89 environmentId,
90 composerRef,
91 terminalUiState,
92 activeThread,
93 activeThreadId,
94 activeThreadRef,
95 activeProject,
96 activeRightPanelSurface,
97 runningTerminalIds,
98 activeServerOrderedTerminalIds,
99 activeTerminalLabelsById,
100 panelTerminalIds,
101 canReuseTerminal,
102 gitCwd,
103 setTerminalUiLaunchContext,
104 setThreadError,
105 } = input;
106 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
107
108 const hasTerminalWriteAccess = () =>
109 readEnvironmentScope(environmentId, AuthTerminalOperateScope);
110 const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(
111 LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
112 {},
113 LastInvokedScriptByProjectSchema,
114 );
115 const storeSetTerminalOpen = useTerminalUiStateStore((s) => s.setTerminalOpen);
116 const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal);
117 const storeSplitTerminal = useTerminalUiStateStore((s) => s.splitTerminal);
118 const storeSplitTerminalVertical = useTerminalUiStateStore((s) => s.splitTerminalVertical);
119 const storeNewTerminal = useTerminalUiStateStore((s) => s.newTerminal);
120 const storeCloseTerminal = useTerminalUiStateStore((s) => s.closeTerminal);
121 const terminalActions = useThreadTerminalActions(activeThreadRef);
122
123 const activeTerminalGroup =
124 terminalUiState.terminalGroups.find(
125 (group) => group.id === terminalUiState.activeTerminalGroupId,
126 ) ??
127 terminalUiState.terminalGroups.find((group) =>
128 group.terminalIds.includes(terminalUiState.activeTerminalId),
129 ) ??
130 null;
131 const hasReachedSplitLimit =
132 (activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP;
133 /*__HOOK__*/
134 const addTerminalContextToDraft = (selection: TerminalContextSelection) => {
135 composerRef.current?.addTerminalContext(selection);
136 };
137 const addTerminalContextToDraftStable = useStableCallback(addTerminalContextToDraft);
138 const setTerminalOpen = (open: boolean) => {
139 if (!activeThreadRef) return;
140 storeSetTerminalOpen(activeThreadRef, open);
141 focusActiveDrawerTerminal(activeThreadRef);
142 };
143 const setTerminalOpenStable = useStableCallback(setTerminalOpen);
144 const toggleTerminalVisibility = () => {
145 if (!activeThreadRef) return;
146 const nextOpen = !terminalUiState.terminalOpen;
147 if (
148 nextOpen &&
149 !readEnvironmentScope(environmentId, AuthTerminalReadScope) &&
150 !hasTerminalWriteAccess()
151 )
152 return;
153 if (nextOpen && hasTerminalWriteAccess() && terminalUiState.terminalIds.length === 0) {
154 // Server-created setup terminals exist before this client's drawer mounts.
155 // Reuse them before allocating a shell from the still-empty UI state.
156 // The server lists a closing terminal until its close finishes, which would end the reopen.
157 const closingIds = new Set(closingTerminalIds(activeThreadRef));
158 const isReusable = (id: string) => !panelTerminalIds.has(id) && !closingIds.has(id);
159 const existingTerminalId =
160 runningTerminalIds.find(isReusable) ?? activeServerOrderedTerminalIds.find(isReusable);
161 if (existingTerminalId !== undefined) {
162 storeEnsureTerminal(activeThreadRef, existingTerminalId, { open: true, active: true });
163 focusActiveDrawerTerminal(activeThreadRef);
164 return;
165 }
166 void terminalActions.launchTerminal({
167 place: (terminalId) => storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),
168 })?.result;
169 focusActiveDrawerTerminal(activeThreadRef);
170 return;
171 }
172 setTerminalOpen(nextOpen);
173 };
174 const toggleTerminalVisibilityStable = useStableCallback(toggleTerminalVisibility);
175 const splitTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
176 if (!activeThreadRef || hasReachedSplitLimit) return;
177 const launched = terminalActions.launchTerminal({
178 place: (terminalId) =>
179 direction === "vertical"
180 ? storeSplitTerminalVertical(activeThreadRef, terminalId)
181 : storeSplitTerminal(activeThreadRef, terminalId),
182 });
183 if (!launched) return;
184 focusTerminal(activeThreadRef, launched.terminalId);
185 void launched.result;
186 };
187 const splitTerminalStable = useStableCallback(splitTerminal);
188 const createNewTerminal = () => {
189 if (!activeThreadRef) return;
190 const launched = terminalActions.launchTerminal({
191 place: (terminalId) => storeNewTerminal(activeThreadRef, terminalId),
192 });
193 if (!launched) return;
194 focusTerminal(activeThreadRef, launched.terminalId);
195 void launched.result;
196 };
197 const createNewTerminalStable = useStableCallback(createNewTerminal);
198 const closeTerminal = (terminalId: string) => {
199 if (!hasTerminalWriteAccess() || !activeThreadRef) return;
200 terminalActions.closeTerminalSession(terminalId, activeThreadRef);
201 storeCloseTerminal(activeThreadRef, terminalId);
202 focusActiveDrawerTerminal(activeThreadRef);
203 };
204 const runProjectScript = async (
205 script: ProjectScript,
206 options?: {
207 cwd?: string;
208 env?: Record<string, string>;
209 worktreePath?: string | null;
210 preferNewTerminal?: boolean;
211 rememberAsLastInvoked?: boolean;
212 shellHistory?: "preserve" | "suppress";
213 },
214 ) => {
215 if (!hasTerminalWriteAccess() || !activeThreadId || !activeProject || !activeThread) return;
216 if (options?.rememberAsLastInvoked !== false) {
217 setLastInvokedScriptByProjectId((current) => {
218 if (current[activeProject.id] === script.id) return current;
219 return { ...current, [activeProject.id]: script.id };
220 });
221 }
222 const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot;
223 const reusableTerminalId =
224 script.stopOnSettle ||
225 options?.preferNewTerminal ||
226 !canReuseTerminal ||
227 !readEnvironmentScope(environmentId, AuthTerminalReadScope)
228 ? null
229 : findReusableProjectScriptTerminal({
230 // Server sessions cover drawer terminals this client has not opened yet, such as a
231 // worktree setup shell; the helper drops the panel-owned ones.
232 drawerTerminalIds: [
233 ...new Set([...terminalUiState.terminalIds, ...activeServerOrderedTerminalIds]),
234 ],
235 activeTerminalId: terminalUiState.activeTerminalId,
236 panelTerminalIds,
237 runningTerminalIds,
238 closingTerminalIds: activeThreadRef ? closingTerminalIds(activeThreadRef) : [],
239 });
240 const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
241
242 setTerminalUiLaunchContext({
243 threadId: activeThreadId,
244 cwd: targetCwd,
245 worktreePath: targetWorktreePath,
246 });
247 if (!activeThreadRef) {
248 return;
249 }
250
251 const launched = terminalActions.launchTerminal({
252 // The drawer opens with the target already placed: opening it empty would claim
253 // DEFAULT_THREAD_TERMINAL_ID, which a right-panel terminal may already own.
254 place: (terminalId) =>
255 reusableTerminalId === null
256 ? storeNewTerminal(activeThreadRef, terminalId)
257 : storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),
258 ...(reusableTerminalId === null
259 ? { size: { cols: SCRIPT_TERMINAL_COLS, rows: SCRIPT_TERMINAL_ROWS } }
260 : { terminalId: reusableTerminalId }),
261 location: { cwd: targetCwd, worktreePath: targetWorktreePath },
262 stopOnSettle: script.stopOnSettle ?? false,
263 ...(options?.env ? { extraEnv: options.env } : {}),
264 });
265 if (!launched) return;
266 const targetTerminalId = launched.terminalId;
267 focusTerminal(activeThreadRef, targetTerminalId);
268 const openResult = await launched.result;
269 if (openResult._tag === "Failure") {
270 if (!isAtomCommandInterrupted(openResult)) {
271 const error = squashAtomCommandFailure(openResult);
272 setThreadError(
273 activeThreadId,
274 error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
275 );
276 }
277 return;
278 }
279
280 const writeResult = await terminalActions.writeToTerminal(
281 targetTerminalId,
282 options?.shellHistory === "preserve"
283 ? `${script.command}\r`
284 : projectScriptTerminalInput(script.command),
285 );
286 if (!writeResult) return;
287 if (writeResult._tag === "Failure") {
288 if (!isAtomCommandInterrupted(writeResult)) {
289 const error = squashAtomCommandFailure(writeResult);
290 setThreadError(
291 activeThreadId,
292 error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
293 );
294 }
295 return;
296 }
297 if (
298 script.autoOpenPreview &&
299 script.previewUrl &&
300 isPreviewAvailableFor(activeThreadRef.environmentId)
301 ) {
302 const previewResult = await openUrlInPreview({
303 threadRef: activeThreadRef,
304 url: resolveDiscoveredServerUrl(activeThreadRef.environmentId, script.previewUrl),
305 openPreview,
306 });
307 if (previewResult._tag === "Failure" && !isAtomCommandInterrupted(previewResult)) {
308 const error = squashAtomCommandFailure(previewResult);
309 toastManager.add(
310 stackedThreadToast({
311 type: "error",
312 title: "Could not open preview",
313 description: error instanceof Error ? error.message : "An unexpected error occurred.",
314 }),
315 );
316 }
317 }
318 };
319 const runProjectScriptStable = useStableCallback(runProjectScript);
320
321 const runShellCommand = (command: string) => {
322 void runProjectScript(
323 {
324 id: "chat-code-block",
325 name: "Chat code block",
326 command,
327 icon: "play",
328 runOnWorktreeCreate: false,
329 },
330 { rememberAsLastInvoked: false, shellHistory: "preserve" },
331 );
332 };
333 const runShellCommandStable = useStableCallback(runShellCommand);
334 const addTerminalSurface = () => {
335 if (!activeThreadRef) return;
336 const launched = terminalActions.launchTerminal({
337 place: (terminalId) =>
338 useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId),
339 });
340 if (!launched) return;
341 focusTerminal(activeThreadRef, launched.terminalId);
342 void launched.result;
343 };
344 const addTerminalSurfaceStable = useStableCallback(addTerminalSurface);
345 const splitPanelTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
346 if (
347 !activeThreadRef ||
348 activeRightPanelSurface?.kind !== "terminal" ||
349 activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP
350 ) {
351 return;
352 }
353 const surfaceId = activeRightPanelSurface.id;
354 const launched = terminalActions.launchTerminal({
355 place: (terminalId) =>
356 useRightPanelStore
357 .getState()
358 .splitTerminal(activeThreadRef, surfaceId, terminalId, direction),
359 });
360 if (!launched) return;
361 focusTerminal(activeThreadRef, launched.terminalId);
362 void launched.result;
363 };
364 const splitPanelTerminalStable = useStableCallback(splitPanelTerminal);
365 const splitPanelTerminalVertical = () => {
366 splitPanelTerminal("vertical");
367 };
368 const splitPanelTerminalVerticalStable = useStableCallback(splitPanelTerminalVertical);
369 const activatePanelTerminal = (terminalId: string) => {
370 if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return;
371 useRightPanelStore
372 .getState()
373 .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
374 focusTerminal(activeThreadRef, terminalId);
375 };
376 const activatePanelTerminalStable = useStableCallback(activatePanelTerminal);
377 const closePanelTerminal = (terminalId: string, target = activeThreadRef) => {
378 if (!target || !readEnvironmentScope(target.environmentId, AuthTerminalOperateScope)) return;
379 const store = useRightPanelStore.getState();
380 const surface = selectThreadRightPanelState(store.byThreadKey, target).surfaces.find(
381 (entry) => entry.kind === "terminal" && entry.terminalIds.includes(terminalId),
382 );
383 if (!surface) return;
384 terminalActions.closeTerminalSession(terminalId, target);
385 storeCloseTerminal(target, terminalId);
386 store.closeTerminal(target, surface.id, terminalId);
387 focusActivePanelTerminal(target);
388 };
389 const closePanelTerminalStable = useStableCallback(closePanelTerminal);
390 const requestCloseTerminal = (terminalId: string) => {
391 if (!hasTerminalWriteAccess()) return;
392 const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
393 void confirmTerminalClose([label]).then((confirmed) => {
394 if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
395 closeTerminal(terminalId);
396 }
397 });
398 };
399 const requestCloseTerminalStable = useStableCallback(requestCloseTerminal);
400 const requestClosePanelTerminal = (terminalId: string) => {
401 if (!hasTerminalWriteAccess()) return;
402 const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
403 void confirmTerminalClose([label]).then((confirmed) => {
404 if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
405 closePanelTerminal(terminalId);
406 }
407 });
408 };
409 const requestClosePanelTerminalStable = useStableCallback(requestClosePanelTerminal);
410 const openTerminalIfClosed = () => {
411 if (!terminalUiState.terminalOpen) setTerminalOpen(true);
412 };
413 // A focused right-panel terminal takes the split/new/close chords; otherwise they act on the drawer.
414 const shortcuts = {
415 "terminal.toggle": () => {
416 if (
417 !terminalUiState.terminalOpen &&
418 !readEnvironmentScope(environmentId, AuthTerminalReadScope) &&
419 !hasTerminalWriteAccess()
420 )
421 return false;
422 toggleTerminalVisibility();
423 },
424 "terminal.split": ({ terminalFocusOwner }) => {
425 if (!hasTerminalWriteAccess()) return false;
426 if (terminalFocusOwner === "right-panel") return void splitPanelTerminal();
427 openTerminalIfClosed();
428 splitTerminal();
429 },
430 "terminal.splitVertical": ({ terminalFocusOwner }) => {
431 if (!hasTerminalWriteAccess()) return false;
432 if (terminalFocusOwner === "right-panel") return void splitPanelTerminal("vertical");
433 openTerminalIfClosed();
434 splitTerminal("vertical");
435 },
436 "terminal.close": ({ terminalFocusOwner }) => {
437 if (!hasTerminalWriteAccess()) return false;
438 if (terminalFocusOwner === "right-panel" && activeRightPanelSurface?.kind === "terminal") {
439 requestClosePanelTerminal(activeRightPanelSurface.activeTerminalId);
440 return;
441 }
442 if (terminalUiState.terminalOpen) requestCloseTerminal(terminalUiState.activeTerminalId);
443 },
444 "terminal.new": ({ terminalFocusOwner }) => {
445 if (!hasTerminalWriteAccess()) return false;
446 if (terminalFocusOwner === "right-panel") return void addTerminalSurface();
447 openTerminalIfClosed();
448 createNewTerminal();
449 },
450 } satisfies ChatShortcutCommands;
451 return {
452 shortcuts,
453 activatePanelTerminalStable,
454 addTerminalContextToDraftStable,
455 addTerminalSurfaceStable,
456 closePanelTerminalStable,
457 createNewTerminalStable,
458 lastInvokedScriptByProjectId,
459 requestClosePanelTerminalStable,
460 requestCloseTerminalStable,
461 runProjectScriptStable,
462 runShellCommandStable,
463 setTerminalOpenStable,
464 splitPanelTerminalStable,
465 splitPanelTerminalVerticalStable,
466 splitTerminalStable,
467 toggleTerminalVisibilityStable,
468 };
469}