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

ThreadTerminalPanel.tsx

253 lines8.3 KB

1import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
2import { SymbolView } from "../../components/AppSymbol";
3import { memo, useCallback, useEffect, useMemo, useRef } from "react";
4import { Pressable, View } from "react-native";
5​
6import { AppText as Text } from "../../components/AppText";
7import { useThemeColor } from "../../lib/useThemeColor";
8import { terminalEnvironment } from "../../state/terminal";
9import { useAtomCommand } from "../../state/use-atom-command";
10import { useAttachedTerminalSession } from "../../state/use-terminal-session";
11import { TerminalSurface } from "./NativeTerminalSurface";
12import { hasNativeTerminalSurface } from "./nativeTerminalModule";
13import {
14 buildThreadTerminalAttachInput,
15 type TerminalGridSize,
16 type ThreadTerminalSubscriptionIdentity,
17} from "./threadTerminalPanelModel";
18​
19interface ThreadTerminalPanelProps {
20 readonly environmentId: EnvironmentId;
21 readonly threadId: ThreadId;
22 readonly cwd: string;
23 readonly worktreePath: string | null;
24 readonly visible: boolean;
25 readonly onClose: () => void;
27​
28const DEFAULT_TERMINAL_COLS = 80;
29const DEFAULT_TERMINAL_ROWS = 24;
30​
31export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
32 props: ThreadTerminalPanelProps,
33) {
34 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
35 const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
36 const closeTerminal = useAtomCommand(terminalEnvironment.close, "terminal close");
37 const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
38 const nativeTerminalAvailable = hasNativeTerminalSurface();
39 const iconColor = useThemeColor("--color-icon");
40 const terminalId = DEFAULT_TERMINAL_ID;
41 const lastGridSizeRef = useRef<TerminalGridSize>({
42 cols: DEFAULT_TERMINAL_COLS,
43 rows: DEFAULT_TERMINAL_ROWS,
44 });
45 const subscriptionIdentity = useMemo<ThreadTerminalSubscriptionIdentity>(
46 () => ({
47 environmentId: props.environmentId,
48 threadId: props.threadId,
49 terminalId,
50 cwd: props.cwd,
51 worktreePath: props.worktreePath,
52 }),
53 [props.cwd, props.environmentId, props.threadId, props.worktreePath, terminalId],
54 );
55 const attachInput = useMemo(
56 () =>
57 props.visible
58 ? buildThreadTerminalAttachInput(subscriptionIdentity, lastGridSizeRef.current)
59 : null,
60 [props.visible, subscriptionIdentity],
61 );
62 const terminal = useAttachedTerminalSession({
63 environmentId: props.environmentId,
64 terminal: attachInput,
65 });
66​
67 const terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`;
68 const isRunning = terminal.status === "running" || terminal.status === "starting";
69​
70 // Close the session and dismiss the panel when the process ends while
71 // attached (e.g. typing `exit`), mirroring the web drawer's
72 // onSessionExited flow.
73 const runningTerminalKeyRef = useRef<string | null>(null);
74 const reopenedStaleTerminalKeyRef = useRef<string | null>(null);
75​
76 // Attach subscriptions are cached with an idle TTL; reopening the panel
77 // after its session ended reuses the stale stream without a new attach
78 // RPC. Issue an explicit open so the server respawns the session and its
79 // snapshot flows into the live subscription.
80 useEffect(() => {
81 if (isRunning) {
82 reopenedStaleTerminalKeyRef.current = null;
83 return;
84 }
85 if (
86 attachInput === null ||
87 (terminal.status !== "closed" && terminal.status !== "exited") ||
88 terminal.version === 0 ||
89 runningTerminalKeyRef.current === terminalKey ||
90 reopenedStaleTerminalKeyRef.current === terminalKey
91 ) {
92 return;
93 }
94 reopenedStaleTerminalKeyRef.current = terminalKey;
95 void openTerminal({
96 environmentId: props.environmentId,
97 input: {
98 threadId: props.threadId,
99 terminalId,
100 cwd: props.cwd,
101 worktreePath: props.worktreePath,
102 cols: lastGridSizeRef.current.cols,
103 rows: lastGridSizeRef.current.rows,
104 },
105 }).then((result) => {
106 // Release the guard on failure so a later render can retry the respawn.
107 if (result._tag === "Failure" && reopenedStaleTerminalKeyRef.current === terminalKey) {
108 reopenedStaleTerminalKeyRef.current = null;
109 }
110 });
111 }, [
112 attachInput,
113 isRunning,
114 openTerminal,
115 props.cwd,
116 props.environmentId,
117 props.threadId,
118 props.worktreePath,
119 terminal.status,
120 terminal.version,
121 terminalId,
122 terminalKey,
123 ]);
124​
125 useEffect(() => {
126 // Forget both markers while hidden: if the process ends while the panel
127 // is unobserved (or was just auto-closed), the next show must take the
128 // stale-reopen path instead of treating it as a live exit or skipping
129 // the respawn.
130 if (attachInput === null) {
131 runningTerminalKeyRef.current = null;
132 reopenedStaleTerminalKeyRef.current = null;
133 return;
134 }
135 if (isRunning) {
136 runningTerminalKeyRef.current = terminalKey;
137 return;
138 }
139 // The web drawer treats both exited and closed as session end.
140 const sessionEnded = terminal.status === "exited" || terminal.status === "closed";
141 if (!sessionEnded || runningTerminalKeyRef.current !== terminalKey) {
142 return;
143 }
144 runningTerminalKeyRef.current = null;
145 // Mark this key handled so the stale-attach effect doesn't respawn the
146 // session the user just ended.
147 reopenedStaleTerminalKeyRef.current = terminalKey;
148 void closeTerminal({
149 environmentId: props.environmentId,
150 input: {
151 threadId: props.threadId,
152 terminalId,
153 },
154 });
155 props.onClose();
156 }, [attachInput, closeTerminal, isRunning, props, terminal.status, terminalId, terminalKey]);
157​
158 const sendResize = useCallback(
159 (size: TerminalGridSize) => {
160 void resizeTerminal({
161 environmentId: props.environmentId,
162 input: {
163 threadId: props.threadId,
164 terminalId,
165 cols: size.cols,
166 rows: size.rows,
167 },
168 });
169 },
170 [props.environmentId, props.threadId, resizeTerminal, terminalId],
171 );
172​
173 useEffect(() => {
174 if (isRunning) {
175 sendResize(lastGridSizeRef.current);
176 }
177 }, [isRunning, sendResize]);
178​
179 const handleInput = useCallback(
180 (data: string) => {
181 if (!isRunning) {
182 return;
183 }
184​
185 void writeTerminal({
186 environmentId: props.environmentId,
187 input: {
188 threadId: props.threadId,
189 terminalId,
190 data,
191 },
192 });
193 },
194 [isRunning, props.environmentId, props.threadId, terminalId, writeTerminal],
195 );
196​
197 const handleResize = useCallback(
198 (size: TerminalGridSize) => {
199 const previousSize = lastGridSizeRef.current;
200 if (size.cols === previousSize.cols && size.rows === previousSize.rows) {
201 return;
202 }
203​
204 lastGridSizeRef.current = size;
205 if (!isRunning) {
206 return;
207 }
208​
209 sendResize(size);
210 },
211 [isRunning, sendResize],
212 );
213​
214 if (!props.visible) {
215 return null;
216 }
217​
218 return (
219 <View className="absolute inset-x-3 bottom-28 top-28 overflow-hidden rounded-[8px] border border-border bg-screen shadow-2xl">
220 <View className="flex-row items-center justify-between border-b border-border px-3 py-2">
221 <View className="min-w-0 flex-1">
222 <Text className="font-t3-bold text-sm text-foreground" numberOfLines={1}>
223 Terminal
224 </Text>
225 <Text className="text-2xs text-foreground-muted" numberOfLines={1}>
226 {nativeTerminalAvailable ? "Native Ghostty surface" : "Text fallback active"}
227 </Text>
228 </View>
229 <View className="flex-row items-center gap-2">
230 {terminal.error ? (
231 <Text className="max-w-44 text-right text-2xs text-red-300" numberOfLines={1}>
232 {terminal.error}
233 </Text>
234 ) : null}
235 <Pressable
236 className="h-8 w-8 items-center justify-center rounded-[8px] bg-subtle"
237 onPress={props.onClose}
238 >
239 <SymbolView name="xmark" size={13} tintColor={iconColor} type="monochrome" />
240 </Pressable>
241 </View>
242 </View>
243 <TerminalSurface
244 terminalKey={terminalKey}
245 buffer={terminal.buffer}
246 isRunning={isRunning}
247 onInput={handleInput}
248 onResize={handleResize}
249 style={{ flex: 1 }}
250 />
251 </View>
252 );
253});