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

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