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

PersistentThreadTerminals.tsx

423 lines15.8 KB

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