The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): open and close thread terminals through one hook (#20289)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 17:39 UTC
d109aa74ea07c03f813956466b207815ff39411d
3 files changed
+250
-371
apps/web/src/components/ChatView.tsx
+59
-207
@@ -25,6 +25,7 @@ import {
25
import { useLoadBalancedEnvironment } from "../hooks/useLoadBalancedEnvironment";
26
import { useScratchProject } from "../hooks/useScratchProject";
27
import { useStableCallback } from "../hooks/useStableCallback";
28
+import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions";
29
import { usePendingThreadRequests } from "./chat/usePendingThreadRequests";
30
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
31
import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
@@ -76,7 +77,6 @@ import {
77
resolveEnvironmentMachineKind,
78
resolveProjectProviderInstanceEnabled,
79
RuntimeMode,
79
- TerminalOpenInput,
80
type WorktreeSetupSnapshot,
81
} from "@t3tools/contracts";
82
import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
@@ -125,11 +125,7 @@ import {
125
resolvePromptInjectedEffort,
126
resolveSelectableModel,
127
} from "@t3tools/shared/model";
128
-import {
129
- projectScriptCwd,
130
- projectScriptRuntimeEnv,
131
- resolveProjectScripts,
132
-} from "@t3tools/shared/projectScripts";
128
+import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts";
129
import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
130
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
131
import {
@@ -140,7 +136,7 @@ import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
136
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
137
import { truncate } from "@t3tools/shared/String";
138
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
143
-import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
139
+import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
140
import { Debouncer } from "@tanstack/react-pacer";
141
import { useAtomValue } from "@effect/atom-react";
142
import { Atom } from "effect/reactivity";
@@ -400,7 +396,6 @@ import {
396
primaryServerKeybindingsAtom,
397
serverEnvironment,
398
} from "../state/server";
403
-import { terminalEnvironment } from "../state/terminal";
399
import { threadEnvironment } from "../state/threads";
400
import { workspacePreparationRetryRunIds } from "@t3tools/client-runtime/state/turn-item-presentation";
401
import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
@@ -1025,9 +1020,6 @@ export default function ChatView(props: ChatViewProps) {
1020
const removeKeybinding = useAtomCommand(serverEnvironment.removeKeybinding, {
1021
reportFailure: false,
1022
});
1028
- const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
1029
- const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
1030
- const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");
1023
const createThread = useOrchestrationCommand(threadEnvironment.create, { reportFailure: false });
1024
const deleteThread = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false });
1025
const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
@@ -1602,6 +1594,7 @@ export default function ChatView(props: ChatViewProps) {
1594
return labels;
1595
}, [activeThreadKnownSessions]);
1596
const activeThreadRef = useActiveThreadRef(activeThread);
1597
+ const terminalActions = useThreadTerminalActions(activeThreadRef);
1598
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
1599
const activeEnvironmentServerBrowser = useEnvironmentSupportsServerBrowser(
1600
activeThreadRef?.environmentId ?? null,
@@ -1690,18 +1683,7 @@ export default function ChatView(props: ChatViewProps) {
1683
),
1684
[rightPanelState.surfaces],
1685
);
1693
- const allocatableActiveTerminalIds = useMemo(
1694
- () => [...new Set([...activeKnownTerminalIds, ...panelTerminalIds])],
1695
- [activeKnownTerminalIds, panelTerminalIds],
1696
- );
1686
const canReuseTerminal = activeThreadKnownSessionsRaw !== null;
1698
- const allocateTerminalId = () =>
1699
- nextTerminalId(
1700
- allocatableActiveTerminalIds,
1701
- canReuseTerminal && readEnvironmentScope(environmentId, AuthTerminalReadScope)
1702
- ? undefined
1703
- : randomUUID(),
1704
- );
1687
const previewPanelOpen = activeRightPanelKind === "preview" && browserAvailable;
1688
const rightPanelOpen = rightPanelState.isOpen;
1689
const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
@@ -3871,119 +3853,40 @@ export default function ChatView(props: ChatViewProps) {
3853
storeEnsureTerminal(activeThreadRef, existingTerminalId, { open: true, active: true });
3854
return;
3855
}
3874
- if (!activeThreadId || !activeProject) {
3875
- return;
3876
- }
3877
- const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;
3878
- if (!cwdForOpen) {
3879
- return;
3880
- }
3881
- const terminalId = allocateTerminalId();
3882
- storeEnsureTerminal(activeThreadRef, terminalId, { open: true });
3883
- void openTerminal({
3884
- environmentId,
3885
- input: {
3886
- threadId: activeThreadId,
3887
- terminalId,
3888
- cwd: cwdForOpen,
3889
- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),
3890
- env: projectScriptRuntimeEnv({
3891
- project: { cwd: activeProject.workspaceRoot },
3892
- worktreePath: activeThreadWorktreePath,
3893
- }),
3894
- },
3895
- });
3856
+ void terminalActions.launchTerminal({
3857
+ place: (terminalId) => storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),
3858
+ })?.result;
3859
return;
3860
}
3861
setTerminalOpen(nextOpen);
3862
};
3863
const toggleTerminalVisibilityStable = useStableCallback(toggleTerminalVisibility);
3864
const splitTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
3902
- if (
3903
- !hasTerminalWriteAccess() ||
3904
- !activeThreadRef ||
3905
- hasReachedSplitLimit ||
3906
- !activeThreadId ||
3907
- !activeProject
3908
- ) {
3909
- return;
3910
- }
3911
- const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;
3912
- if (!cwdForOpen) {
3913
- return;
3914
- }
3915
- const terminalId = allocateTerminalId();
3916
- if (direction === "vertical") {
3917
- storeSplitTerminalVertical(activeThreadRef, terminalId);
3918
- } else {
3919
- storeSplitTerminal(activeThreadRef, terminalId);
3920
- }
3921
- setTerminalFocusRequestId((value) => value + 1);
3922
- void openTerminal({
3923
- environmentId,
3924
- input: {
3925
- threadId: activeThreadId,
3926
- terminalId,
3927
- cwd: cwdForOpen,
3928
- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),
3929
- env: projectScriptRuntimeEnv({
3930
- project: { cwd: activeProject.workspaceRoot },
3931
- worktreePath: activeThreadWorktreePath,
3932
- }),
3933
- },
3865
+ if (!activeThreadRef || hasReachedSplitLimit) return;
3866
+ const launched = terminalActions.launchTerminal({
3867
+ place: (terminalId) =>
3868
+ direction === "vertical"
3869
+ ? storeSplitTerminalVertical(activeThreadRef, terminalId)
3870
+ : storeSplitTerminal(activeThreadRef, terminalId),
3871
});
3872
+ if (!launched) return;
3873
+ setTerminalFocusRequestId((value) => value + 1);
3874
+ void launched.result;
3875
};
3876
const splitTerminalStable = useStableCallback(splitTerminal);
3877
const createNewTerminal = () => {
3938
- if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) {
3939
- return;
3940
- }
3941
- const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;
3942
- if (!cwdForOpen) {
3943
- return;
3944
- }
3945
- const terminalId = allocateTerminalId();
3946
- storeNewTerminal(activeThreadRef, terminalId);
3947
- setTerminalFocusRequestId((value) => value + 1);
3948
- void openTerminal({
3949
- environmentId,
3950
- input: {
3951
- threadId: activeThreadId,
3952
- terminalId,
3953
- cwd: cwdForOpen,
3954
- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),
3955
- env: projectScriptRuntimeEnv({
3956
- project: { cwd: activeProject.workspaceRoot },
3957
- worktreePath: activeThreadWorktreePath,
3958
- }),
3959
- },
3878
+ if (!activeThreadRef) return;
3879
+ const launched = terminalActions.launchTerminal({
3880
+ place: (terminalId) => storeNewTerminal(activeThreadRef, terminalId),
3881
});
3882
+ if (!launched) return;
3883
+ setTerminalFocusRequestId((value) => value + 1);
3884
+ void launched.result;
3885
};
3886
const createNewTerminalStable = useStableCallback(createNewTerminal);
3887
const closeTerminal = (terminalId: string) => {
3964
- if (!hasTerminalWriteAccess() || !activeThreadId || !activeThreadRef) return;
3965
- const fallbackExitWrite = () =>
3966
- writeTerminal({
3967
- environmentId,
3968
- input: { threadId: activeThreadId, terminalId, data: "exit\n" },
3969
- });
3970
- void (async () => {
3971
- const closeResult = await closeTerminalMutation({
3972
- environmentId,
3973
- input: {
3974
- threadId: activeThreadId,
3975
- terminalId,
3976
- deleteHistory: true,
3977
- },
3978
- });
3979
- if (
3980
- closeResult._tag === "Failure" &&
3981
- !isAtomCommandInterrupted(closeResult) &&
3982
- hasTerminalWriteAccess()
3983
- ) {
3984
- await fallbackExitWrite();
3985
- }
3986
- })();
3888
+ if (!hasTerminalWriteAccess() || !activeThreadRef) return;
3889
+ terminalActions.closeTerminalSession(terminalId);
3890
storeCloseTerminal(activeThreadRef, terminalId);
3891
setTerminalFocusRequestId((value) => value + 1);
3892
};
@@ -4026,39 +3929,20 @@ export default function ChatView(props: ChatViewProps) {
3929
}
3930
setTerminalFocusRequestId((value) => value + 1);
3931
4029
- const runtimeEnv = projectScriptRuntimeEnv({
4030
- project: {
4031
- cwd: activeProject.workspaceRoot,
4032
- },
4033
- worktreePath: targetWorktreePath,
3932
+ const launched = terminalActions.launchTerminal({
3933
+ place: (terminalId) =>
3934
+ shouldCreateNewTerminal
3935
+ ? storeNewTerminal(activeThreadRef, terminalId)
3936
+ : storeSetActiveTerminal(activeThreadRef, terminalId),
3937
+ ...(shouldCreateNewTerminal
3938
+ ? { size: { cols: SCRIPT_TERMINAL_COLS, rows: SCRIPT_TERMINAL_ROWS } }
3939
+ : { terminalId: baseTerminalId }),
3940
+ location: { cwd: targetCwd, worktreePath: targetWorktreePath },
3941
...(options?.env ? { extraEnv: options.env } : {}),
3942
});
4036
- const targetTerminalId = shouldCreateNewTerminal ? allocateTerminalId() : baseTerminalId;
4037
- const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
4038
- ? {
4039
- threadId: activeThreadId,
4040
- terminalId: targetTerminalId,
4041
- cwd: targetCwd,
4042
- ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
4043
- env: runtimeEnv,
4044
- cols: SCRIPT_TERMINAL_COLS,
4045
- rows: SCRIPT_TERMINAL_ROWS,
4046
- }
4047
- : {
4048
- threadId: activeThreadId,
4049
- terminalId: targetTerminalId,
4050
- cwd: targetCwd,
4051
- ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
4052
- env: runtimeEnv,
4053
- };
4054
-
4055
- if (shouldCreateNewTerminal) {
4056
- storeNewTerminal(activeThreadRef, targetTerminalId);
4057
- } else {
4058
- storeSetActiveTerminal(activeThreadRef, targetTerminalId);
4059
- }
4060
-
4061
- const openResult = await openTerminal({ environmentId, input: openTerminalInput });
3943
+ if (!launched) return;
3944
+ const targetTerminalId = launched.terminalId;
3945
+ const openResult = await launched.result;
3946
if (openResult._tag === "Failure") {
3947
if (!isAtomCommandInterrupted(openResult)) {
3948
const error = squashAtomCommandFailure(openResult);
@@ -4070,15 +3954,11 @@ export default function ChatView(props: ChatViewProps) {
3954
return;
3955
}
3956
4073
- if (!hasTerminalWriteAccess()) return;
4074
- const writeResult = await writeTerminal({
4075
- environmentId,
4076
- input: {
4077
- threadId: activeThreadId,
4078
- terminalId: targetTerminalId,
4079
- data: `${script.command}\r`,
4080
- },
4081
- });
3957
+ const writeResult = await terminalActions.writeToTerminal(
3958
+ targetTerminalId,
3959
+ `${script.command}\r`,
3960
+ );
3961
+ if (!writeResult) return;
3962
if (writeResult._tag === "Failure") {
3963
if (!isAtomCommandInterrupted(writeResult)) {
3964
const error = squashAtomCommandFailure(writeResult);
@@ -4846,56 +4726,34 @@ export default function ChatView(props: ChatViewProps) {
4726
};
4727
const togglePreviewPanelStable = useStableCallback(togglePreviewPanel);
4728
const addTerminalSurface = () => {
4849
- if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) return;
4850
- const cwd = gitCwd ?? activeProject.workspaceRoot;
4851
- const terminalId = allocateTerminalId();
4852
- useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId);
4853
- setTerminalFocusRequestId((value) => value + 1);
4854
- void openTerminal({
4855
- environmentId: activeThreadRef.environmentId,
4856
- input: {
4857
- threadId: activeThreadId,
4858
- terminalId,
4859
- cwd,
4860
- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),
4861
- env: projectScriptRuntimeEnv({
4862
- project: { cwd: activeProject.workspaceRoot },
4863
- worktreePath: activeThreadWorktreePath,
4864
- }),
4865
- },
4729
+ if (!activeThreadRef) return;
4730
+ const launched = terminalActions.launchTerminal({
4731
+ place: (terminalId) =>
4732
+ useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId),
4733
});
4734
+ if (!launched) return;
4735
+ setTerminalFocusRequestId((value) => value + 1);
4736
+ void launched.result;
4737
};
4738
const addTerminalSurfaceStable = useStableCallback(addTerminalSurface);
4739
const splitPanelTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
4740
if (
4871
- !hasTerminalWriteAccess() ||
4741
!activeThreadRef ||
4873
- !activeThreadId ||
4874
- !activeProject ||
4742
activeRightPanelSurface?.kind !== "terminal" ||
4743
activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP
4744
) {
4745
return;
4746
}
4880
- const terminalId = allocateTerminalId();
4881
- const cwd = gitCwd ?? activeProject.workspaceRoot;
4882
- useRightPanelStore
4883
- .getState()
4884
- .splitTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId, direction);
4885
- setTerminalFocusRequestId((value) => value + 1);
4886
- void openTerminal({
4887
- environmentId: activeThreadRef.environmentId,
4888
- input: {
4889
- threadId: activeThreadId,
4890
- terminalId,
4891
- cwd,
4892
- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),
4893
- env: projectScriptRuntimeEnv({
4894
- project: { cwd: activeProject.workspaceRoot },
4895
- worktreePath: activeThreadWorktreePath,
4896
- }),
4897
- },
4747
+ const surfaceId = activeRightPanelSurface.id;
4748
+ const launched = terminalActions.launchTerminal({
4749
+ place: (terminalId) =>
4750
+ useRightPanelStore
4751
+ .getState()
4752
+ .splitTerminal(activeThreadRef, surfaceId, terminalId, direction),
4753
});
4754
+ if (!launched) return;
4755
+ setTerminalFocusRequestId((value) => value + 1);
4756
+ void launched.result;
4757
};
4758
const splitPanelTerminalStable = useStableCallback(splitPanelTerminal);
4759
const splitPanelTerminalVertical = () => {
@@ -4917,10 +4775,7 @@ export default function ChatView(props: ChatViewProps) {
4775
activeRightPanelSurface?.kind !== "terminal"
4776
)
4777
return;
4920
- void closeTerminalMutation({
4921
- environmentId: activeThreadRef.environmentId,
4922
- input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },
4923
- });
4778
+ terminalActions.closeTerminalSession(terminalId);
4779
storeCloseTerminal(activeThreadRef, terminalId);
4780
useRightPanelStore
4781
.getState()
@@ -5004,10 +4859,7 @@ export default function ChatView(props: ChatViewProps) {
4859
) {
4860
for (const terminalId of surface.terminalIds) {
4861
storeCloseTerminal(activeThreadRef, terminalId);
5007
- void closeTerminalMutation({
5008
- environmentId: activeThreadRef.environmentId,
5009
- input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },
5010
- });
4862
+ terminalActions.closeTerminalSession(terminalId);
4863
}
4864
}
4865
}
apps/web/src/components/PersistentThreadTerminals.tsx
+29
-164
@@ -1,30 +1,28 @@
1
import {
2
AuthTerminalOperateScope,
3
- AuthTerminalReadScope,
3
type EnvironmentId,
4
type ResolvedKeybindingsConfig,
5
type ScopedThreadRef,
6
type ThreadId,
7
} from "@t3tools/contracts";
8
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
10
-import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
9
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
12
-import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
10
+import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
11
import { memo, useCallback, useEffect, useMemo, useState } from "react";
12
import { useComposerDraftStore } from "../composerDraftStore";
13
+import { useStableCallback } from "../hooks/useStableCallback";
14
import type { TerminalContextSelection } from "../lib/terminalContext";
16
-import { cn, randomUUID } from "~/lib/utils";
15
+import { cn } from "~/lib/utils";
16
import {
17
selectThreadRightPanelState,
18
useRightPanelStore,
19
type RightPanelSurface,
20
} from "../rightPanelStore";
21
import { useProject, useThreadShell } from "../state/entities";
23
-import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
24
-import { terminalEnvironment } from "../state/terminal";
22
+import { useEnvironmentScope } from "../state/session";
23
import { useKnownTerminalSessions } from "../state/terminalSessions";
26
-import { useAtomCommand } from "../state/use-atom-command";
24
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
25
+import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions";
26
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
27
28
/** Where a drawer or panel opens new terminals when a script run overrides the thread's own. */
@@ -100,13 +98,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
98
onAddTerminalContext,
99
}: PersistentThreadTerminalDrawerProps) {
100
const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
103
- const hasTerminalWriteAccess = useCallback(
104
- () => readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope),
105
- [threadRef.environmentId],
106
- );
107
- const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
108
- const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
109
- const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");
101
+ const terminalActions = useThreadTerminalActions(threadRef);
102
const serverThread = useThreadShell(threadRef);
103
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
104
const projectRef = serverThread
@@ -188,30 +180,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
180
() => drawerTerminalSessions.map((session) => session.target.terminalId),
181
[drawerTerminalSessions],
182
);
191
- // Every client-side id source participates in allocation: the server list
192
- // lags fresh opens, and panel terminals are filtered out of the drawer's
193
- // sessions — an id collision attaches two viewports to one PTY session.
194
- const allocatableTerminalIds = useMemo(
195
- () => [
196
- ...new Set([
197
- ...serverOrderedTerminalIds,
198
- ...terminalUiState.terminalIds,
199
- ...panelTerminalIds,
200
- ]),
201
- ],
202
- [panelTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds],
203
- );
204
- const allocateTerminalId = useCallback(
205
- () =>
206
- nextTerminalId(
207
- allocatableTerminalIds,
208
- knownTerminalSessions === null ||
209
- !readEnvironmentScope(threadRef.environmentId, AuthTerminalReadScope)
210
- ? randomUUID()
211
- : undefined,
212
- ),
213
- [allocatableTerminalIds, knownTerminalSessions, threadRef.environmentId],
214
- );
183
const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight);
184
const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal);
185
const storeSplitTerminalVertical = useTerminalUiStateStore(
@@ -277,94 +245,25 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
245
[storeSetTerminalHeight, threadRef],
246
);
247
280
- const splitTerminal = useCallback(() => {
281
- if (!hasTerminalWriteAccess() || !cwd) {
282
- return;
283
- }
284
- const terminalId = allocateTerminalId();
285
- storeSplitTerminal(threadRef, terminalId);
286
- bumpFocusRequestId();
287
- void openTerminal({
288
- environmentId: threadRef.environmentId,
289
- input: {
290
- threadId,
291
- terminalId,
292
- cwd,
293
- ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}),
294
- env: runtimeEnv,
295
- },
296
- });
297
- }, [
298
- allocateTerminalId,
299
- bumpFocusRequestId,
300
- cwd,
301
- effectiveWorktreePath,
302
- runtimeEnv,
303
- storeSplitTerminal,
304
- threadId,
305
- threadRef,
306
- openTerminal,
307
- hasTerminalWriteAccess,
308
- ]);
309
- const splitTerminalVertical = useCallback(() => {
310
- if (!hasTerminalWriteAccess() || !cwd) {
311
- return;
312
- }
313
- const terminalId = allocateTerminalId();
314
- storeSplitTerminalVertical(threadRef, terminalId);
315
- bumpFocusRequestId();
316
- void openTerminal({
317
- environmentId: threadRef.environmentId,
318
- input: {
319
- threadId,
320
- terminalId,
321
- cwd,
322
- ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}),
323
- env: runtimeEnv,
324
- },
248
+ const launchDrawerTerminal = (place: (terminalId: string) => void) => {
249
+ if (!cwd) return;
250
+ const launched = terminalActions.launchTerminal({
251
+ place,
252
+ location: { cwd, worktreePath: effectiveWorktreePath },
253
});
326
- }, [
327
- allocateTerminalId,
328
- bumpFocusRequestId,
329
- cwd,
330
- effectiveWorktreePath,
331
- openTerminal,
332
- hasTerminalWriteAccess,
333
- runtimeEnv,
334
- storeSplitTerminalVertical,
335
- threadId,
336
- threadRef,
337
- ]);
338
-
339
- const createNewTerminal = useCallback(() => {
340
- if (!hasTerminalWriteAccess() || !cwd) {
341
- return;
342
- }
343
- const terminalId = allocateTerminalId();
344
- storeNewTerminal(threadRef, terminalId);
254
+ if (!launched) return;
255
bumpFocusRequestId();
346
- void openTerminal({
347
- environmentId: threadRef.environmentId,
348
- input: {
349
- threadId,
350
- terminalId,
351
- cwd,
352
- ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}),
353
- env: runtimeEnv,
354
- },
355
- });
356
- }, [
357
- bumpFocusRequestId,
358
- cwd,
359
- effectiveWorktreePath,
360
- allocateTerminalId,
361
- runtimeEnv,
362
- storeNewTerminal,
363
- threadId,
364
- threadRef,
365
- openTerminal,
366
- hasTerminalWriteAccess,
367
- ]);
256
+ void launched.result;
257
+ };
258
+ const splitTerminal = useStableCallback(() =>
259
+ launchDrawerTerminal((terminalId) => storeSplitTerminal(threadRef, terminalId)),
260
+ );
261
+ const splitTerminalVertical = useStableCallback(() =>
262
+ launchDrawerTerminal((terminalId) => storeSplitTerminalVertical(threadRef, terminalId)),
263
+ );
264
+ const createNewTerminal = useStableCallback(() =>
265
+ launchDrawerTerminal((terminalId) => storeNewTerminal(threadRef, terminalId)),
266
+ );
267
268
const activateTerminal = useCallback(
269
(terminalId: string) => {
@@ -374,46 +273,12 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
273
[bumpFocusRequestId, storeSetActiveTerminal, threadRef],
274
);
275
377
- const closeTerminal = useCallback(
378
- (terminalId: string) => {
379
- if (!hasTerminalWriteAccess()) return;
380
- const fallbackExitWrite = () =>
381
- writeTerminal({
382
- environmentId: threadRef.environmentId,
383
- input: { threadId, terminalId, data: "exit\n" },
384
- });
385
-
386
- void (async () => {
387
- const closeResult = await closeTerminalMutation({
388
- environmentId: threadRef.environmentId,
389
- input: {
390
- threadId,
391
- terminalId,
392
- deleteHistory: true,
393
- },
394
- });
395
- if (
396
- closeResult._tag === "Failure" &&
397
- !isAtomCommandInterrupted(closeResult) &&
398
- hasTerminalWriteAccess()
399
- ) {
400
- await fallbackExitWrite();
401
- }
402
- })();
403
-
404
- storeCloseTerminal(threadRef, terminalId);
405
- bumpFocusRequestId();
406
- },
407
- [
408
- bumpFocusRequestId,
409
- storeCloseTerminal,
410
- threadId,
411
- threadRef,
412
- closeTerminalMutation,
413
- hasTerminalWriteAccess,
414
- writeTerminal,
415
- ],
416
- );
276
+ const closeTerminal = useStableCallback((terminalId: string) => {
277
+ if (!terminalActions.canWrite()) return;
278
+ terminalActions.closeTerminalSession(terminalId);
279
+ storeCloseTerminal(threadRef, terminalId);
280
+ bumpFocusRequestId();
281
+ });
282
283
const handleAddTerminalContext = useCallback(
284
(selection: TerminalContextSelection) => {
apps/web/src/components/terminal/useThreadTerminalActions.ts
new
+162
@@ -0,0 +1,162 @@
1
+import {
2
+ AuthTerminalOperateScope,
3
+ AuthTerminalReadScope,
4
+ type ScopedThreadRef,
5
+} from "@t3tools/contracts";
6
+import { scopeProjectRef } from "@t3tools/client-runtime/environment";
7
+import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
8
+import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
9
+import { nextTerminalId } from "@t3tools/shared/terminalLabels";
10
+import { useComposerDraftStore } from "../../composerDraftStore";
11
+import { useStableCallback } from "../../hooks/useStableCallback";
12
+import { randomUUID } from "~/lib/utils";
13
+import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore";
14
+import { useProject, useThreadShell } from "../../state/entities";
15
+import { readEnvironmentScope } from "../../state/session";
16
+import { terminalEnvironment } from "../../state/terminal";
17
+import { useKnownTerminalSessions } from "../../state/terminalSessions";
18
+import { useAtomCommand } from "../../state/use-atom-command";
19
+import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../../terminalUiStateStore";
20
+
21
+/** Where a new terminal starts. Omitted fields fall back to the thread's project and worktree. */
22
+export interface TerminalLaunchLocation {
23
+ readonly cwd: string;
24
+ readonly worktreePath: string | null;
25
+}
26
+
27
+/**
28
+ * Opens and closes a thread's terminal sessions. Every surface that hosts a
29
+ * terminal (the drawer, a right panel tab, the setup flow, script runs) goes
30
+ * through here, so ids are allocated from one view of the thread's terminals
31
+ * and every new session starts with the same cwd and environment.
32
+ */
33
+export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
34
+ const openTerminalCommand = useAtomCommand(terminalEnvironment.open, "terminal open");
35
+ const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
36
+ const closeTerminalCommand = useAtomCommand(terminalEnvironment.close, "terminal close");
37
+ const serverThread = useThreadShell(threadRef);
38
+ const draftThread = useComposerDraftStore((store) =>
39
+ threadRef ? store.getDraftThreadByRef(threadRef) : null,
40
+ );
41
+ const projectRef = serverThread
42
+ ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
43
+ : draftThread
44
+ ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
45
+ : null;
46
+ const project = useProject(projectRef);
47
+ const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
48
+ const knownSessions = useKnownTerminalSessions({
49
+ environmentId: threadRef?.environmentId ?? null,
50
+ threadId: threadRef?.threadId ?? null,
51
+ });
52
+ const drawerTerminalIds = useTerminalUiStateStore(
53
+ (state) => selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef).terminalIds,
54
+ );
55
+ const panelSurfaces = useRightPanelStore(
56
+ (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,
57
+ );
58
+
59
+ const canWrite = () =>
60
+ threadRef !== null && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
61
+
62
+ // Every client-side id source participates: the server list lags fresh opens,
63
+ // and an id collision attaches two viewports to one PTY session. Without a
64
+ // readable session list the next free number may already be taken on the
65
+ // server, so the id gets a unique suffix.
66
+ const allocateTerminalId = () => {
67
+ const ids = new Set([
68
+ ...(knownSessions ?? []).map((session) => session.target.terminalId),
69
+ ...drawerTerminalIds,
70
+ ...panelSurfaces.flatMap((surface) =>
71
+ surface.kind === "terminal" ? surface.terminalIds : [],
72
+ ),
73
+ ]);
74
+ const canReuse =
75
+ knownSessions !== null &&
76
+ threadRef !== null &&
77
+ readEnvironmentScope(threadRef.environmentId, AuthTerminalReadScope);
78
+ return nextTerminalId([...ids], canReuse ? undefined : randomUUID());
79
+ };
80
+
81
+ const defaultLaunchLocation = (): TerminalLaunchLocation | null =>
82
+ project
83
+ ? {
84
+ cwd: projectScriptCwd({
85
+ project: { cwd: project.workspaceRoot },
86
+ worktreePath: threadWorktreePath,
87
+ }),
88
+ worktreePath: threadWorktreePath,
89
+ }
90
+ : null;
91
+
92
+ /**
93
+ * Starts a session for `terminalId` on the server. `place` records the id in
94
+ * the surface that will show it, before the open resolves, so the viewport
95
+ * mounts while the session starts.
96
+ */
97
+ const launchTerminal = (input: {
98
+ readonly place: (terminalId: string) => void;
99
+ readonly terminalId?: string;
100
+ readonly location?: TerminalLaunchLocation | null;
101
+ readonly extraEnv?: Record<string, string>;
102
+ readonly size?: { readonly cols: number; readonly rows: number };
103
+ }) => {
104
+ if (!threadRef || !canWrite() || !project) return null;
105
+ const location = input.location ?? defaultLaunchLocation();
106
+ if (!location) return null;
107
+ const terminalId = input.terminalId ?? allocateTerminalId();
108
+ input.place(terminalId);
109
+ const result = openTerminalCommand({
110
+ environmentId: threadRef.environmentId,
111
+ input: {
112
+ threadId: threadRef.threadId,
113
+ terminalId,
114
+ cwd: location.cwd,
115
+ ...(location.worktreePath !== null ? { worktreePath: location.worktreePath } : {}),
116
+ env: projectScriptRuntimeEnv({
117
+ project: { cwd: project.workspaceRoot },
118
+ worktreePath: location.worktreePath,
119
+ ...(input.extraEnv ? { extraEnv: input.extraEnv } : {}),
120
+ }),
121
+ ...input.size,
122
+ },
123
+ });
124
+ return { terminalId, result };
125
+ };
126
+
127
+ /** Ends a session and deletes its history. A failed close falls back to typing `exit`. */
128
+ const closeTerminalSession = (terminalId: string) => {
129
+ if (!threadRef || !canWrite()) return;
130
+ const environmentId = threadRef.environmentId;
131
+ const threadId = threadRef.threadId;
132
+ void (async () => {
133
+ const closeResult = await closeTerminalCommand({
134
+ environmentId,
135
+ input: { threadId, terminalId, deleteHistory: true },
136
+ });
137
+ if (
138
+ closeResult._tag === "Failure" &&
139
+ !isAtomCommandInterrupted(closeResult) &&
140
+ readEnvironmentScope(environmentId, AuthTerminalOperateScope)
141
+ ) {
142
+ await writeTerminal({ environmentId, input: { threadId, terminalId, data: "exit\n" } });
143
+ }
144
+ })();
145
+ };
146
+
147
+ const writeToTerminal = (terminalId: string, data: string) => {
148
+ if (!threadRef || !canWrite()) return null;
149
+ return writeTerminal({
150
+ environmentId: threadRef.environmentId,
151
+ input: { threadId: threadRef.threadId, terminalId, data },
152
+ });
153
+ };
154
+
155
+ return {
156
+ canWrite: useStableCallback(canWrite),
157
+ allocateTerminalId: useStableCallback(allocateTerminalId),
158
+ launchTerminal: useStableCallback(launchTerminal),
159
+ closeTerminalSession: useStableCallback(closeTerminalSession),
160
+ writeToTerminal: useStableCallback(writeToTerminal),
161
+ };
162
+}