Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useThreadTerminalActions.ts

162 lines6.7 KB

1import {
2 AuthTerminalOperateScope,
3 AuthTerminalReadScope,
4 type ScopedThreadRef,
5} from "@t3tools/contracts";
6import { scopeProjectRef } from "@t3tools/client-runtime/environment";
7import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
8import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
9import { nextTerminalId } from "@t3tools/shared/terminalLabels";
10import { useComposerDraftStore } from "../../composerDraftStore";
11import { useStableCallback } from "../../hooks/useStableCallback";
12import { randomUUID } from "~/lib/utils";
13import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore";
14import { useProject, useQuietThreadShell } from "../../state/entities";
15import { readEnvironmentScope } from "../../state/session";
16import { terminalEnvironment } from "../../state/terminal";
17import { useKnownTerminalSessions } from "../../state/terminalSessions";
18import { useAtomCommand } from "../../state/use-atom-command";
19import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../../terminalUiStateStore";
20​
21/** Where a new terminal starts. Omitted fields fall back to the thread's project and worktree. */
22export interface TerminalLaunchLocation {
23 readonly cwd: string;
24 readonly worktreePath: string | null;
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 */
33export 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 = useQuietThreadShell(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 };