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 22, 19:30 UTC
refactor(web): ChatView's terminal actions live in useChatTerminalActions (#23063)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 13:40 UTC
379a391fcb9951afae0bcf1afe61236f095fc867
2 files changed
+448
-320
apps/web/src/components/ChatView.tsx
+40
-320
@@ -1,3 +1,4 @@
1
+import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useChatTerminalActions";
2
import { useComposerSend } from "./chat/useComposerSend";
3
import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
4
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
@@ -21,7 +22,6 @@ import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnviron
22
import { useStableCallback } from "../hooks/useStableCallback";
23
import { useProjectScriptEditing } from "./chat/useProjectScriptEditing";
24
import { RightPanelSurfaceContent } from "./chat/RightPanelSurfaceContent";
24
-import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions";
25
import { usePendingThreadRequests } from "./chat/usePendingThreadRequests";
26
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
27
import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
@@ -38,7 +38,6 @@ import {
38
pasteTextToFocusComposer,
39
shouldRedirectInputToComposer,
40
} from "./chat/composerFocusRedirect";
41
-import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
41
import * as Schema from "effect/Schema";
42
import {
43
AuthOrchestrationOperateScope,
@@ -53,7 +52,6 @@ import {
52
type MessageId,
53
type ModelSelection,
54
type OrchestrationV2ProviderTurn,
56
- type ProjectScript,
55
type PreviewAnnotationPayload,
56
ProviderInstanceId,
57
type ServerProvider,
@@ -99,11 +97,7 @@ import {
97
scopeThreadRef,
98
} from "@t3tools/client-runtime/environment";
99
import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
102
-import {
103
- projectScriptCwd,
104
- projectScriptTerminalInput,
105
- resolveProjectScripts,
106
-} from "@t3tools/shared/projectScripts";
100
+import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts";
101
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
102
import {
103
latestUnheldRun,
@@ -147,7 +141,7 @@ import {
141
import { type LegendListRef } from "@legendapp/list/react";
142
import { useUiStateStore } from "../uiStateStore";
143
import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
150
-import { DEFAULT_INTERACTION_MODE, MAX_TERMINALS_PER_GROUP, type ChatMessage } from "../types";
144
+import { DEFAULT_INTERACTION_MODE, type ChatMessage } from "../types";
145
import { useTheme } from "../hooks/useTheme";
146
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
147
import { isCommandPaletteOpen } from "../commandPaletteBus";
@@ -173,8 +167,7 @@ import {
167
setActivePreviewTab,
168
useThreadPreviewState,
169
} from "../previewStateStore";
176
-import { BrowserSettingsReadError, openUrlInPreview } from "../browser/openFileInPreview";
177
-import { resolveDiscoveredServerUrl } from "../browser/browserTargetResolver";
170
+import { BrowserSettingsReadError } from "../browser/openFileInPreview";
171
import { previewRuntimeTabId } from "../browser/previewRuntimeTabId";
172
import { addBrowserSurface } from "./preview/addBrowserSurface";
173
import { ThreadPreviewMiniPlayer } from "./preview/ThreadPreviewMiniPlayer";
@@ -227,10 +220,8 @@ import { useNewThreadHandler } from "../hooks/useHandleNewThread";
220
import { useRemoveClonedProject } from "../hooks/useRemoveClonedProject";
221
import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
222
import { resolveAppModelSelectionForInstance } from "../modelSelection";
230
-import { confirmTerminalClose } from "../lib/terminalCloseConfirm";
223
import { isPreviewFocused } from "../lib/previewFocus";
224
import { getTerminalFocusOwner } from "../lib/terminalFocus";
233
-import { findReusableProjectScriptTerminal } from "../lib/projectScriptTerminal";
225
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
226
import {
227
deriveLogicalProjectKeyFromSettings,
@@ -249,7 +240,7 @@ import {
240
useComposerDraftStore,
241
DraftId,
242
} from "../composerDraftStore";
252
-import { type TerminalContextDraft, type TerminalContextSelection } from "../lib/terminalContext";
243
+import { type TerminalContextDraft } from "../lib/terminalContext";
244
import { collectInlineContextIds } from "../lib/composerContextReferences";
245
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
246
import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";
@@ -375,8 +366,6 @@ import {
366
shouldShowPlanFollowUpPrompt,
367
shouldRenderPreviewMiniPlayer,
368
getStartedThreadModelChangeBlockReason,
378
- LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
379
- LastInvokedScriptByProjectSchema,
369
deriveLockedProvider,
370
resolveFileAttachmentUrl,
371
resolveComposerInteractionMode,
@@ -440,9 +429,6 @@ const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray<EnvironmentPresentation> = [
429
430
const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet<string> = new Set();
431
443
-const SCRIPT_TERMINAL_COLS = 120;
444
-const SCRIPT_TERMINAL_ROWS = 30;
445
-
432
type ChatViewProps =
433
| {
434
environmentId: EnvironmentId;
@@ -463,12 +449,6 @@ type ChatViewProps =
449
draftId: DraftId;
450
};
451
466
-interface TerminalLaunchContext {
467
- threadId: ThreadId;
468
- cwd: string;
469
- worktreePath: string | null;
470
-}
471
-
452
const EMPTY_HELD_TURN_DIFF_SUMMARIES: readonly never[] = [];
453
const noopHeldTurnDiff = (_turnId: RunId, _filePath?: string) => {};
454
const noopHeldRevert = (_targetTurnCount: number) => {};
@@ -485,8 +465,6 @@ export default function ChatView(props: ChatViewProps) {
465
} = props;
466
const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
467
const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
488
- const hasTerminalWriteAccess = () =>
489
- readEnvironmentScope(environmentId, AuthTerminalOperateScope);
468
const canReadTerminal = useEnvironmentScope(environmentId, AuthTerminalReadScope);
469
const draftId = routeKind === "draft" ? props.draftId : null;
470
const handleNewThread = useNewThreadHandler();
@@ -816,11 +794,6 @@ export default function ChatView(props: ChatViewProps) {
794
pendingServerThreadStartFromOriginByThreadId,
795
setPendingServerThreadStartFromOriginByThreadId,
796
] = useState<Record<string, boolean>>({});
819
- const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(
820
- LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
821
- {},
822
- LastInvokedScriptByProjectSchema,
823
- );
797
const legendListRef = useRef<LegendListRef | null>(null);
798
const getTimelineScrollableNode = () => legendListRef.current?.getScrollableNode() ?? null;
799
const getTimelineScrollableNodeStable = useStableCallback(getTimelineScrollableNode);
@@ -853,12 +826,6 @@ export default function ChatView(props: ChatViewProps) {
826
const terminalUiState = useTerminalUiStateStore((state) =>
827
selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef),
828
);
856
- const storeSetTerminalOpen = useTerminalUiStateStore((s) => s.setTerminalOpen);
857
- const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal);
858
- const storeSplitTerminal = useTerminalUiStateStore((s) => s.splitTerminal);
859
- const storeSplitTerminalVertical = useTerminalUiStateStore((s) => s.splitTerminalVertical);
860
- const storeNewTerminal = useTerminalUiStateStore((s) => s.newTerminal);
861
- const storeCloseTerminal = useTerminalUiStateStore((s) => s.closeTerminal);
829
830
const fallbackDraftProjectRef = draftThread
831
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
@@ -1026,7 +993,6 @@ export default function ChatView(props: ChatViewProps) {
993
return labels;
994
})();
995
const activeThreadRef = useActiveThreadRef(activeThread);
1029
- const terminalActions = useThreadTerminalActions(activeThreadRef);
996
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
997
const activeEnvironmentServerBrowser = useEnvironmentSupportsServerBrowser(
998
activeThreadRef?.environmentId ?? null,
@@ -2379,17 +2345,6 @@ export default function ChatView(props: ChatViewProps) {
2345
sendInFlightRef,
2346
});
2347
2382
- const activeTerminalGroup =
2383
- terminalUiState.terminalGroups.find(
2384
- (group) => group.id === terminalUiState.activeTerminalGroupId,
2385
- ) ??
2386
- terminalUiState.terminalGroups.find((group) =>
2387
- group.terminalIds.includes(terminalUiState.activeTerminalId),
2388
- ) ??
2389
- null;
2390
- const hasReachedSplitLimit =
2391
- (activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP;
2392
-
2348
const focusComposer = () => {
2349
composerRef.current?.focusAtEnd();
2350
};
@@ -2460,199 +2415,42 @@ export default function ChatView(props: ChatViewProps) {
2415
};
2416
const sendAppMessageStable = useStableCallback(sendAppMessage);
2417
const queuedRunsControlRef = useRef<QueuedRunsControlHandle>(null);
2463
- const addTerminalContextToDraft = (selection: TerminalContextSelection) => {
2464
- composerRef.current?.addTerminalContext(selection);
2465
- };
2466
- const addTerminalContextToDraftStable = useStableCallback(addTerminalContextToDraft);
2467
- const setTerminalOpen = (open: boolean) => {
2468
- if (!activeThreadRef) return;
2469
- storeSetTerminalOpen(activeThreadRef, open);
2470
- };
2471
- const setTerminalOpenStable = useStableCallback(setTerminalOpen);
2472
- const toggleTerminalVisibility = () => {
2473
- if (!activeThreadRef) return;
2474
- const nextOpen = !terminalUiState.terminalOpen;
2475
- if (
2476
- nextOpen &&
2477
- !readEnvironmentScope(environmentId, AuthTerminalReadScope) &&
2478
- !hasTerminalWriteAccess()
2479
- )
2480
- return;
2481
- if (nextOpen && hasTerminalWriteAccess() && terminalUiState.terminalIds.length === 0) {
2482
- // Server-created setup terminals exist before this client's drawer mounts.
2483
- // Reuse them before allocating a shell from the still-empty UI state.
2484
- const existingTerminalId =
2485
- runningTerminalIds.find((id) => !panelTerminalIds.has(id)) ??
2486
- activeServerOrderedTerminalIds.find((id) => !panelTerminalIds.has(id));
2487
- if (existingTerminalId !== undefined) {
2488
- storeEnsureTerminal(activeThreadRef, existingTerminalId, { open: true, active: true });
2489
- return;
2490
- }
2491
- void terminalActions.launchTerminal({
2492
- place: (terminalId) => storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),
2493
- })?.result;
2494
- return;
2495
- }
2496
- setTerminalOpen(nextOpen);
2497
- };
2498
- const toggleTerminalVisibilityStable = useStableCallback(toggleTerminalVisibility);
2499
- const splitTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
2500
- if (!activeThreadRef || hasReachedSplitLimit) return;
2501
- const launched = terminalActions.launchTerminal({
2502
- place: (terminalId) =>
2503
- direction === "vertical"
2504
- ? storeSplitTerminalVertical(activeThreadRef, terminalId)
2505
- : storeSplitTerminal(activeThreadRef, terminalId),
2506
- });
2507
- if (!launched) return;
2508
- setTerminalFocusRequestId((value) => value + 1);
2509
- void launched.result;
2510
- };
2511
- const splitTerminalStable = useStableCallback(splitTerminal);
2512
- const createNewTerminal = () => {
2513
- if (!activeThreadRef) return;
2514
- const launched = terminalActions.launchTerminal({
2515
- place: (terminalId) => storeNewTerminal(activeThreadRef, terminalId),
2516
- });
2517
- if (!launched) return;
2518
- setTerminalFocusRequestId((value) => value + 1);
2519
- void launched.result;
2520
- };
2521
- const createNewTerminalStable = useStableCallback(createNewTerminal);
2522
- const closeTerminal = (terminalId: string) => {
2523
- if (!hasTerminalWriteAccess() || !activeThreadRef) return;
2524
- terminalActions.closeTerminalSession(terminalId);
2525
- storeCloseTerminal(activeThreadRef, terminalId);
2526
- setTerminalFocusRequestId((value) => value + 1);
2527
- };
2528
- const runProjectScript = async (
2529
- script: ProjectScript,
2530
- options?: {
2531
- cwd?: string;
2532
- env?: Record<string, string>;
2533
- worktreePath?: string | null;
2534
- preferNewTerminal?: boolean;
2535
- rememberAsLastInvoked?: boolean;
2536
- shellHistory?: "preserve" | "suppress";
2537
- },
2538
- ) => {
2539
- if (!hasTerminalWriteAccess() || !activeThreadId || !activeProject || !activeThread) return;
2540
- if (options?.rememberAsLastInvoked !== false) {
2541
- setLastInvokedScriptByProjectId((current) => {
2542
- if (current[activeProject.id] === script.id) return current;
2543
- return { ...current, [activeProject.id]: script.id };
2544
- });
2545
- }
2546
- const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot;
2547
- const reusableTerminalId =
2548
- options?.preferNewTerminal ||
2549
- !canReuseTerminal ||
2550
- !readEnvironmentScope(environmentId, AuthTerminalReadScope)
2551
- ? null
2552
- : findReusableProjectScriptTerminal({
2553
- // Server sessions cover drawer terminals this client has not opened yet, such as a
2554
- // worktree setup shell; the helper drops the panel-owned ones.
2555
- drawerTerminalIds: [
2556
- ...new Set([...terminalUiState.terminalIds, ...activeServerOrderedTerminalIds]),
2557
- ],
2558
- activeTerminalId: terminalUiState.activeTerminalId,
2559
- panelTerminalIds,
2560
- runningTerminalIds,
2561
- });
2562
- const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
2563
-
2564
- setTerminalUiLaunchContext({
2565
- threadId: activeThreadId,
2566
- cwd: targetCwd,
2567
- worktreePath: targetWorktreePath,
2568
- });
2569
- if (!activeThreadRef) {
2570
- return;
2571
- }
2572
- setTerminalFocusRequestId((value) => value + 1);
2573
-
2574
- const launched = terminalActions.launchTerminal({
2575
- // The drawer opens with the target already placed: opening it empty would claim
2576
- // DEFAULT_THREAD_TERMINAL_ID, which a right-panel terminal may already own.
2577
- place: (terminalId) =>
2578
- reusableTerminalId === null
2579
- ? storeNewTerminal(activeThreadRef, terminalId)
2580
- : storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),
2581
- ...(reusableTerminalId === null
2582
- ? { size: { cols: SCRIPT_TERMINAL_COLS, rows: SCRIPT_TERMINAL_ROWS } }
2583
- : { terminalId: reusableTerminalId }),
2584
- location: { cwd: targetCwd, worktreePath: targetWorktreePath },
2585
- ...(options?.env ? { extraEnv: options.env } : {}),
2586
- });
2587
- if (!launched) return;
2588
- const targetTerminalId = launched.terminalId;
2589
- const openResult = await launched.result;
2590
- if (openResult._tag === "Failure") {
2591
- if (!isAtomCommandInterrupted(openResult)) {
2592
- const error = squashAtomCommandFailure(openResult);
2593
- setThreadError(
2594
- activeThreadId,
2595
- error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
2596
- );
2597
- }
2598
- return;
2599
- }
2600
-
2601
- const writeResult = await terminalActions.writeToTerminal(
2602
- targetTerminalId,
2603
- options?.shellHistory === "preserve"
2604
- ? `${script.command}\r`
2605
- : projectScriptTerminalInput(script.command),
2606
- );
2607
- if (!writeResult) return;
2608
- if (writeResult._tag === "Failure") {
2609
- if (!isAtomCommandInterrupted(writeResult)) {
2610
- const error = squashAtomCommandFailure(writeResult);
2611
- setThreadError(
2612
- activeThreadId,
2613
- error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
2614
- );
2615
- }
2616
- return;
2617
- }
2618
- if (script.autoOpenPreview && script.previewUrl && isPreviewSupportedInRuntime()) {
2619
- const previewResult = await openUrlInPreview({
2620
- threadRef: activeThreadRef,
2621
- url: resolveDiscoveredServerUrl(activeThreadRef.environmentId, script.previewUrl),
2622
- openPreview,
2623
- });
2624
- if (previewResult._tag === "Failure" && !isAtomCommandInterrupted(previewResult)) {
2625
- const error = squashAtomCommandFailure(previewResult);
2626
- toastManager.add(
2627
- stackedThreadToast({
2628
- type: "error",
2629
- title: "Could not open preview",
2630
- description: error instanceof Error ? error.message : "An unexpected error occurred.",
2631
- }),
2632
- );
2633
- }
2634
- }
2635
- };
2636
- const runProjectScriptStable = useStableCallback(runProjectScript);
2637
-
2638
- const runProjectScriptRef = useRef(runProjectScriptStable);
2639
- useLayoutEffect(() => {
2640
- runProjectScriptRef.current = runProjectScriptStable;
2641
- }, [runProjectScriptStable]);
2642
- const runShellCommand = (command: string) => {
2643
- void runProjectScriptRef.current(
2644
- {
2645
- id: "chat-code-block",
2646
- name: "Chat code block",
2647
- command,
2648
- icon: "play",
2649
- runOnWorktreeCreate: false,
2650
- },
2651
- { rememberAsLastInvoked: false, shellHistory: "preserve" },
2652
- );
2653
- };
2654
- const runShellCommandStable = useStableCallback(runShellCommand);
2418
2419
+ const {
2420
+ activatePanelTerminalStable,
2421
+ addTerminalContextToDraftStable,
2422
+ addTerminalSurfaceStable,
2423
+ closePanelTerminalStable,
2424
+ createNewTerminalStable,
2425
+ lastInvokedScriptByProjectId,
2426
+ requestClosePanelTerminalStable,
2427
+ requestCloseTerminalStable,
2428
+ runProjectScriptStable,
2429
+ runShellCommandStable,
2430
+ setTerminalOpenStable,
2431
+ splitPanelTerminalStable,
2432
+ splitPanelTerminalVerticalStable,
2433
+ splitTerminalStable,
2434
+ toggleTerminalVisibilityStable,
2435
+ } = useChatTerminalActions({
2436
+ environmentId,
2437
+ composerRef,
2438
+ terminalUiState,
2439
+ activeThread,
2440
+ activeThreadId,
2441
+ activeThreadRef,
2442
+ activeProject,
2443
+ activeRightPanelSurface,
2444
+ runningTerminalIds,
2445
+ activeServerOrderedTerminalIds,
2446
+ activeTerminalLabelsById,
2447
+ panelTerminalIds,
2448
+ canReuseTerminal,
2449
+ gitCwd,
2450
+ setTerminalFocusRequestId,
2451
+ setTerminalUiLaunchContext,
2452
+ setThreadError,
2453
+ });
2454
const {
2455
saveProjectScript: saveProjectScriptStable,
2456
updateProjectScript: updateProjectScriptStable,
@@ -2853,84 +2651,6 @@ export default function ChatView(props: ChatViewProps) {
2651
}
2652
};
2653
const togglePreviewPanelStable = useStableCallback(togglePreviewPanel);
2856
- const addTerminalSurface = () => {
2857
- if (!activeThreadRef) return;
2858
- const launched = terminalActions.launchTerminal({
2859
- place: (terminalId) =>
2860
- useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId),
2861
- });
2862
- if (!launched) return;
2863
- setTerminalFocusRequestId((value) => value + 1);
2864
- void launched.result;
2865
- };
2866
- const addTerminalSurfaceStable = useStableCallback(addTerminalSurface);
2867
- const splitPanelTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
2868
- if (
2869
- !activeThreadRef ||
2870
- activeRightPanelSurface?.kind !== "terminal" ||
2871
- activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP
2872
- ) {
2873
- return;
2874
- }
2875
- const surfaceId = activeRightPanelSurface.id;
2876
- const launched = terminalActions.launchTerminal({
2877
- place: (terminalId) =>
2878
- useRightPanelStore
2879
- .getState()
2880
- .splitTerminal(activeThreadRef, surfaceId, terminalId, direction),
2881
- });
2882
- if (!launched) return;
2883
- setTerminalFocusRequestId((value) => value + 1);
2884
- void launched.result;
2885
- };
2886
- const splitPanelTerminalStable = useStableCallback(splitPanelTerminal);
2887
- const splitPanelTerminalVertical = () => {
2888
- splitPanelTerminal("vertical");
2889
- };
2890
- const splitPanelTerminalVerticalStable = useStableCallback(splitPanelTerminalVertical);
2891
- const activatePanelTerminal = (terminalId: string) => {
2892
- if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return;
2893
- useRightPanelStore
2894
- .getState()
2895
- .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
2896
- setTerminalFocusRequestId((value) => value + 1);
2897
- };
2898
- const activatePanelTerminalStable = useStableCallback(activatePanelTerminal);
2899
- const closePanelTerminal = (terminalId: string) => {
2900
- if (
2901
- !hasTerminalWriteAccess() ||
2902
- !activeThreadRef ||
2903
- activeRightPanelSurface?.kind !== "terminal"
2904
- )
2905
- return;
2906
- terminalActions.closeTerminalSession(terminalId);
2907
- storeCloseTerminal(activeThreadRef, terminalId);
2908
- useRightPanelStore
2909
- .getState()
2910
- .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
2911
- setTerminalFocusRequestId((value) => value + 1);
2912
- };
2913
- const closePanelTerminalStable = useStableCallback(closePanelTerminal);
2914
- const requestCloseTerminal = (terminalId: string) => {
2915
- if (!hasTerminalWriteAccess()) return;
2916
- const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
2917
- void confirmTerminalClose([label]).then((confirmed) => {
2918
- if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
2919
- closeTerminal(terminalId);
2920
- }
2921
- });
2922
- };
2923
- const requestCloseTerminalStable = useStableCallback(requestCloseTerminal);
2924
- const requestClosePanelTerminal = (terminalId: string) => {
2925
- if (!hasTerminalWriteAccess()) return;
2926
- const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
2927
- void confirmTerminalClose([label]).then((confirmed) => {
2928
- if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
2929
- closePanelTerminal(terminalId);
2930
- }
2931
- });
2932
- };
2933
- const requestClosePanelTerminalStable = useStableCallback(requestClosePanelTerminal);
2654
const activateRightPanelSurface = (surface: RightPanelSurface) => {
2655
if (!activeThreadRef) return;
2656
explicitDiffOpenRef.current = resolveExplicitDiffOpenOnActivate({
apps/web/src/components/chat/useChatTerminalActions.ts
new
+408
@@ -0,0 +1,408 @@
1
+import type {
2
+ EnvironmentProject,
3
+ EnvironmentThreadShell,
4
+} from "@t3tools/client-runtime/state/shell";
5
+import type { Dispatch } from "react";
6
+import type { ComposerHandleRef } from "../../composerHandleContext";
7
+import type { selectThreadTerminalUiState } from "../../terminalUiStateStore";
8
+import { useStableCallback } from "../../hooks/useStableCallback";
9
+import { useThreadTerminalActions } from "../terminal/useThreadTerminalActions";
10
+import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
11
+import {
12
+ AuthTerminalReadScope,
13
+ AuthTerminalOperateScope,
14
+ type EnvironmentId,
15
+ type ProjectScript,
16
+ type ScopedThreadRef,
17
+ type ThreadId,
18
+} from "@t3tools/contracts";
19
+import { projectScriptTerminalInput } from "@t3tools/shared/projectScripts";
20
+import { type SetStateAction } from "react";
21
+import {
22
+ isAtomCommandInterrupted,
23
+ squashAtomCommandFailure,
24
+} from "@t3tools/client-runtime/state/runtime";
25
+import { MAX_TERMINALS_PER_GROUP } from "../../types";
26
+import { type RightPanelSurface, useRightPanelStore } from "../../rightPanelStore";
27
+import { isPreviewSupportedInRuntime } from "../../previewStateStore";
28
+import { openUrlInPreview } from "../../browser/openFileInPreview";
29
+import { resolveDiscoveredServerUrl } from "../../browser/browserTargetResolver";
30
+import { stackedThreadToast, toastManager } from "../ui/toast";
31
+import { confirmTerminalClose } from "../../lib/terminalCloseConfirm";
32
+import { findReusableProjectScriptTerminal } from "../../lib/projectScriptTerminal";
33
+import { type TerminalContextSelection } from "../../lib/terminalContext";
34
+import { useTerminalUiStateStore } from "../../terminalUiStateStore";
35
+import {
36
+ LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
37
+ LastInvokedScriptByProjectSchema,
38
+ makeThreadErrorSetter,
39
+} from "../ChatView.logic";
40
+import { useLocalStorage } from "~/hooks/useLocalStorage";
41
+import { previewEnvironment } from "../../state/preview";
42
+import { readEnvironmentScope } from "../../state/session";
43
+import { useAtomCommand } from "../../state/use-atom-command";
44
+const SCRIPT_TERMINAL_COLS = 120;
45
+const SCRIPT_TERMINAL_ROWS = 30;
46
+
47
+export interface TerminalLaunchContext {
48
+ threadId: ThreadId;
49
+ cwd: string;
50
+ worktreePath: string | null;
51
+}
52
+
53
+interface ChatTerminalActionsInput {
54
+ readonly environmentId: EnvironmentId;
55
+ readonly composerRef: ComposerHandleRef;
56
+ readonly terminalUiState: ReturnType<typeof selectThreadTerminalUiState>;
57
+ readonly activeThread: EnvironmentThreadShell | undefined;
58
+ readonly activeThreadId: ThreadId | null;
59
+ readonly activeThreadRef: ScopedThreadRef | null;
60
+ readonly activeProject: EnvironmentProject | null;
61
+ readonly activeRightPanelSurface: RightPanelSurface | null;
62
+ readonly runningTerminalIds: ReadonlyArray<string>;
63
+ readonly activeServerOrderedTerminalIds: ReadonlyArray<string>;
64
+ readonly activeTerminalLabelsById: ReadonlyMap<string, string>;
65
+ readonly panelTerminalIds: ReadonlySet<string>;
66
+ readonly canReuseTerminal: boolean;
67
+ readonly gitCwd: string | null;
68
+ readonly setTerminalFocusRequestId: Dispatch<SetStateAction<number>>;
69
+ readonly setTerminalUiLaunchContext: Dispatch<SetStateAction<TerminalLaunchContext | null>>;
70
+ readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
71
+}
72
+
73
+/**
74
+ * The thread's terminals: the drawer's and the right panel's, and project scripts and chat
75
+ * code blocks, which run in a reused or new drawer terminal.
76
+ */
77
+export function useChatTerminalActions(input: ChatTerminalActionsInput) {
78
+ const {
79
+ environmentId,
80
+ composerRef,
81
+ terminalUiState,
82
+ activeThread,
83
+ activeThreadId,
84
+ activeThreadRef,
85
+ activeProject,
86
+ activeRightPanelSurface,
87
+ runningTerminalIds,
88
+ activeServerOrderedTerminalIds,
89
+ activeTerminalLabelsById,
90
+ panelTerminalIds,
91
+ canReuseTerminal,
92
+ gitCwd,
93
+ setTerminalFocusRequestId,
94
+ setTerminalUiLaunchContext,
95
+ setThreadError,
96
+ } = input;
97
+ const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
98
+
99
+ const hasTerminalWriteAccess = () =>
100
+ readEnvironmentScope(environmentId, AuthTerminalOperateScope);
101
+ const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(
102
+ LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
103
+ {},
104
+ LastInvokedScriptByProjectSchema,
105
+ );
106
+ const storeSetTerminalOpen = useTerminalUiStateStore((s) => s.setTerminalOpen);
107
+ const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal);
108
+ const storeSplitTerminal = useTerminalUiStateStore((s) => s.splitTerminal);
109
+ const storeSplitTerminalVertical = useTerminalUiStateStore((s) => s.splitTerminalVertical);
110
+ const storeNewTerminal = useTerminalUiStateStore((s) => s.newTerminal);
111
+ const storeCloseTerminal = useTerminalUiStateStore((s) => s.closeTerminal);
112
+ const terminalActions = useThreadTerminalActions(activeThreadRef);
113
+
114
+ const activeTerminalGroup =
115
+ terminalUiState.terminalGroups.find(
116
+ (group) => group.id === terminalUiState.activeTerminalGroupId,
117
+ ) ??
118
+ terminalUiState.terminalGroups.find((group) =>
119
+ group.terminalIds.includes(terminalUiState.activeTerminalId),
120
+ ) ??
121
+ null;
122
+ const hasReachedSplitLimit =
123
+ (activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP;
124
+ /*__HOOK__*/
125
+ const addTerminalContextToDraft = (selection: TerminalContextSelection) => {
126
+ composerRef.current?.addTerminalContext(selection);
127
+ };
128
+ const addTerminalContextToDraftStable = useStableCallback(addTerminalContextToDraft);
129
+ const setTerminalOpen = (open: boolean) => {
130
+ if (!activeThreadRef) return;
131
+ storeSetTerminalOpen(activeThreadRef, open);
132
+ };
133
+ const setTerminalOpenStable = useStableCallback(setTerminalOpen);
134
+ const toggleTerminalVisibility = () => {
135
+ if (!activeThreadRef) return;
136
+ const nextOpen = !terminalUiState.terminalOpen;
137
+ if (
138
+ nextOpen &&
139
+ !readEnvironmentScope(environmentId, AuthTerminalReadScope) &&
140
+ !hasTerminalWriteAccess()
141
+ )
142
+ return;
143
+ if (nextOpen && hasTerminalWriteAccess() && terminalUiState.terminalIds.length === 0) {
144
+ // Server-created setup terminals exist before this client's drawer mounts.
145
+ // Reuse them before allocating a shell from the still-empty UI state.
146
+ const existingTerminalId =
147
+ runningTerminalIds.find((id) => !panelTerminalIds.has(id)) ??
148
+ activeServerOrderedTerminalIds.find((id) => !panelTerminalIds.has(id));
149
+ if (existingTerminalId !== undefined) {
150
+ storeEnsureTerminal(activeThreadRef, existingTerminalId, { open: true, active: true });
151
+ return;
152
+ }
153
+ void terminalActions.launchTerminal({
154
+ place: (terminalId) => storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),
155
+ })?.result;
156
+ return;
157
+ }
158
+ setTerminalOpen(nextOpen);
159
+ };
160
+ const toggleTerminalVisibilityStable = useStableCallback(toggleTerminalVisibility);
161
+ const splitTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
162
+ if (!activeThreadRef || hasReachedSplitLimit) return;
163
+ const launched = terminalActions.launchTerminal({
164
+ place: (terminalId) =>
165
+ direction === "vertical"
166
+ ? storeSplitTerminalVertical(activeThreadRef, terminalId)
167
+ : storeSplitTerminal(activeThreadRef, terminalId),
168
+ });
169
+ if (!launched) return;
170
+ setTerminalFocusRequestId((value) => value + 1);
171
+ void launched.result;
172
+ };
173
+ const splitTerminalStable = useStableCallback(splitTerminal);
174
+ const createNewTerminal = () => {
175
+ if (!activeThreadRef) return;
176
+ const launched = terminalActions.launchTerminal({
177
+ place: (terminalId) => storeNewTerminal(activeThreadRef, terminalId),
178
+ });
179
+ if (!launched) return;
180
+ setTerminalFocusRequestId((value) => value + 1);
181
+ void launched.result;
182
+ };
183
+ const createNewTerminalStable = useStableCallback(createNewTerminal);
184
+ const closeTerminal = (terminalId: string) => {
185
+ if (!hasTerminalWriteAccess() || !activeThreadRef) return;
186
+ terminalActions.closeTerminalSession(terminalId);
187
+ storeCloseTerminal(activeThreadRef, terminalId);
188
+ setTerminalFocusRequestId((value) => value + 1);
189
+ };
190
+ const runProjectScript = async (
191
+ script: ProjectScript,
192
+ options?: {
193
+ cwd?: string;
194
+ env?: Record<string, string>;
195
+ worktreePath?: string | null;
196
+ preferNewTerminal?: boolean;
197
+ rememberAsLastInvoked?: boolean;
198
+ shellHistory?: "preserve" | "suppress";
199
+ },
200
+ ) => {
201
+ if (!hasTerminalWriteAccess() || !activeThreadId || !activeProject || !activeThread) return;
202
+ if (options?.rememberAsLastInvoked !== false) {
203
+ setLastInvokedScriptByProjectId((current) => {
204
+ if (current[activeProject.id] === script.id) return current;
205
+ return { ...current, [activeProject.id]: script.id };
206
+ });
207
+ }
208
+ const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot;
209
+ const reusableTerminalId =
210
+ options?.preferNewTerminal ||
211
+ !canReuseTerminal ||
212
+ !readEnvironmentScope(environmentId, AuthTerminalReadScope)
213
+ ? null
214
+ : findReusableProjectScriptTerminal({
215
+ // Server sessions cover drawer terminals this client has not opened yet, such as a
216
+ // worktree setup shell; the helper drops the panel-owned ones.
217
+ drawerTerminalIds: [
218
+ ...new Set([...terminalUiState.terminalIds, ...activeServerOrderedTerminalIds]),
219
+ ],
220
+ activeTerminalId: terminalUiState.activeTerminalId,
221
+ panelTerminalIds,
222
+ runningTerminalIds,
223
+ });
224
+ const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
225
+
226
+ setTerminalUiLaunchContext({
227
+ threadId: activeThreadId,
228
+ cwd: targetCwd,
229
+ worktreePath: targetWorktreePath,
230
+ });
231
+ if (!activeThreadRef) {
232
+ return;
233
+ }
234
+ setTerminalFocusRequestId((value) => value + 1);
235
+
236
+ const launched = terminalActions.launchTerminal({
237
+ // The drawer opens with the target already placed: opening it empty would claim
238
+ // DEFAULT_THREAD_TERMINAL_ID, which a right-panel terminal may already own.
239
+ place: (terminalId) =>
240
+ reusableTerminalId === null
241
+ ? storeNewTerminal(activeThreadRef, terminalId)
242
+ : storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),
243
+ ...(reusableTerminalId === null
244
+ ? { size: { cols: SCRIPT_TERMINAL_COLS, rows: SCRIPT_TERMINAL_ROWS } }
245
+ : { terminalId: reusableTerminalId }),
246
+ location: { cwd: targetCwd, worktreePath: targetWorktreePath },
247
+ ...(options?.env ? { extraEnv: options.env } : {}),
248
+ });
249
+ if (!launched) return;
250
+ const targetTerminalId = launched.terminalId;
251
+ const openResult = await launched.result;
252
+ if (openResult._tag === "Failure") {
253
+ if (!isAtomCommandInterrupted(openResult)) {
254
+ const error = squashAtomCommandFailure(openResult);
255
+ setThreadError(
256
+ activeThreadId,
257
+ error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
258
+ );
259
+ }
260
+ return;
261
+ }
262
+
263
+ const writeResult = await terminalActions.writeToTerminal(
264
+ targetTerminalId,
265
+ options?.shellHistory === "preserve"
266
+ ? `${script.command}\r`
267
+ : projectScriptTerminalInput(script.command),
268
+ );
269
+ if (!writeResult) return;
270
+ if (writeResult._tag === "Failure") {
271
+ if (!isAtomCommandInterrupted(writeResult)) {
272
+ const error = squashAtomCommandFailure(writeResult);
273
+ setThreadError(
274
+ activeThreadId,
275
+ error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
276
+ );
277
+ }
278
+ return;
279
+ }
280
+ if (script.autoOpenPreview && script.previewUrl && isPreviewSupportedInRuntime()) {
281
+ const previewResult = await openUrlInPreview({
282
+ threadRef: activeThreadRef,
283
+ url: resolveDiscoveredServerUrl(activeThreadRef.environmentId, script.previewUrl),
284
+ openPreview,
285
+ });
286
+ if (previewResult._tag === "Failure" && !isAtomCommandInterrupted(previewResult)) {
287
+ const error = squashAtomCommandFailure(previewResult);
288
+ toastManager.add(
289
+ stackedThreadToast({
290
+ type: "error",
291
+ title: "Could not open preview",
292
+ description: error instanceof Error ? error.message : "An unexpected error occurred.",
293
+ }),
294
+ );
295
+ }
296
+ }
297
+ };
298
+ const runProjectScriptStable = useStableCallback(runProjectScript);
299
+
300
+ const runShellCommand = (command: string) => {
301
+ void runProjectScript(
302
+ {
303
+ id: "chat-code-block",
304
+ name: "Chat code block",
305
+ command,
306
+ icon: "play",
307
+ runOnWorktreeCreate: false,
308
+ },
309
+ { rememberAsLastInvoked: false, shellHistory: "preserve" },
310
+ );
311
+ };
312
+ const runShellCommandStable = useStableCallback(runShellCommand);
313
+ const addTerminalSurface = () => {
314
+ if (!activeThreadRef) return;
315
+ const launched = terminalActions.launchTerminal({
316
+ place: (terminalId) =>
317
+ useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId),
318
+ });
319
+ if (!launched) return;
320
+ setTerminalFocusRequestId((value) => value + 1);
321
+ void launched.result;
322
+ };
323
+ const addTerminalSurfaceStable = useStableCallback(addTerminalSurface);
324
+ const splitPanelTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
325
+ if (
326
+ !activeThreadRef ||
327
+ activeRightPanelSurface?.kind !== "terminal" ||
328
+ activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP
329
+ ) {
330
+ return;
331
+ }
332
+ const surfaceId = activeRightPanelSurface.id;
333
+ const launched = terminalActions.launchTerminal({
334
+ place: (terminalId) =>
335
+ useRightPanelStore
336
+ .getState()
337
+ .splitTerminal(activeThreadRef, surfaceId, terminalId, direction),
338
+ });
339
+ if (!launched) return;
340
+ setTerminalFocusRequestId((value) => value + 1);
341
+ void launched.result;
342
+ };
343
+ const splitPanelTerminalStable = useStableCallback(splitPanelTerminal);
344
+ const splitPanelTerminalVertical = () => {
345
+ splitPanelTerminal("vertical");
346
+ };
347
+ const splitPanelTerminalVerticalStable = useStableCallback(splitPanelTerminalVertical);
348
+ const activatePanelTerminal = (terminalId: string) => {
349
+ if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return;
350
+ useRightPanelStore
351
+ .getState()
352
+ .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
353
+ setTerminalFocusRequestId((value) => value + 1);
354
+ };
355
+ const activatePanelTerminalStable = useStableCallback(activatePanelTerminal);
356
+ const closePanelTerminal = (terminalId: string) => {
357
+ if (
358
+ !hasTerminalWriteAccess() ||
359
+ !activeThreadRef ||
360
+ activeRightPanelSurface?.kind !== "terminal"
361
+ )
362
+ return;
363
+ terminalActions.closeTerminalSession(terminalId);
364
+ storeCloseTerminal(activeThreadRef, terminalId);
365
+ useRightPanelStore
366
+ .getState()
367
+ .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
368
+ setTerminalFocusRequestId((value) => value + 1);
369
+ };
370
+ const closePanelTerminalStable = useStableCallback(closePanelTerminal);
371
+ const requestCloseTerminal = (terminalId: string) => {
372
+ if (!hasTerminalWriteAccess()) return;
373
+ const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
374
+ void confirmTerminalClose([label]).then((confirmed) => {
375
+ if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
376
+ closeTerminal(terminalId);
377
+ }
378
+ });
379
+ };
380
+ const requestCloseTerminalStable = useStableCallback(requestCloseTerminal);
381
+ const requestClosePanelTerminal = (terminalId: string) => {
382
+ if (!hasTerminalWriteAccess()) return;
383
+ const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
384
+ void confirmTerminalClose([label]).then((confirmed) => {
385
+ if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
386
+ closePanelTerminal(terminalId);
387
+ }
388
+ });
389
+ };
390
+ const requestClosePanelTerminalStable = useStableCallback(requestClosePanelTerminal);
391
+ return {
392
+ activatePanelTerminalStable,
393
+ addTerminalContextToDraftStable,
394
+ addTerminalSurfaceStable,
395
+ closePanelTerminalStable,
396
+ createNewTerminalStable,
397
+ lastInvokedScriptByProjectId,
398
+ requestClosePanelTerminalStable,
399
+ requestCloseTerminalStable,
400
+ runProjectScriptStable,
401
+ runShellCommandStable,
402
+ setTerminalOpenStable,
403
+ splitPanelTerminalStable,
404
+ splitPanelTerminalVerticalStable,
405
+ splitTerminalStable,
406
+ toggleTerminalVisibilityStable,
407
+ };
408
+}