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