Open History to see the last commit
1import {
2 AuthTerminalOperateScope,
3 type EnvironmentId,
4 type ResolvedKeybindingsConfig,
5 type ScopedThreadRef,
6 type ThreadId,
7} from "@t3tools/contracts";
8import { scopeProjectRef } from "@t3tools/client-runtime/environment";
9import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
10import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
11import { type ComponentProps, lazy, memo, Suspense, useEffect, useState } from "react";
12import { useComposerDraftStore } from "../composerDraftStore";
13import { useStableCallback } from "../hooks/useStableCallback";
14import type { TerminalContextSelection } from "../lib/terminalContext";
15import { cn } from "~/lib/utils";
16import {
17 selectThreadRightPanelState,
18 useRightPanelStore,
19 type RightPanelSurface,
20} from "../rightPanelStore";
21import { useProject, useQuietThreadShell } from "../state/entities";
22import { useEnvironmentScope } from "../state/session";
23import { useKnownTerminalSessions } from "../state/terminalSessions";
24import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
25import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions";
26
27const LazyThreadTerminalDrawer = lazy(() => import("./ThreadTerminalDrawer"));
28function ThreadTerminalDrawer(props: ComponentProps<typeof LazyThreadTerminalDrawer>) {
29 // Keep existing terminal sessions mounted when hidden, but an empty closed drawer
30 // has no terminal to render or synchronize and need not load its renderer.
31 if (props.visible === false && props.terminalIds.length === 0) return null;
32 return (
33 <Suspense fallback={null}>
34 <LazyThreadTerminalDrawer {...props} />
35 </Suspense>
36 );
37}
38
39/** Where a drawer or panel opens new terminals when a script run overrides the thread's own. */
40export type PersistentTerminalLaunchContext = {
41 readonly cwd: string;
42 readonly worktreePath: string | null;
43};
44
45/** Same terminal ids (order ignored) — avoids reconcile when only server session ordering differs. */
46function terminalIdListsEqual(left: readonly string[], right: readonly string[]): boolean {
47 if (left.length !== right.length) {
48 return false;
49 }
50 if (left.length === 0) {
51 return true;
52 }
53 const sortedLeft = left.toSorted((a, b) => a.localeCompare(b));
54 const sortedRight = right.toSorted((a, b) => a.localeCompare(b));
55 for (let index = 0; index < sortedLeft.length; index += 1) {
56 if (sortedLeft[index] !== sortedRight[index]) {
57 return false;
58 }
59 }
60 return true;
61}
62
63/**
64 * Server knows about fewer sessions than the client, but every server id still exists locally.
65 * Typical right after `terminal.open`: known-session list lags; reconciling would drop the new id
66 * and later re-add it as a separate group (no split layout).
67 */
68function serverTerminalIdsStrictSubsetOfClient(
69 serverIds: readonly string[],
70 clientIds: readonly string[],
71): boolean {
72 if (serverIds.length >= clientIds.length || clientIds.length === 0) {
73 return false;
74 }
75 const clientSet = new Set(clientIds);
76 for (const id of serverIds) {
77 if (!clientSet.has(id)) {
78 return false;
79 }
80 }
81 return true;
82}
83
84interface TerminalLaunchLocationWithEnv {
85 readonly cwd: string;
86 readonly worktreePath: string | null;
87 readonly runtimeEnv: Record<string, string>;
88}
89
90interface PersistentThreadTerminalDrawerProps {
91 threadRef: { environmentId: EnvironmentId; threadId: ThreadId };
92 threadId: ThreadId;
93 active: boolean;
94 launchContext: PersistentTerminalLaunchContext | null;
95 focusRequestId: number;
96 splitShortcutLabel: string | undefined;
97 splitVerticalShortcutLabel: string | undefined;
98 newShortcutLabel: string | undefined;
99 closeShortcutLabel: string | undefined;
100 keybindings: ResolvedKeybindingsConfig;
101 onAddTerminalContext: (selection: TerminalContextSelection) => void;
102}
103
104export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDrawer({
105 threadRef,
106 threadId,
107 active,
108 launchContext,
109 focusRequestId,
110 splitShortcutLabel,
111 splitVerticalShortcutLabel,
112 newShortcutLabel,
113 closeShortcutLabel,
114 keybindings,
115 onAddTerminalContext,
116}: PersistentThreadTerminalDrawerProps) {
117 const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
118 const terminalActions = useThreadTerminalActions(threadRef);
119 const serverThread = useQuietThreadShell(threadRef);
120 const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
121 const projectRef = serverThread
122 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
123 : draftThread
124 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
125 : null;
126 const project = useProject(projectRef);
127 const terminalUiState = useTerminalUiStateStore((state) =>
128 selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef),
129 );
130 const visible = active && terminalUiState.terminalOpen;
131 const knownTerminalSessions = useKnownTerminalSessions({
132 environmentId: threadRef.environmentId,
133 threadId,
134 });
135 const panelSurfaces = useRightPanelStore(
136 (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,
137 );
138 const panelTerminalIds = new Set(
139 panelSurfaces.flatMap((surface) => (surface.kind === "terminal" ? surface.terminalIds : [])),
140 );
141 const drawerTerminalSessions =
142 knownTerminalSessions?.filter((session) => !panelTerminalIds.has(session.target.terminalId)) ??
143 [];
144 const terminalLabelsById = new Map<string, string>();
145 for (const session of drawerTerminalSessions) {
146 terminalLabelsById.set(
147 session.target.terminalId,
148 resolveTerminalSessionLabel(session.target.terminalId, session.state.summary),
149 );
150 }
151 const terminalLaunchLocationsById = new Map<string, TerminalLaunchLocationWithEnv>();
152 for (const session of drawerTerminalSessions) {
153 const summary = session.state.summary;
154 if (!project || !summary) continue;
155 const worktreePathForLaunch =
156 launchContext !== null ? launchContext.worktreePath : summary.worktreePath;
157 terminalLaunchLocationsById.set(session.target.terminalId, {
158 cwd: launchContext?.cwd ?? summary.cwd,
159 worktreePath: worktreePathForLaunch,
160 runtimeEnv: projectScriptRuntimeEnv({
161 project: { cwd: project.workspaceRoot },
162 worktreePath: worktreePathForLaunch,
163 }),
164 });
165 }
166 const serverOrderedTerminalIds = drawerTerminalSessions.map(
167 (session) => session.target.terminalId,
168 );
169 const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight);
170 const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal);
171 const storeSplitTerminalVertical = useTerminalUiStateStore(
172 (state) => state.splitTerminalVertical,
173 );
174 const storeNewTerminal = useTerminalUiStateStore((state) => state.newTerminal);
175 const storeSetActiveTerminal = useTerminalUiStateStore((state) => state.setActiveTerminal);
176 const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal);
177 const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds);
178
179 useEffect(() => {
180 if (terminalIdListsEqual(serverOrderedTerminalIds, terminalUiState.terminalIds)) {
181 return;
182 }
183 if (
184 serverTerminalIdsStrictSubsetOfClient(serverOrderedTerminalIds, terminalUiState.terminalIds)
185 ) {
186 return;
187 }
188 reconcileTerminalIds(threadRef, serverOrderedTerminalIds);
189 }, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]);
190 const [localFocusRequestId, setLocalFocusRequestId] = useState(0);
191 const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
192 const effectiveWorktreePath = launchContext !== null ? launchContext.worktreePath : worktreePath;
193 const cwd =
194 launchContext?.cwd ??
195 (project
196 ? projectScriptCwd({
197 project: { cwd: project.workspaceRoot },
198 worktreePath: effectiveWorktreePath,
199 })
200 : null);
201 const runtimeEnv = project
202 ? projectScriptRuntimeEnv({
203 project: { cwd: project.workspaceRoot },
204 worktreePath: effectiveWorktreePath,
205 })
206 : {};
207
208 const bumpFocusRequestId = () => {
209 if (!visible) {
210 return;
211 }
212 setLocalFocusRequestId((value) => value + 1);
213 };
214
215 const setTerminalHeight = (height: number) => {
216 storeSetTerminalHeight(threadRef, height);
217 };
218
219 const launchDrawerTerminal = (place: (terminalId: string) => void) => {
220 if (!cwd) return;
221 const launched = terminalActions.launchTerminal({
222 place,
223 location: { cwd, worktreePath: effectiveWorktreePath },
224 });
225 if (!launched) return;
226 bumpFocusRequestId();
227 void launched.result;
228 };
229 const splitTerminal = useStableCallback(() =>
230 launchDrawerTerminal((terminalId) => storeSplitTerminal(threadRef, terminalId)),
231 );
232 const splitTerminalVertical = useStableCallback(() =>
233 launchDrawerTerminal((terminalId) => storeSplitTerminalVertical(threadRef, terminalId)),
234 );
235 const createNewTerminal = useStableCallback(() =>
236 launchDrawerTerminal((terminalId) => storeNewTerminal(threadRef, terminalId)),
237 );
238
239 const activateTerminal = (terminalId: string) => {
240 storeSetActiveTerminal(threadRef, terminalId);
241 bumpFocusRequestId();
242 };
243
244 const closeTerminal = useStableCallback((terminalId: string) => {
245 if (!terminalActions.canWrite()) return;
246 terminalActions.closeTerminalSession(terminalId);
247 storeCloseTerminal(threadRef, terminalId);
248 bumpFocusRequestId();
249 });
250
251 const handleAddTerminalContext = (selection: TerminalContextSelection) => {
252 if (!visible) {
253 return;
254 }
255 onAddTerminalContext(selection);
256 };
257
258 if (!project || (!terminalUiState.terminalOpen && !active) || !cwd) {
259 return null;
260 }
261
262 return (
263 <div
264 className={cn(
265 "grid shrink-0 overflow-clip",
266 active ? (visible ? "grid-rows-[1fr]" : "grid-rows-[0fr]") : "hidden",
267 active &&
268 "[[data-panel-animations=true]_&]:transition-[grid-template-rows] [[data-panel-animations=true]_&]:duration-(--panel-animation-duration) [[data-panel-animations=true]_&]:ease-out",
269 active && visible && "[[data-panel-animations=true]_&]:starting:grid-rows-[0fr]!",
270 )}
271 >
272 <div className="min-h-0 overflow-clip">
273 <ThreadTerminalDrawer
274 threadRef={threadRef}
275 threadId={threadId}
276 cwd={cwd}
277 worktreePath={effectiveWorktreePath}
278 runtimeEnv={runtimeEnv}
279 visible={visible}
280 height={terminalUiState.terminalHeight}
281 // Known-session order is MRU and changes on focus; persisted store order keeps sidebar labels stable.
282 terminalIds={canOperateTerminal ? terminalUiState.terminalIds : serverOrderedTerminalIds}
283 activeTerminalId={terminalUiState.activeTerminalId}
284 terminalGroups={terminalUiState.terminalGroups}
285 activeTerminalGroupId={terminalUiState.activeTerminalGroupId}
286 focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
287 onSplitTerminal={splitTerminal}
288 onSplitTerminalVertical={splitTerminalVertical}
289 onNewTerminal={createNewTerminal}
290 splitShortcutLabel={visible ? splitShortcutLabel : undefined}
291 splitVerticalShortcutLabel={visible ? splitVerticalShortcutLabel : undefined}
292 newShortcutLabel={visible ? newShortcutLabel : undefined}
293 closeShortcutLabel={visible ? closeShortcutLabel : undefined}
294 keybindings={keybindings}
295 onActiveTerminalChange={activateTerminal}
296 onCloseTerminal={closeTerminal}
297 onHeightChange={setTerminalHeight}
298 onAddTerminalContext={handleAddTerminalContext}
299 terminalLabelsById={terminalLabelsById}
300 terminalLaunchLocationsById={terminalLaunchLocationsById}
301 />
302 </div>
303 </div>
304 );
305});
306
307export interface PersistentThreadTerminalPanelProps {
308 visible: boolean;
309 threadRef: ScopedThreadRef;
310 surface: Extract<RightPanelSurface, { kind: "terminal" }>;
311 launchContext: PersistentTerminalLaunchContext | null;
312 focusRequestId: number;
313 keybindings: ResolvedKeybindingsConfig;
314 onAddTerminalContext: (selection: TerminalContextSelection) => void;
315 onSplitTerminal: () => void;
316 onSplitTerminalVertical: () => void;
317 onNewTerminal: () => void;
318 onActiveTerminalChange: (terminalId: string) => void;
319 onCloseTerminal: (terminalId: string) => void;
320 splitShortcutLabel?: string | undefined;
321 splitVerticalShortcutLabel?: string | undefined;
322 newShortcutLabel?: string | undefined;
323 closeShortcutLabel?: string | undefined;
324}
325
326export const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPanel({
327 visible,
328 threadRef,
329 surface,
330 launchContext,
331 focusRequestId,
332 keybindings,
333 onAddTerminalContext,
334 onSplitTerminal,
335 onSplitTerminalVertical,
336 onNewTerminal,
337 onActiveTerminalChange,
338 onCloseTerminal,
339 splitShortcutLabel,
340 splitVerticalShortcutLabel,
341 newShortcutLabel,
342 closeShortcutLabel,
343}: PersistentThreadTerminalPanelProps) {
344 const serverThread = useQuietThreadShell(threadRef);
345 const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
346 const projectRef = serverThread
347 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
348 : draftThread
349 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
350 : null;
351 const project = useProject(projectRef);
352 const knownTerminalSessions = useKnownTerminalSessions({
353 environmentId: threadRef.environmentId,
354 threadId: threadRef.threadId,
355 });
356 const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
357 const activeSummary =
358 knownTerminalSessions?.find((session) => session.target.terminalId === surface.activeTerminalId)
359 ?.state.summary ?? null;
360 const worktreePath =
361 launchContext?.worktreePath ?? activeSummary?.worktreePath ?? threadWorktreePath;
362 const cwd =
363 launchContext?.cwd ??
364 activeSummary?.cwd ??
365 (project ? projectScriptCwd({ project: { cwd: project.workspaceRoot }, worktreePath }) : null);
366 const runtimeEnv = project
367 ? projectScriptRuntimeEnv({ project: { cwd: project.workspaceRoot }, worktreePath })
368 : {};
369 const terminalLabelsById = new Map<string, string>();
370 const terminalLaunchLocationsById = new Map<string, TerminalLaunchLocationWithEnv>();
371 for (const terminalId of surface.terminalIds) {
372 const summary =
373 knownTerminalSessions?.find((session) => session.target.terminalId === terminalId)?.state
374 .summary ?? null;
375 terminalLabelsById.set(terminalId, resolveTerminalSessionLabel(terminalId, summary));
376 if (!project) continue;
377 const terminalWorktreePath =
378 launchContext?.worktreePath ?? summary?.worktreePath ?? threadWorktreePath;
379 terminalLaunchLocationsById.set(terminalId, {
380 cwd:
381 launchContext?.cwd ??
382 summary?.cwd ??
383 projectScriptCwd({
384 project: { cwd: project.workspaceRoot },
385 worktreePath: terminalWorktreePath,
386 }),
387 worktreePath: terminalWorktreePath,
388 runtimeEnv: projectScriptRuntimeEnv({
389 project: { cwd: project.workspaceRoot },
390 worktreePath: terminalWorktreePath,
391 }),
392 });
393 }
394
395 if (!project || !cwd) return null;
396
397 return (
398 <ThreadTerminalDrawer
399 mode="panel"
400 visible={visible}
401 threadRef={threadRef}
402 threadId={threadRef.threadId}
403 cwd={cwd}
404 worktreePath={worktreePath}
405 runtimeEnv={runtimeEnv}
406 height={0}
407 terminalIds={surface.terminalIds}
408 activeTerminalId={surface.activeTerminalId}
409 terminalGroups={[
410 {
411 id: surface.id,
412 terminalIds: surface.terminalIds,
413 ...(surface.splitDirection === "vertical" ? { splitDirection: "vertical" as const } : {}),
414 },
415 ]}
416 activeTerminalGroupId={surface.id}
417 focusRequestId={focusRequestId}
418 onSplitTerminal={onSplitTerminal}
419 onSplitTerminalVertical={onSplitTerminalVertical}
420 onNewTerminal={onNewTerminal}
421 splitShortcutLabel={splitShortcutLabel}
422 splitVerticalShortcutLabel={splitVerticalShortcutLabel}
423 newShortcutLabel={newShortcutLabel}
424 closeShortcutLabel={closeShortcutLabel}
425 onActiveTerminalChange={onActiveTerminalChange}
426 onCloseTerminal={onCloseTerminal}
427 onHeightChange={() => undefined}
428 onAddTerminalContext={onAddTerminalContext}
429 terminalLabelsById={terminalLabelsById}
430 terminalLaunchLocationsById={terminalLaunchLocationsById}
431 keybindings={keybindings}
432 />
433 );
434});