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

useThreadTerminalActions.ts

152 lines6.4 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/** Allocate terminal ids and launch locations centrally so all surfaces share one view of sessions. */
28export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
29 const openTerminalCommand = useAtomCommand(terminalEnvironment.open, "terminal open");
30 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
31 const closeTerminalCommand = useAtomCommand(terminalEnvironment.close, "terminal close");
32 const serverThread = useQuietThreadShell(threadRef);
33 const draftThread = useComposerDraftStore((store) =>
34 threadRef ? store.getDraftThreadByRef(threadRef) : null,
35 );
36 const projectRef = serverThread
37 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
38 : draftThread
39 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
40 : null;
41 const project = useProject(projectRef);
42 const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
43 const knownSessions = useKnownTerminalSessions({
44 environmentId: threadRef?.environmentId ?? null,
45 threadId: threadRef?.threadId ?? null,
46 });
47 const drawerTerminalIds = useTerminalUiStateStore(
48 (state) => selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef).terminalIds,
49 );
50 const panelSurfaces = useRightPanelStore(
51 (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,
52 );
53​
54 const canWrite = () =>
55 threadRef !== null && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
56​
57 // Server lists lag and colliding ids share a PTY; without read access, suffix ids to avoid unseen sessions.
58 const allocateTerminalId = () => {
59 const ids = new Set([
60 ...(knownSessions ?? []).map((session) => session.target.terminalId),
61 ...drawerTerminalIds,
62 ...panelSurfaces.flatMap((surface) =>
63 surface.kind === "terminal" ? surface.terminalIds : [],
64 ),
65 ]);
66 const canReuse =
67 knownSessions !== null &&
68 threadRef !== null &&
69 readEnvironmentScope(threadRef.environmentId, AuthTerminalReadScope);
70 return nextTerminalId([...ids], canReuse ? undefined : randomUUID());
71 };
72​
73 const defaultLaunchLocation = (): TerminalLaunchLocation | null =>
74 project
75 ? {
76 cwd: projectScriptCwd({
77 project: { cwd: project.workspaceRoot },
78 worktreePath: threadWorktreePath,
79 }),
80 worktreePath: threadWorktreePath,
81 }
82 : null;
83​
84 /** place mounts the destination before the server open resolves. */
85 const launchTerminal = (input: {
86 readonly place: (terminalId: string) => void;
87 readonly terminalId?: string;
88 readonly location?: TerminalLaunchLocation | null;
89 readonly extraEnv?: Record<string, string>;
90 readonly stopOnSettle?: boolean;
91 readonly size?: { readonly cols: number; readonly rows: number };
92 }) => {
93 if (!threadRef || !canWrite() || !project) return null;
94 const location = input.location ?? defaultLaunchLocation();
95 if (!location) return null;
96 const terminalId = input.terminalId ?? allocateTerminalId();
97 input.place(terminalId);
98 const result = openTerminalCommand({
99 environmentId: threadRef.environmentId,
100 input: {
101 threadId: threadRef.threadId,
102 terminalId,
103 cwd: location.cwd,
104 ...(location.worktreePath !== null ? { worktreePath: location.worktreePath } : {}),
105 env: projectScriptRuntimeEnv({
106 project: { cwd: project.workspaceRoot },
107 worktreePath: location.worktreePath,
108 ...(input.extraEnv ? { extraEnv: input.extraEnv } : {}),
109 }),
110 ...input.size,
111 ...(input.stopOnSettle !== undefined ? { stopOnSettle: input.stopOnSettle } : {}),
112 },
113 });
114 return { terminalId, result };
115 };
116​
117 /** Ends a session and deletes its history. A failed close falls back to typing `exit`. */
118 const closeTerminalSession = (terminalId: string, target = threadRef) => {
119 if (!target || !readEnvironmentScope(target.environmentId, AuthTerminalOperateScope)) return;
120 const environmentId = target.environmentId;
121 const threadId = target.threadId;
122 void (async () => {
123 const closeResult = await closeTerminalCommand({
124 environmentId,
125 input: { threadId, terminalId, deleteHistory: true },
126 });
127 if (
128 closeResult._tag === "Failure" &&
129 !isAtomCommandInterrupted(closeResult) &&
130 readEnvironmentScope(environmentId, AuthTerminalOperateScope)
131 ) {
132 await writeTerminal({ environmentId, input: { threadId, terminalId, data: "exit\n" } });
133 }
134 })();
135 };
136​
137 const writeToTerminal = (terminalId: string, data: string) => {
138 if (!threadRef || !canWrite()) return null;
139 return writeTerminal({
140 environmentId: threadRef.environmentId,
141 input: { threadId: threadRef.threadId, terminalId, data },
142 });
143 };
144​
145 return {
146 canWrite: useStableCallback(canWrite),
147 allocateTerminalId: useStableCallback(allocateTerminalId),
148 launchTerminal: useStableCallback(launchTerminal),
149 closeTerminalSession: useStableCallback(closeTerminalSession),
150 writeToTerminal: useStableCallback(writeToTerminal),
151 };