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