terminals
This commit is contained in:
1 parent
cace5784c3
commit
4e38d93a8f
36 files changed
+1434
-417
No files matched your search
@@ -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<TerminalInputEvent>) => {
|
||||
onInput(event.nativeEvent.data);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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>,
|
||||
): 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<ReturnType<typeof setTimeout> | null>(null);
|
||||
const attachStreamLogCountRef = useRef(0);
|
||||
const firstNonEmptyBufferLoggedRef = useRef(false);
|
||||
const lastBufferReplayKeyRef = useRef<string | null>(null);
|
||||
const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(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(" · ")}
|
||||
>
|
||||
<Stack.Toolbar.Label>{getTerminalLabel(session.terminalId)}</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
|
||||
@@ -12,7 +12,7 @@ describe("terminalBufferReplay", () => {
|
||||
).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",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<string, unknown>): void {
|
||||
if (!isTerminalDebugEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (data !== undefined) {
|
||||
console.log(`[t3-terminal] ${message}`, data);
|
||||
} else {
|
||||
console.log(`[t3-terminal] ${message}`);
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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>): 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<string>;
|
||||
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<TerminalMenuSession> {
|
||||
const sessionsById = new Map<string, TerminalMenuSession>();
|
||||
|
||||
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: {
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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: {
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu icon="terminal" disabled={!props.canOpenTerminal} separateBackground>
|
||||
{props.projectScripts.length > 0 ? (
|
||||
<Stack.Toolbar.Menu icon="play" inline title="Project scripts">
|
||||
<Stack.Toolbar.Label>Project scripts</Stack.Toolbar.Label>
|
||||
{props.projectScripts.map((script) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={script.id}
|
||||
icon={projectScriptMenuIcon(script.icon)}
|
||||
onPress={() => void props.onRunProjectScript(script)}
|
||||
subtitle={script.command}
|
||||
>
|
||||
<Stack.Toolbar.Label>{projectScriptMenuLabel(script)}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
props.projectScripts.map((script) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={script.id}
|
||||
icon={projectScriptMenuIcon(script.icon)}
|
||||
onPress={() => void props.onRunProjectScript(script)}
|
||||
subtitle={script.command}
|
||||
>
|
||||
<Stack.Toolbar.Label>{projectScriptMenuLabel(script)}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))
|
||||
) : (
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="play"
|
||||
@@ -206,34 +202,31 @@ export function ThreadGitControls(props: {
|
||||
<Stack.Toolbar.Label>No project scripts</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
)}
|
||||
<Stack.Toolbar.Menu icon="terminal" inline title="Terminals">
|
||||
<Stack.Toolbar.Label>Terminals</Stack.Toolbar.Label>
|
||||
{props.terminalSessions.map((session) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={session.terminalId}
|
||||
icon="terminal"
|
||||
onPress={() => props.onOpenTerminal(session.terminalId)}
|
||||
subtitle={[
|
||||
getTerminalStatusLabel({
|
||||
status: session.status,
|
||||
hasRunningSubprocess: session.hasRunningSubprocess,
|
||||
}),
|
||||
basename(session.cwd),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Stack.Toolbar.Label>{getTerminalLabel(session.terminalId)}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
{props.terminalSessions.map((session) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="plus"
|
||||
onPress={props.onOpenNewTerminal}
|
||||
subtitle="Start another shell for this thread"
|
||||
key={session.terminalId}
|
||||
icon="terminal"
|
||||
onPress={() => props.onOpenTerminal(session.terminalId)}
|
||||
subtitle={[
|
||||
getTerminalStatusLabel({
|
||||
status: session.status,
|
||||
hasRunningSubprocess: session.hasRunningSubprocess,
|
||||
}),
|
||||
basename(session.cwd),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="plus"
|
||||
onPress={props.onOpenNewTerminal}
|
||||
subtitle="Start another shell for this thread"
|
||||
>
|
||||
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
<Stack.Toolbar.Menu icon="point.topleft.down.curvedto.point.bottomright.up">
|
||||
<Stack.Toolbar.MenuAction
|
||||
|
||||
@@ -12,7 +12,7 @@ import { dismissGitActionResult, useGitActionProgress } from "../../state/use-gi
|
||||
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { buildThreadRoutePath, buildThreadTerminalRoutePath } from "../../lib/routes";
|
||||
import { buildThreadRoutePath, buildThreadTerminalNavigation } from "../../lib/routes";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { connectionTone } from "../connection/connectionTone";
|
||||
|
||||
@@ -27,13 +27,14 @@ import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
|
||||
import {
|
||||
buildTerminalMenuSessions,
|
||||
nextTerminalId,
|
||||
nextOpenTerminalId,
|
||||
resolveProjectScriptTerminalId,
|
||||
} from "../terminal/terminalMenu";
|
||||
import {
|
||||
resolvePreferredThreadWorktreePath,
|
||||
stagePendingTerminalLaunch,
|
||||
} from "../terminal/terminalLaunchContext";
|
||||
import { terminalDebugLog } from "../terminal/terminalDebugLog";
|
||||
import { ThreadDetailScreen } from "./ThreadDetailScreen";
|
||||
import { ThreadGitControls } from "./ThreadGitControls";
|
||||
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
|
||||
@@ -145,27 +146,52 @@ export function ThreadRouteScreen() {
|
||||
|
||||
const handleOpenTerminal = useCallback(
|
||||
(nextTerminalId?: string | null) => {
|
||||
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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<typeof terminalSessionManager.attach>[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 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -91,6 +91,7 @@ describe("ProjectSetupScriptRunner", () => {
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
label: "setup-setup",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -3929,6 +3929,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
label: "Primary",
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
|
||||
@@ -198,7 +198,10 @@ interface CreateManagerOptions {
|
||||
shellResolver?: () => string;
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
subprocessChecker?: (terminalPid: number) => Effect.Effect<boolean>;
|
||||
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,
|
||||
});
|
||||
|
||||
@@ -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>()(
|
||||
"TerminalSubprocessCheckError",
|
||||
@@ -78,8 +80,15 @@ class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcess
|
||||
},
|
||||
) {}
|
||||
|
||||
interface TerminalSubprocessChecker {
|
||||
(terminalPid: number): Effect.Effect<boolean, TerminalSubprocessCheckError>;
|
||||
interface TerminalSubprocessInspectResult {
|
||||
readonly hasRunningSubprocess: boolean;
|
||||
readonly childCommand: string | null;
|
||||
}
|
||||
|
||||
interface TerminalSubprocessInspector {
|
||||
(
|
||||
terminalPid: number,
|
||||
): Effect.Effect<TerminalSubprocessInspectResult, TerminalSubprocessCheckError>;
|
||||
}
|
||||
|
||||
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<string, string> | null;
|
||||
}
|
||||
|
||||
@@ -154,6 +165,38 @@ interface TerminalManagerState {
|
||||
killFibers: Map<PtyProcess, Fiber.Fiber<void, never>>;
|
||||
}
|
||||
|
||||
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<boolean, TerminalSubprocessCheckError> {
|
||||
platform: NodeJS.Platform,
|
||||
): Effect.Effect<TerminalSubprocessInspectResult, TerminalSubprocessCheckError> {
|
||||
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<boolean, TerminalSubprocessCheckError> {
|
||||
platform: NodeJS.Platform,
|
||||
): Effect.fn.Return<TerminalSubprocessInspectResult, TerminalSubprocessCheckError> {
|
||||
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<boolean, TerminalSubprocessCheckError> {
|
||||
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<boolean>())),
|
||||
}).pipe(Effect.as(Option.none<TerminalSubprocessInspectResult>())),
|
||||
),
|
||||
);
|
||||
|
||||
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<TerminalSessionState> = 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;
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -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<string, string>();
|
||||
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}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -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<string>([...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,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -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: {
|
||||
<TerminalViewport
|
||||
threadRef={props.threadRef}
|
||||
threadId={THREAD_ID}
|
||||
terminalId="default"
|
||||
terminalId="term-1"
|
||||
terminalLabel="Terminal"
|
||||
cwd="/repo/project"
|
||||
onSessionExited={() => undefined}
|
||||
@@ -188,7 +189,7 @@ async function mountTerminalViewport(props: {
|
||||
<TerminalViewport
|
||||
threadRef={nextProps.threadRef}
|
||||
threadId={THREAD_ID}
|
||||
terminalId="default"
|
||||
terminalId="term-1"
|
||||
terminalLabel="Terminal"
|
||||
cwd="/repo/project"
|
||||
onSessionExited={() => undefined}
|
||||
|
||||
@@ -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<string, string>;
|
||||
}
|
||||
|
||||
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<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
@@ -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<string, string>();
|
||||
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 (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
style={{ height: `${drawerHeight}px` }}
|
||||
>
|
||||
<div
|
||||
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
|
||||
onPointerDown={handleResizePointerDown}
|
||||
onPointerMove={handleResizePointerMove}
|
||||
onPointerUp={handleResizePointerEnd}
|
||||
onPointerCancel={handleResizePointerEnd}
|
||||
/>
|
||||
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 px-4 py-6 text-center text-sm text-muted-foreground">
|
||||
<p>No terminal sessions for this thread yet.</p>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-border/80 bg-background px-3 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent"
|
||||
onClick={onNewTerminalAction}
|
||||
>
|
||||
{newTerminalActionLabel}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
@@ -1216,9 +1251,7 @@ export default function ThreadTerminalDrawer({
|
||||
}`}
|
||||
onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
|
||||
>
|
||||
{terminalGroup.terminalIds.length > 1
|
||||
? `Split ${groupIndex + 1}`
|
||||
: `Terminal ${groupIndex + 1}`}
|
||||
Group {groupIndex + 1}
|
||||
</button>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import type { WsRpcClient } from "@t3tools/client-runtime";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
@@ -67,6 +68,70 @@ vi.mock("../../rpc/wsRpcClient", () => ({
|
||||
createWsRpcClient: mockCreateWsRpcClient,
|
||||
}));
|
||||
|
||||
vi.mock("@t3tools/client-runtime", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@t3tools/client-runtime")>();
|
||||
const stubWsClient: WsRpcClient = {
|
||||
dispose: async () => undefined,
|
||||
reconnect: async () => undefined,
|
||||
orchestration: {
|
||||
dispatchCommand: vi.fn(),
|
||||
getTurnDiff: vi.fn(),
|
||||
getFullThreadDiff: vi.fn(),
|
||||
subscribeShell: vi.fn(() => () => undefined),
|
||||
subscribeThread: mockSubscribeThread,
|
||||
},
|
||||
terminal: {
|
||||
open: vi.fn(),
|
||||
attach: vi.fn(() => () => undefined),
|
||||
write: vi.fn(),
|
||||
resize: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
restart: vi.fn(),
|
||||
close: vi.fn(),
|
||||
onMetadata: vi.fn(() => () => undefined),
|
||||
},
|
||||
projects: {
|
||||
searchEntries: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
},
|
||||
filesystem: {
|
||||
browse: vi.fn(),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: vi.fn(),
|
||||
},
|
||||
git: {
|
||||
pull: vi.fn(),
|
||||
refreshStatus: vi.fn(),
|
||||
onStatus: vi.fn(() => () => undefined),
|
||||
runStackedAction: vi.fn(),
|
||||
listBranches: vi.fn(),
|
||||
createWorktree: vi.fn(),
|
||||
removeWorktree: vi.fn(),
|
||||
createBranch: vi.fn(),
|
||||
checkout: vi.fn(),
|
||||
init: vi.fn(),
|
||||
resolvePullRequest: vi.fn(),
|
||||
preparePullRequestThread: vi.fn(),
|
||||
getReviewDiffs: vi.fn(),
|
||||
},
|
||||
server: {
|
||||
getConfig: vi.fn(),
|
||||
refreshProviders: vi.fn(),
|
||||
upsertKeybinding: vi.fn(),
|
||||
getSettings: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
subscribeConfig: vi.fn(() => () => undefined),
|
||||
subscribeLifecycle: vi.fn(() => () => undefined),
|
||||
subscribeAuthAccess: vi.fn(() => () => undefined),
|
||||
},
|
||||
};
|
||||
return {
|
||||
...actual,
|
||||
createWsRpcClient: vi.fn(() => stubWsClient),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../rpc/wsTransport", () => ({
|
||||
WsTransport: MockWsTransport,
|
||||
}));
|
||||
|
||||
@@ -11,7 +11,13 @@ class MockHTMLElement {
|
||||
};
|
||||
|
||||
closest(selector: string): MockHTMLElement | null {
|
||||
return selector === ".thread-terminal-drawer .xterm" && this.isConnected ? this : null;
|
||||
if (!this.isConnected) {
|
||||
return null;
|
||||
}
|
||||
if (selector === ".thread-terminal-drawer .xterm" || selector === ".thread-terminal-drawer") {
|
||||
return this;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,4 +59,15 @@ describe("isTerminalFocused", () => {
|
||||
|
||||
expect(isTerminalFocused()).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for focus inside the terminal drawer (e.g. sidebar)", () => {
|
||||
const sidebarButton = new MockHTMLElement();
|
||||
sidebarButton.className = "terminal-sidebar-button";
|
||||
sidebarButton.isConnected = true;
|
||||
|
||||
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
|
||||
globalThis.document = { activeElement: sidebarButton } as Document;
|
||||
|
||||
expect(isTerminalFocused()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -3,5 +3,7 @@ export function isTerminalFocused(): boolean {
|
||||
if (!(activeElement instanceof HTMLElement)) return false;
|
||||
if (!activeElement.isConnected) return false;
|
||||
if (activeElement.classList.contains("xterm-helper-textarea")) return true;
|
||||
return activeElement.closest(".thread-terminal-drawer .xterm") !== null;
|
||||
if (activeElement.closest(".thread-terminal-drawer .xterm") !== null) return true;
|
||||
// Sidebar / toolbar / resize affordances: still "terminal UI" for split vs diff.toggle (⌘D).
|
||||
return activeElement.closest(".thread-terminal-drawer") !== null;
|
||||
}
|
||||
@@ -341,6 +341,7 @@ describe("wsApi", () => {
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
hasRunningSubprocess: true,
|
||||
label: "terminal-1",
|
||||
updatedAt: "2026-02-24T00:00:00.000Z",
|
||||
},
|
||||
} satisfies TerminalMetadataStreamEvent;
|
||||
|
||||
@@ -20,7 +20,7 @@ describe("terminalUiStateStore actions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a closed default terminal UI state for unknown threads", () => {
|
||||
it("returns an empty default terminal UI state for unknown threads", () => {
|
||||
const terminalUiState = selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
@@ -28,10 +28,10 @@ describe("terminalUiStateStore actions", () => {
|
||||
expect(terminalUiState).toEqual({
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
terminalIds: [],
|
||||
activeTerminalId: "",
|
||||
terminalGroups: [],
|
||||
activeTerminalGroupId: "",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -45,10 +45,10 @@ describe("terminalUiStateStore actions", () => {
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.terminalOpen).toBe(true);
|
||||
expect(terminalUiState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalUiState.terminalIds).toEqual(["terminal-2"]);
|
||||
expect(terminalUiState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -58,19 +58,23 @@ describe("terminalUiStateStore actions", () => {
|
||||
store.splitTerminal(THREAD_REF, "terminal-3");
|
||||
store.splitTerminal(THREAD_REF, "terminal-4");
|
||||
store.splitTerminal(THREAD_REF, "terminal-5");
|
||||
store.splitTerminal(THREAD_REF, "terminal-6");
|
||||
|
||||
const terminalUiState = selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.terminalIds).toEqual([
|
||||
"default",
|
||||
"terminal-2",
|
||||
"terminal-3",
|
||||
"terminal-4",
|
||||
"terminal-5",
|
||||
]);
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2", "terminal-3", "terminal-4"] },
|
||||
{
|
||||
id: "group-terminal-2",
|
||||
terminalIds: ["terminal-2", "terminal-3", "terminal-4", "terminal-5"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -81,11 +85,10 @@ describe("terminalUiStateStore actions", () => {
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalUiState.terminalIds).toEqual(["terminal-2"]);
|
||||
expect(terminalUiState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalUiState.activeTerminalGroupId).toBe("group-terminal-2");
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
|
||||
]);
|
||||
});
|
||||
@@ -99,10 +102,9 @@ describe("terminalUiStateStore actions", () => {
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.terminalOpen).toBe(true);
|
||||
expect(terminalUiState.terminalIds).toEqual(["default", "setup-setup"]);
|
||||
expect(terminalUiState.terminalIds).toEqual(["setup-setup"]);
|
||||
expect(terminalUiState.activeTerminalId).toBe("setup-setup");
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-setup-setup", terminalIds: ["setup-setup"] },
|
||||
]);
|
||||
});
|
||||
@@ -123,28 +125,28 @@ describe("terminalUiStateStore actions", () => {
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
OTHER_THREAD_REF,
|
||||
).terminalIds,
|
||||
).toEqual(["default", "env-b-terminal"]);
|
||||
).toEqual(["env-b-terminal"]);
|
||||
});
|
||||
|
||||
it("migrates legacy persisted terminal UI state using the stored version", () => {
|
||||
it("drops persisted entries whose thread keys are not valid scoped keys", () => {
|
||||
const migrated = migratePersistedTerminalUiStateStoreState(
|
||||
{
|
||||
terminalStateByThreadKey: {
|
||||
[scopedThreadKey(THREAD_REF)]: {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: ["default"],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
terminalIds: ["term-1"],
|
||||
activeTerminalId: "term-1",
|
||||
terminalGroups: [{ id: "group-term-1", terminalIds: ["term-1"] }],
|
||||
activeTerminalGroupId: "group-term-1",
|
||||
},
|
||||
"legacy-thread-id": {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: ["default"],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
terminalIds: ["term-1"],
|
||||
activeTerminalId: "term-1",
|
||||
terminalGroups: [{ id: "group-term-1", terminalIds: ["term-1"] }],
|
||||
activeTerminalGroupId: "group-term-1",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -156,10 +158,10 @@ describe("terminalUiStateStore actions", () => {
|
||||
[scopedThreadKey(THREAD_REF)]: {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: ["default"],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
terminalIds: ["term-1"],
|
||||
activeTerminalId: "term-1",
|
||||
terminalGroups: [{ id: "group-term-1", terminalIds: ["term-1"] }],
|
||||
activeTerminalGroupId: "group-term-1",
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -167,7 +169,8 @@ describe("terminalUiStateStore actions", () => {
|
||||
|
||||
it("resets to default and clears persisted entry when closing the last terminal", () => {
|
||||
const store = useTerminalUiStateStore.getState();
|
||||
store.closeTerminal(THREAD_REF, "default");
|
||||
store.newTerminal(THREAD_REF, "terminal-only");
|
||||
store.closeTerminal(THREAD_REF, "terminal-only");
|
||||
|
||||
expect(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey[scopedThreadKey(THREAD_REF)],
|
||||
@@ -177,7 +180,7 @@ describe("terminalUiStateStore actions", () => {
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
).terminalIds,
|
||||
).toEqual(["default"]);
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a valid active terminal after closing an active split terminal", () => {
|
||||
@@ -191,9 +194,26 @@ describe("terminalUiStateStore actions", () => {
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalUiState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalUiState.terminalIds).toEqual(["terminal-2"]);
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("reconciles terminal ids from an external ordered list", () => {
|
||||
const store = useTerminalUiStateStore.getState();
|
||||
store.setTerminalOpen(THREAD_REF, true);
|
||||
store.reconcileTerminalIds(THREAD_REF, ["term-a", "term-b"]);
|
||||
|
||||
const terminalUiState = selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.terminalIds).toEqual(["term-a", "term-b"]);
|
||||
expect(terminalUiState.activeTerminalId).toBe("term-a");
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-term-a", terminalIds: ["term-a"] },
|
||||
{ id: "group-term-b", terminalIds: ["term-b"] },
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import { resolveStorage } from "./lib/storage";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_TERMINALS_PER_GROUP,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
@@ -36,20 +35,22 @@ interface PersistedTerminalUiStateStoreState {
|
||||
|
||||
export function migratePersistedTerminalUiStateStoreState(
|
||||
persistedState: unknown,
|
||||
version: number,
|
||||
_version: number,
|
||||
): PersistedTerminalUiStateStoreState {
|
||||
if (version <= 2 && persistedState && typeof persistedState === "object") {
|
||||
const candidate = persistedState as PersistedTerminalUiStateStoreState;
|
||||
const persistedUiStateByThreadKey =
|
||||
candidate.terminalUiStateByThreadKey ?? candidate.terminalStateByThreadKey ?? {};
|
||||
const nextTerminalUiStateByThreadKey = Object.fromEntries(
|
||||
Object.entries(persistedUiStateByThreadKey).filter(([threadKey]) =>
|
||||
parseScopedThreadKey(threadKey),
|
||||
),
|
||||
);
|
||||
return { terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey };
|
||||
if (!persistedState || typeof persistedState !== "object") {
|
||||
return { terminalUiStateByThreadKey: {} };
|
||||
}
|
||||
return { terminalUiStateByThreadKey: {} };
|
||||
|
||||
const candidate = persistedState as PersistedTerminalUiStateStoreState;
|
||||
const persistedUiStateByThreadKey =
|
||||
candidate.terminalUiStateByThreadKey ?? candidate.terminalStateByThreadKey ?? {};
|
||||
const terminalUiStateByThreadKey = Object.fromEntries(
|
||||
Object.entries(persistedUiStateByThreadKey).filter(([threadKey]) =>
|
||||
parseScopedThreadKey(threadKey),
|
||||
),
|
||||
);
|
||||
|
||||
return { terminalUiStateByThreadKey };
|
||||
}
|
||||
|
||||
function createTerminalUiStateStorage() {
|
||||
@@ -57,8 +58,7 @@ function createTerminalUiStateStorage() {
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
@@ -91,6 +91,10 @@ function normalizeTerminalGroups(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalIds: string[],
|
||||
): ThreadTerminalGroup[] {
|
||||
if (terminalIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const nextGroups: ThreadTerminalGroup[] = [];
|
||||
@@ -109,7 +113,7 @@ function normalizeTerminalGroups(
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? terminalIds[0] ?? "");
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
@@ -124,15 +128,6 @@ function normalizeTerminalGroups(
|
||||
});
|
||||
}
|
||||
|
||||
if (nextGroups.length === 0) {
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return nextGroups;
|
||||
}
|
||||
|
||||
@@ -173,15 +168,10 @@ function threadTerminalUiStateEqual(
|
||||
const DEFAULT_THREAD_TERMINAL_UI_STATE: ThreadTerminalUiState = Object.freeze({
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [],
|
||||
activeTerminalId: "",
|
||||
terminalGroups: [],
|
||||
activeTerminalGroupId: "",
|
||||
});
|
||||
|
||||
function createDefaultThreadTerminalUiState(): ThreadTerminalUiState {
|
||||
@@ -197,11 +187,10 @@ function getDefaultThreadTerminalUiState(): ThreadTerminalUiState {
|
||||
}
|
||||
|
||||
function normalizeThreadTerminalUiState(state: ThreadTerminalUiState): ThreadTerminalUiState {
|
||||
const terminalIds = normalizeTerminalIds(state.terminalIds);
|
||||
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const nextTerminalIds = normalizeTerminalIds(state.terminalIds);
|
||||
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
|
||||
? state.activeTerminalId
|
||||
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
: (nextTerminalIds[0] ?? "");
|
||||
const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
|
||||
const activeGroupIdFromState = terminalGroups.some(
|
||||
(group) => group.id === state.activeTerminalGroupId,
|
||||
@@ -221,10 +210,7 @@ function normalizeThreadTerminalUiState(state: ThreadTerminalUiState): ThreadTer
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId:
|
||||
activeGroupIdFromState ??
|
||||
activeGroupIdFromTerminal ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
activeGroupIdFromState ?? activeGroupIdFromTerminal ?? terminalGroups[0]?.id ?? "",
|
||||
};
|
||||
return threadTerminalUiStateEqual(state, normalized) ? state : normalized;
|
||||
}
|
||||
@@ -255,6 +241,7 @@ function upsertTerminalIntoGroups(
|
||||
mode: "split" | "new",
|
||||
): ThreadTerminalUiState {
|
||||
const normalized = normalizeThreadTerminalUiState(state);
|
||||
const effectiveMode: "split" | "new" = normalized.terminalIds.length === 0 ? "new" : mode;
|
||||
if (!isValidTerminalId(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
@@ -275,7 +262,7 @@ function upsertTerminalIntoGroups(
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === "new") {
|
||||
if (effectiveMode === "new") {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [terminalId] });
|
||||
@@ -411,7 +398,7 @@ function closeThreadTerminal(
|
||||
normalized.activeTerminalId === terminalId
|
||||
? (remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
"")
|
||||
: normalized.activeTerminalId;
|
||||
|
||||
const terminalGroups = normalized.terminalGroups
|
||||
@@ -436,6 +423,32 @@ function closeThreadTerminal(
|
||||
});
|
||||
}
|
||||
|
||||
function reconcileThreadTerminalSessionIds(
|
||||
state: ThreadTerminalUiState,
|
||||
nextIds: string[],
|
||||
): ThreadTerminalUiState {
|
||||
const normalized = normalizeThreadTerminalUiState(state);
|
||||
if (arraysEqual(normalized.terminalIds, nextIds)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const nextActiveTerminalId = nextIds.includes(normalized.activeTerminalId)
|
||||
? normalized.activeTerminalId
|
||||
: (nextIds[0] ?? "");
|
||||
|
||||
const terminalGroups = normalizeTerminalGroups(normalized.terminalGroups, nextIds);
|
||||
const activeGroupIdFromTerminal =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ?? null;
|
||||
|
||||
return normalizeThreadTerminalUiState({
|
||||
...normalized,
|
||||
terminalIds: nextIds,
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: activeGroupIdFromTerminal ?? terminalGroups[0]?.id ?? "",
|
||||
});
|
||||
}
|
||||
|
||||
export function selectThreadTerminalUiState(
|
||||
terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>,
|
||||
threadRef: ScopedThreadRef | null | undefined,
|
||||
@@ -491,6 +504,7 @@ interface TerminalUiStateStoreState {
|
||||
) => void;
|
||||
setActiveTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
closeTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
reconcileTerminalIds: (threadRef: ScopedThreadRef, nextIds: string[]) => void;
|
||||
clearTerminalUiState: (threadRef: ScopedThreadRef) => void;
|
||||
removeTerminalUiState: (threadRef: ScopedThreadRef) => void;
|
||||
removeOrphanedTerminalUiStates: (activeThreadKeys: Set<string>) => void;
|
||||
@@ -553,6 +567,8 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
|
||||
updateTerminal(threadRef, (state) => setThreadActiveTerminal(state, terminalId)),
|
||||
closeTerminal: (threadRef, terminalId) =>
|
||||
updateTerminal(threadRef, (state) => closeThreadTerminal(state, terminalId)),
|
||||
reconcileTerminalIds: (threadRef, nextIds) =>
|
||||
updateTerminal(threadRef, (state) => reconcileThreadTerminalSessionIds(state, nextIds)),
|
||||
clearTerminalUiState: (threadRef) =>
|
||||
set((state) => {
|
||||
const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey(
|
||||
@@ -600,7 +616,7 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
|
||||
},
|
||||
{
|
||||
name: TERMINAL_UI_STATE_STORAGE_KEY,
|
||||
version: 3,
|
||||
version: 4,
|
||||
storage: createJSONStorage(createTerminalUiStateStorage),
|
||||
migrate: migratePersistedTerminalUiStateStoreState,
|
||||
partialize: (state) => ({
|
||||
|
||||
@@ -22,7 +22,7 @@ export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
|
||||
export const DEFAULT_INTERACTION_MODE: ProviderInteractionMode = "default";
|
||||
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
|
||||
export const DEFAULT_THREAD_TERMINAL_ID = "default";
|
||||
export const DEFAULT_THREAD_TERMINAL_ID = "term-1";
|
||||
export const MAX_TERMINALS_PER_GROUP = 4;
|
||||
export type ProjectScript = ContractProjectScript;
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ function resetAtomRegistry() {
|
||||
const TARGET = {
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalId: "term-1",
|
||||
} as const;
|
||||
|
||||
const BASE_SNAPSHOT: TerminalSessionSnapshot = {
|
||||
@@ -41,6 +41,7 @@ const BASE_SNAPSHOT: TerminalSessionSnapshot = {
|
||||
history: "hello",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
label: "Terminal 1",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
@@ -161,7 +162,7 @@ describe("createTerminalSessionManager", () => {
|
||||
const otherTarget = {
|
||||
environmentId: EnvironmentId.make("env-remote"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalId: "term-1",
|
||||
} as const;
|
||||
|
||||
for (const target of [TARGET, otherTarget]) {
|
||||
@@ -181,7 +182,7 @@ describe("createTerminalSessionManager", () => {
|
||||
expect(manager.getSnapshot(otherTarget).buffer).toBe("env-remote");
|
||||
});
|
||||
|
||||
it("lists known sessions for a thread ordered by recency", () => {
|
||||
it("lists known sessions for a thread ordered by terminal id (numeric-aware)", () => {
|
||||
const manager = createTerminalSessionManager({
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
@@ -190,6 +191,19 @@ describe("createTerminalSessionManager", () => {
|
||||
{
|
||||
type: "snapshot",
|
||||
terminals: [
|
||||
{
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: "term-10",
|
||||
cwd: "/repo",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 125,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-01T00:00:05.000Z",
|
||||
hasRunningSubprocess: false,
|
||||
label: "Terminal 10",
|
||||
},
|
||||
{
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
@@ -201,6 +215,7 @@ describe("createTerminalSessionManager", () => {
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
hasRunningSubprocess: false,
|
||||
label: "Terminal 1",
|
||||
},
|
||||
{
|
||||
threadId: TARGET.threadId,
|
||||
@@ -213,6 +228,7 @@ describe("createTerminalSessionManager", () => {
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-01T00:00:02.000Z",
|
||||
hasRunningSubprocess: false,
|
||||
label: "Terminal 2",
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -225,7 +241,7 @@ describe("createTerminalSessionManager", () => {
|
||||
threadId: TARGET.threadId,
|
||||
})
|
||||
.map((session) => session.target.terminalId),
|
||||
).toEqual(["term-2", "default"]);
|
||||
).toEqual(["term-1", "term-2", "term-10"]);
|
||||
});
|
||||
|
||||
it("drops known sessions when an environment is invalidated", () => {
|
||||
@@ -271,6 +287,7 @@ describe("createTerminalSessionManager", () => {
|
||||
exitSignal: null,
|
||||
updatedAt: BASE_SNAPSHOT.updatedAt,
|
||||
hasRunningSubprocess: false,
|
||||
label: "Terminal 1",
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -384,6 +401,7 @@ describe("createTerminalSessionManager", () => {
|
||||
snapshot: {
|
||||
...BASE_SNAPSHOT,
|
||||
terminalId: "term-2",
|
||||
label: "Terminal 2",
|
||||
updatedAt: "2026-04-01T00:00:02.000Z",
|
||||
},
|
||||
},
|
||||
@@ -405,6 +423,7 @@ describe("createTerminalSessionManager", () => {
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-01T00:00:05.000Z",
|
||||
hasRunningSubprocess: true,
|
||||
label: "Terminal 2",
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -452,6 +471,7 @@ describe("createTerminalSessionManager", () => {
|
||||
exitSignal: null,
|
||||
updatedAt: BASE_SNAPSHOT.updatedAt,
|
||||
hasRunningSubprocess: false,
|
||||
label: "Terminal 1",
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -470,6 +490,7 @@ describe("createTerminalSessionManager", () => {
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-01T00:00:05.000Z",
|
||||
hasRunningSubprocess: true,
|
||||
label: "Terminal 1",
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -504,6 +525,7 @@ describe("createTerminalSessionManager", () => {
|
||||
exitSignal: null,
|
||||
updatedAt: BASE_SNAPSHOT.updatedAt,
|
||||
hasRunningSubprocess: true,
|
||||
label: "Terminal 1",
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
TerminalSummary,
|
||||
EnvironmentId,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_TERMINAL_ID, ThreadId, type TerminalAttachInput } from "@t3tools/contracts";
|
||||
import { ThreadId, type TerminalAttachInput } from "@t3tools/contracts";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
export interface TerminalSessionState {
|
||||
@@ -77,7 +77,7 @@ export interface TerminalMetadataClient {
|
||||
export interface TerminalAttachClient {
|
||||
readonly terminal: {
|
||||
readonly attach: (
|
||||
input: TerminalAttachInput & { readonly terminalId: string },
|
||||
input: TerminalAttachInput,
|
||||
listener: (event: TerminalAttachStreamEvent) => void,
|
||||
options?: { readonly onResubscribe?: () => void },
|
||||
) => () => void;
|
||||
@@ -268,14 +268,9 @@ function listKnownSessionsFromMetadata(
|
||||
target,
|
||||
state: combineSessionState(summary, getBuffer(target)),
|
||||
}))
|
||||
.sort((left, right) => {
|
||||
const leftUpdatedAt = left.state.updatedAt ? Date.parse(left.state.updatedAt) : 0;
|
||||
const rightUpdatedAt = right.state.updatedAt ? Date.parse(right.state.updatedAt) : 0;
|
||||
if (leftUpdatedAt !== rightUpdatedAt) {
|
||||
return rightUpdatedAt - leftUpdatedAt;
|
||||
}
|
||||
return left.target.terminalId.localeCompare(right.target.terminalId);
|
||||
});
|
||||
.sort((left, right) =>
|
||||
left.target.terminalId.localeCompare(right.target.terminalId, undefined, { numeric: true }),
|
||||
);
|
||||
}
|
||||
|
||||
export const terminalSessionStateAtom = Atom.family((target: KnownTerminalSessionTarget) =>
|
||||
@@ -569,12 +564,8 @@ export function createTerminalSessionManager(config: TerminalSessionManagerConfi
|
||||
readonly onEvent?: (event: TerminalAttachStreamEvent) => void;
|
||||
readonly options?: { readonly onResubscribe?: () => void };
|
||||
}): () => void {
|
||||
const terminal = {
|
||||
...input.terminal,
|
||||
terminalId: input.terminal.terminalId ?? DEFAULT_TERMINAL_ID,
|
||||
};
|
||||
return input.client.terminal.attach(
|
||||
terminal,
|
||||
input.terminal,
|
||||
(event) => {
|
||||
applyAttachEvent({ environmentId: input.environmentId }, event);
|
||||
input.onEvent?.(event);
|
||||
|
||||
@@ -31,6 +31,7 @@ describe("TerminalOpenInput", () => {
|
||||
expect(
|
||||
decodes(TerminalOpenInput, {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: "/tmp/project",
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
@@ -42,6 +43,7 @@ describe("TerminalOpenInput", () => {
|
||||
expect(
|
||||
decodes(TerminalOpenInput, {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: "/tmp/project",
|
||||
cols: 10,
|
||||
rows: 2,
|
||||
@@ -49,19 +51,21 @@ describe("TerminalOpenInput", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("defaults terminalId when missing", () => {
|
||||
const parsed = decodeSync(TerminalOpenInput, {
|
||||
threadId: "thread-1",
|
||||
cwd: "/tmp/project",
|
||||
cols: 100,
|
||||
rows: 24,
|
||||
});
|
||||
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
|
||||
it("requires terminalId — the client must always pick an id", () => {
|
||||
expect(
|
||||
decodes(TerminalOpenInput, {
|
||||
threadId: "thread-1",
|
||||
cwd: "/tmp/project",
|
||||
cols: 100,
|
||||
rows: 24,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts optional env overrides", () => {
|
||||
const parsed = decodeSync(TerminalOpenInput, {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: "/tmp/project",
|
||||
worktreePath: "/tmp/project/.t3/worktrees/feature-a",
|
||||
cols: 100,
|
||||
@@ -98,6 +102,7 @@ describe("TerminalWriteInput", () => {
|
||||
expect(
|
||||
decodes(TerminalWriteInput, {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
data: "echo hello\n",
|
||||
}),
|
||||
).toBe(true);
|
||||
@@ -107,10 +112,20 @@ describe("TerminalWriteInput", () => {
|
||||
expect(
|
||||
decodes(TerminalWriteInput, {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
data: "",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects missing terminalId", () => {
|
||||
expect(
|
||||
decodes(TerminalWriteInput, {
|
||||
threadId: "thread-1",
|
||||
data: "echo hello\n",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("TerminalThreadInput", () => {
|
||||
@@ -125,17 +140,33 @@ describe("TerminalResizeInput", () => {
|
||||
expect(
|
||||
decodes(TerminalResizeInput, {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects missing terminalId", () => {
|
||||
expect(
|
||||
decodes(TerminalResizeInput, {
|
||||
threadId: "thread-1",
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("TerminalClearInput", () => {
|
||||
it("defaults terminal id", () => {
|
||||
it("requires terminalId", () => {
|
||||
expect(decodes(TerminalClearInput, { threadId: "thread-1" })).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts an explicit terminalId", () => {
|
||||
const parsed = decodeSync(TerminalClearInput, {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
});
|
||||
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
|
||||
});
|
||||
@@ -165,6 +196,7 @@ describe("TerminalSessionSnapshot", () => {
|
||||
history: "hello\n",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
label: "Primary",
|
||||
updatedAt: new Date().toISOString(),
|
||||
}),
|
||||
).toBe(true);
|
||||
@@ -212,6 +244,7 @@ describe("TerminalEvent", () => {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
hasRunningSubprocess: true,
|
||||
label: "vim",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -232,6 +265,7 @@ describe("TerminalEvent", () => {
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
label: "Primary",
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { Effect, Schema } from "effect";
|
||||
import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
|
||||
export const DEFAULT_TERMINAL_ID = "default";
|
||||
/**
|
||||
* Client-side id for the first shell opened on a thread. Ids are uniformly
|
||||
* `term-N`; there's no "default" intrinsic. Kept as a named constant so callers
|
||||
* that want "the primary shell" don't hardcode `"term-1"`.
|
||||
*/
|
||||
export const DEFAULT_TERMINAL_ID = "term-1";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
const TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(20)).check(
|
||||
@@ -19,18 +24,15 @@ const TerminalEnvSchema = Schema.Record(TerminalEnvKeySchema, TerminalEnvValueSc
|
||||
Schema.isMaxProperties(128),
|
||||
);
|
||||
|
||||
const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_TERMINAL_ID)),
|
||||
);
|
||||
|
||||
export const TerminalThreadInput = Schema.Struct({
|
||||
threadId: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type TerminalThreadInput = typeof TerminalThreadInput.Type;
|
||||
|
||||
/** Terminal ids are ALWAYS chosen by the client and sent explicitly — no server-side allocation. */
|
||||
const TerminalSessionInput = Schema.Struct({
|
||||
...TerminalThreadInput.fields,
|
||||
terminalId: TerminalIdWithDefaultSchema,
|
||||
terminalId: TerminalIdSchema,
|
||||
});
|
||||
export type TerminalSessionInput = Schema.Codec.Encoded<typeof TerminalSessionInput>;
|
||||
|
||||
@@ -100,6 +102,8 @@ export const TerminalSessionSnapshot = Schema.Struct({
|
||||
history: Schema.String,
|
||||
exitCode: Schema.NullOr(Schema.Int),
|
||||
exitSignal: Schema.NullOr(Schema.Int),
|
||||
/** Server-computed display title (idle shell vs subprocess command). */
|
||||
label: Schema.String.check(Schema.isMaxLength(128)),
|
||||
updatedAt: Schema.String,
|
||||
sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
|
||||
});
|
||||
@@ -115,6 +119,8 @@ export const TerminalSummary = Schema.Struct({
|
||||
exitCode: Schema.NullOr(Schema.Int),
|
||||
exitSignal: Schema.NullOr(Schema.Int),
|
||||
hasRunningSubprocess: Schema.Boolean,
|
||||
/** Server-computed display title (idle shell vs subprocess command). */
|
||||
label: Schema.String.check(Schema.isMaxLength(128)),
|
||||
updatedAt: Schema.String,
|
||||
});
|
||||
export type TerminalSummary = typeof TerminalSummary.Type;
|
||||
@@ -193,6 +199,7 @@ const TerminalActivityEvent = Schema.Struct({
|
||||
...TerminalEventBaseSchema.fields,
|
||||
type: Schema.Literal("activity"),
|
||||
hasRunningSubprocess: Schema.Boolean,
|
||||
label: Schema.String.check(Schema.isMaxLength(128)),
|
||||
});
|
||||
|
||||
export const TerminalEvent = Schema.Union([
|
||||
|
||||
@@ -83,6 +83,10 @@
|
||||
"./composerTrigger": {
|
||||
"types": "./src/composerTrigger.ts",
|
||||
"import": "./src/composerTrigger.ts"
|
||||
},
|
||||
"./terminalLabels": {
|
||||
"types": "./src/terminalLabels.ts",
|
||||
"import": "./src/terminalLabels.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { TerminalSummary } from "@t3tools/contracts";
|
||||
import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
|
||||
|
||||
import { getTerminalLabel, nextTerminalId, resolveTerminalSessionLabel } from "./terminalLabels.ts";
|
||||
|
||||
describe("getTerminalLabel", () => {
|
||||
it("uses the numeric suffix for term-* ids", () => {
|
||||
expect(getTerminalLabel(DEFAULT_TERMINAL_ID)).toBe("Terminal 1");
|
||||
expect(getTerminalLabel("term-2")).toBe("Terminal 2");
|
||||
expect(getTerminalLabel("term-12")).toBe("Terminal 12");
|
||||
expect(getTerminalLabel("terminal-3")).toBe("Terminal 3");
|
||||
});
|
||||
|
||||
it("falls back to the raw id for unknown shapes", () => {
|
||||
expect(getTerminalLabel("custom-session")).toBe("custom-session");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveTerminalSessionLabel", () => {
|
||||
it("prefers a non-empty summary label", () => {
|
||||
const summary = { label: " bun " } as Pick<TerminalSummary, "label">;
|
||||
expect(resolveTerminalSessionLabel("term-1", summary)).toBe("bun");
|
||||
});
|
||||
|
||||
it("falls back to getTerminalLabel when summary is missing or blank", () => {
|
||||
expect(resolveTerminalSessionLabel(DEFAULT_TERMINAL_ID, { label: " " })).toBe("Terminal 1");
|
||||
expect(resolveTerminalSessionLabel(DEFAULT_TERMINAL_ID, null)).toBe("Terminal 1");
|
||||
expect(resolveTerminalSessionLabel("term-2", undefined)).toBe("Terminal 2");
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextTerminalId", () => {
|
||||
it("allocates term-1 when no terminals are listed yet", () => {
|
||||
expect(nextTerminalId([])).toBe(DEFAULT_TERMINAL_ID);
|
||||
expect(nextTerminalId([])).toBe("term-1");
|
||||
});
|
||||
|
||||
it("allocates term-2 when only term-1 exists", () => {
|
||||
expect(nextTerminalId([DEFAULT_TERMINAL_ID])).toBe("term-2");
|
||||
});
|
||||
|
||||
it("skips over taken term-N slots", () => {
|
||||
expect(nextTerminalId([DEFAULT_TERMINAL_ID, "term-2", "term-3"])).toBe("term-4");
|
||||
expect(nextTerminalId([DEFAULT_TERMINAL_ID, "term-3"])).toBe("term-2");
|
||||
expect(nextTerminalId(["term-2", "term-3"])).toBe("term-1");
|
||||
});
|
||||
|
||||
it("ignores blank/whitespace-only ids", () => {
|
||||
expect(nextTerminalId(["", " ", DEFAULT_TERMINAL_ID])).toBe("term-2");
|
||||
expect(nextTerminalId(["", " "])).toBe("term-1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { TerminalSummary } from "@t3tools/contracts";
|
||||
|
||||
/** Human-readable label for a terminal tab; matches mobile and web sidebars. */
|
||||
export function getTerminalLabel(terminalId: string): string {
|
||||
const numericSuffix = /^term(?:inal)?-(\d+)$/i.exec(terminalId)?.[1];
|
||||
if (numericSuffix) {
|
||||
return `Terminal ${numericSuffix}`;
|
||||
}
|
||||
|
||||
return terminalId;
|
||||
}
|
||||
|
||||
/** Prefer server summary label when present; otherwise fall back to `getTerminalLabel`. */
|
||||
export function resolveTerminalSessionLabel(
|
||||
terminalId: string,
|
||||
summary: Pick<TerminalSummary, "label"> | null | undefined,
|
||||
): string {
|
||||
const trimmed = summary?.label?.trim();
|
||||
if (trimmed && trimmed.length > 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return getTerminalLabel(terminalId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Client-side terminal id allocator. Ids are ALWAYS chosen by the client and sent explicitly
|
||||
* on every `terminal.open` / `terminal.attach` call — the server never allocates.
|
||||
*
|
||||
* Returns the lowest unused `term-N` id (starting at `term-1`), skipping any ids already in
|
||||
* `existingTerminalIds`.
|
||||
*/
|
||||
export function nextTerminalId(existingTerminalIds: ReadonlyArray<string>): string {
|
||||
const usedIds = new Set(existingTerminalIds.filter((id) => id.trim().length > 0));
|
||||
let nextIndex = 1;
|
||||
while (usedIds.has(`term-${nextIndex}`)) {
|
||||
nextIndex += 1;
|
||||
}
|
||||
|
||||
return `term-${nextIndex}`;
|
||||
}
|
||||
Reference in new issue
Block a user