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 launchContext: PersistentTerminalLaunchContext | null;
85 focusRequestId: number;
86 splitShortcutLabel: string | undefined;
87 splitVerticalShortcutLabel: string | undefined;
88 newShortcutLabel: string | undefined;
89 closeShortcutLabel: string | undefined;
90 keybindings: ResolvedKeybindingsConfig;
91 onAddTerminalContext: (selection: TerminalContextSelection) => void;
92}
93
94export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDrawer({
95 threadRef,
96 threadId,
97 active,
98 launchContext,
99 focusRequestId,
100 splitShortcutLabel,
101 splitVerticalShortcutLabel,
102 newShortcutLabel,
103 closeShortcutLabel,
104 keybindings,
105 onAddTerminalContext,
106}: PersistentThreadTerminalDrawerProps) {
107 const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
108 const terminalActions = useThreadTerminalActions(threadRef);
109 const serverThread = useQuietThreadShell(threadRef);
110 const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
111 const projectRef = serverThread
112 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
113 : draftThread
114 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
115 : null;
116 const project = useProject(projectRef);
117 const terminalUiState = useTerminalUiStateStore((state) =>
118 selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef),
119 );
120 const visible = active && terminalUiState.terminalOpen;
121 const knownTerminalSessions = useKnownTerminalSessions({
122 environmentId: threadRef.environmentId,
123 threadId,
124 });
125 const panelSurfaces = useRightPanelStore(
126 (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,
127 );
128 const panelTerminalIds = new Set(
129 panelSurfaces.flatMap((surface) => (surface.kind === "terminal" ? surface.terminalIds : [])),
130 );
131 const drawerTerminalSessions =
132 knownTerminalSessions?.filter((session) => !panelTerminalIds.has(session.target.terminalId)) ??
133 [];
134 const terminalLabelsById = new Map<string, string>();
135 for (const session of drawerTerminalSessions) {
136 terminalLabelsById.set(
137 session.target.terminalId,
138 resolveTerminalSessionLabel(session.target.terminalId, session.state.summary),
139 );
140 }
141 const terminalLaunchLocationsById = new Map<string, TerminalLaunchLocationWithEnv>();
142 for (const session of drawerTerminalSessions) {
143 const summary = session.state.summary;
144 if (!project || !summary) continue;
145 const worktreePathForLaunch =
146 launchContext !== null ? launchContext.worktreePath : summary.worktreePath;
147 terminalLaunchLocationsById.set(session.target.terminalId, {
148 cwd: launchContext?.cwd ?? summary.cwd,
149 worktreePath: worktreePathForLaunch,
150 runtimeEnv: projectScriptRuntimeEnv({
151 project: { cwd: project.workspaceRoot },
152 worktreePath: worktreePathForLaunch,
153 }),
154 });
155 }
156 const serverOrderedTerminalIds = drawerTerminalSessions.map(
157 (session) => session.target.terminalId,
158 );
159 const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight);
160 const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal);
161 const storeSplitTerminalVertical = useTerminalUiStateStore(
162 (state) => state.splitTerminalVertical,
163 );
164 const storeNewTerminal = useTerminalUiStateStore((state) => state.newTerminal);
165 const storeSetActiveTerminal = useTerminalUiStateStore((state) => state.setActiveTerminal);
166 const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal);
167 const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds);
168
169 useEffect(() => {
170 if (terminalIdListsEqual(serverOrderedTerminalIds, terminalUiState.terminalIds)) {
171 return;
172 }
173 if (
174 serverTerminalIdsStrictSubsetOfClient(serverOrderedTerminalIds, terminalUiState.terminalIds)
175 ) {
176 return;
177 }
178 reconcileTerminalIds(threadRef, serverOrderedTerminalIds);
179 }, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]);
180 const [localFocusRequestId, setLocalFocusRequestId] = useState(0);
181 const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
182 const effectiveWorktreePath = launchContext !== null ? launchContext.worktreePath : worktreePath;
183 const cwd =
184 launchContext?.cwd ??
185 (project
186 ? projectScriptCwd({
187 project: { cwd: project.workspaceRoot },
188 worktreePath: effectiveWorktreePath,
189 })
190 : null);
191 const runtimeEnv = project
192 ? projectScriptRuntimeEnv({
193 project: { cwd: project.workspaceRoot },
194 worktreePath: effectiveWorktreePath,
195 })
196 : {};
197
198 const bumpFocusRequestId = () => {
199 if (!visible) {
200 return;
201 }
202 setLocalFocusRequestId((value) => value + 1);
203 };
204
205 const setTerminalHeight = (height: number) => {
206 storeSetTerminalHeight(threadRef, height);
207 };
208
209 const launchDrawerTerminal = (place: (terminalId: string) => void) => {
210 if (!cwd) return;
211 const launched = terminalActions.launchTerminal({
212 place,
213 location: { cwd, worktreePath: effectiveWorktreePath },
214 });
215 if (!launched) return;
216 bumpFocusRequestId();
217 void launched.result;
218 };
219 const splitTerminal = useStableCallback(() =>
220 launchDrawerTerminal((terminalId) => storeSplitTerminal(threadRef, terminalId)),
221 );
222 const splitTerminalVertical = useStableCallback(() =>
223 launchDrawerTerminal((terminalId) => storeSplitTerminalVertical(threadRef, terminalId)),
224 );
225 const createNewTerminal = useStableCallback(() =>
226 launchDrawerTerminal((terminalId) => storeNewTerminal(threadRef, terminalId)),
227 );
228
229 const activateTerminal = (terminalId: string) => {
230 storeSetActiveTerminal(threadRef, terminalId);
231 bumpFocusRequestId();
232 };
233
234 const closeTerminal = useStableCallback((terminalId: string) => {
235 if (!terminalActions.canWrite()) return;
236 terminalActions.closeTerminalSession(terminalId);
237 storeCloseTerminal(threadRef, terminalId);
238 bumpFocusRequestId();
239 });
240
241 const handleAddTerminalContext = (selection: TerminalContextSelection) => {
242 if (!visible) {
243 return;
244 }
245 onAddTerminalContext(selection);
246 };
247
248 if (!project || (!terminalUiState.terminalOpen && !active) || !cwd) {
249 return null;
250 }
251
252 return (
253 <div
254 className={cn(
255 "grid shrink-0 overflow-clip",
256 active ? (visible ? "grid-rows-[1fr]" : "grid-rows-[0fr]") : "hidden",
257 active &&
258 "[[data-panel-animations=true]_&]:transition-[grid-template-rows] [[data-panel-animations=true]_&]:duration-(--panel-animation-duration) [[data-panel-animations=true]_&]:ease-out",
259 active && visible && "[[data-panel-animations=true]_&]:starting:grid-rows-[0fr]!",
260 )}
261 >
262 <div className="min-h-0 overflow-clip">
263 <ThreadTerminalDrawer
264 threadRef={threadRef}
265 threadId={threadId}
266 cwd={cwd}
267 worktreePath={effectiveWorktreePath}
268 runtimeEnv={runtimeEnv}
269 visible={visible}
270 height={terminalUiState.terminalHeight}
271 // Known-session order is MRU and changes on focus; persisted store order keeps sidebar labels stable.
272 terminalIds={canOperateTerminal ? terminalUiState.terminalIds : serverOrderedTerminalIds}
273 activeTerminalId={terminalUiState.activeTerminalId}
274 terminalGroups={terminalUiState.terminalGroups}
275 activeTerminalGroupId={terminalUiState.activeTerminalGroupId}
276 focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
277 onSplitTerminal={splitTerminal}
278 onSplitTerminalVertical={splitTerminalVertical}
279 onNewTerminal={createNewTerminal}
280 splitShortcutLabel={visible ? splitShortcutLabel : undefined}
281 splitVerticalShortcutLabel={visible ? splitVerticalShortcutLabel : undefined}
282 newShortcutLabel={visible ? newShortcutLabel : undefined}
283 closeShortcutLabel={visible ? closeShortcutLabel : undefined}
284 keybindings={keybindings}
285 onActiveTerminalChange={activateTerminal}
286 onCloseTerminal={closeTerminal}
287 onHeightChange={setTerminalHeight}
288 onAddTerminalContext={handleAddTerminalContext}
289 terminalLabelsById={terminalLabelsById}
290 terminalLaunchLocationsById={terminalLaunchLocationsById}
291 />
292 </div>
293 </div>
294 );
295});
296
297export interface PersistentThreadTerminalPanelProps {
298 visible: boolean;
299 threadRef: ScopedThreadRef;
300 surface: Extract<RightPanelSurface, { kind: "terminal" }>;
301 launchContext: PersistentTerminalLaunchContext | null;
302 focusRequestId: number;
303 keybindings: ResolvedKeybindingsConfig;
304 onAddTerminalContext: (selection: TerminalContextSelection) => void;
305 onSplitTerminal: () => void;
306 onSplitTerminalVertical: () => void;
307 onNewTerminal: () => void;
308 onActiveTerminalChange: (terminalId: string) => void;
309 onCloseTerminal: (terminalId: string) => void;
310 splitShortcutLabel?: string | undefined;
311 splitVerticalShortcutLabel?: string | undefined;
312 newShortcutLabel?: string | undefined;
313 closeShortcutLabel?: string | undefined;
314}
315
316export const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPanel({
317 visible,
318 threadRef,
319 surface,
320 launchContext,
321 focusRequestId,
322 keybindings,
323 onAddTerminalContext,
324 onSplitTerminal,
325 onSplitTerminalVertical,
326 onNewTerminal,
327 onActiveTerminalChange,
328 onCloseTerminal,
329 splitShortcutLabel,
330 splitVerticalShortcutLabel,
331 newShortcutLabel,
332 closeShortcutLabel,
333}: PersistentThreadTerminalPanelProps) {
334 const serverThread = useQuietThreadShell(threadRef);
335 const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
336 const projectRef = serverThread
337 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
338 : draftThread
339 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
340 : null;
341 const project = useProject(projectRef);
342 const knownTerminalSessions = useKnownTerminalSessions({
343 environmentId: threadRef.environmentId,
344 threadId: threadRef.threadId,
345 });
346 const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
347 const activeSummary =
348 knownTerminalSessions?.find((session) => session.target.terminalId === surface.activeTerminalId)
349 ?.state.summary ?? null;
350 const worktreePath = resolveTerminalWorktreePath({
351 launchContext,
352 summary: activeSummary,
353 threadWorktreePath,
354 });
355 const cwd =
356 launchContext?.cwd ??
357 activeSummary?.cwd ??
358 (project ? projectScriptCwd({ project: { cwd: project.workspaceRoot }, worktreePath }) : null);
359 const runtimeEnv = project
360 ? projectScriptRuntimeEnv({ project: { cwd: project.workspaceRoot }, worktreePath })
361 : {};
362 const terminalLabelsById = new Map<string, string>();
363 const terminalLaunchLocationsById = new Map<string, TerminalLaunchLocationWithEnv>();
364 for (const terminalId of surface.terminalIds) {
365 const summary =
366 knownTerminalSessions?.find((session) => session.target.terminalId === terminalId)?.state
367 .summary ?? null;
368 terminalLabelsById.set(terminalId, resolveTerminalSessionLabel(terminalId, summary));
369 if (!project) continue;
370 const terminalWorktreePath = resolveTerminalWorktreePath({
371 launchContext,
372 summary,
373 threadWorktreePath,
374 });
375 terminalLaunchLocationsById.set(terminalId, {
376 cwd:
377 launchContext?.cwd ??
378 summary?.cwd ??
379 projectScriptCwd({
380 project: { cwd: project.workspaceRoot },
381 worktreePath: terminalWorktreePath,
382 }),
383 worktreePath: terminalWorktreePath,
384 runtimeEnv: projectScriptRuntimeEnv({
385 project: { cwd: project.workspaceRoot },
386 worktreePath: terminalWorktreePath,
387 }),
388 });
389 }
390
391 if (!project || !cwd) return null;
392
393 return (
394 <ThreadTerminalDrawer
395 mode="panel"
396 visible={visible}
397 threadRef={threadRef}
398 threadId={threadRef.threadId}
399 cwd={cwd}
400 worktreePath={worktreePath}
401 runtimeEnv={runtimeEnv}
402 height={0}
403 terminalIds={surface.terminalIds}
404 activeTerminalId={surface.activeTerminalId}
405 terminalGroups={[
406 {
407 id: surface.id,
408 terminalIds: surface.terminalIds,
409 ...(surface.splitDirection === "vertical" ? { splitDirection: "vertical" as const } : {}),
410 },
411 ]}
412 activeTerminalGroupId={surface.id}
413 focusRequestId={focusRequestId}
414 onSplitTerminal={onSplitTerminal}
415 onSplitTerminalVertical={onSplitTerminalVertical}
416 onNewTerminal={onNewTerminal}
417 splitShortcutLabel={splitShortcutLabel}
418 splitVerticalShortcutLabel={splitVerticalShortcutLabel}
419 newShortcutLabel={newShortcutLabel}
420 closeShortcutLabel={closeShortcutLabel}
421 onActiveTerminalChange={onActiveTerminalChange}
422 onCloseTerminal={onCloseTerminal}
423 onHeightChange={() => undefined}
424 onAddTerminalContext={onAddTerminalContext}
425 terminalLabelsById={terminalLabelsById}
426 terminalLaunchLocationsById={terminalLaunchLocationsById}
427 keybindings={keybindings}
428 />
429 );
430});