From 4e38d93a8f7ca1bc5d4d920b3e56833c11e779bc Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 27 Apr 2026 12:39:22 -0700 Subject: [PATCH] terminals --- .../terminal/NativeTerminalSurface.tsx | 13 +- .../features/terminal/ThreadTerminalPanel.tsx | 11 + .../terminal/ThreadTerminalRouteScreen.tsx | 288 +++++++++++++---- .../terminal/terminalBufferReplay.test.ts | 4 +- .../features/terminal/terminalBufferReplay.ts | 15 +- .../src/features/terminal/terminalDebugLog.ts | 24 ++ .../features/terminal/terminalMenu.test.ts | 64 +++- .../src/features/terminal/terminalMenu.ts | 67 ++-- .../terminal/terminalRouteBootstrap.ts | 1 + .../features/threads/ThreadGitControls.tsx | 71 ++-- .../features/threads/ThreadRouteScreen.tsx | 44 ++- apps/mobile/src/lib/routes.ts | 29 +- .../state/use-remote-environment-registry.ts | 4 + apps/mobile/src/state/use-terminal-session.ts | 3 + .../Layers/ProjectSetupScriptRunner.test.ts | 1 + apps/server/src/server.test.ts | 1 + .../src/terminal/Layers/Manager.test.ts | 42 ++- apps/server/src/terminal/Layers/Manager.ts | 246 ++++++++++---- apps/web/src/components/ChatView.browser.tsx | 22 ++ apps/web/src/components/ChatView.tsx | 302 ++++++++++++++++-- .../ThreadTerminalDrawer.browser.tsx | 7 +- .../src/components/ThreadTerminalDrawer.tsx | 93 ++++-- .../service.threadSubscriptions.test.ts | 65 ++++ apps/web/src/lib/terminalFocus.test.ts | 19 +- apps/web/src/lib/terminalFocus.ts | 4 +- apps/web/src/localApi.test.ts | 1 + apps/web/src/terminalUiStateStore.test.ts | 82 +++-- apps/web/src/terminalUiStateStore.ts | 104 +++--- apps/web/src/types.ts | 2 +- .../src/terminalSessionState.test.ts | 30 +- .../src/terminalSessionState.ts | 21 +- packages/contracts/src/terminal.test.ts | 52 ++- packages/contracts/src/terminal.ts | 21 +- packages/shared/package.json | 4 + packages/shared/src/terminalLabels.test.ts | 54 ++++ packages/shared/src/terminalLabels.ts | 40 +++ 36 files changed, 1434 insertions(+), 417 deletions(-) create mode 100644 apps/mobile/src/features/terminal/terminalDebugLog.ts create mode 100644 packages/shared/src/terminalLabels.test.ts create mode 100644 packages/shared/src/terminalLabels.ts diff --git a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx index d775f53a25..30dd0e8603 100644 --- a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx +++ b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx @@ -1,4 +1,4 @@ -import { memo, useCallback } from "react"; +import { memo, useCallback, useEffect } from "react"; import { Pressable, ScrollView, @@ -17,6 +17,7 @@ import { getPierreTerminalTheme, type TerminalTheme, } from "./terminalTheme"; +import { terminalDebugLog } from "./terminalDebugLog"; interface TerminalInputEvent { readonly data: string; @@ -168,6 +169,16 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme); const { onInput, onResize } = props; const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView(); + const hasNativeSurface = Boolean(NativeTerminalSurfaceView); + + useEffect(() => { + terminalDebugLog("native:surface", { + terminalKey: props.terminalKey, + native: hasNativeSurface, + bufferLen: props.buffer.length, + isRunning: props.isRunning, + }); + }, [hasNativeSurface, props.buffer.length, props.isRunning, props.terminalKey]); const handleNativeInput = useCallback( (event: NativeSyntheticEvent) => { onInput(event.nativeEvent.data); diff --git a/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx b/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx index e614400eb3..04c240a13d 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx @@ -12,6 +12,7 @@ import { } from "../../state/use-terminal-session"; import { TerminalSurface } from "./NativeTerminalSurface"; import { hasNativeTerminalSurface } from "./nativeTerminalModule"; +import { terminalDebugLog } from "./terminalDebugLog"; interface ThreadTerminalPanelProps { readonly environmentId: EnvironmentId; @@ -51,9 +52,19 @@ export const ThreadTerminalPanel = memo(function ThreadTerminalPanel( const client = getEnvironmentClient(props.environmentId); if (!client) { + terminalDebugLog("panel:attach-skip", { + reason: "no-environment-client", + environmentId: props.environmentId, + }); return; } + terminalDebugLog("panel:attach", { + environmentId: props.environmentId, + threadId: props.threadId, + terminalId, + }); + return attachTerminalSession({ environmentId: props.environmentId, client, diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index c1318c3f8d..26c91f7ca1 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -1,4 +1,10 @@ -import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + DEFAULT_TERMINAL_ID, + EnvironmentId, + type TerminalAttachStreamEvent, + ThreadId, +} from "@t3tools/contracts"; +import type { KnownTerminalSession } from "@t3tools/client-runtime"; import { Stack, useLocalSearchParams, useRouter } from "expo-router"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native"; @@ -7,7 +13,7 @@ import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-re import { EmptyState } from "../../components/EmptyState"; import { LoadingScreen } from "../../components/LoadingScreen"; -import { buildThreadTerminalRoutePath } from "../../lib/routes"; +import { buildThreadTerminalNavigation } from "../../lib/routes"; import { getEnvironmentClient, useRemoteEnvironmentState, @@ -23,6 +29,7 @@ import { useSelectedThreadDetail } from "../../state/use-thread-detail"; import { TerminalSurface } from "./NativeTerminalSurface"; import { getPierreTerminalTheme } from "./terminalTheme"; import { loadPreferences, savePreferencesPatch } from "../../lib/storage"; +import { terminalDebugLog } from "./terminalDebugLog"; import { getTerminalBufferReplayKey, getTerminalSurfaceReplayBuffer, @@ -37,9 +44,10 @@ import { import { basename, buildTerminalMenuSessions, - getTerminalLabel, getTerminalStatusLabel, - nextTerminalId, + nextOpenTerminalId, + resolveTerminalSessionLabel, + type TerminalMenuSession, } from "./terminalMenu"; import { DEFAULT_TERMINAL_FONT_SIZE, @@ -71,13 +79,6 @@ type TerminalToolbarAction = readonly modifier: PendingModifier; }; -interface TerminalMenuSession { - readonly terminalId: string; - readonly cwd: string | null; - readonly status: "starting" | "running" | "exited" | "error" | "closed"; - readonly updatedAt: string | null; -} - function getTerminalStatusTone(input: { readonly status: TerminalMenuSession["status"]; readonly hasRunningSubprocess?: boolean; @@ -174,6 +175,22 @@ function withAlpha(hexColor: string, alpha: string): string { return /^#[0-9a-f]{6}$/i.test(hexColor) ? `${hexColor}${alpha}` : hexColor; } +function pickRunningTerminalSessionForBootstrap( + sessions: ReadonlyArray, +): KnownTerminalSession | null { + const running = sessions.filter( + (session) => session.state.status === "running" || session.state.status === "starting", + ); + if (running.length === 0) { + return null; + } + return ( + running.find((session) => session.target.terminalId === DEFAULT_TERMINAL_ID) ?? + running[0] ?? + null + ); +} + export function ThreadTerminalRouteScreen() { const router = useRouter(); const keyboard = useAnimatedKeyboard(); @@ -217,12 +234,15 @@ export function ThreadTerminalRouteScreen() { const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE); const hasOpenedRef = useRef(false); const bufferReplayTimerRef = useRef | null>(null); + const attachStreamLogCountRef = useRef(0); + const firstNonEmptyBufferLoggedRef = useRef(false); const lastBufferReplayKeyRef = useRef(null); const [readyBufferReplayKey, setReadyBufferReplayKey] = useState(null); const [hasResolvedFontPreference, setHasResolvedFontPreference] = useState( cachedFontSize !== null, ); - const [hasMeasuredSurface, setHasMeasuredSurface] = useState(cachedRouteGridSize !== null); + /** Default grid is always valid for attach; onResize refines cols/rows. Requiring a cached size blocked bootstrap for new terminal routes. */ + const [hasMeasuredSurface, setHasMeasuredSurface] = useState(true); const [pendingModifierState, setPendingModifierState] = useState<{ readonly terminalId: string; readonly value: PendingModifier | null; @@ -252,22 +272,79 @@ export function ThreadTerminalRouteScreen() { readyReplayKey: readyBufferReplayKey, }); const isRunning = terminal.status === "running" || terminal.status === "starting"; + + useEffect(() => { + terminalDebugLog("surface:props", { + terminalKey, + atomBufferLen: terminal.buffer.length, + surfaceBufferLen: terminalSurfaceBuffer.length, + replayKey: bufferReplayKey, + readyReplayKey: readyBufferReplayKey, + status: terminal.status, + version: terminal.version, + }); + }, [ + bufferReplayKey, + readyBufferReplayKey, + terminal.buffer.length, + terminal.status, + terminal.version, + terminalKey, + terminalSurfaceBuffer.length, + ]); + + useEffect(() => { + terminalDebugLog("session:status", { + terminalKey, + status: terminal.status, + error: terminal.error, + summary: terminal.summary?.cwd ?? null, + bufferLen: terminal.buffer.length, + version: terminal.version, + }); + }, [ + terminal.buffer.length, + terminal.error, + terminal.status, + terminal.summary?.cwd, + terminal.version, + terminalKey, + ]); + + useEffect(() => { + if (terminal.buffer.length === 0 || firstNonEmptyBufferLoggedRef.current) { + return; + } + firstNonEmptyBufferLoggedRef.current = true; + terminalDebugLog("session:first-nonempty-buffer", { + terminalKey, + length: terminal.buffer.length, + preview: terminal.buffer.slice(0, 160), + }); + }, [terminal.buffer, terminal.buffer.length, terminalKey]); const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null; const hostPlatform = useMemo( () => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null), [selectedEnvironmentConnection?.environmentLabel], ); const runningSession = useMemo( - () => - knownSessions.find( - (session) => session.state.status === "running" || session.state.status === "starting", - ) ?? null, + () => pickRunningTerminalSessionForBootstrap(knownSessions), [knownSessions], ); const activeKnownSession = useMemo( () => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null, [knownSessions, terminalId], ); + + const terminalAttachLaunchHintsRef = useRef({ + terminalSummary: terminal.summary, + activeKnownSummary: activeKnownSession?.state.summary ?? null, + }); + terminalAttachLaunchHintsRef.current = { + terminalSummary: terminal.summary, + activeKnownSummary: activeKnownSession?.state.summary ?? null, + }; + const terminalStatusTone = useMemo( () => getTerminalStatusTone({ @@ -339,6 +416,7 @@ export function ThreadTerminalRouteScreen() { cwd: cwd ?? null, status: terminal.status, hasRunningSubprocess: terminal.hasRunningSubprocess, + displayLabel: resolveTerminalSessionLabel(terminalId, terminal.summary), updatedAt: terminal.updatedAt, }, }), @@ -347,19 +425,47 @@ export function ThreadTerminalRouteScreen() { knownSessions, selectedThreadProject?.workspaceRoot, terminal.hasRunningSubprocess, + terminal.summary, terminal.status, terminal.updatedAt, terminalId, ], ); + const logAttachStreamEvent = useCallback((event: TerminalAttachStreamEvent) => { + const n = ++attachStreamLogCountRef.current; + if (event.type === "output" && n > 32 && n % 64 !== 0) { + return; + } + if (event.type === "snapshot") { + terminalDebugLog("attach:stream", { + n, + type: event.type, + status: event.snapshot.status, + historyLen: event.snapshot.history.length, + cwd: event.snapshot.cwd, + }); + return; + } + if (event.type === "output") { + terminalDebugLog("attach:stream", { n, type: event.type, dataLen: event.data.length }); + return; + } + terminalDebugLog("attach:stream", { n, type: event.type }); + }, []); + const attachTerminal = useCallback(() => { if (!selectedThread || !selectedThreadProject?.workspaceRoot) { + terminalDebugLog("attach:abort", { reason: "no-thread-or-workspace" }); return null; } const client = getEnvironmentClient(selectedThread.environmentId); if (!client) { + terminalDebugLog("attach:abort", { + reason: "no-environment-client", + environmentId: selectedThread.environmentId, + }); return null; } @@ -378,13 +484,22 @@ export function ThreadTerminalRouteScreen() { worktreePath: pendingLaunch.worktreePath, } : resolveTerminalOpenLocation({ - terminalLocation: terminal.summary, - activeSessionLocation: activeKnownSession?.state.summary ?? null, + terminalLocation: terminalAttachLaunchHintsRef.current.terminalSummary, + activeSessionLocation: terminalAttachLaunchHintsRef.current.activeKnownSummary, workspaceRoot: selectedThreadProject.workspaceRoot, threadShellWorktreePath: selectedThread.worktreePath ?? null, threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null, }); + terminalDebugLog("attach:start", { + terminalId, + threadId: selectedThread.id, + cols: lastGridSize.cols, + rows: lastGridSize.rows, + cwd: launchLocation.cwd, + worktreePath: launchLocation.worktreePath, + }); + return attachTerminalSession({ environmentId: selectedThread.environmentId, client, @@ -397,6 +512,7 @@ export function ThreadTerminalRouteScreen() { rows: lastGridSize.rows, env: pendingLaunch?.env, }, + onEvent: logAttachStreamEvent, onSnapshot: () => { if (!pendingLaunch?.initialInput || initialInputSent) { return; @@ -411,6 +527,9 @@ export function ThreadTerminalRouteScreen() { }, }); } catch (error) { + terminalDebugLog("attach:error", { + message: error instanceof Error ? error.message : String(error), + }); if (pendingLaunch) { stagePendingTerminalLaunch({ target: pendingLaunchTarget, @@ -423,16 +542,34 @@ export function ThreadTerminalRouteScreen() { }, [ lastGridSize.cols, lastGridSize.rows, - activeKnownSession?.state.summary, + logAttachStreamEvent, selectedThreadDetail?.worktreePath, selectedThread, selectedThreadProject?.workspaceRoot, - terminal.summary, terminalId, ]); + const attachTerminalRef = useRef(attachTerminal); + attachTerminalRef.current = attachTerminal; + const selectedThreadRef = useRef(selectedThread); + selectedThreadRef.current = selectedThread; + const selectedThreadProjectBootstrapRef = useRef(selectedThreadProject); + selectedThreadProjectBootstrapRef.current = selectedThreadProject; + const runningSessionRef = useRef(runningSession); + runningSessionRef.current = runningSession; + const terminalBootstrapRef = useRef({ + status: terminal.status, + bufferLen: terminal.buffer.length, + }); + terminalBootstrapRef.current = { + status: terminal.status, + bufferLen: terminal.buffer.length, + }; + useEffect(() => { hasOpenedRef.current = false; + attachStreamLogCountRef.current = 0; + firstNonEmptyBufferLoggedRef.current = false; }, [terminalKey]); const clearBufferReplayTimer = useCallback(() => { @@ -445,9 +582,14 @@ export function ThreadTerminalRouteScreen() { const scheduleBufferReplayReady = useCallback(() => { clearBufferReplayTimer(); const replayKey = bufferReplayKey; + terminalDebugLog("replay:schedule-ready", { + replayKey, + delayMs: TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS, + }); bufferReplayTimerRef.current = setTimeout(() => { bufferReplayTimerRef.current = null; setReadyBufferReplayKey(replayKey); + terminalDebugLog("replay:ready", { replayKey }); }, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS); }, [bufferReplayKey, clearBufferReplayTimer]); @@ -482,27 +624,9 @@ export function ThreadTerminalRouteScreen() { rows: DEFAULT_TERMINAL_ROWS, }, ); - setHasMeasuredSurface( - getCachedTerminalGridSize({ - environmentId: routeEnvironmentId, - threadId: routeThreadId, - terminalId, - }) !== null, - ); + setHasMeasuredSurface(true); }, [routeEnvironmentId, routeThreadId, terminalId]); - useEffect(() => { - setHasMeasuredSurface( - routeEnvironmentId !== null && - routeThreadId !== null && - getCachedTerminalGridSize({ - environmentId: routeEnvironmentId, - threadId: routeThreadId, - terminalId, - }) !== null, - ); - }, [fontSize, routeEnvironmentId, routeThreadId, terminalId]); - useEffect(() => { let cancelled = false; @@ -539,50 +663,79 @@ export function ThreadTerminalRouteScreen() { }); }, [fontSize, hasResolvedFontPreference]); + // Subscribes `terminal.attach` once per route+terminal until thread/env/attach args change. + // Use refs for `attachTerminal` / `selectedThread` / `runningSession`: their identities change when + // unrelated store updates (e.g. terminal buffer) re-render the parent, which was firing cleanup + // → detach immediately after the first snapshot. useEffect(() => { if (!hasResolvedFontPreference || !hasMeasuredSurface) { return; } + const thread = selectedThreadRef.current; + const project = selectedThreadProjectBootstrapRef.current; + const running = runningSessionRef.current; + const termSnap = terminalBootstrapRef.current; + const bootstrapAction = resolveTerminalRouteBootstrap({ - hasThread: selectedThread !== null, - hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot), + hasThread: thread !== null, + hasWorkspaceRoot: Boolean(project?.workspaceRoot), hasOpened: hasOpenedRef.current, requestedTerminalId, currentTerminalId: terminalId, - runningTerminalId: runningSession?.target.terminalId ?? null, - currentTerminalStatus: terminal.status, - hasCurrentTerminalHydration: terminal.summary !== null || terminal.buffer.length > 0, + runningTerminalId: running?.target.terminalId ?? null, + currentTerminalStatus: termSnap.status, + // Metadata summary (cwd/status) is not scrollback. Only `terminal.attach` fills `buffer`; + // treating summary as "hydrated" skipped attach while status was running → empty surface. + hasCurrentTerminalHydration: termSnap.bufferLen > 0, }); - if (bootstrapAction.kind === "idle" || !selectedThread) { + if (bootstrapAction.kind !== "idle") { + terminalDebugLog("bootstrap:action", { + kind: bootstrapAction.kind, + hasOpenedBefore: hasOpenedRef.current, + hasHydration: termSnap.bufferLen > 0, + terminalStatus: termSnap.status, + bufLen: termSnap.bufferLen, + }); + } + if (bootstrapAction.kind === "idle" || !thread) { return; } if (bootstrapAction.kind === "redirect") { - router.replace(buildThreadTerminalRoutePath(selectedThread, bootstrapAction.terminalId)); + router.replace(buildThreadTerminalNavigation(thread, bootstrapAction.terminalId)); return; } hasOpenedRef.current = true; try { - return attachTerminal() ?? undefined; - } catch { + const detach = attachTerminalRef.current(); + terminalDebugLog("bootstrap:subscribe", { hasDetach: Boolean(detach) }); + if (!detach) { + hasOpenedRef.current = false; + return; + } + return () => { + detach(); + hasOpenedRef.current = false; + terminalDebugLog("bootstrap:unsubscribe"); + }; + } catch (error) { hasOpenedRef.current = false; + terminalDebugLog("bootstrap:attach-threw", { + message: error instanceof Error ? error.message : String(error), + }); return; } }, [ - attachTerminal, - requestedTerminalId, - router, - runningSession, - selectedThread, - selectedThreadProject?.workspaceRoot, - terminal.buffer.length, - terminal.summary, - terminal.status, - terminalId, hasMeasuredSurface, hasResolvedFontPreference, + requestedTerminalId, + router, + selectedThread?.environmentId, + selectedThread?.id, + selectedThreadProject?.workspaceRoot, + terminalId, ]); const writeInput = useCallback( @@ -626,6 +779,11 @@ export function ThreadTerminalRouteScreen() { const handleResize = useCallback( (size: { readonly cols: number; readonly rows: number }) => { + terminalDebugLog("native:onResize", { + cols: size.cols, + rows: size.rows, + terminalKey, + }); setHasMeasuredSurface(true); if (readyBufferReplayKey !== bufferReplayKey) { scheduleBufferReplayReady(); @@ -672,6 +830,7 @@ export function ThreadTerminalRouteScreen() { scheduleBufferReplayReady, selectedThread, terminalId, + terminalKey, ], ); @@ -681,7 +840,7 @@ export function ThreadTerminalRouteScreen() { return; } - router.replace(buildThreadTerminalRoutePath(selectedThread, nextTerminalId)); + router.replace(buildThreadTerminalNavigation(selectedThread, nextTerminalId)); }, [router, selectedThread, terminalId], ); @@ -692,12 +851,15 @@ export function ThreadTerminalRouteScreen() { } router.replace( - buildThreadTerminalRoutePath( + buildThreadTerminalNavigation( selectedThread, - nextTerminalId(terminalMenuSessions.map((session) => session.terminalId)), + nextOpenTerminalId({ + listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), + activeRouteTerminalId: terminalId, + }), ), ); - }, [router, selectedThread, terminalMenuSessions]); + }, [router, selectedThread, terminalId, terminalMenuSessions]); const adjustFontSize = useCallback((delta: number) => { setTimeout(() => { @@ -856,7 +1018,7 @@ export function ThreadTerminalRouteScreen() { .filter(Boolean) .join(" · ")} > - {getTerminalLabel(session.terminalId)} + {session.displayLabel} ))} { ).toBe("env-1:thread-1:default:10"); }); - it("holds back terminal history until the measured surface is ready", () => { + it("shows terminal history while replay key is unset (initial mount / after key change)", () => { const replayKey = getTerminalBufferReplayKey({ terminalKey: "env-1:thread-1:default", fontSize: 10, @@ -24,7 +24,7 @@ describe("terminalBufferReplay", () => { replayKey, readyReplayKey: null, }), - ).toBe(""); + ).toBe("fastfetch output"); expect( getTerminalSurfaceReplayBuffer({ buffer: "fastfetch output", diff --git a/apps/mobile/src/features/terminal/terminalBufferReplay.ts b/apps/mobile/src/features/terminal/terminalBufferReplay.ts index 4682fca2ef..edbdeb37f3 100644 --- a/apps/mobile/src/features/terminal/terminalBufferReplay.ts +++ b/apps/mobile/src/features/terminal/terminalBufferReplay.ts @@ -1,3 +1,5 @@ +import { terminalDebugLog } from "./terminalDebugLog"; + export const TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS = 180; export function getTerminalBufferReplayKey(input: { @@ -12,5 +14,16 @@ export function getTerminalSurfaceReplayBuffer(input: { readonly replayKey: string; readonly readyReplayKey: string | null; }): string { - return input.readyReplayKey === input.replayKey ? input.buffer : ""; + // Pass live buffer whenever ready key is unset or matches. Only return "" when ready key is + // stale vs current replay key (e.g. mid font-size transition). + if (input.readyReplayKey !== null && input.readyReplayKey !== input.replayKey) { + terminalDebugLog("replay:stale-key-hiding-buffer", { + replayKey: input.replayKey, + readyReplayKey: input.readyReplayKey, + bufferLen: input.buffer.length, + }); + return ""; + } + + return input.buffer; } diff --git a/apps/mobile/src/features/terminal/terminalDebugLog.ts b/apps/mobile/src/features/terminal/terminalDebugLog.ts new file mode 100644 index 0000000000..eb11419b33 --- /dev/null +++ b/apps/mobile/src/features/terminal/terminalDebugLog.ts @@ -0,0 +1,24 @@ +/** + * Debug logging for the mobile terminal pipeline. Prefix: `[t3-terminal]`. + * + * Enabled when `__DEV__` is true, or set `globalThis.__T3_TERMINAL_DEBUG__ = true` in a JS + * debugger / Metro console to trace release/TestFlight builds. + */ +export function isTerminalDebugEnabled(): boolean { + return ( + (typeof __DEV__ !== "undefined" && __DEV__) || + (typeof globalThis !== "undefined" && + (globalThis as { __T3_TERMINAL_DEBUG__?: boolean }).__T3_TERMINAL_DEBUG__ === true) + ); +} + +export function terminalDebugLog(message: string, data?: Record): void { + if (!isTerminalDebugEnabled()) { + return; + } + if (data !== undefined) { + console.log(`[t3-terminal] ${message}`, data); + } else { + console.log(`[t3-terminal] ${message}`); + } +} diff --git a/apps/mobile/src/features/terminal/terminalMenu.test.ts b/apps/mobile/src/features/terminal/terminalMenu.test.ts index b49cef5443..f5def9542d 100644 --- a/apps/mobile/src/features/terminal/terminalMenu.test.ts +++ b/apps/mobile/src/features/terminal/terminalMenu.test.ts @@ -3,7 +3,14 @@ import { describe, expect, it } from "vitest"; import type { KnownTerminalSession } from "@t3tools/client-runtime"; import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { buildTerminalMenuSessions, resolveProjectScriptTerminalId } from "./terminalMenu"; +import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; + +import { + buildTerminalMenuSessions, + nextOpenTerminalId, + nextTerminalId, + resolveProjectScriptTerminalId, +} from "./terminalMenu"; function makeKnownSession(input: { readonly terminalId: string; @@ -29,6 +36,7 @@ function makeKnownSession(input: { exitCode: null, exitSignal: null, hasRunningSubprocess: false, + label: getTerminalLabel(input.terminalId), updatedAt: input.updatedAt ?? "2026-04-15T20:00:00.000Z", } : null, @@ -43,7 +51,7 @@ function makeKnownSession(input: { } describe("buildTerminalMenuSessions", () => { - it("keeps the default shell and only includes running sessions by default", () => { + it("only lists server-known sessions that are running or starting (plus current)", () => { expect( buildTerminalMenuSessions({ knownSessions: [ @@ -63,18 +71,12 @@ describe("buildTerminalMenuSessions", () => { workspaceRoot: "/workspace/root", }), ).toEqual([ - { - terminalId: DEFAULT_TERMINAL_ID, - cwd: "/workspace/root", - status: "closed", - hasRunningSubprocess: false, - updatedAt: null, - }, { terminalId: "term-3", cwd: "/workspace/feature", status: "running", hasRunningSubprocess: false, + displayLabel: "Terminal 3", updatedAt: "2026-04-15T20:05:00.000Z", }, ]); @@ -90,28 +92,58 @@ describe("buildTerminalMenuSessions", () => { cwd: "/workspace/exited", status: "exited", hasRunningSubprocess: false, + displayLabel: "Terminal 4", updatedAt: "2026-04-15T20:07:00.000Z", }, }), ).toEqual([ - { - terminalId: DEFAULT_TERMINAL_ID, - cwd: "/workspace/root", - status: "closed", - hasRunningSubprocess: false, - updatedAt: null, - }, { terminalId: "term-4", cwd: "/workspace/exited", status: "exited", hasRunningSubprocess: false, + displayLabel: "Terminal 4", updatedAt: "2026-04-15T20:07:00.000Z", }, ]); }); }); +describe("nextTerminalId", () => { + it("uses the primary id when no terminals are listed yet", () => { + expect(nextTerminalId([])).toBe(DEFAULT_TERMINAL_ID); + }); + + it("allocates term-2 when only the primary shell exists", () => { + expect(nextTerminalId([DEFAULT_TERMINAL_ID])).toBe("term-2"); + }); +}); + +describe("nextOpenTerminalId", () => { + it("matches nextTerminalId when not on a terminal route", () => { + expect(nextOpenTerminalId({ listedTerminalIds: [] })).toBe(DEFAULT_TERMINAL_ID); + expect(nextOpenTerminalId({ listedTerminalIds: [DEFAULT_TERMINAL_ID] })).toBe("term-2"); + }); + + it("avoids the mounted primary tab when the session list is still empty", () => { + expect( + nextOpenTerminalId({ + listedTerminalIds: [], + activeRouteTerminalId: DEFAULT_TERMINAL_ID, + }), + ).toBe("term-2"); + }); + + it("does not double-count when the route id is already listed", () => { + expect( + nextOpenTerminalId({ + listedTerminalIds: [DEFAULT_TERMINAL_ID], + activeRouteTerminalId: DEFAULT_TERMINAL_ID, + }), + ).toBe("term-2"); + }); +}); + describe("resolveProjectScriptTerminalId", () => { it("reuses the default shell when no terminal is running", () => { expect( diff --git a/apps/mobile/src/features/terminal/terminalMenu.ts b/apps/mobile/src/features/terminal/terminalMenu.ts index 2b3d3517cb..04ffaa682c 100644 --- a/apps/mobile/src/features/terminal/terminalMenu.ts +++ b/apps/mobile/src/features/terminal/terminalMenu.ts @@ -1,11 +1,20 @@ import type { KnownTerminalSession } from "@t3tools/client-runtime"; import { DEFAULT_TERMINAL_ID, type ProjectScript } from "@t3tools/contracts"; +import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels"; + +export { + getTerminalLabel, + nextTerminalId, + resolveTerminalSessionLabel, +} from "@t3tools/shared/terminalLabels"; export interface TerminalMenuSession { readonly terminalId: string; readonly cwd: string | null; readonly status: "starting" | "running" | "exited" | "error" | "closed"; readonly hasRunningSubprocess: boolean; + /** Server-authoritative title with the same fallback rules as web. */ + readonly displayLabel: string; readonly updatedAt: string | null; } @@ -23,19 +32,6 @@ export function basename(input: string | null): string | null { return segments[segments.length - 1] ?? normalized; } -export function getTerminalLabel(terminalId: string): string { - if (terminalId === DEFAULT_TERMINAL_ID) { - return "Main shell"; - } - - const numericSuffix = /^term(?:inal)?-(\d+)$/i.exec(terminalId)?.[1]; - if (numericSuffix) { - return `Terminal ${numericSuffix}`; - } - - return terminalId; -} - export function getTerminalStatusLabel(input: { readonly status: TerminalMenuSession["status"]; readonly hasRunningSubprocess?: boolean; @@ -56,14 +52,23 @@ export function getTerminalStatusLabel(input: { return "Not started"; } -export function nextTerminalId(existingTerminalIds: ReadonlyArray): string { - const usedIds = new Set(existingTerminalIds); - let nextIndex = 2; - while (usedIds.has(`term-${nextIndex}`)) { - nextIndex += 1; +/** + * Picks an id for "open another shell". Counts the terminal screen already mounted + * (`activeRouteTerminalId`) as occupied so an empty session list on the primary route + * still advances to `term-2` instead of `replace`-navigating to the same `default` tab. + */ +export function nextOpenTerminalId(input: { + readonly listedTerminalIds: ReadonlyArray; + readonly activeRouteTerminalId?: string | null; +}): string { + const listed = input.listedTerminalIds.filter((id) => id.trim().length > 0); + const routeId = input.activeRouteTerminalId?.trim() ? input.activeRouteTerminalId : null; + + if (!routeId || listed.includes(routeId)) { + return nextTerminalId(listed); } - return `term-${nextIndex}`; + return nextTerminalId([...listed, routeId]); } export function buildTerminalMenuSessions(input: { @@ -73,14 +78,6 @@ export function buildTerminalMenuSessions(input: { }): ReadonlyArray { const sessionsById = new Map(); - sessionsById.set(DEFAULT_TERMINAL_ID, { - terminalId: DEFAULT_TERMINAL_ID, - cwd: input.workspaceRoot, - status: "closed", - hasRunningSubprocess: false, - updatedAt: null, - }); - for (const session of input.knownSessions) { if ( session.state.status !== "running" && @@ -95,6 +92,7 @@ export function buildTerminalMenuSessions(input: { cwd: session.state.summary?.cwd ?? input.workspaceRoot, status: session.state.status, hasRunningSubprocess: session.state.hasRunningSubprocess, + displayLabel: resolveTerminalSessionLabel(session.target.terminalId, session.state.summary), updatedAt: session.state.updatedAt, }); } @@ -103,18 +101,9 @@ export function buildTerminalMenuSessions(input: { sessionsById.set(input.currentSession.terminalId, input.currentSession); } - return Array.from(sessionsById.values()).sort((left, right) => { - if (left.terminalId === DEFAULT_TERMINAL_ID) return -1; - if (right.terminalId === DEFAULT_TERMINAL_ID) return 1; - - const leftUpdatedAt = left.updatedAt ? Date.parse(left.updatedAt) : 0; - const rightUpdatedAt = right.updatedAt ? Date.parse(right.updatedAt) : 0; - if (leftUpdatedAt !== rightUpdatedAt) { - return rightUpdatedAt - leftUpdatedAt; - } - - return left.terminalId.localeCompare(right.terminalId); - }); + return Array.from(sessionsById.values()).sort((left, right) => + left.terminalId.localeCompare(right.terminalId, undefined, { numeric: true }), + ); } export function resolveProjectScriptTerminalId(input: { diff --git a/apps/mobile/src/features/terminal/terminalRouteBootstrap.ts b/apps/mobile/src/features/terminal/terminalRouteBootstrap.ts index 09f027265e..20514224d6 100644 --- a/apps/mobile/src/features/terminal/terminalRouteBootstrap.ts +++ b/apps/mobile/src/features/terminal/terminalRouteBootstrap.ts @@ -6,6 +6,7 @@ export function resolveTerminalRouteBootstrap(input: { readonly currentTerminalId: string; readonly runningTerminalId: string | null; readonly currentTerminalStatus: "starting" | "running" | "exited" | "error" | "closed"; + /** True once the attach stream has populated scrollback (`buffer` non-empty), not merely metadata. */ readonly hasCurrentTerminalHydration: boolean; }): | { readonly kind: "idle" } diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index f177d3fa2b..628b725127 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -11,7 +11,6 @@ import { Alert, Linking } from "react-native"; import { buildThreadReviewRoutePath } from "../../lib/routes"; import { basename, - getTerminalLabel, getTerminalStatusLabel, projectScriptMenuIcon, projectScriptMenuLabel, @@ -183,19 +182,16 @@ export function ThreadGitControls(props: { {props.projectScripts.length > 0 ? ( - - Project scripts - {props.projectScripts.map((script) => ( - void props.onRunProjectScript(script)} - subtitle={script.command} - > - {projectScriptMenuLabel(script)} - - ))} - + props.projectScripts.map((script) => ( + void props.onRunProjectScript(script)} + subtitle={script.command} + > + {projectScriptMenuLabel(script)} + + )) ) : ( No project scripts )} - - Terminals - {props.terminalSessions.map((session) => ( - props.onOpenTerminal(session.terminalId)} - subtitle={[ - getTerminalStatusLabel({ - status: session.status, - hasRunningSubprocess: session.hasRunningSubprocess, - }), - basename(session.cwd), - ] - .filter(Boolean) - .join(" · ")} - > - {getTerminalLabel(session.terminalId)} - - ))} + {props.terminalSessions.map((session) => ( props.onOpenTerminal(session.terminalId)} + subtitle={[ + getTerminalStatusLabel({ + status: session.status, + hasRunningSubprocess: session.hasRunningSubprocess, + }), + basename(session.cwd), + ] + .filter(Boolean) + .join(" · ")} > - Open new terminal + {session.displayLabel} - + ))} + + Open new terminal + { + terminalDebugLog("terminal-menu:open-existing", { + terminalId: nextTerminalId ?? null, + hasThread: Boolean(selectedThread), + hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot), + }); + if (!selectedThread || !selectedThreadProject?.workspaceRoot) { return; } - void router.push(buildThreadTerminalRoutePath(selectedThread, nextTerminalId)); + void router.push(buildThreadTerminalNavigation(selectedThread, nextTerminalId)); }, [router, selectedThread, selectedThreadProject?.workspaceRoot], ); const handleOpenNewTerminal = useCallback(() => { + terminalDebugLog("terminal-menu:open-new", { + hasThread: Boolean(selectedThread), + hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot), + listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), + }); + if (!selectedThread || !selectedThreadProject?.workspaceRoot) { return; } - const nextId = nextTerminalId(terminalMenuSessions.map((session) => session.terminalId)); - void router.push(buildThreadTerminalRoutePath(selectedThread, nextId)); + const nextId = nextOpenTerminalId({ + listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), + }); + void router.push(buildThreadTerminalNavigation(selectedThread, nextId)); }, [router, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]); const handleRunProjectScript = useCallback( async (script: ProjectScript) => { + terminalDebugLog("project-script:press", { + scriptId: script.id, + command: script.command, + hasThread: Boolean(selectedThread), + hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot), + }); + if (!selectedThread || !selectedThreadProject?.workspaceRoot) { + terminalDebugLog("project-script:abort", { + scriptId: script.id, + reason: "no-thread-or-workspace", + }); return; } @@ -200,8 +226,14 @@ export function ThreadRouteScreen() { initialInput: `${script.command}\r`, }, }); + terminalDebugLog("project-script:staged", { + scriptId: script.id, + terminalId: targetTerminalId, + cwd, + worktreePath: preferredWorktreePath, + }); - void router.push(buildThreadTerminalRoutePath(selectedThread, targetTerminalId)); + void router.push(buildThreadTerminalNavigation(selectedThread, targetTerminalId)); }, [ router, diff --git a/apps/mobile/src/lib/routes.ts b/apps/mobile/src/lib/routes.ts index 6fbbe49c86..9d5ccc89f8 100644 --- a/apps/mobile/src/lib/routes.ts +++ b/apps/mobile/src/lib/routes.ts @@ -1,4 +1,4 @@ -import type { Router } from "expo-router"; +import type { Href, Router } from "expo-router"; import type { SelectedThreadRef } from "../state/remote-runtime-types"; import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime"; @@ -41,6 +41,33 @@ export function buildThreadTerminalRoutePath( return `${basePath}?terminalId=${encodeURIComponent(terminalId)}`; } +/** + * Prefer this over {@link buildThreadTerminalRoutePath} with `router.push(string)` — Expo Router + * often does not merge query strings into `useLocalSearchParams`, which breaks terminal bootstrap + * (`requestedTerminalId` stays null while the UI assumes `default`). + */ +export function buildThreadTerminalNavigation( + input: ThreadRouteInput | PlainThreadRouteInput, + terminalId?: string | null, +): Href { + const environmentId = String(input.environmentId); + const threadId = String("threadId" in input ? input.threadId : input.id); + + const params: { environmentId: string; threadId: string; terminalId?: string } = { + environmentId, + threadId, + }; + + if (terminalId != null && terminalId !== "") { + params.terminalId = terminalId; + } + + return { + pathname: "/threads/[environmentId]/[threadId]/terminal", + params, + }; +} + export function dismissRoute(router: Router) { if (router.canGoBack()) { router.back(); diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index 591a698dc8..159bd49077 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -18,6 +18,7 @@ import * as Option from "effect/Option"; import { pipe } from "effect/Function"; import { Atom } from "effect/unstable/reactivity"; import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/connection"; +import { terminalDebugLog } from "../features/terminal/terminalDebugLog"; import { clearSavedConnection, loadSavedConnections, saveConnection } from "../lib/storage"; import { appAtomRegistry } from "./atom-registry"; import { type ConnectedEnvironmentSummary, type EnvironmentSession } from "./remote-runtime-types"; @@ -268,6 +269,9 @@ export async function connectSavedEnvironment( client, }), ); + terminalDebugLog("registry:terminal-metadata-subscribed", { + environmentId: connection.environmentId, + }); notifyEnvironmentConnectionListeners(); try { diff --git a/apps/mobile/src/state/use-terminal-session.ts b/apps/mobile/src/state/use-terminal-session.ts index 7bc8e29dc8..9ea13eef3e 100644 --- a/apps/mobile/src/state/use-terminal-session.ts +++ b/apps/mobile/src/state/use-terminal-session.ts @@ -13,6 +13,7 @@ import { import type { EnvironmentId, TerminalAttachInput, + TerminalAttachStreamEvent, TerminalMetadataStreamEvent, TerminalSessionSnapshot, } from "@t3tools/contracts"; @@ -43,12 +44,14 @@ export function attachTerminalSession(input: { readonly client: Parameters[0]["client"]; readonly terminal: TerminalAttachInput; readonly onSnapshot?: (snapshot: TerminalSessionSnapshot) => void; + readonly onEvent?: (event: TerminalAttachStreamEvent) => void; }) { return terminalSessionManager.attach({ environmentId: input.environmentId, client: input.client, terminal: input.terminal, ...(input.onSnapshot ? { onSnapshot: input.onSnapshot } : {}), + ...(input.onEvent ? { onEvent: input.onEvent } : {}), }); } diff --git a/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts index 5f66a5f800..c30a2a7dcd 100644 --- a/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts @@ -91,6 +91,7 @@ describe("ProjectSetupScriptRunner", () => { history: "", exitCode: null, exitSignal: null, + label: "setup-setup", updatedAt: "2026-01-01T00:00:00.000Z", }), ); diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 8211d63bb6..43ae1b11e6 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -3929,6 +3929,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { history: "", exitCode: null, exitSignal: null, + label: "Primary", updatedAt: new Date().toISOString(), }; diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index e4a5d7a8b7..28f9f396e3 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -198,7 +198,10 @@ interface CreateManagerOptions { shellResolver?: () => string; platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; - subprocessChecker?: (terminalPid: number) => Effect.Effect; + subprocessInspector?: (terminalPid: number) => Effect.Effect<{ + readonly hasRunningSubprocess: boolean; + readonly childCommand: string | null; + }>; subprocessPollIntervalMs?: number; processKillGraceMs?: number; maxRetainedInactiveSessions?: number; @@ -234,8 +237,8 @@ const createManager = ( ...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}), ...(options.platform !== undefined ? { platform: options.platform } : {}), ...(options.env !== undefined ? { env: options.env } : {}), - ...(options.subprocessChecker !== undefined - ? { subprocessChecker: options.subprocessChecker } + ...(options.subprocessInspector !== undefined + ? { subprocessInspector: options.subprocessInspector } : {}), ...(options.subprocessPollIntervalMs !== undefined ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } @@ -275,7 +278,7 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( const third = yield* manager.open(openInput()); assert.equal(first.threadId, "thread-1"); - assert.equal(first.terminalId, "default"); + assert.equal(first.terminalId, DEFAULT_TERMINAL_ID); assert.equal(second.threadId, "thread-1"); assert.equal(third.threadId, "thread-1"); expect(ptyAdapter.spawnInputs).toHaveLength(1); @@ -445,7 +448,7 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( (event) => event.type === "cleared" && event.threadId === "thread-1" && - event.terminalId === "default", + event.terminalId === DEFAULT_TERMINAL_ID, ), ).toBe(true); }), @@ -617,27 +620,40 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( it.effect("emits subprocess activity events when child-process state changes", () => Effect.gen(function* () { - let hasRunningSubprocess = false; + let inspect: { + readonly hasRunningSubprocess: boolean; + readonly childCommand: string | null; + } = { hasRunningSubprocess: false, childCommand: null }; const { manager, getEvents } = yield* createManager(5, { - subprocessChecker: () => Effect.succeed(hasRunningSubprocess), + subprocessInspector: () => Effect.succeed(inspect), subprocessPollIntervalMs: 20, }); yield* manager.open(openInput()); expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false); - hasRunningSubprocess = true; + inspect = { hasRunningSubprocess: true, childCommand: "vim" }; yield* waitFor( Effect.map(getEvents, (events) => - events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true), + events.some( + (event) => + event.type === "activity" && + event.hasRunningSubprocess === true && + event.label === "vim", + ), ), "1200 millis", ); - hasRunningSubprocess = false; + inspect = { hasRunningSubprocess: false, childCommand: null }; yield* waitFor( Effect.map(getEvents, (events) => - events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false), + events.some( + (event) => + event.type === "activity" && + event.hasRunningSubprocess === false && + event.label === "Terminal 1", + ), ), "1200 millis", ); @@ -648,9 +664,9 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( Effect.gen(function* () { let checks = 0; const { manager } = yield* createManager(5, { - subprocessChecker: () => { + subprocessInspector: () => { checks += 1; - return Effect.succeed(false); + return Effect.succeed({ hasRunningSubprocess: false, childCommand: null }); }, subprocessPollIntervalMs: 20, }); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index aee0a0813b..b88598847c 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -12,6 +12,7 @@ import { type TerminalSummary, } from "@t3tools/contracts"; import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker"; +import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; import { Effect, Encoding, @@ -58,6 +59,7 @@ const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128; const DEFAULT_OPEN_COLS = 120; const DEFAULT_OPEN_ROWS = 30; const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]); +const MAX_TERMINAL_LABEL_LENGTH = 128; class TerminalSubprocessCheckError extends Schema.TaggedErrorClass()( "TerminalSubprocessCheckError", @@ -78,8 +80,15 @@ class TerminalProcessSignalError extends Schema.TaggedErrorClass; +interface TerminalSubprocessInspectResult { + readonly hasRunningSubprocess: boolean; + readonly childCommand: string | null; +} + +interface TerminalSubprocessInspector { + ( + terminalPid: number, + ): Effect.Effect; } interface ShellCandidate { @@ -119,6 +128,8 @@ interface TerminalSessionState { unsubscribeData: (() => void) | null; unsubscribeExit: (() => void) | null; hasRunningSubprocess: boolean; + /** Normalized child command name when `hasRunningSubprocess`; cleared when idle. */ + childCommandLabel: string | null; runtimeEnv: Record | null; } @@ -154,6 +165,38 @@ interface TerminalManagerState { killFibers: Map>; } +function truncateTerminalWireLabel(value: string): string { + if (value.length <= MAX_TERMINAL_LABEL_LENGTH) return value; + return value.slice(0, MAX_TERMINAL_LABEL_LENGTH); +} + +function normalizeChildCommandName(raw: string, platform: NodeJS.Platform): string | null { + let trimmed = raw.trim(); + if (trimmed.length === 0) return null; + if ( + (trimmed.startsWith("[") && trimmed.endsWith("]")) || + (trimmed.startsWith("(") && trimmed.endsWith(")")) + ) { + trimmed = trimmed.slice(1, -1).trim(); + } + const firstToken = (trimmed.split(/\s+/)[0] ?? trimmed).trim(); + if (firstToken.length === 0) return null; + const base = platform === "win32" ? path.win32.basename(firstToken) : path.basename(firstToken); + const withoutExe = + platform === "win32" && base.toLowerCase().endsWith(".exe") ? base.slice(0, -4) : base; + return withoutExe.length > 0 ? withoutExe : null; +} + +function terminalWireLabel(session: TerminalSessionState): string { + if (session.hasRunningSubprocess && session.childCommandLabel) { + const trimmed = session.childCommandLabel.trim(); + if (trimmed.length > 0) { + return truncateTerminalWireLabel(trimmed); + } + } + return truncateTerminalWireLabel(getTerminalLabel(session.terminalId)); +} + function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { return { threadId: session.threadId, @@ -165,6 +208,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { history: session.history, exitCode: session.exitCode, exitSignal: session.exitSignal, + label: terminalWireLabel(session), updatedAt: session.updatedAt, sequence: session.eventSequence, }; @@ -181,6 +225,7 @@ function summary(session: TerminalSessionState): TerminalSummary { exitCode: session.exitCode, exitSignal: session.exitSignal, hasRunningSubprocess: session.hasRunningSubprocess, + label: terminalWireLabel(session), updatedAt: session.updatedAt, }; } @@ -426,13 +471,25 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean { ); } -function checkWindowsSubprocessActivity( +function parseFirstChildPidFromPgrep(stdout: string): number | null { + for (const line of stdout.split(/\r?\n/g)) { + const n = Number.parseInt(line.trim(), 10); + if (Number.isInteger(n) && n > 0) { + return n; + } + } + return null; +} + +function windowsInspectSubprocess( terminalPid: number, -): Effect.Effect { + platform: NodeJS.Platform, +): Effect.Effect { const command = [ - `$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`, - "if ($children) { exit 0 }", - "exit 1", + `$c = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue | Select-Object -First 1`, + "if ($null -eq $c) { exit 1 }", + "Write-Output $c.Name", + "exit 0", ].join("; "); return Effect.tryPromise({ try: () => @@ -444,17 +501,33 @@ function checkWindowsSubprocessActivity( }), catch: (cause) => new TerminalSubprocessCheckError({ - message: "Failed to check Windows terminal subprocess activity.", + message: "Failed to inspect Windows terminal subprocesses.", cause, terminalPid, command: "powershell", }), - }).pipe(Effect.map((result) => result.code === 0)); + }).pipe( + Effect.map((result) => { + if (result.code !== 0) { + return { hasRunningSubprocess: false, childCommand: null } as const; + } + const name = result.stdout.trim().split(/\r?\n/)[0]?.trim() ?? ""; + if (name.length === 0) { + return { hasRunningSubprocess: true, childCommand: null } as const; + } + const normalized = normalizeChildCommandName(name, platform); + return { + hasRunningSubprocess: true, + childCommand: normalized ? truncateTerminalWireLabel(normalized) : null, + } as const; + }), + ); } -const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* ( +const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(function* ( terminalPid: number, -): Effect.fn.Return { + platform: NodeJS.Platform, +): Effect.fn.Return { const runPgrep = Effect.tryPromise({ try: () => runProcess("pgrep", ["-P", String(terminalPid)], { @@ -489,44 +562,93 @@ const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessAct }), }); + let childPid: number | null = null; + const pgrepResult = yield* Effect.exit(runPgrep); if (pgrepResult._tag === "Success") { if (pgrepResult.value.code === 0) { - return pgrepResult.value.stdout.trim().length > 0; - } - if (pgrepResult.value.code === 1) { - return false; + childPid = parseFirstChildPidFromPgrep(pgrepResult.value.stdout); + } else if (pgrepResult.value.code === 1) { + return { hasRunningSubprocess: false, childCommand: null }; } } - const psResult = yield* Effect.exit(runPs); - if (psResult._tag === "Failure" || psResult.value.code !== 0) { - return false; - } - - for (const line of psResult.value.stdout.split(/\r?\n/g)) { - const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); - const pid = Number(pidRaw); - const ppid = Number(ppidRaw); - if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; - if (ppid === terminalPid) { - return true; + if (childPid === null) { + const psResult = yield* Effect.exit(runPs); + if (psResult._tag === "Failure" || psResult.value.code !== 0) { + return { hasRunningSubprocess: false, childCommand: null }; + } + for (const line of psResult.value.stdout.split(/\r?\n/g)) { + const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); + const pid = Number(pidRaw); + const ppid = Number(ppidRaw); + if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; + if (ppid === terminalPid) { + childPid = pid; + break; + } } } - return false; + + if (childPid === null) { + return { hasRunningSubprocess: false, childCommand: null }; + } + + const runComm = Effect.tryPromise({ + try: () => + runProcess("ps", ["-p", String(childPid), "-o", "comm="], { + timeoutMs: 1_000, + allowNonZeroExit: true, + maxBufferBytes: 8_192, + outputMode: "truncate", + }), + catch: () => null, + }); + + const commResult = yield* Effect.exit(runComm); + let rawComm: string | null = null; + if (commResult._tag === "Success" && commResult.value && commResult.value.code === 0) { + rawComm = commResult.value.stdout.trim(); + } + + if (!rawComm || rawComm.length === 0) { + const runArgs = Effect.tryPromise({ + try: () => + runProcess("ps", ["-p", String(childPid), "-o", "args="], { + timeoutMs: 1_000, + allowNonZeroExit: true, + maxBufferBytes: 16_384, + outputMode: "truncate", + }), + catch: () => null, + }); + const argsResult = yield* Effect.exit(runArgs); + if (argsResult._tag === "Success" && argsResult.value && argsResult.value.code === 0) { + const first = argsResult.value.stdout.trim().split(/\s+/)[0] ?? ""; + rawComm = first.length > 0 ? first : null; + } + } + + const normalized = rawComm ? normalizeChildCommandName(rawComm, platform) : null; + return { + hasRunningSubprocess: true, + childCommand: normalized ? truncateTerminalWireLabel(normalized) : null, + }; }); -const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* ( - terminalPid: number, -): Effect.fn.Return { - if (!Number.isInteger(terminalPid) || terminalPid <= 0) { - return false; - } - if (process.platform === "win32") { - return yield* checkWindowsSubprocessActivity(terminalPid); - } - return yield* checkPosixSubprocessActivity(terminalPid); -}); +function defaultSubprocessInspectorForPlatform( + platform: NodeJS.Platform, +): TerminalSubprocessInspector { + return Effect.fn("terminal.defaultSubprocessInspector")(function* (terminalPid: number) { + if (!Number.isInteger(terminalPid) || terminalPid <= 0) { + return { hasRunningSubprocess: false, childCommand: null }; + } + if (platform === "win32") { + return yield* windowsInspectSubprocess(terminalPid, platform); + } + return yield* posixInspectSubprocess(terminalPid, platform); + }); +} function capHistory(history: string, maxLines: number): string { if (history.length === 0) return history; @@ -775,7 +897,7 @@ interface TerminalManagerOptions { shellResolver?: () => string; platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; - subprocessChecker?: TerminalSubprocessChecker; + subprocessInspector?: TerminalSubprocessInspector; subprocessPollIntervalMs?: number; processKillGraceMs?: number; maxRetainedInactiveSessions?: number; @@ -801,7 +923,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const platform = options.platform ?? process.platform; const baseEnv = options.env ?? process.env; const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv)); - const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker; + const subprocessInspector = + options.subprocessInspector ?? defaultSubprocessInspectorForPlatform(platform); const subprocessPollIntervalMs = options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS; const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; @@ -1290,6 +1413,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session.process = null; session.pid = null; session.hasRunningSubprocess = false; + session.childCommandLabel = null; session.status = "exited"; session.pendingHistoryControlSequence = ""; session.pendingProcessEvents = []; @@ -1358,6 +1482,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session.process = null; session.pid = null; session.hasRunningSubprocess = false; + session.childCommandLabel = null; session.status = "exited"; session.pendingHistoryControlSequence = ""; session.pendingProcessEvents = []; @@ -1451,6 +1576,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session.exitCode = null; session.exitSignal = null; session.hasRunningSubprocess = false; + session.childCommandLabel = null; session.pendingProcessEvents = []; session.pendingProcessEventIndex = 0; session.processEventDrainRunning = false; @@ -1528,6 +1654,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session.unsubscribeData = null; session.unsubscribeExit = null; session.hasRunningSubprocess = false; + session.childCommandLabel = null; session.pendingProcessEvents = []; session.pendingProcessEventIndex = 0; session.processEventDrainRunning = false; @@ -1608,7 +1735,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session: TerminalSessionState & { pid: number }, ) { const terminalPid = session.pid; - const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe( + const inspectResult = yield* subprocessInspector(terminalPid).pipe( Effect.map(Option.some), Effect.catch((reason) => Effect.logWarning("failed to check terminal subprocess activity", { @@ -1616,14 +1743,17 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith terminalId: session.terminalId, terminalPid, reason, - }).pipe(Effect.as(Option.none())), + }).pipe(Effect.as(Option.none())), ), ); - if (Option.isNone(hasRunningSubprocess)) { + if (Option.isNone(inspectResult)) { return; } + const next = inspectResult.value; + const nextChildLabel = next.hasRunningSubprocess ? next.childCommand : null; + const event = yield* modifyManagerState((state) => { const liveSession: Option.Option = Option.fromNullishOr( state.sessions.get(toSessionKey(session.threadId, session.terminalId)), @@ -1632,12 +1762,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith Option.isNone(liveSession) || liveSession.value.status !== "running" || liveSession.value.pid !== terminalPid || - liveSession.value.hasRunningSubprocess === hasRunningSubprocess.value + (liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess && + liveSession.value.childCommandLabel === nextChildLabel) ) { return [Option.none(), state] as const; } - liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value; + liveSession.value.hasRunningSubprocess = next.hasRunningSubprocess; + liveSession.value.childCommandLabel = nextChildLabel; const eventStamp = advanceEventSequence(liveSession.value); return [ @@ -1646,7 +1778,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: liveSession.value.threadId, terminalId: liveSession.value.terminalId, sequence: eventStamp.sequence, - hasRunningSubprocess: hasRunningSubprocess.value, + hasRunningSubprocess: next.hasRunningSubprocess, + label: terminalWireLabel(liveSession.value), }), state, ] as const; @@ -1711,7 +1844,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith ); const openLocked = Effect.fn("terminal.openLocked")(function* (input: TerminalOpenInput) { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const terminalId = input.terminalId; yield* assertValidCwd(input.cwd); const sessionKey = toSessionKey(input.threadId, terminalId); @@ -1743,6 +1876,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith unsubscribeData: null, unsubscribeExit: null, hasRunningSubprocess: false, + childCommandLabel: null, runtimeEnv: normalizedRuntimeEnv(input.env), }; @@ -1839,7 +1973,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith withThreadLock( input.threadId, Effect.gen(function* () { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const terminalId = input.terminalId; const existing = yield* getSession(input.threadId, terminalId); if (Option.isNone(existing)) { @@ -1918,10 +2052,12 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith let unsubscribe: (() => void) | null = null; return Effect.gen(function* () { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; const bufferedEvents: TerminalEvent[] = []; let deliverLive = false; + const initialSnapshot = yield* openOrAttachForStream(input); + const terminalId = initialSnapshot.terminalId; + unsubscribe = yield* subscribe((event) => { if (event.threadId !== input.threadId || event.terminalId !== terminalId) { return Effect.void; @@ -1936,7 +2072,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith return attachEvent ? listener(attachEvent) : Effect.void; }); - const initialSnapshot = yield* openOrAttachForStream(input); yield* listener({ type: "snapshot", snapshot: initialSnapshot, @@ -2044,7 +2179,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith }; const write: TerminalManagerShape["write"] = Effect.fn("terminal.write")(function* (input) { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const terminalId = input.terminalId; const session = yield* requireSession(input.threadId, terminalId); const process = session.process; if (!process || session.status !== "running") { @@ -2058,7 +2193,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith }); const resize: TerminalManagerShape["resize"] = Effect.fn("terminal.resize")(function* (input) { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const terminalId = input.terminalId; const session = yield* requireSession(input.threadId, terminalId); const process = session.process; if (!process || session.status !== "running") { @@ -2077,7 +2212,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith withThreadLock( input.threadId, Effect.gen(function* () { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const terminalId = input.terminalId; const session = yield* requireSession(input.threadId, terminalId); session.history = ""; session.pendingHistoryControlSequence = ""; @@ -2100,7 +2235,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith input.threadId, Effect.gen(function* () { yield* increment(terminalRestartsTotal, { scope: "thread" }); - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const terminalId = input.terminalId; yield* assertValidCwd(input.cwd); const sessionKey = toSessionKey(input.threadId, terminalId); @@ -2131,6 +2266,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith unsubscribeData: null, unsubscribeExit: null, hasRunningSubprocess: false, + childCommandLabel: null, runtimeEnv: normalizedRuntimeEnv(input.env), }; const createdSession = session; diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index c38419fd38..48ba6c4483 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -993,6 +993,7 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown { history: "", exitCode: null, exitSignal: null, + label: "Terminal 1", updatedAt: NOW_ISO, }; } @@ -1767,6 +1768,26 @@ describe("ChatView timeline estimator parity (full app)", () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, snapshot, + configureFixture: (nextFixture) => { + nextFixture.terminalMetadataEvents = [ + { + type: "upsert", + terminal: { + threadId: THREAD_ID, + terminalId: DEFAULT_TERMINAL_ID, + cwd: "/repo/project", + worktreePath: null, + status: "running", + pid: 123, + exitCode: null, + exitSignal: null, + hasRunningSubprocess: false, + label: "Terminal 1", + updatedAt: isoAt(0), + }, + }, + ]; + }, }); try { @@ -3550,6 +3571,7 @@ describe("ChatView timeline estimator parity (full app)", () => { exitCode: null, exitSignal: null, hasRunningSubprocess: true, + label: "Terminal 1", updatedAt: isoAt(1_200), }, }, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 8755f9f3e5..1245562fb9 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -29,6 +29,7 @@ import { import { applyClaudePromptEffortPrefix, createModelSelection } from "@t3tools/shared/model"; import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; import { truncate } from "@t3tools/shared/String"; +import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels"; import { Debouncer } from "@tanstack/react-pacer"; import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useNavigate, useSearch } from "@tanstack/react-router"; @@ -100,7 +101,7 @@ import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings" import PlanSidebar from "./PlanSidebar"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; import { ChevronDownIcon } from "lucide-react"; -import { cn, randomUUID } from "~/lib/utils"; +import { cn } from "~/lib/utils"; import { toastManager } from "./ui/toast"; import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings"; import { type NewProjectScriptInput } from "./ProjectScriptsControl"; @@ -133,7 +134,7 @@ import { type TerminalContextSelection, } from "../lib/terminalContext"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; -import { useThreadRunningTerminalIds } from "../terminalSessionState"; +import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../terminalSessionState"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; @@ -408,6 +409,45 @@ function useLocalDispatchState(input: { }; } +/** Same terminal ids (order ignored) — avoids reconcile when only server session ordering differs. */ +function terminalIdListsEqual(left: readonly string[], right: readonly string[]): boolean { + if (left.length !== right.length) { + return false; + } + if (left.length === 0) { + return true; + } + const sortedLeft = [...left].sort((a, b) => a.localeCompare(b)); + const sortedRight = [...right].sort((a, b) => a.localeCompare(b)); + for (let index = 0; index < sortedLeft.length; index += 1) { + if (sortedLeft[index] !== sortedRight[index]) { + return false; + } + } + return true; +} + +/** + * Server knows about fewer sessions than the client, but every server id still exists locally. + * Typical right after `terminal.open`: known-session list lags; reconciling would drop the new id + * and later re-add it as a separate group (no split layout). + */ +function serverTerminalIdsStrictSubsetOfClient( + serverIds: readonly string[], + clientIds: readonly string[], +): boolean { + if (serverIds.length >= clientIds.length || clientIds.length === 0) { + return false; + } + const clientSet = new Set(clientIds); + for (const id of serverIds) { + if (!clientSet.has(id)) { + return false; + } + } + return true; +} + interface PersistentThreadTerminalDrawerProps { threadRef: { environmentId: EnvironmentId; threadId: ThreadId }; threadId: ThreadId; @@ -444,11 +484,42 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra const terminalUiState = useTerminalUiStateStore((state) => selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef), ); + const knownTerminalSessions = useKnownTerminalSessions({ + environmentId: threadRef.environmentId, + threadId, + }); + const terminalLabelsById = useMemo(() => { + const next = new Map(); + for (const session of knownTerminalSessions) { + next.set( + session.target.terminalId, + resolveTerminalSessionLabel(session.target.terminalId, session.state.summary), + ); + } + return next; + }, [knownTerminalSessions]); + const serverOrderedTerminalIds = useMemo( + () => knownTerminalSessions.map((session) => session.target.terminalId), + [knownTerminalSessions], + ); const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight); const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal); const storeNewTerminal = useTerminalUiStateStore((state) => state.newTerminal); const storeSetActiveTerminal = useTerminalUiStateStore((state) => state.setActiveTerminal); const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal); + const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds); + + useEffect(() => { + if (terminalIdListsEqual(serverOrderedTerminalIds, terminalUiState.terminalIds)) { + return; + } + if ( + serverTerminalIdsStrictSubsetOfClient(serverOrderedTerminalIds, terminalUiState.terminalIds) + ) { + return; + } + reconcileTerminalIds(threadRef, serverOrderedTerminalIds); + }, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]); const [localFocusRequestId, setLocalFocusRequestId] = useState(0); const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; const effectiveWorktreePath = useMemo(() => { @@ -494,14 +565,68 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra ); const splitTerminal = useCallback(() => { - storeSplitTerminal(threadRef, `terminal-${randomUUID()}`); + const api = readEnvironmentApi(threadRef.environmentId); + if (!api || !cwd) { + return; + } + const terminalId = nextTerminalId(serverOrderedTerminalIds); + storeSplitTerminal(threadRef, terminalId); bumpFocusRequestId(); - }, [bumpFocusRequestId, storeSplitTerminal, threadRef]); + void (async () => { + try { + await api.terminal.open({ + threadId, + terminalId, + cwd, + ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}), + env: runtimeEnv, + }); + } catch { + // Opening failed; the tab is already in the store — user can retry or close it. + } + })(); + }, [ + bumpFocusRequestId, + cwd, + effectiveWorktreePath, + runtimeEnv, + serverOrderedTerminalIds, + storeSplitTerminal, + threadId, + threadRef, + ]); const createNewTerminal = useCallback(() => { - storeNewTerminal(threadRef, `terminal-${randomUUID()}`); + const api = readEnvironmentApi(threadRef.environmentId); + if (!api || !cwd) { + return; + } + const terminalId = nextTerminalId(serverOrderedTerminalIds); + storeNewTerminal(threadRef, terminalId); bumpFocusRequestId(); - }, [bumpFocusRequestId, storeNewTerminal, threadRef]); + void (async () => { + try { + await api.terminal.open({ + threadId, + terminalId, + cwd, + ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}), + env: runtimeEnv, + }); + } catch { + // Opening failed; the tab is already in the store — user can retry or close it. + } + })(); + }, [ + bumpFocusRequestId, + cwd, + effectiveWorktreePath, + runtimeEnv, + serverOrderedTerminalIds, + storeNewTerminal, + threadId, + threadRef, + ]); const activateTerminal = useCallback( (terminalId: string) => { @@ -537,13 +662,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra storeCloseTerminal(threadRef, terminalId); bumpFocusRequestId(); }, - [ - bumpFocusRequestId, - storeCloseTerminal, - terminalUiState.terminalIds.length, - threadId, - threadRef, - ], + [bumpFocusRequestId, storeCloseTerminal, terminalUiState.terminalIds, threadId, threadRef], ); const handleAddTerminalContext = useCallback( @@ -570,6 +689,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra runtimeEnv={runtimeEnv} visible={visible} height={terminalUiState.terminalHeight} + // Known-session order is MRU and changes on focus; persisted store order keeps sidebar labels stable. terminalIds={terminalUiState.terminalIds} activeTerminalId={terminalUiState.activeTerminalId} terminalGroups={terminalUiState.terminalGroups} @@ -585,6 +705,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra onCloseTerminal={closeTerminal} onHeightChange={setTerminalHeight} onAddTerminalContext={handleAddTerminalContext} + terminalLabelsById={terminalLabelsById} /> ); @@ -797,11 +918,52 @@ export default function ChatView(props: ChatViewProps) { environmentId: activeThread?.environmentId ?? null, threadId: activeThreadId, }); + const activeThreadKnownSessionsRaw = useKnownTerminalSessions({ + environmentId: activeThread?.environmentId ?? null, + threadId: activeThreadId, + }); + const activeThreadKnownSessions = useMemo(() => { + if (activeThreadId === null) { + return []; + } + return activeThreadKnownSessionsRaw.filter( + (session) => session.target.threadId === activeThreadId, + ); + }, [activeThreadId, activeThreadKnownSessionsRaw]); + const activeServerOrderedTerminalIds = useMemo( + () => activeThreadKnownSessions.map((session) => session.target.terminalId), + [activeThreadKnownSessions], + ); + const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds); const activeThreadRef = useMemo( () => (activeThread ? scopeThreadRef(activeThread.environmentId, activeThread.id) : null), [activeThread], ); const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null; + + useEffect(() => { + if (!activeThreadRef) { + return; + } + if (terminalIdListsEqual(activeServerOrderedTerminalIds, terminalUiState.terminalIds)) { + return; + } + if ( + serverTerminalIdsStrictSubsetOfClient( + activeServerOrderedTerminalIds, + terminalUiState.terminalIds, + ) + ) { + return; + } + reconcileTerminalIds(activeThreadRef, activeServerOrderedTerminalIds); + }, [ + activeThreadRef, + activeServerOrderedTerminalIds, + reconcileTerminalIds, + terminalUiState.terminalIds, + ]); + const existingOpenTerminalThreadKeys = useMemo(() => { const existingThreadKeys = new Set([...serverThreadKeys, ...draftThreadKeys]); return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey)); @@ -1581,22 +1743,93 @@ export default function ChatView(props: ChatViewProps) { setTerminalOpen(!terminalUiState.terminalOpen); }, [activeThreadRef, setTerminalOpen, terminalUiState.terminalOpen]); const splitTerminal = useCallback(() => { - if (!activeThreadRef || hasReachedSplitLimit) return; - const terminalId = `terminal-${randomUUID()}`; + if (!activeThreadRef || hasReachedSplitLimit || !activeThreadId || !activeProject) { + return; + } + const cwdForOpen = gitCwd ?? activeProject.cwd; + if (!cwdForOpen) { + return; + } + const api = readEnvironmentApi(environmentId); + if (!api) { + return; + } + const terminalId = nextTerminalId(activeServerOrderedTerminalIds); storeSplitTerminal(activeThreadRef, terminalId); setTerminalFocusRequestId((value) => value + 1); - }, [activeThreadRef, hasReachedSplitLimit, storeSplitTerminal]); + void (async () => { + try { + await api.terminal.open({ + threadId: activeThreadId, + terminalId, + cwd: cwdForOpen, + ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), + env: projectScriptRuntimeEnv({ + project: { cwd: activeProject.cwd }, + worktreePath: activeThreadWorktreePath, + }), + }); + } catch { + // Opening failed; the tab is already in the store — user can retry or close it. + } + })(); + }, [ + activeProject, + activeServerOrderedTerminalIds, + activeThreadId, + activeThreadRef, + activeThreadWorktreePath, + environmentId, + gitCwd, + hasReachedSplitLimit, + storeSplitTerminal, + ]); const createNewTerminal = useCallback(() => { - if (!activeThreadRef) return; - const terminalId = `terminal-${randomUUID()}`; + if (!activeThreadRef || !activeThreadId || !activeProject) { + return; + } + const cwdForOpen = gitCwd ?? activeProject.cwd; + if (!cwdForOpen) { + return; + } + const api = readEnvironmentApi(environmentId); + if (!api) { + return; + } + const terminalId = nextTerminalId(activeServerOrderedTerminalIds); storeNewTerminal(activeThreadRef, terminalId); setTerminalFocusRequestId((value) => value + 1); - }, [activeThreadRef, storeNewTerminal]); + void (async () => { + try { + await api.terminal.open({ + threadId: activeThreadId, + terminalId, + cwd: cwdForOpen, + ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), + env: projectScriptRuntimeEnv({ + project: { cwd: activeProject.cwd }, + worktreePath: activeThreadWorktreePath, + }), + }); + } catch { + // Opening failed; the tab is already in the store — user can retry or close it. + } + })(); + }, [ + activeProject, + activeServerOrderedTerminalIds, + activeThreadId, + activeThreadRef, + activeThreadWorktreePath, + environmentId, + gitCwd, + storeNewTerminal, + ]); const closeTerminal = useCallback( (terminalId: string) => { const api = readEnvironmentApi(environmentId); - if (!activeThreadId || !api) return; - const isFinalTerminal = terminalUiState.terminalIds.length <= 1; + if (!activeThreadId || !api || !activeThreadRef) return; + const isFinalTerminal = activeServerOrderedTerminalIds.length <= 1; const fallbackExitWrite = () => api.terminal .write({ threadId: activeThreadId, terminalId, data: "exit\n" }) @@ -1617,17 +1850,15 @@ export default function ChatView(props: ChatViewProps) { } else { void fallbackExitWrite(); } - if (activeThreadRef) { - storeCloseTerminal(activeThreadRef, terminalId); - } + storeCloseTerminal(activeThreadRef, terminalId); setTerminalFocusRequestId((value) => value + 1); }, [ activeThreadId, activeThreadRef, + activeServerOrderedTerminalIds, environmentId, storeCloseTerminal, - terminalUiState.terminalIds.length, ], ); const runProjectScript = useCallback( @@ -1652,14 +1883,11 @@ export default function ChatView(props: ChatViewProps) { const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd; const baseTerminalId = terminalUiState.activeTerminalId || - terminalUiState.terminalIds[0] || + activeServerOrderedTerminalIds[0] || DEFAULT_THREAD_TERMINAL_ID; const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId); const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy; const shouldCreateNewTerminal = wantsNewTerminal; - const targetTerminalId = shouldCreateNewTerminal - ? `terminal-${randomUUID()}` - : baseTerminalId; const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null; setTerminalUiLaunchContext({ @@ -1671,11 +1899,6 @@ export default function ChatView(props: ChatViewProps) { if (!activeThreadRef) { return; } - if (shouldCreateNewTerminal) { - storeNewTerminal(activeThreadRef, targetTerminalId); - } else { - storeSetActiveTerminal(activeThreadRef, targetTerminalId); - } setTerminalFocusRequestId((value) => value + 1); const runtimeEnv = projectScriptRuntimeEnv({ @@ -1685,6 +1908,9 @@ export default function ChatView(props: ChatViewProps) { worktreePath: targetWorktreePath, ...(options?.env ? { extraEnv: options.env } : {}), }); + const targetTerminalId = shouldCreateNewTerminal + ? nextTerminalId(activeServerOrderedTerminalIds) + : baseTerminalId; const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal ? { threadId: activeThreadId, @@ -1703,6 +1929,12 @@ export default function ChatView(props: ChatViewProps) { env: runtimeEnv, }; + if (shouldCreateNewTerminal) { + storeNewTerminal(activeThreadRef, targetTerminalId); + } else { + storeSetActiveTerminal(activeThreadRef, targetTerminalId); + } + try { await api.terminal.open(openTerminalInput); await api.terminal.write({ @@ -1729,9 +1961,9 @@ export default function ChatView(props: ChatViewProps) { storeSetActiveTerminal, setLastInvokedScriptByProjectId, environmentId, + activeServerOrderedTerminalIds, runningTerminalIds, terminalUiState.activeTerminalId, - terminalUiState.terminalIds, ], ); diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx index 2df2e04f5c..626393764d 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx @@ -128,7 +128,7 @@ function createEnvironmentApi() { terminal: { open: vi.fn(async () => ({ threadId: THREAD_ID, - terminalId: "default", + terminalId: "term-1", cwd: "/repo/project", worktreePath: null, status: "running" as const, @@ -136,6 +136,7 @@ function createEnvironmentApi() { history: "", exitCode: null, exitSignal: null, + label: "Terminal 1", updatedAt: "2026-04-07T00:00:00.000Z", })), write: vi.fn(async () => undefined), @@ -168,7 +169,7 @@ async function mountTerminalViewport(props: { undefined} @@ -188,7 +189,7 @@ async function mountTerminalViewport(props: { undefined} diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 02d19509cd..0e8d67234c 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -7,6 +7,7 @@ import { type TerminalSessionSnapshot, type ThreadId, } from "@t3tools/contracts"; +import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; import { Terminal, type ITheme } from "@xterm/xterm"; import { type PointerEvent as ReactPointerEvent, @@ -41,7 +42,6 @@ import { } from "../keybindings"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, - DEFAULT_THREAD_TERMINAL_ID, MAX_TERMINALS_PER_GROUP, type ThreadTerminalGroup, } from "../types"; @@ -763,6 +763,8 @@ interface ThreadTerminalDrawerProps { onHeightChange: (height: number) => void; onAddTerminalContext: (selection: TerminalContextSelection) => void; keybindings: ResolvedKeybindingsConfig; + /** Prefer server-provided tab titles when present (e.g. active subprocess name). */ + terminalLabelsById?: ReadonlyMap; } interface TerminalActionButtonProps { @@ -817,6 +819,7 @@ export default function ThreadTerminalDrawer({ onHeightChange, onAddTerminalContext, keybindings, + terminalLabelsById, }: ThreadTerminalDrawerProps) { const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height)); const [resizeEpoch, setResizeEpoch] = useState(0); @@ -831,15 +834,20 @@ export default function ThreadTerminalDrawer({ const didResizeDuringDragRef = useRef(false); const normalizedTerminalIds = useMemo(() => { - const cleaned = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))]; - return cleaned.length > 0 ? cleaned : [DEFAULT_THREAD_TERMINAL_ID]; + return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))]; }, [terminalIds]); - const resolvedActiveTerminalId = normalizedTerminalIds.includes(activeTerminalId) - ? activeTerminalId - : (normalizedTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID); + const resolvedActiveTerminalId = + normalizedTerminalIds.length === 0 + ? "" + : normalizedTerminalIds.includes(activeTerminalId) + ? activeTerminalId + : (normalizedTerminalIds[0] ?? ""); const resolvedTerminalGroups = useMemo(() => { + if (normalizedTerminalIds.length === 0) { + return []; + } const validTerminalIdSet = new Set(normalizedTerminalIds); const assignedTerminalIds = new Set(); const usedGroupIds = new Set(); @@ -876,7 +884,7 @@ export default function ThreadTerminalDrawer({ const baseGroupId = terminalGroup.id.trim().length > 0 ? terminalGroup.id.trim() - : `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`; + : `group-${nextTerminalIds[0] ?? normalizedTerminalIds[0] ?? ""}`; nextGroups.push({ id: assignUniqueGroupId(baseGroupId), terminalIds: nextTerminalIds, @@ -891,17 +899,17 @@ export default function ThreadTerminalDrawer({ }); } - if (nextGroups.length > 0) { - return nextGroups; - } + const terminalOrderIndex = new Map( + normalizedTerminalIds.map((id, index) => [id, index] as const), + ); + nextGroups.sort((left, right) => { + const rank = (ids: readonly string[]) => + Math.min(...ids.map((id) => terminalOrderIndex.get(id) ?? Number.POSITIVE_INFINITY)); + return rank(left.terminalIds) - rank(right.terminalIds); + }); - return [ - { - id: `group-${resolvedActiveTerminalId}`, - terminalIds: [resolvedActiveTerminalId], - }, - ]; - }, [normalizedTerminalIds, resolvedActiveTerminalId, terminalGroups]); + return nextGroups; + }, [normalizedTerminalIds, terminalGroups]); const resolvedActiveGroupIndex = useMemo(() => { const indexById = resolvedTerminalGroups.findIndex( @@ -914,22 +922,22 @@ export default function ThreadTerminalDrawer({ return indexByTerminal >= 0 ? indexByTerminal : 0; }, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]); - const visibleTerminalIds = resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [ - resolvedActiveTerminalId, - ]; + const visibleTerminalIds = + resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? + (normalizedTerminalIds.length > 0 ? [resolvedActiveTerminalId] : []); const hasTerminalSidebar = normalizedTerminalIds.length > 1; const isSplitView = visibleTerminalIds.length > 1; const showGroupHeaders = resolvedTerminalGroups.length > 1 || resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1); const hasReachedSplitLimit = visibleTerminalIds.length >= MAX_TERMINALS_PER_GROUP; - const terminalLabelById = useMemo( - () => - new Map( - normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]), - ), - [normalizedTerminalIds], - ); + const terminalLabelById = useMemo(() => { + const next = new Map(); + for (const terminalId of normalizedTerminalIds) { + next.set(terminalId, terminalLabelsById?.get(terminalId) ?? getTerminalLabel(terminalId)); + } + return next; + }, [normalizedTerminalIds, terminalLabelsById]); const splitTerminalActionLabel = hasReachedSplitLimit ? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)` : splitShortcutLabel @@ -1051,6 +1059,33 @@ export default function ThreadTerminalDrawer({ }; }, [syncHeight]); + if (normalizedTerminalIds.length === 0) { + return ( + + ); + } + return (