Refactor remote terminal session state handling
- Tighten environment/thread ID typing across mobile and shared state - Track terminal metadata and subprocess status when attaching sessions - Update launch and status flows for remote terminals
This commit is contained in:
1 parent
dc994a1fe4
commit
3fe96f17b4
78 files changed
+3063
-2505
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
@@ -12,10 +13,10 @@ export function ConnectionEnvironmentRow(props: {
|
||||
readonly environment: ConnectedEnvironmentSummary;
|
||||
readonly expanded: boolean;
|
||||
readonly onToggle: () => void;
|
||||
readonly onReconnect: (environmentId: string) => void;
|
||||
readonly onRemove: (environmentId: string) => void;
|
||||
readonly onReconnect: (environmentId: EnvironmentId) => void;
|
||||
readonly onRemove: (environmentId: EnvironmentId) => void;
|
||||
readonly onUpdate: (
|
||||
environmentId: string,
|
||||
environmentId: EnvironmentId,
|
||||
updates: { readonly label: string; readonly displayUrl: string },
|
||||
) => void;
|
||||
}) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import Stack from "expo-router/stack";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
@@ -440,8 +440,8 @@ export function ReviewSheet() {
|
||||
const headerMuted = String(useThemeColor("--color-foreground-muted"));
|
||||
const headerIcon = String(useThemeColor("--color-icon"));
|
||||
const { environmentId, threadId } = useLocalSearchParams<{
|
||||
environmentId: string;
|
||||
threadId: string;
|
||||
environmentId: EnvironmentId;
|
||||
threadId: ThreadId;
|
||||
}>();
|
||||
const { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
|
||||
const reviewCache = useReviewCacheForThread({ environmentId, threadId });
|
||||
@@ -641,7 +641,7 @@ export function ReviewSheet() {
|
||||
[reviewListItems, viewportWidth],
|
||||
);
|
||||
const loadGitDiffs = useCallback(async () => {
|
||||
if (!environmentId || !cwd) {
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -667,7 +667,7 @@ export function ReviewSheet() {
|
||||
|
||||
const loadTurnDiff = useCallback(
|
||||
async (checkpoint: OrchestrationCheckpointSummary, force = false) => {
|
||||
if (!environmentId || !threadId) {
|
||||
if (!threadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
|
||||
import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { memo, useCallback, useEffect, useState } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { getEnvironmentClient } from "../../state/use-remote-environment-registry";
|
||||
import { useTerminalSession, useTerminalSessionTarget } from "../../state/use-terminal-session";
|
||||
import {
|
||||
attachTerminalSession,
|
||||
useTerminalSession,
|
||||
useTerminalSessionTarget,
|
||||
} from "../../state/use-terminal-session";
|
||||
import { TerminalSurface } from "./NativeTerminalSurface";
|
||||
import { hasNativeTerminalSurface } from "./nativeTerminalModule";
|
||||
|
||||
interface ThreadTerminalPanelProps {
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly cwd: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly visible: boolean;
|
||||
@@ -36,31 +40,31 @@ export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
|
||||
cols: DEFAULT_TERMINAL_COLS,
|
||||
rows: DEFAULT_TERMINAL_ROWS,
|
||||
});
|
||||
const hasOpenedRef = useRef(false);
|
||||
|
||||
const terminalKey = useMemo(
|
||||
() => `${props.environmentId}:${props.threadId}:${terminalId}`,
|
||||
[props.environmentId, props.threadId, terminalId],
|
||||
);
|
||||
const terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`;
|
||||
const isRunning = terminal.status === "running" || terminal.status === "starting";
|
||||
|
||||
useEffect(() => {
|
||||
hasOpenedRef.current = false;
|
||||
}, [terminalKey]);
|
||||
if (!props.visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
const openTerminal = useCallback(async () => {
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
await client.terminal.open({
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
cwd: props.cwd,
|
||||
worktreePath: props.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
return attachTerminalSession({
|
||||
environmentId: props.environmentId,
|
||||
client,
|
||||
terminal: {
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
cwd: props.cwd,
|
||||
worktreePath: props.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
},
|
||||
});
|
||||
}, [
|
||||
lastGridSize.cols,
|
||||
@@ -69,20 +73,10 @@ export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
props.worktreePath,
|
||||
props.visible,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.visible || hasOpenedRef.current || terminal.status !== "closed") {
|
||||
return;
|
||||
}
|
||||
|
||||
hasOpenedRef.current = true;
|
||||
void openTerminal().catch(() => {
|
||||
hasOpenedRef.current = false;
|
||||
});
|
||||
}, [openTerminal, props.visible, terminal.status]);
|
||||
|
||||
const handleInput = useCallback(
|
||||
(data: string) => {
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
|
||||
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
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";
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
useRemoteEnvironmentState,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
terminalSessionManager,
|
||||
attachTerminalSession,
|
||||
useKnownTerminalSessions,
|
||||
useTerminalSession,
|
||||
useTerminalSessionTarget,
|
||||
@@ -187,8 +187,12 @@ export function ThreadTerminalRouteScreen() {
|
||||
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
|
||||
useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const routeEnvironmentId = firstRouteParam(params.environmentId);
|
||||
const routeThreadId = firstRouteParam(params.threadId);
|
||||
const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
|
||||
const routeThreadIdRaw = firstRouteParam(params.threadId);
|
||||
const routeEnvironmentId = routeEnvironmentIdRaw
|
||||
? EnvironmentId.make(routeEnvironmentIdRaw)
|
||||
: null;
|
||||
const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
|
||||
const requestedTerminalId = firstRouteParam(params.terminalId);
|
||||
const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const cachedFontSize = getCachedTerminalFontSize();
|
||||
@@ -232,13 +236,9 @@ export function ThreadTerminalRouteScreen() {
|
||||
terminalId,
|
||||
});
|
||||
const terminal = useTerminalSession(target);
|
||||
const terminalKey = useMemo(
|
||||
() =>
|
||||
selectedThread
|
||||
? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
|
||||
: terminalId,
|
||||
[selectedThread, terminalId],
|
||||
);
|
||||
const terminalKey = selectedThread
|
||||
? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
|
||||
: terminalId;
|
||||
const bufferReplayKey = useMemo(
|
||||
() => getTerminalBufferReplayKey({ terminalKey, fontSize }),
|
||||
[fontSize, terminalKey],
|
||||
@@ -252,7 +252,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
readyReplayKey: readyBufferReplayKey,
|
||||
});
|
||||
const isRunning = terminal.status === "running" || terminal.status === "starting";
|
||||
const cwd = terminal.snapshot?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
|
||||
const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
|
||||
const hostPlatform = useMemo(
|
||||
() => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
|
||||
[selectedEnvironmentConnection?.environmentLabel],
|
||||
@@ -338,6 +338,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
terminalId,
|
||||
cwd: cwd ?? null,
|
||||
status: terminal.status,
|
||||
hasRunningSubprocess: terminal.hasRunningSubprocess,
|
||||
updatedAt: terminal.updatedAt,
|
||||
},
|
||||
}),
|
||||
@@ -345,20 +346,21 @@ export function ThreadTerminalRouteScreen() {
|
||||
cwd,
|
||||
knownSessions,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminal.hasRunningSubprocess,
|
||||
terminal.status,
|
||||
terminal.updatedAt,
|
||||
terminalId,
|
||||
],
|
||||
);
|
||||
|
||||
const openTerminal = useCallback(async () => {
|
||||
const attachTerminal = useCallback(() => {
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThread.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const pendingLaunchTarget = {
|
||||
@@ -367,6 +369,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
terminalId,
|
||||
};
|
||||
const pendingLaunch = takePendingTerminalLaunch(pendingLaunchTarget);
|
||||
let initialInputSent = false;
|
||||
|
||||
try {
|
||||
const launchLocation = pendingLaunch
|
||||
@@ -375,35 +378,38 @@ export function ThreadTerminalRouteScreen() {
|
||||
worktreePath: pendingLaunch.worktreePath,
|
||||
}
|
||||
: resolveTerminalOpenLocation({
|
||||
terminalSnapshot: terminal.snapshot,
|
||||
activeSessionSnapshot: activeKnownSession?.state.snapshot ?? null,
|
||||
terminalLocation: terminal.summary,
|
||||
activeSessionLocation: activeKnownSession?.state.summary ?? null,
|
||||
workspaceRoot: selectedThreadProject.workspaceRoot,
|
||||
threadShellWorktreePath: selectedThread.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
});
|
||||
|
||||
const snapshot = await client.terminal.open({
|
||||
threadId: selectedThread.id,
|
||||
terminalId,
|
||||
cwd: launchLocation.cwd,
|
||||
worktreePath: launchLocation.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
env: pendingLaunch?.env,
|
||||
});
|
||||
|
||||
terminalSessionManager.syncSnapshot(
|
||||
{ environmentId: selectedThread.environmentId },
|
||||
snapshot,
|
||||
);
|
||||
|
||||
if (pendingLaunch?.initialInput) {
|
||||
await client.terminal.write({
|
||||
return attachTerminalSession({
|
||||
environmentId: selectedThread.environmentId,
|
||||
client,
|
||||
terminal: {
|
||||
threadId: selectedThread.id,
|
||||
terminalId,
|
||||
data: pendingLaunch.initialInput,
|
||||
});
|
||||
}
|
||||
cwd: launchLocation.cwd,
|
||||
worktreePath: launchLocation.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
env: pendingLaunch?.env,
|
||||
},
|
||||
onSnapshot: () => {
|
||||
if (!pendingLaunch?.initialInput || initialInputSent) {
|
||||
return;
|
||||
}
|
||||
|
||||
initialInputSent = true;
|
||||
void client.terminal.write({
|
||||
threadId: selectedThread.id,
|
||||
terminalId,
|
||||
data: pendingLaunch.initialInput,
|
||||
});
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (pendingLaunch) {
|
||||
stagePendingTerminalLaunch({
|
||||
@@ -417,11 +423,11 @@ export function ThreadTerminalRouteScreen() {
|
||||
}, [
|
||||
lastGridSize.cols,
|
||||
lastGridSize.rows,
|
||||
activeKnownSession?.state.snapshot,
|
||||
activeKnownSession?.state.summary,
|
||||
selectedThreadDetail?.worktreePath,
|
||||
selectedThread,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminal.snapshot,
|
||||
terminal.summary,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
@@ -546,7 +552,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
currentTerminalId: terminalId,
|
||||
runningTerminalId: runningSession?.target.terminalId ?? null,
|
||||
currentTerminalStatus: terminal.status,
|
||||
hasCurrentTerminalHydration: terminal.snapshot !== null || terminal.buffer.length > 0,
|
||||
hasCurrentTerminalHydration: terminal.summary !== null || terminal.buffer.length > 0,
|
||||
});
|
||||
if (bootstrapAction.kind === "idle" || !selectedThread) {
|
||||
return;
|
||||
@@ -558,18 +564,21 @@ export function ThreadTerminalRouteScreen() {
|
||||
}
|
||||
|
||||
hasOpenedRef.current = true;
|
||||
void openTerminal().catch(() => {
|
||||
try {
|
||||
return attachTerminal() ?? undefined;
|
||||
} catch {
|
||||
hasOpenedRef.current = false;
|
||||
});
|
||||
return;
|
||||
}
|
||||
}, [
|
||||
openTerminal,
|
||||
attachTerminal,
|
||||
requestedTerminalId,
|
||||
router,
|
||||
runningSession,
|
||||
selectedThread,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminal.buffer.length,
|
||||
terminal.snapshot,
|
||||
terminal.summary,
|
||||
terminal.status,
|
||||
terminalId,
|
||||
hasMeasuredSurface,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
peekPendingTerminalLaunch,
|
||||
@@ -32,8 +33,8 @@ describe("resolveTerminalOpenLocation", () => {
|
||||
it("uses the thread detail worktree path before the workspace root for a fresh mobile open", () => {
|
||||
expect(
|
||||
resolveTerminalOpenLocation({
|
||||
terminalSnapshot: null,
|
||||
activeSessionSnapshot: null,
|
||||
terminalLocation: null,
|
||||
activeSessionLocation: null,
|
||||
workspaceRoot: "/repo/root",
|
||||
threadShellWorktreePath: null,
|
||||
threadDetailWorktreePath: "/repo/worktrees/feature",
|
||||
@@ -47,8 +48,8 @@ describe("resolveTerminalOpenLocation", () => {
|
||||
it("preserves the running terminal snapshot cwd when attaching to an existing session", () => {
|
||||
expect(
|
||||
resolveTerminalOpenLocation({
|
||||
terminalSnapshot: null,
|
||||
activeSessionSnapshot: {
|
||||
terminalLocation: null,
|
||||
activeSessionLocation: {
|
||||
cwd: "/repo/worktrees/feature",
|
||||
worktreePath: "/repo/worktrees/feature",
|
||||
},
|
||||
@@ -66,8 +67,8 @@ describe("resolveTerminalOpenLocation", () => {
|
||||
describe("pending terminal launches", () => {
|
||||
it("stages and consumes launch details for a specific terminal target", () => {
|
||||
const target = {
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: "term-2",
|
||||
};
|
||||
|
||||
@@ -98,13 +99,13 @@ describe("pending terminal launches", () => {
|
||||
|
||||
it("keeps pending launches isolated per terminal target", () => {
|
||||
const primaryTarget = {
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: "term-2",
|
||||
};
|
||||
const otherTarget = {
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: "term-3",
|
||||
};
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
interface TerminalSnapshotLike {
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
interface TerminalLocationLike {
|
||||
readonly cwd: string;
|
||||
readonly worktreePath: string | null;
|
||||
}
|
||||
|
||||
interface PendingTerminalLaunchTarget {
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly terminalId: string;
|
||||
}
|
||||
|
||||
@@ -60,8 +62,8 @@ export function resolvePreferredThreadWorktreePath(input: {
|
||||
}
|
||||
|
||||
export function resolveTerminalOpenLocation(input: {
|
||||
readonly terminalSnapshot: TerminalSnapshotLike | null;
|
||||
readonly activeSessionSnapshot: TerminalSnapshotLike | null;
|
||||
readonly terminalLocation: TerminalLocationLike | null;
|
||||
readonly activeSessionLocation: TerminalLocationLike | null;
|
||||
readonly workspaceRoot: string;
|
||||
readonly threadShellWorktreePath: string | null;
|
||||
readonly threadDetailWorktreePath: string | null;
|
||||
@@ -76,13 +78,13 @@ export function resolveTerminalOpenLocation(input: {
|
||||
|
||||
return {
|
||||
cwd:
|
||||
input.terminalSnapshot?.cwd ??
|
||||
input.activeSessionSnapshot?.cwd ??
|
||||
input.terminalLocation?.cwd ??
|
||||
input.activeSessionLocation?.cwd ??
|
||||
preferredThreadWorktreePath ??
|
||||
input.workspaceRoot,
|
||||
worktreePath:
|
||||
input.terminalSnapshot?.worktreePath ??
|
||||
input.activeSessionSnapshot?.worktreePath ??
|
||||
input.terminalLocation?.worktreePath ??
|
||||
input.activeSessionLocation?.worktreePath ??
|
||||
preferredThreadWorktreePath,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { KnownTerminalSession } from "@t3tools/client-runtime";
|
||||
import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
|
||||
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { buildTerminalMenuSessions, resolveProjectScriptTerminalId } from "./terminalMenu";
|
||||
|
||||
@@ -13,12 +13,12 @@ function makeKnownSession(input: {
|
||||
}): KnownTerminalSession {
|
||||
return {
|
||||
target: {
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: input.terminalId,
|
||||
},
|
||||
state: {
|
||||
snapshot: input.cwd
|
||||
summary: input.cwd
|
||||
? {
|
||||
threadId: "thread-1",
|
||||
terminalId: input.terminalId,
|
||||
@@ -26,9 +26,9 @@ function makeKnownSession(input: {
|
||||
worktreePath: input.cwd,
|
||||
status: input.status === "closed" ? "error" : input.status,
|
||||
pid: input.status === "running" ? 123 : null,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: input.updatedAt ?? "2026-04-15T20:00:00.000Z",
|
||||
}
|
||||
: null,
|
||||
@@ -67,12 +67,14 @@ describe("buildTerminalMenuSessions", () => {
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: "/workspace/root",
|
||||
status: "closed",
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: null,
|
||||
},
|
||||
{
|
||||
terminalId: "term-3",
|
||||
cwd: "/workspace/feature",
|
||||
status: "running",
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: "2026-04-15T20:05:00.000Z",
|
||||
},
|
||||
]);
|
||||
@@ -87,6 +89,7 @@ describe("buildTerminalMenuSessions", () => {
|
||||
terminalId: "term-4",
|
||||
cwd: "/workspace/exited",
|
||||
status: "exited",
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: "2026-04-15T20:07:00.000Z",
|
||||
},
|
||||
}),
|
||||
@@ -95,12 +98,14 @@ describe("buildTerminalMenuSessions", () => {
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: "/workspace/root",
|
||||
status: "closed",
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: null,
|
||||
},
|
||||
{
|
||||
terminalId: "term-4",
|
||||
cwd: "/workspace/exited",
|
||||
status: "exited",
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: "2026-04-15T20:07:00.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -5,6 +5,7 @@ export interface TerminalMenuSession {
|
||||
readonly terminalId: string;
|
||||
readonly cwd: string | null;
|
||||
readonly status: "starting" | "running" | "exited" | "error" | "closed";
|
||||
readonly hasRunningSubprocess: boolean;
|
||||
readonly updatedAt: string | null;
|
||||
}
|
||||
|
||||
@@ -76,6 +77,7 @@ export function buildTerminalMenuSessions(input: {
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: input.workspaceRoot,
|
||||
status: "closed",
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: null,
|
||||
});
|
||||
|
||||
@@ -90,8 +92,9 @@ export function buildTerminalMenuSessions(input: {
|
||||
|
||||
sessionsById.set(session.target.terminalId, {
|
||||
terminalId: session.target.terminalId,
|
||||
cwd: session.state.snapshot?.cwd ?? input.workspaceRoot,
|
||||
cwd: session.state.summary?.cwd ?? input.workspaceRoot,
|
||||
status: session.state.status,
|
||||
hasRunningSubprocess: session.state.hasRunningSubprocess,
|
||||
updatedAt: session.state.updatedAt,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
cacheTerminalFontSize,
|
||||
@@ -23,13 +24,13 @@ describe("terminalUiState", () => {
|
||||
|
||||
it("stores terminal grid sizes per terminal target", () => {
|
||||
const primaryTarget = {
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: "default",
|
||||
};
|
||||
const otherTarget = {
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: "term-2",
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { DEFAULT_TERMINAL_FONT_SIZE, normalizeTerminalFontSize } from "./terminalPreferences";
|
||||
|
||||
export interface TerminalGridSize {
|
||||
@@ -6,8 +8,8 @@ export interface TerminalGridSize {
|
||||
}
|
||||
|
||||
export interface TerminalUiStateTarget {
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly terminalId: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import { MenuView } from "@react-native-menu/menu";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ModelSelection,
|
||||
OrchestrationThread,
|
||||
ProviderInteractionMode,
|
||||
@@ -67,7 +68,7 @@ export interface ThreadComposerProps {
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly queueCount: number;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectCwd: string | null;
|
||||
readonly onChangeDraftMessage: (value: string) => void;
|
||||
readonly onPickDraftImages: () => Promise<void>;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
ModelSelection,
|
||||
OrchestrationThread,
|
||||
ProviderApprovalDecision,
|
||||
@@ -53,7 +54,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly connectionStateLabel: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle";
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
readonly selectedThreadQueueCount: number;
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
|
||||
@@ -213,7 +213,13 @@ export function ThreadGitControls(props: {
|
||||
key={session.terminalId}
|
||||
icon="terminal"
|
||||
onPress={() => props.onOpenTerminal(session.terminalId)}
|
||||
subtitle={[getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
|
||||
subtitle={[
|
||||
getTerminalStatusLabel({
|
||||
status: session.status,
|
||||
hasRunningSubprocess: session.hasRunningSubprocess,
|
||||
}),
|
||||
basename(session.cwd),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useCallback, useMemo, useState } from "react";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Option from "effect/Option";
|
||||
import { pipe } from "effect/Function";
|
||||
import type { ProjectScript } from "@t3tools/contracts";
|
||||
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -76,7 +76,8 @@ export function ThreadRouteScreen() {
|
||||
threadId?: string | string[];
|
||||
}>();
|
||||
const [drawerVisible, setDrawerVisible] = useState(false);
|
||||
const environmentId = firstRouteParam(params.environmentId);
|
||||
const environmentIdRaw = firstRouteParam(params.environmentId);
|
||||
const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
|
||||
const threadId = firstRouteParam(params.threadId);
|
||||
const routeEnvironmentRuntime = environmentId
|
||||
? (environmentStateById[environmentId] ?? null)
|
||||
@@ -93,7 +94,7 @@ export function ThreadRouteScreen() {
|
||||
|
||||
/* ─── Git status for native header trigger ───────────────────────── */
|
||||
const gitStatus = useGitStatus({
|
||||
environmentId: selectedThread?.environmentId ?? "",
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
const knownTerminalSessions = useKnownTerminalSessions({
|
||||
|
||||
@@ -28,7 +28,7 @@ export function GitBranchesSheet() {
|
||||
const subtleStrongColor = useThemeColor("--color-subtle-strong");
|
||||
|
||||
const gitStatus = useGitStatus({
|
||||
environmentId: selectedThread?.environmentId ?? "",
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ export function GitCommitSheet() {
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
|
||||
const gitStatus = useGitStatus({
|
||||
environmentId: selectedThread?.environmentId ?? "",
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ export function GitOverviewSheet() {
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
|
||||
const gitStatus = useGitStatus({
|
||||
environmentId: selectedThread?.environmentId ?? "",
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type EnvironmentId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
type GitBranch,
|
||||
@@ -29,8 +30,10 @@ function useRefreshRemoteData() {
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
|
||||
return useCallback(
|
||||
async (environmentIds?: ReadonlyArray<string>) => {
|
||||
const targets = environmentIds ?? Object.keys(savedConnectionsById);
|
||||
async (environmentIds?: ReadonlyArray<EnvironmentId>) => {
|
||||
const targets =
|
||||
environmentIds ??
|
||||
Object.values(savedConnectionsById).map((connection) => connection.environmentId);
|
||||
|
||||
await Promise.all(
|
||||
targets.map(async (environmentId) => {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
getEnvironmentRuntimeTargetKey,
|
||||
type EnvironmentRuntimeState,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -17,7 +18,9 @@ export const environmentRuntimeManager = createEnvironmentRuntimeManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
});
|
||||
|
||||
export function useEnvironmentRuntime(environmentId: string | null): EnvironmentRuntimeState {
|
||||
export function useEnvironmentRuntime(
|
||||
environmentId: EnvironmentId | null,
|
||||
): EnvironmentRuntimeState {
|
||||
const targetKey = getEnvironmentRuntimeTargetKey({ environmentId });
|
||||
const state = useAtomValue(
|
||||
targetKey !== null ? environmentRuntimeStateAtom(targetKey) : EMPTY_ENVIRONMENT_RUNTIME_ATOM,
|
||||
@@ -26,13 +29,13 @@ export function useEnvironmentRuntime(environmentId: string | null): Environment
|
||||
}
|
||||
|
||||
export function useEnvironmentRuntimeStates(
|
||||
environmentIds: ReadonlyArray<string>,
|
||||
): Readonly<Record<string, EnvironmentRuntimeState>> {
|
||||
environmentIds: ReadonlyArray<EnvironmentId>,
|
||||
): Readonly<Record<EnvironmentId, EnvironmentRuntimeState>> {
|
||||
const stableEnvironmentIds = useMemo(
|
||||
() => Arr.sort(new Set(environmentIds), Order.String),
|
||||
[environmentIds],
|
||||
);
|
||||
const snapshotCacheRef = useRef<Readonly<Record<string, EnvironmentRuntimeState>>>({});
|
||||
const snapshotCacheRef = useRef<Readonly<Record<EnvironmentId, EnvironmentRuntimeState>>>({});
|
||||
|
||||
const subscribe = useCallback(
|
||||
(onStoreChange: () => void) => {
|
||||
@@ -51,7 +54,7 @@ export function useEnvironmentRuntimeStates(
|
||||
const getSnapshot = useCallback(() => {
|
||||
const previous = snapshotCacheRef.current;
|
||||
let hasChanged = Object.keys(previous).length !== stableEnvironmentIds.length;
|
||||
const next: Record<string, EnvironmentRuntimeState> = {};
|
||||
const next: Record<EnvironmentId, EnvironmentRuntimeState> = {};
|
||||
|
||||
for (const environmentId of stableEnvironmentIds) {
|
||||
const snapshot = environmentRuntimeManager.getSnapshot({ environmentId });
|
||||
|
||||
@@ -51,7 +51,9 @@ function deriveOverallConnectionState(
|
||||
export function useRemoteCatalog() {
|
||||
const { connectedEnvironments, connectionState } = useRemoteConnectionStatus();
|
||||
const { environmentStateById, savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const shellSnapshotStates = useShellSnapshotStates(Object.keys(savedConnectionsById));
|
||||
const shellSnapshotStates = useShellSnapshotStates(
|
||||
Object.values(savedConnectionsById).map((connection) => connection.environmentId),
|
||||
);
|
||||
|
||||
const projects = useMemo(
|
||||
() =>
|
||||
|
||||
@@ -23,16 +23,17 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { type ConnectedEnvironmentSummary, type EnvironmentSession } from "./remote-runtime-types";
|
||||
import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime";
|
||||
import { shellSnapshotManager } from "./use-shell-snapshot";
|
||||
import { terminalSessionManager } from "./use-terminal-session";
|
||||
import { subscribeTerminalMetadata, terminalSessionManager } from "./use-terminal-session";
|
||||
|
||||
const environmentSessions = new Map<string, EnvironmentSession>();
|
||||
const environmentSessions = new Map<EnvironmentId, EnvironmentSession>();
|
||||
const environmentConnectionListeners = new Set<() => void>();
|
||||
const terminalMetadataUnsubscribers = new Map<EnvironmentId, () => void>();
|
||||
|
||||
interface RemoteEnvironmentLocalState {
|
||||
readonly isLoadingSavedConnection: boolean;
|
||||
readonly connectionPairingUrl: string;
|
||||
readonly pendingConnectionError: string | null;
|
||||
readonly savedConnectionsById: Record<string, SavedRemoteConnection>;
|
||||
readonly savedConnectionsById: Record<EnvironmentId, SavedRemoteConnection>;
|
||||
}
|
||||
|
||||
const isLoadingSavedConnectionAtom = Atom.make(true).pipe(
|
||||
@@ -50,7 +51,7 @@ const pendingConnectionErrorAtom = Atom.make<string | null>(null).pipe(
|
||||
Atom.withLabel("mobile:pending-connection-error"),
|
||||
);
|
||||
|
||||
const savedConnectionsByIdAtom = Atom.make<Record<string, SavedRemoteConnection>>({}).pipe(
|
||||
const savedConnectionsByIdAtom = Atom.make<Record<EnvironmentId, SavedRemoteConnection>>({}).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("mobile:saved-connections"),
|
||||
);
|
||||
@@ -59,7 +60,7 @@ function notifyEnvironmentConnectionListeners() {
|
||||
for (const listener of environmentConnectionListeners) listener();
|
||||
}
|
||||
|
||||
function getSavedConnectionsById(): Record<string, SavedRemoteConnection> {
|
||||
function getSavedConnectionsById(): Record<EnvironmentId, SavedRemoteConnection> {
|
||||
return appAtomRegistry.get(savedConnectionsByIdAtom);
|
||||
}
|
||||
|
||||
@@ -83,7 +84,7 @@ function clearPendingConnectionError(): void {
|
||||
appAtomRegistry.set(pendingConnectionErrorAtom, null);
|
||||
}
|
||||
|
||||
function replaceSavedConnections(connections: Record<string, SavedRemoteConnection>): void {
|
||||
function replaceSavedConnections(connections: Record<EnvironmentId, SavedRemoteConnection>): void {
|
||||
appAtomRegistry.set(savedConnectionsByIdAtom, connections);
|
||||
}
|
||||
|
||||
@@ -95,7 +96,7 @@ function upsertSavedConnection(connection: SavedRemoteConnection): void {
|
||||
});
|
||||
}
|
||||
|
||||
function removeSavedConnection(environmentId: string): void {
|
||||
function removeSavedConnection(environmentId: EnvironmentId): void {
|
||||
const current = appAtomRegistry.get(savedConnectionsByIdAtom);
|
||||
const next = { ...current };
|
||||
delete next[environmentId];
|
||||
@@ -131,7 +132,7 @@ export function subscribeEnvironmentConnections(listener: () => void): () => voi
|
||||
}
|
||||
|
||||
function setEnvironmentConnectionStatus(
|
||||
environmentId: string,
|
||||
environmentId: EnvironmentId,
|
||||
state: ConnectedEnvironmentSummary["connectionState"],
|
||||
error?: string | null,
|
||||
) {
|
||||
@@ -142,18 +143,20 @@ function setEnvironmentConnectionStatus(
|
||||
}));
|
||||
}
|
||||
|
||||
export function getEnvironmentClient(environmentId: string) {
|
||||
export function getEnvironmentClient(environmentId: EnvironmentId) {
|
||||
return environmentSessions.get(environmentId)?.client ?? null;
|
||||
}
|
||||
|
||||
export async function disconnectEnvironment(
|
||||
environmentId: string,
|
||||
environmentId: EnvironmentId,
|
||||
options?: { readonly removeSaved?: boolean },
|
||||
) {
|
||||
const session = environmentSessions.get(environmentId);
|
||||
environmentSessions.delete(environmentId);
|
||||
notifyEnvironmentConnectionListeners();
|
||||
await session?.connection.dispose();
|
||||
terminalMetadataUnsubscribers.get(environmentId)?.();
|
||||
terminalMetadataUnsubscribers.delete(environmentId);
|
||||
shellSnapshotManager.invalidate({ environmentId });
|
||||
terminalSessionManager.invalidateEnvironment(environmentId);
|
||||
environmentRuntimeManager.invalidate({ environmentId });
|
||||
@@ -246,9 +249,6 @@ export async function connectSavedEnvironment(
|
||||
onShellResubscribe: (environmentId) => {
|
||||
shellSnapshotManager.markPending({ environmentId });
|
||||
},
|
||||
applyTerminalEvent: (event, environmentId) => {
|
||||
terminalSessionManager.applyEvent({ environmentId }, event);
|
||||
},
|
||||
onConfigSnapshot: (serverConfig) => {
|
||||
environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (runtime) => ({
|
||||
...runtime,
|
||||
@@ -261,6 +261,13 @@ export async function connectSavedEnvironment(
|
||||
client,
|
||||
connection: environmentConnection,
|
||||
});
|
||||
terminalMetadataUnsubscribers.set(
|
||||
connection.environmentId,
|
||||
subscribeTerminalMetadata({
|
||||
environmentId: connection.environmentId,
|
||||
client,
|
||||
}),
|
||||
);
|
||||
notifyEnvironmentConnectionListeners();
|
||||
|
||||
try {
|
||||
@@ -335,6 +342,10 @@ export function useRemoteEnvironmentBootstrap() {
|
||||
void session.connection.dispose();
|
||||
}
|
||||
environmentSessions.clear();
|
||||
for (const unsubscribe of terminalMetadataUnsubscribers.values()) {
|
||||
unsubscribe();
|
||||
}
|
||||
terminalMetadataUnsubscribers.clear();
|
||||
environmentRuntimeManager.invalidate();
|
||||
shellSnapshotManager.invalidate();
|
||||
terminalSessionManager.invalidate();
|
||||
@@ -345,7 +356,9 @@ export function useRemoteEnvironmentBootstrap() {
|
||||
|
||||
export function useRemoteEnvironmentState() {
|
||||
const state = useRemoteEnvironmentLocalState();
|
||||
const environmentStateById = useEnvironmentRuntimeStates(Object.keys(state.savedConnectionsById));
|
||||
const environmentStateById = useEnvironmentRuntimeStates(
|
||||
Object.values(state.savedConnectionsById).map((connection) => connection.environmentId),
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
@@ -427,7 +440,7 @@ export function useRemoteConnections() {
|
||||
|
||||
const onUpdateEnvironment = useCallback(
|
||||
async (
|
||||
environmentId: string,
|
||||
environmentId: EnvironmentId,
|
||||
updates: { readonly label: string; readonly displayUrl: string },
|
||||
) => {
|
||||
const connection = getSavedConnectionsById()[environmentId];
|
||||
@@ -447,7 +460,7 @@ export function useRemoteConnections() {
|
||||
[],
|
||||
);
|
||||
|
||||
const onReconnectEnvironment = useCallback((environmentId: string) => {
|
||||
const onReconnectEnvironment = useCallback((environmentId: EnvironmentId) => {
|
||||
const connection = getSavedConnectionsById()[environmentId];
|
||||
if (!connection) {
|
||||
return;
|
||||
@@ -455,7 +468,7 @@ export function useRemoteConnections() {
|
||||
void connectSavedEnvironment(connection, { persist: false });
|
||||
}, []);
|
||||
|
||||
const onRemoveEnvironmentPress = useCallback((environmentId: string) => {
|
||||
const onRemoveEnvironmentPress = useCallback((environmentId: EnvironmentId) => {
|
||||
const connection = getSavedConnectionsById()[environmentId];
|
||||
if (!connection) {
|
||||
return;
|
||||
|
||||
@@ -36,7 +36,7 @@ export function useSelectedThreadCommands(input: {
|
||||
const onRefresh = useCallback(async () => {
|
||||
const targets = selectedThread
|
||||
? [selectedThread.environmentId]
|
||||
: Object.keys(savedConnectionsById);
|
||||
: Object.values(savedConnectionsById).map((connection) => connection.environmentId);
|
||||
|
||||
await Promise.all(
|
||||
targets.map(async (environmentId) => {
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
shellSnapshotStateAtom,
|
||||
type ShellSnapshotState,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -17,7 +18,7 @@ export const shellSnapshotManager = createShellSnapshotManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
});
|
||||
|
||||
export function useShellSnapshot(environmentId: string | null): ShellSnapshotState {
|
||||
export function useShellSnapshot(environmentId: EnvironmentId | null): ShellSnapshotState {
|
||||
const targetKey = getShellSnapshotTargetKey({ environmentId });
|
||||
const state = useAtomValue(
|
||||
targetKey !== null ? shellSnapshotStateAtom(targetKey) : EMPTY_SHELL_SNAPSHOT_ATOM,
|
||||
@@ -26,13 +27,13 @@ export function useShellSnapshot(environmentId: string | null): ShellSnapshotSta
|
||||
}
|
||||
|
||||
export function useShellSnapshotStates(
|
||||
environmentIds: ReadonlyArray<string>,
|
||||
): Readonly<Record<string, ShellSnapshotState>> {
|
||||
environmentIds: ReadonlyArray<EnvironmentId>,
|
||||
): Readonly<Record<EnvironmentId, ShellSnapshotState>> {
|
||||
const stableEnvironmentIds = useMemo(
|
||||
() => Arr.sort(new Set(environmentIds), Order.String),
|
||||
[environmentIds],
|
||||
);
|
||||
const snapshotCacheRef = useRef<Readonly<Record<string, ShellSnapshotState>>>({});
|
||||
const snapshotCacheRef = useRef<Readonly<Record<EnvironmentId, ShellSnapshotState>>>({});
|
||||
|
||||
const subscribe = useCallback(
|
||||
(onStoreChange: () => void) => {
|
||||
@@ -51,7 +52,7 @@ export function useShellSnapshotStates(
|
||||
const getSnapshot = useCallback(() => {
|
||||
const previous = snapshotCacheRef.current;
|
||||
let hasChanged = Object.keys(previous).length !== stableEnvironmentIds.length;
|
||||
const next: Record<string, ShellSnapshotState> = {};
|
||||
const next: Record<EnvironmentId, ShellSnapshotState> = {};
|
||||
|
||||
for (const environmentId of stableEnvironmentIds) {
|
||||
const snapshot = shellSnapshotManager.getSnapshot({ environmentId });
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
createTerminalSessionManager,
|
||||
EMPTY_KNOWN_TERMINAL_SESSIONS_ATOM,
|
||||
EMPTY_TERMINAL_SESSION_ATOM,
|
||||
EMPTY_TERMINAL_SESSION_STATE,
|
||||
getTerminalSessionTargetKey,
|
||||
getKnownTerminalSessionTarget,
|
||||
getKnownTerminalSessionListFilter,
|
||||
knownTerminalSessionsAtom,
|
||||
terminalSessionStateAtom,
|
||||
type TerminalSessionTarget,
|
||||
type TerminalSessionState,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
TerminalAttachInput,
|
||||
TerminalMetadataStreamEvent,
|
||||
TerminalSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -16,23 +24,42 @@ export const terminalSessionManager = createTerminalSessionManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
});
|
||||
|
||||
export function useTerminalSession(input: {
|
||||
readonly environmentId: string | null;
|
||||
readonly threadId: string | null;
|
||||
readonly terminalId: string | null;
|
||||
}): TerminalSessionState {
|
||||
const targetKey = getTerminalSessionTargetKey(input);
|
||||
const state = useAtomValue(
|
||||
targetKey !== null ? terminalSessionStateAtom(targetKey) : EMPTY_TERMINAL_SESSION_ATOM,
|
||||
);
|
||||
return targetKey === null ? EMPTY_TERMINAL_SESSION_STATE : state;
|
||||
export function subscribeTerminalMetadata(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly client: {
|
||||
readonly terminal: {
|
||||
readonly onMetadata: (
|
||||
listener: (event: TerminalMetadataStreamEvent) => void,
|
||||
options?: { readonly onResubscribe?: () => void },
|
||||
) => () => void;
|
||||
};
|
||||
};
|
||||
}) {
|
||||
return terminalSessionManager.subscribeMetadata(input);
|
||||
}
|
||||
|
||||
export function useTerminalSessionTarget(input: {
|
||||
readonly environmentId: string | null;
|
||||
readonly threadId: string | null;
|
||||
readonly terminalId: string | null;
|
||||
export function attachTerminalSession(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly client: Parameters<typeof terminalSessionManager.attach>[0]["client"];
|
||||
readonly terminal: TerminalAttachInput;
|
||||
readonly onSnapshot?: (snapshot: TerminalSessionSnapshot) => void;
|
||||
}) {
|
||||
return terminalSessionManager.attach({
|
||||
environmentId: input.environmentId,
|
||||
client: input.client,
|
||||
terminal: input.terminal,
|
||||
...(input.onSnapshot ? { onSnapshot: input.onSnapshot } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useTerminalSession(input: TerminalSessionTarget): TerminalSessionState {
|
||||
const target = getKnownTerminalSessionTarget(input);
|
||||
return useAtomValue(
|
||||
target !== null ? terminalSessionStateAtom(target) : EMPTY_TERMINAL_SESSION_ATOM,
|
||||
);
|
||||
}
|
||||
|
||||
export function useTerminalSessionTarget(input: TerminalSessionTarget) {
|
||||
return useMemo(
|
||||
() => ({
|
||||
environmentId: input.environmentId,
|
||||
@@ -44,20 +71,11 @@ export function useTerminalSessionTarget(input: {
|
||||
}
|
||||
|
||||
export function useKnownTerminalSessions(input: {
|
||||
readonly environmentId: string | null;
|
||||
readonly threadId: string | null;
|
||||
readonly environmentId: TerminalSessionTarget["environmentId"];
|
||||
readonly threadId: TerminalSessionTarget["threadId"];
|
||||
}) {
|
||||
const knownSessionsIndex = useAtomValue(knownTerminalSessionsAtom);
|
||||
|
||||
return useMemo(() => {
|
||||
if (input.environmentId === null || input.threadId === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
void knownSessionsIndex;
|
||||
return terminalSessionManager.listSessions({
|
||||
environmentId: input.environmentId,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
}, [input.environmentId, input.threadId, knownSessionsIndex]);
|
||||
const filter = getKnownTerminalSessionListFilter(input);
|
||||
return useAtomValue(
|
||||
filter !== null ? knownTerminalSessionsAtom(filter) : EMPTY_KNOWN_TERMINAL_SESSIONS_ATOM,
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
import { useMemo } from "react";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
|
||||
import { EnvironmentScopedProjectShell } from "@t3tools/client-runtime";
|
||||
@@ -15,7 +16,7 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
|
||||
}
|
||||
|
||||
function deriveSelectedThread(
|
||||
selectedThreadRef: { readonly environmentId: string; readonly threadId: string } | null,
|
||||
selectedThreadRef: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null,
|
||||
threads: ReadonlyArray<EnvironmentScopedThreadShell>,
|
||||
): EnvironmentScopedThreadShell | null {
|
||||
if (!selectedThreadRef) {
|
||||
@@ -62,7 +63,10 @@ export function useThreadSelection() {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { environmentId, threadId };
|
||||
return {
|
||||
environmentId: EnvironmentId.make(environmentId),
|
||||
threadId: ThreadId.make(threadId),
|
||||
};
|
||||
}, [params.environmentId, params.threadId]);
|
||||
const selectedThread = useMemo(
|
||||
() => deriveSelectedThread(selectedThreadRef, threads),
|
||||
|
||||
@@ -51,12 +51,14 @@ describe("ProjectSetupScriptRunner", () => {
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
open,
|
||||
attachStream: () => Effect.die(new Error("unused")),
|
||||
write,
|
||||
resize: () => Effect.void,
|
||||
clear: () => Effect.void,
|
||||
restart: () => Effect.die(new Error("unused")),
|
||||
close: () => Effect.void,
|
||||
subscribe: () => Effect.succeed(() => undefined),
|
||||
subscribeMetadata: () => Effect.succeed(() => undefined),
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -119,12 +121,14 @@ describe("ProjectSetupScriptRunner", () => {
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
open,
|
||||
attachStream: () => Effect.die(new Error("unused")),
|
||||
write,
|
||||
resize: () => Effect.void,
|
||||
clear: () => Effect.void,
|
||||
restart: () => Effect.die(new Error("unused")),
|
||||
close: () => Effect.void,
|
||||
subscribe: () => Effect.succeed(() => undefined),
|
||||
subscribeMetadata: () => Effect.succeed(() => undefined),
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -4,7 +4,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type TerminalAttachStreamEvent,
|
||||
type TerminalEvent,
|
||||
type TerminalMetadataStreamEvent,
|
||||
type TerminalOpenInput,
|
||||
type TerminalRestartInput,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -280,6 +282,33 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("attaches to running sessions without restarting them", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter } = yield* createManager();
|
||||
|
||||
yield* manager.open(openInput());
|
||||
const scope = yield* Effect.scope;
|
||||
const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
|
||||
const unsubscribe = yield* manager.attachStream(
|
||||
{
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cols: 100,
|
||||
rows: 40,
|
||||
},
|
||||
(event) => Ref.update(attachEvents, (events) => [...events, event]),
|
||||
);
|
||||
yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe));
|
||||
|
||||
const snapshot = (yield* Ref.get(attachEvents)).find((event) => event.type === "snapshot");
|
||||
expect(snapshot).toBeDefined();
|
||||
if (!snapshot || snapshot.type !== "snapshot") return;
|
||||
assert.equal(snapshot.snapshot.threadId, "thread-1");
|
||||
assert.equal(snapshot.snapshot.terminalId, DEFAULT_TERMINAL_ID);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(1);
|
||||
}),
|
||||
);
|
||||
|
||||
const makeDirectory = (filePath: string) =>
|
||||
Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
|
||||
fs.makeDirectory(filePath, { recursive: true }),
|
||||
@@ -1094,6 +1123,101 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("subscribes terminal metadata with an initial snapshot and live deltas", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager } = yield* createManager();
|
||||
yield* manager.open(openInput({ threadId: "existing-thread" }));
|
||||
|
||||
const scope = yield* Effect.scope;
|
||||
const metadataEvents = yield* Ref.make<ReadonlyArray<TerminalMetadataStreamEvent>>([]);
|
||||
const unsubscribe = yield* manager.subscribeMetadata((event) =>
|
||||
Ref.update(metadataEvents, (events) => [...events, event]),
|
||||
);
|
||||
yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe));
|
||||
|
||||
const initialEvents = yield* Ref.get(metadataEvents);
|
||||
expect(initialEvents[0]).toMatchObject({
|
||||
type: "snapshot",
|
||||
terminals: [
|
||||
{
|
||||
threadId: "existing-thread",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* manager.open(openInput({ threadId: "new-thread" }));
|
||||
|
||||
yield* waitFor(
|
||||
Effect.map(Ref.get(metadataEvents), (events) =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "upsert" &&
|
||||
event.terminal.threadId === "new-thread" &&
|
||||
event.terminal.terminalId === DEFAULT_TERMINAL_ID,
|
||||
),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
yield* manager.close({ threadId: "new-thread", terminalId: DEFAULT_TERMINAL_ID });
|
||||
|
||||
yield* waitFor(
|
||||
Effect.map(Ref.get(metadataEvents), (events) =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "remove" &&
|
||||
event.threadId === "new-thread" &&
|
||||
event.terminalId === DEFAULT_TERMINAL_ID,
|
||||
),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"streams attach snapshots followed by live events without duplicate start snapshots",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter } = yield* createManager(5, {
|
||||
ptyAdapter: new FakePtyAdapter("async"),
|
||||
});
|
||||
const scope = yield* Effect.scope;
|
||||
const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
|
||||
const unsubscribe = yield* manager.attachStream(openInput(), (event) =>
|
||||
Ref.update(attachEvents, (events) => [...events, event]),
|
||||
);
|
||||
yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe));
|
||||
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
|
||||
expect(yield* Ref.get(attachEvents)).toMatchObject([
|
||||
{
|
||||
type: "snapshot",
|
||||
snapshot: {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
process.emitData("hello from attach\n");
|
||||
|
||||
yield* waitFor(
|
||||
Effect.map(Ref.get(attachEvents), (events) =>
|
||||
events.some((event) => event.type === "output" && event.data === "hello from attach\n"),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
const events = yield* Ref.get(attachEvents);
|
||||
expect(events.filter((event) => event.type === "snapshot")).toHaveLength(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves queued PTY output ordering through exit callbacks", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter, getEvents } = yield* createManager(5, {
|
||||
@@ -1123,10 +1247,26 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
(event) => event.type === "output" || event.type === "exited",
|
||||
);
|
||||
expect(relevant).toEqual([
|
||||
expect.objectContaining({ type: "output", data: "first\n" }),
|
||||
expect.objectContaining({ type: "output", data: "second\n" }),
|
||||
expect.objectContaining({ type: "exited", exitCode: 0, exitSignal: 0 }),
|
||||
expect.objectContaining({ type: "output", data: "first\n", sequence: 2 }),
|
||||
expect.objectContaining({ type: "output", data: "second\n", sequence: 3 }),
|
||||
expect.objectContaining({ type: "exited", exitCode: 0, exitSignal: 0, sequence: 4 }),
|
||||
]);
|
||||
|
||||
const scope = yield* Effect.scope;
|
||||
const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
|
||||
const unsubscribe = yield* manager.attachStream(
|
||||
{
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
},
|
||||
(event) => Ref.update(attachEvents, (events) => [...events, event]),
|
||||
);
|
||||
yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe));
|
||||
|
||||
const snapshot = (yield* Ref.get(attachEvents)).find((event) => event.type === "snapshot");
|
||||
expect(snapshot).toBeDefined();
|
||||
if (!snapshot || snapshot.type !== "snapshot") return;
|
||||
expect(snapshot.snapshot.sequence).toBe(4);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -2,9 +2,14 @@ import path from "node:path";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type TerminalAttachInput,
|
||||
type TerminalAttachStreamEvent,
|
||||
type TerminalEvent,
|
||||
type TerminalMetadataStreamEvent,
|
||||
type TerminalOpenInput,
|
||||
type TerminalSessionSnapshot,
|
||||
type TerminalSessionStatus,
|
||||
type TerminalSummary,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
|
||||
import {
|
||||
@@ -107,6 +112,7 @@ interface TerminalSessionState {
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
updatedAt: string;
|
||||
eventSequence: number;
|
||||
cols: number;
|
||||
rows: number;
|
||||
process: PtyProcess | null;
|
||||
@@ -129,6 +135,7 @@ type DrainProcessEventAction =
|
||||
type: "output";
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
sequence: number;
|
||||
history: string | null;
|
||||
data: string;
|
||||
}
|
||||
@@ -137,6 +144,7 @@ type DrainProcessEventAction =
|
||||
process: PtyProcess | null;
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
sequence: number;
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
};
|
||||
@@ -158,9 +166,80 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
|
||||
exitCode: session.exitCode,
|
||||
exitSignal: session.exitSignal,
|
||||
updatedAt: session.updatedAt,
|
||||
sequence: session.eventSequence,
|
||||
};
|
||||
}
|
||||
|
||||
function summary(session: TerminalSessionState): TerminalSummary {
|
||||
return {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
cwd: session.cwd,
|
||||
worktreePath: session.worktreePath,
|
||||
status: session.status,
|
||||
pid: session.pid,
|
||||
exitCode: session.exitCode,
|
||||
exitSignal: session.exitSignal,
|
||||
hasRunningSubprocess: session.hasRunningSubprocess,
|
||||
updatedAt: session.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function shouldPublishTerminalMetadataEvent(event: TerminalEvent): boolean {
|
||||
switch (event.type) {
|
||||
case "started":
|
||||
case "restarted":
|
||||
case "exited":
|
||||
case "closed":
|
||||
case "error":
|
||||
case "activity":
|
||||
return true;
|
||||
case "output":
|
||||
case "cleared":
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function terminalEventToAttachEvent(event: TerminalEvent): TerminalAttachStreamEvent | null {
|
||||
switch (event.type) {
|
||||
case "started":
|
||||
return {
|
||||
type: "snapshot",
|
||||
snapshot: event.snapshot,
|
||||
};
|
||||
case "output":
|
||||
case "exited":
|
||||
case "closed":
|
||||
case "error":
|
||||
case "cleared":
|
||||
case "restarted":
|
||||
case "activity":
|
||||
return event;
|
||||
}
|
||||
}
|
||||
|
||||
function isDuplicateAttachSnapshotEvent(
|
||||
event: TerminalEvent,
|
||||
initialSnapshot: TerminalSessionSnapshot,
|
||||
) {
|
||||
return typeof event.sequence === "number" && typeof initialSnapshot.sequence === "number"
|
||||
? event.sequence <= initialSnapshot.sequence
|
||||
: event.type === "started" &&
|
||||
event.snapshot.threadId === initialSnapshot.threadId &&
|
||||
event.snapshot.terminalId === initialSnapshot.terminalId &&
|
||||
event.snapshot.updatedAt <= initialSnapshot.updatedAt;
|
||||
}
|
||||
|
||||
function advanceEventSequence(session: TerminalSessionState): {
|
||||
readonly updatedAt: string;
|
||||
readonly sequence: number;
|
||||
} {
|
||||
const updatedAt = new Date().toISOString();
|
||||
session.eventSequence += 1;
|
||||
session.updatedAt = updatedAt;
|
||||
return { updatedAt, sequence: session.eventSequence };
|
||||
}
|
||||
|
||||
function cleanupProcessHandles(session: TerminalSessionState): void {
|
||||
session.unsubscribeData?.();
|
||||
session.unsubscribeData = null;
|
||||
@@ -1194,12 +1273,13 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
historyLineLimit,
|
||||
);
|
||||
}
|
||||
session.updatedAt = new Date().toISOString();
|
||||
const eventStamp = advanceEventSequence(session);
|
||||
|
||||
return {
|
||||
type: "output",
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
sequence: eventStamp.sequence,
|
||||
history: sanitized.visibleText.length > 0 ? session.history : null,
|
||||
data: nextEvent.data,
|
||||
} as const;
|
||||
@@ -1221,13 +1301,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.exitSignal = Number.isInteger(nextEvent.event.signal)
|
||||
? nextEvent.event.signal
|
||||
: null;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
const eventStamp = advanceEventSequence(session);
|
||||
|
||||
return {
|
||||
type: "exit",
|
||||
process,
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
sequence: eventStamp.sequence,
|
||||
exitCode: session.exitCode,
|
||||
exitSignal: session.exitSignal,
|
||||
} as const;
|
||||
@@ -1246,7 +1327,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
type: "output",
|
||||
threadId: action.threadId,
|
||||
terminalId: action.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
sequence: action.sequence,
|
||||
data: action.data,
|
||||
});
|
||||
continue;
|
||||
@@ -1257,7 +1338,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
type: "exited",
|
||||
threadId: action.threadId,
|
||||
terminalId: action.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
sequence: action.sequence,
|
||||
exitCode: action.exitCode,
|
||||
exitSignal: action.exitSignal,
|
||||
});
|
||||
@@ -1404,13 +1485,17 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
runFork(drainProcessEvents(session, processPid));
|
||||
});
|
||||
|
||||
let eventStamp: ReturnType<typeof advanceEventSequence> = {
|
||||
updatedAt: session.updatedAt,
|
||||
sequence: session.eventSequence,
|
||||
};
|
||||
yield* modifyManagerState((state) => {
|
||||
session.process = ptyProcess;
|
||||
session.pid = processPid;
|
||||
session.status = "running";
|
||||
session.updatedAt = new Date().toISOString();
|
||||
session.unsubscribeData = unsubscribeData;
|
||||
session.unsubscribeExit = unsubscribeExit;
|
||||
eventStamp = advanceEventSequence(session);
|
||||
return [undefined, state] as const;
|
||||
});
|
||||
|
||||
@@ -1418,7 +1503,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
type: eventType,
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
sequence: eventStamp.sequence,
|
||||
snapshot: snapshot(session),
|
||||
});
|
||||
}),
|
||||
@@ -1446,7 +1531,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
advanceEventSequence(session);
|
||||
return [undefined, state] as const;
|
||||
});
|
||||
|
||||
@@ -1457,7 +1542,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
type: "error",
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
sequence: session.eventSequence,
|
||||
message,
|
||||
});
|
||||
yield* Effect.logError("failed to start terminal", {
|
||||
@@ -1476,6 +1561,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
) {
|
||||
const key = toSessionKey(threadId, terminalId);
|
||||
const session = yield* getSession(threadId, terminalId);
|
||||
const closedEventSequence = Option.isSome(session) ? session.value.eventSequence + 1 : 0;
|
||||
|
||||
if (Option.isSome(session)) {
|
||||
yield* stopProcess(session.value);
|
||||
@@ -1498,7 +1584,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
type: "closed",
|
||||
threadId,
|
||||
terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
sequence: closedEventSequence,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1552,14 +1638,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
}
|
||||
|
||||
liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value;
|
||||
liveSession.value.updatedAt = new Date().toISOString();
|
||||
const eventStamp = advanceEventSequence(liveSession.value);
|
||||
|
||||
return [
|
||||
Option.some({
|
||||
type: "activity" as const,
|
||||
threadId: liveSession.value.threadId,
|
||||
terminalId: liveSession.value.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
sequence: eventStamp.sequence,
|
||||
hasRunningSubprocess: hasRunningSubprocess.value,
|
||||
}),
|
||||
state,
|
||||
@@ -1624,141 +1710,339 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
);
|
||||
|
||||
const openLocked = Effect.fn("terminal.openLocked")(function* (input: TerminalOpenInput) {
|
||||
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
|
||||
yield* assertValidCwd(input.cwd);
|
||||
|
||||
const sessionKey = toSessionKey(input.threadId, terminalId);
|
||||
const existing = yield* getSession(input.threadId, terminalId);
|
||||
if (Option.isNone(existing)) {
|
||||
yield* flushPersist(input.threadId, terminalId);
|
||||
const history = yield* readHistory(input.threadId, terminalId);
|
||||
const cols = input.cols ?? DEFAULT_OPEN_COLS;
|
||||
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
|
||||
const session: TerminalSessionState = {
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
worktreePath: input.worktreePath ?? null,
|
||||
status: "starting",
|
||||
pid: null,
|
||||
history,
|
||||
pendingHistoryControlSequence: "",
|
||||
pendingProcessEvents: [],
|
||||
pendingProcessEventIndex: 0,
|
||||
processEventDrainRunning: false,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
eventSequence: 0,
|
||||
cols,
|
||||
rows,
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
|
||||
const createdSession = session;
|
||||
yield* modifyManagerState((state) => {
|
||||
const sessions = new Map(state.sessions);
|
||||
sessions.set(sessionKey, createdSession);
|
||||
return [undefined, { ...state, sessions }] as const;
|
||||
});
|
||||
|
||||
yield* evictInactiveSessionsIfNeeded();
|
||||
yield* startSession(
|
||||
session,
|
||||
{
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
|
||||
cols,
|
||||
rows,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
},
|
||||
"started",
|
||||
);
|
||||
return snapshot(session);
|
||||
}
|
||||
|
||||
const liveSession = existing.value;
|
||||
const nextRuntimeEnv = normalizedRuntimeEnv(input.env);
|
||||
const currentRuntimeEnv = liveSession.runtimeEnv;
|
||||
const targetCols = input.cols ?? liveSession.cols;
|
||||
const targetRows = input.rows ?? liveSession.rows;
|
||||
const runtimeEnvChanged = !Equal.equals(currentRuntimeEnv, nextRuntimeEnv);
|
||||
const nextWorktreePath =
|
||||
input.worktreePath !== undefined ? (input.worktreePath ?? null) : liveSession.worktreePath;
|
||||
const launchContextChanged =
|
||||
liveSession.cwd !== input.cwd ||
|
||||
runtimeEnvChanged ||
|
||||
liveSession.worktreePath !== nextWorktreePath;
|
||||
|
||||
if (launchContextChanged) {
|
||||
yield* stopProcess(liveSession);
|
||||
liveSession.cwd = input.cwd;
|
||||
liveSession.worktreePath = nextWorktreePath;
|
||||
liveSession.runtimeEnv = nextRuntimeEnv;
|
||||
liveSession.history = "";
|
||||
liveSession.pendingHistoryControlSequence = "";
|
||||
liveSession.pendingProcessEvents = [];
|
||||
liveSession.pendingProcessEventIndex = 0;
|
||||
liveSession.processEventDrainRunning = false;
|
||||
yield* persistHistory(liveSession.threadId, liveSession.terminalId, liveSession.history);
|
||||
} else if (liveSession.status === "exited" || liveSession.status === "error") {
|
||||
liveSession.runtimeEnv = nextRuntimeEnv;
|
||||
liveSession.worktreePath = nextWorktreePath;
|
||||
liveSession.history = "";
|
||||
liveSession.pendingHistoryControlSequence = "";
|
||||
liveSession.pendingProcessEvents = [];
|
||||
liveSession.pendingProcessEventIndex = 0;
|
||||
liveSession.processEventDrainRunning = false;
|
||||
yield* persistHistory(liveSession.threadId, liveSession.terminalId, liveSession.history);
|
||||
}
|
||||
|
||||
if (!liveSession.process) {
|
||||
yield* startSession(
|
||||
liveSession,
|
||||
{
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
worktreePath: liveSession.worktreePath,
|
||||
cols: targetCols,
|
||||
rows: targetRows,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
},
|
||||
"started",
|
||||
);
|
||||
return snapshot(liveSession);
|
||||
}
|
||||
|
||||
if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) {
|
||||
liveSession.cols = targetCols;
|
||||
liveSession.rows = targetRows;
|
||||
liveSession.updatedAt = new Date().toISOString();
|
||||
liveSession.process.resize(targetCols, targetRows);
|
||||
}
|
||||
|
||||
return snapshot(liveSession);
|
||||
});
|
||||
|
||||
const open: TerminalManagerShape["open"] = (input) =>
|
||||
withThreadLock(input.threadId, openLocked(input));
|
||||
|
||||
const openOrAttachForStream = (input: TerminalAttachInput) =>
|
||||
withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
|
||||
yield* assertValidCwd(input.cwd);
|
||||
|
||||
const sessionKey = toSessionKey(input.threadId, terminalId);
|
||||
const existing = yield* getSession(input.threadId, terminalId);
|
||||
|
||||
if (Option.isNone(existing)) {
|
||||
yield* flushPersist(input.threadId, terminalId);
|
||||
const history = yield* readHistory(input.threadId, terminalId);
|
||||
const cols = input.cols ?? DEFAULT_OPEN_COLS;
|
||||
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
|
||||
const session: TerminalSessionState = {
|
||||
threadId: input.threadId,
|
||||
if (!input.cwd) {
|
||||
return yield* new TerminalSessionLookupError({
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
});
|
||||
}
|
||||
|
||||
return yield* openLocked({
|
||||
...input,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
worktreePath: input.worktreePath ?? null,
|
||||
status: "starting",
|
||||
pid: null,
|
||||
history,
|
||||
pendingHistoryControlSequence: "",
|
||||
pendingProcessEvents: [],
|
||||
pendingProcessEventIndex: 0,
|
||||
processEventDrainRunning: false,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
cols,
|
||||
rows,
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
|
||||
const createdSession = session;
|
||||
yield* modifyManagerState((state) => {
|
||||
const sessions = new Map(state.sessions);
|
||||
sessions.set(sessionKey, createdSession);
|
||||
return [undefined, { ...state, sessions }] as const;
|
||||
});
|
||||
|
||||
yield* evictInactiveSessionsIfNeeded();
|
||||
yield* startSession(
|
||||
session,
|
||||
{
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
|
||||
cols,
|
||||
rows,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
},
|
||||
"started",
|
||||
);
|
||||
return snapshot(session);
|
||||
}
|
||||
|
||||
const liveSession = existing.value;
|
||||
const nextRuntimeEnv = normalizedRuntimeEnv(input.env);
|
||||
const currentRuntimeEnv = liveSession.runtimeEnv;
|
||||
const targetCols = input.cols ?? liveSession.cols;
|
||||
const targetRows = input.rows ?? liveSession.rows;
|
||||
const runtimeEnvChanged = !Equal.equals(currentRuntimeEnv, nextRuntimeEnv);
|
||||
const nextWorktreePath =
|
||||
input.worktreePath !== undefined
|
||||
? (input.worktreePath ?? null)
|
||||
: liveSession.worktreePath;
|
||||
const launchContextChanged =
|
||||
liveSession.cwd !== input.cwd ||
|
||||
runtimeEnvChanged ||
|
||||
liveSession.worktreePath !== nextWorktreePath;
|
||||
const session = existing.value;
|
||||
const targetCols = input.cols ?? session.cols;
|
||||
const targetRows = input.rows ?? session.rows;
|
||||
|
||||
if (launchContextChanged) {
|
||||
yield* stopProcess(liveSession);
|
||||
liveSession.cwd = input.cwd;
|
||||
liveSession.worktreePath = nextWorktreePath;
|
||||
liveSession.runtimeEnv = nextRuntimeEnv;
|
||||
liveSession.history = "";
|
||||
liveSession.pendingHistoryControlSequence = "";
|
||||
liveSession.pendingProcessEvents = [];
|
||||
liveSession.pendingProcessEventIndex = 0;
|
||||
liveSession.processEventDrainRunning = false;
|
||||
yield* persistHistory(
|
||||
liveSession.threadId,
|
||||
liveSession.terminalId,
|
||||
liveSession.history,
|
||||
);
|
||||
} else if (liveSession.status === "exited" || liveSession.status === "error") {
|
||||
liveSession.runtimeEnv = nextRuntimeEnv;
|
||||
liveSession.worktreePath = nextWorktreePath;
|
||||
liveSession.history = "";
|
||||
liveSession.pendingHistoryControlSequence = "";
|
||||
liveSession.pendingProcessEvents = [];
|
||||
liveSession.pendingProcessEventIndex = 0;
|
||||
liveSession.processEventDrainRunning = false;
|
||||
yield* persistHistory(
|
||||
liveSession.threadId,
|
||||
liveSession.terminalId,
|
||||
liveSession.history,
|
||||
);
|
||||
if (!session.process && input.cwd) {
|
||||
return yield* openLocked({
|
||||
...input,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
});
|
||||
}
|
||||
|
||||
if (!liveSession.process) {
|
||||
yield* startSession(
|
||||
liveSession,
|
||||
{
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
worktreePath: liveSession.worktreePath,
|
||||
cols: targetCols,
|
||||
rows: targetRows,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
},
|
||||
"started",
|
||||
);
|
||||
return snapshot(liveSession);
|
||||
if (
|
||||
session.process &&
|
||||
session.status === "running" &&
|
||||
(session.cols !== targetCols || session.rows !== targetRows)
|
||||
) {
|
||||
session.cols = targetCols;
|
||||
session.rows = targetRows;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
yield* Effect.sync(() => session.process?.resize(targetCols, targetRows));
|
||||
}
|
||||
|
||||
if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) {
|
||||
liveSession.cols = targetCols;
|
||||
liveSession.rows = targetRows;
|
||||
liveSession.updatedAt = new Date().toISOString();
|
||||
liveSession.process.resize(targetCols, targetRows);
|
||||
}
|
||||
|
||||
return snapshot(liveSession);
|
||||
return snapshot(session);
|
||||
}),
|
||||
);
|
||||
|
||||
const readAllTerminalMetadata = () =>
|
||||
readManagerState.pipe(
|
||||
Effect.map((state) =>
|
||||
[...state.sessions.values()]
|
||||
.map(summary)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.updatedAt.localeCompare(left.updatedAt) ||
|
||||
left.threadId.localeCompare(right.threadId) ||
|
||||
left.terminalId.localeCompare(right.terminalId),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const readTerminalMetadata = (input: {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
}) =>
|
||||
getSession(input.threadId, input.terminalId).pipe(
|
||||
Effect.map((session) => (Option.isSome(session) ? summary(session.value) : null)),
|
||||
);
|
||||
|
||||
const subscribe: TerminalManagerShape["subscribe"] = (listener) =>
|
||||
Effect.sync(() => {
|
||||
terminalEventListeners.add(listener);
|
||||
return () => {
|
||||
terminalEventListeners.delete(listener);
|
||||
};
|
||||
});
|
||||
|
||||
const attachStream: TerminalManagerShape["attachStream"] = (input, listener) => {
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const bufferedEvents: TerminalEvent[] = [];
|
||||
let deliverLive = false;
|
||||
|
||||
unsubscribe = yield* subscribe((event) => {
|
||||
if (event.threadId !== input.threadId || event.terminalId !== terminalId) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
if (!deliverLive) {
|
||||
bufferedEvents.push(event);
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
const attachEvent = terminalEventToAttachEvent(event);
|
||||
return attachEvent ? listener(attachEvent) : Effect.void;
|
||||
});
|
||||
|
||||
const initialSnapshot = yield* openOrAttachForStream(input);
|
||||
yield* listener({
|
||||
type: "snapshot",
|
||||
snapshot: initialSnapshot,
|
||||
});
|
||||
|
||||
for (const event of bufferedEvents) {
|
||||
if (isDuplicateAttachSnapshotEvent(event, initialSnapshot)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const attachEvent = terminalEventToAttachEvent(event);
|
||||
if (attachEvent) {
|
||||
yield* listener(attachEvent);
|
||||
}
|
||||
}
|
||||
|
||||
deliverLive = true;
|
||||
return () => {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
};
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.flatMap(
|
||||
Effect.sync(() => {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
}),
|
||||
() => Effect.failCause(cause),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const metadataEventFromTerminalEvent = (
|
||||
event: TerminalEvent,
|
||||
): Effect.Effect<TerminalMetadataStreamEvent | null> => {
|
||||
if (!shouldPublishTerminalMetadataEvent(event)) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
|
||||
if (event.type === "closed") {
|
||||
return Effect.succeed({
|
||||
type: "remove" as const,
|
||||
threadId: event.threadId,
|
||||
terminalId: event.terminalId,
|
||||
});
|
||||
}
|
||||
|
||||
return readTerminalMetadata({
|
||||
threadId: event.threadId,
|
||||
terminalId: event.terminalId,
|
||||
}).pipe(
|
||||
Effect.map((terminal) =>
|
||||
terminal
|
||||
? {
|
||||
type: "upsert" as const,
|
||||
terminal,
|
||||
}
|
||||
: null,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const offerMetadataEvent = (
|
||||
listener: (event: TerminalMetadataStreamEvent) => Effect.Effect<void>,
|
||||
event: TerminalEvent,
|
||||
) =>
|
||||
metadataEventFromTerminalEvent(event).pipe(
|
||||
Effect.flatMap((metadataEvent) => (metadataEvent ? listener(metadataEvent) : Effect.void)),
|
||||
);
|
||||
|
||||
const subscribeMetadata: TerminalManagerShape["subscribeMetadata"] = (listener) => {
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bufferedEvents: TerminalEvent[] = [];
|
||||
let deliverLive = false;
|
||||
|
||||
unsubscribe = yield* subscribe((event) => {
|
||||
if (!deliverLive) {
|
||||
bufferedEvents.push(event);
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return offerMetadataEvent(listener, event);
|
||||
});
|
||||
|
||||
const terminals = yield* readAllTerminalMetadata();
|
||||
yield* listener({
|
||||
type: "snapshot",
|
||||
terminals,
|
||||
});
|
||||
|
||||
for (const event of bufferedEvents) {
|
||||
yield* offerMetadataEvent(listener, event);
|
||||
}
|
||||
|
||||
deliverLive = true;
|
||||
return () => {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const write: TerminalManagerShape["write"] = Effect.fn("terminal.write")(function* (input) {
|
||||
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const session = yield* requireSession(input.threadId, terminalId);
|
||||
@@ -1800,13 +2084,13 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
const eventStamp = advanceEventSequence(session);
|
||||
yield* persistHistory(input.threadId, terminalId, session.history);
|
||||
yield* publishEvent({
|
||||
type: "cleared",
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
sequence: eventStamp.sequence,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1840,6 +2124,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
eventSequence: 0,
|
||||
cols,
|
||||
rows,
|
||||
process: null,
|
||||
@@ -1913,18 +2198,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
|
||||
return {
|
||||
open,
|
||||
attachStream,
|
||||
write,
|
||||
resize,
|
||||
clear,
|
||||
restart,
|
||||
close,
|
||||
subscribe: (listener) =>
|
||||
Effect.sync(() => {
|
||||
terminalEventListeners.add(listener);
|
||||
return () => {
|
||||
terminalEventListeners.delete(listener);
|
||||
};
|
||||
}),
|
||||
subscribe,
|
||||
subscribeMetadata,
|
||||
} satisfies TerminalManagerShape;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -7,12 +7,15 @@
|
||||
* @module TerminalManager
|
||||
*/
|
||||
import {
|
||||
TerminalAttachInput,
|
||||
TerminalAttachStreamEvent,
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
TerminalEvent,
|
||||
TerminalCwdError,
|
||||
TerminalError,
|
||||
TerminalHistoryError,
|
||||
TerminalMetadataStreamEvent,
|
||||
TerminalNotRunningError,
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
@@ -78,6 +81,16 @@ export interface TerminalManagerShape {
|
||||
input: TerminalOpenInput,
|
||||
) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;
|
||||
|
||||
/**
|
||||
* Attach to a terminal and stream its initial snapshot followed by live events.
|
||||
*
|
||||
* Returns an unsubscribe function.
|
||||
*/
|
||||
readonly attachStream: (
|
||||
input: TerminalAttachInput,
|
||||
listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
|
||||
) => Effect.Effect<() => void, TerminalError>;
|
||||
|
||||
/**
|
||||
* Write input bytes to a terminal session.
|
||||
*/
|
||||
@@ -117,6 +130,15 @@ export interface TerminalManagerShape {
|
||||
readonly subscribe: (
|
||||
listener: (event: TerminalEvent) => Effect.Effect<void>,
|
||||
) => Effect.Effect<() => void>;
|
||||
|
||||
/**
|
||||
* Subscribe to lightweight terminal metadata with an initial full snapshot.
|
||||
*
|
||||
* Returns an unsubscribe function.
|
||||
*/
|
||||
readonly subscribeMetadata: (
|
||||
listener: (event: TerminalMetadataStreamEvent) => Effect.Effect<void>,
|
||||
) => Effect.Effect<() => void>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -19,7 +19,10 @@ import {
|
||||
OrchestrationReplayEventsError,
|
||||
FilesystemBrowseError,
|
||||
ThreadId,
|
||||
type TerminalAttachStreamEvent,
|
||||
type TerminalError,
|
||||
type TerminalEvent,
|
||||
type TerminalMetadataStreamEvent,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -87,6 +90,7 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
}
|
||||
|
||||
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
|
||||
|
||||
function toAuthAccessStreamEvent(
|
||||
change: BootstrapCredentialChange | SessionCredentialChange,
|
||||
revision: number,
|
||||
@@ -926,6 +930,17 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
|
||||
"rpc.aggregate": "terminal",
|
||||
}),
|
||||
[WS_METHODS.terminalAttach]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.terminalAttach,
|
||||
Stream.callback<TerminalAttachStreamEvent, TerminalError>((queue) =>
|
||||
Effect.acquireRelease(
|
||||
terminalManager.attachStream(input, (event) => Queue.offer(queue, event)),
|
||||
(unsubscribe) => Effect.sync(unsubscribe),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "terminal" },
|
||||
),
|
||||
[WS_METHODS.terminalWrite]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {
|
||||
"rpc.aggregate": "terminal",
|
||||
@@ -957,6 +972,17 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
),
|
||||
{ "rpc.aggregate": "terminal" },
|
||||
),
|
||||
[WS_METHODS.subscribeTerminalMetadata]: (_input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeTerminalMetadata,
|
||||
Stream.callback<TerminalMetadataStreamEvent>((queue) =>
|
||||
Effect.acquireRelease(
|
||||
terminalManager.subscribeMetadata((event) => Queue.offer(queue, event)),
|
||||
(unsubscribe) => Effect.sync(unsubscribe),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "terminal" },
|
||||
),
|
||||
[WS_METHODS.subscribeServerConfig]: (_input) =>
|
||||
observeRpcStreamEffect(
|
||||
WS_METHODS.subscribeServerConfig,
|
||||
|
||||
@@ -10,12 +10,14 @@ import {
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ServerConfig,
|
||||
type TerminalMetadataStreamEvent,
|
||||
type ServerLifecycleWelcomePayload,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
WS_METHODS,
|
||||
OrchestrationSessionStatus,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
DEFAULT_TERMINAL_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
@@ -49,7 +51,8 @@ import { getServerConfig } from "../rpc/serverState";
|
||||
import { getRouter } from "../router";
|
||||
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
|
||||
import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { terminalSessionManager } from "../terminalSessionState";
|
||||
import { useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers";
|
||||
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
|
||||
@@ -95,6 +98,7 @@ interface TestFixture {
|
||||
snapshot: OrchestrationReadModel;
|
||||
serverConfig: ServerConfig;
|
||||
welcome: ServerLifecycleWelcomePayload;
|
||||
terminalMetadataEvents: ReadonlyArray<TerminalMetadataStreamEvent>;
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
@@ -385,6 +389,7 @@ function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
|
||||
bootstrapProjectId: PROJECT_ID,
|
||||
bootstrapThreadId: THREAD_ID,
|
||||
},
|
||||
terminalMetadataEvents: [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1599,6 +1604,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
]
|
||||
: [];
|
||||
}
|
||||
if (request._tag === WS_METHODS.subscribeTerminalMetadata) {
|
||||
return fixture.terminalMetadataEvents;
|
||||
}
|
||||
return [];
|
||||
},
|
||||
});
|
||||
@@ -1632,12 +1640,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
projectOrder: [],
|
||||
threadLastVisitedAtById: {},
|
||||
});
|
||||
useTerminalStateStore.persist.clearStorage();
|
||||
useTerminalStateStore.setState({
|
||||
terminalStateByThreadKey: {},
|
||||
terminalLaunchContextByThreadKey: {},
|
||||
terminalEventEntriesByKey: {},
|
||||
nextTerminalEventId: 1,
|
||||
useTerminalUiStateStore.persist.clearStorage();
|
||||
useTerminalUiStateStore.setState({
|
||||
terminalUiStateByThreadKey: {},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1746,24 +1751,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
}
|
||||
|
||||
useTerminalStateStore.setState({
|
||||
terminalStateByThreadKey: {
|
||||
useTerminalUiStateStore.setState({
|
||||
terminalUiStateByThreadKey: {
|
||||
[THREAD_KEY]: {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
},
|
||||
},
|
||||
terminalLaunchContextByThreadKey: {
|
||||
[THREAD_KEY]: {
|
||||
cwd: "/repo/project",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -2323,8 +2321,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
it("sends bootstrap turn-starts and waits for server setup on first-send worktree drafts", async () => {
|
||||
useTerminalStateStore.setState({
|
||||
terminalStateByThreadKey: {},
|
||||
useTerminalUiStateStore.setState({
|
||||
terminalUiStateByThreadKey: {},
|
||||
});
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadKey: {
|
||||
@@ -2707,8 +2705,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
it("shows the send state once bootstrap dispatch is in flight", async () => {
|
||||
useTerminalStateStore.setState({
|
||||
terminalStateByThreadKey: {},
|
||||
useTerminalUiStateStore.setState({
|
||||
terminalUiStateByThreadKey: {},
|
||||
});
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadKey: {
|
||||
@@ -3531,6 +3529,67 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("shows the sidebar terminal indicator from terminal metadata activity", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-terminal-metadata-indicator" as MessageId,
|
||||
targetText: "terminal metadata indicator target",
|
||||
}),
|
||||
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: true,
|
||||
updatedAt: isoAt(1_200),
|
||||
},
|
||||
},
|
||||
];
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(
|
||||
terminalSessionManager.listSessions({
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
threadId: THREAD_ID,
|
||||
}),
|
||||
).toMatchObject([
|
||||
{
|
||||
state: {
|
||||
hasRunningSubprocess: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const terminalIndicator = document.querySelector<HTMLElement>(
|
||||
'[aria-label="Terminal process running"]',
|
||||
);
|
||||
expect(terminalIndicator).not.toBeNull();
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows the confirm archive action after clicking the archive button", async () => {
|
||||
localStorage.setItem(
|
||||
"t3code:client-settings:v1",
|
||||
|
||||
@@ -132,7 +132,8 @@ import {
|
||||
type TerminalContextDraft,
|
||||
type TerminalContextSelection,
|
||||
} from "../lib/terminalContext";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { useThreadRunningTerminalIds } from "../terminalSessionState";
|
||||
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
|
||||
import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
|
||||
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
|
||||
@@ -440,14 +441,14 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
|
||||
: null;
|
||||
const project = useStore(useMemo(() => createProjectSelectorByRef(projectRef), [projectRef]));
|
||||
const terminalState = useTerminalStateStore((state) =>
|
||||
selectThreadTerminalState(state.terminalStateByThreadKey, threadRef),
|
||||
const terminalUiState = useTerminalUiStateStore((state) =>
|
||||
selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef),
|
||||
);
|
||||
const storeSetTerminalHeight = useTerminalStateStore((state) => state.setTerminalHeight);
|
||||
const storeSplitTerminal = useTerminalStateStore((state) => state.splitTerminal);
|
||||
const storeNewTerminal = useTerminalStateStore((state) => state.newTerminal);
|
||||
const storeSetActiveTerminal = useTerminalStateStore((state) => state.setActiveTerminal);
|
||||
const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal);
|
||||
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 [localFocusRequestId, setLocalFocusRequestId] = useState(0);
|
||||
const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const effectiveWorktreePath = useMemo(() => {
|
||||
@@ -514,7 +515,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
(terminalId: string) => {
|
||||
const api = readEnvironmentApi(threadRef.environmentId);
|
||||
if (!api) return;
|
||||
const isFinalTerminal = terminalState.terminalIds.length <= 1;
|
||||
const isFinalTerminal = terminalUiState.terminalIds.length <= 1;
|
||||
const fallbackExitWrite = () =>
|
||||
api.terminal.write({ threadId, terminalId, data: "exit\n" }).catch(() => undefined);
|
||||
|
||||
@@ -536,7 +537,13 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
storeCloseTerminal(threadRef, terminalId);
|
||||
bumpFocusRequestId();
|
||||
},
|
||||
[bumpFocusRequestId, storeCloseTerminal, terminalState.terminalIds.length, threadId, threadRef],
|
||||
[
|
||||
bumpFocusRequestId,
|
||||
storeCloseTerminal,
|
||||
terminalUiState.terminalIds.length,
|
||||
threadId,
|
||||
threadRef,
|
||||
],
|
||||
);
|
||||
|
||||
const handleAddTerminalContext = useCallback(
|
||||
@@ -549,7 +556,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
[onAddTerminalContext, visible],
|
||||
);
|
||||
|
||||
if (!project || !terminalState.terminalOpen || !cwd) {
|
||||
if (!project || !terminalUiState.terminalOpen || !cwd) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -562,11 +569,11 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
worktreePath={effectiveWorktreePath}
|
||||
runtimeEnv={runtimeEnv}
|
||||
visible={visible}
|
||||
height={terminalState.terminalHeight}
|
||||
terminalIds={terminalState.terminalIds}
|
||||
activeTerminalId={terminalState.activeTerminalId}
|
||||
terminalGroups={terminalState.terminalGroups}
|
||||
activeTerminalGroupId={terminalState.activeTerminalGroupId}
|
||||
height={terminalUiState.terminalHeight}
|
||||
terminalIds={terminalUiState.terminalIds}
|
||||
activeTerminalId={terminalUiState.activeTerminalId}
|
||||
terminalGroups={terminalUiState.terminalGroups}
|
||||
activeTerminalGroupId={terminalUiState.activeTerminalGroupId}
|
||||
focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
|
||||
onSplitTerminal={splitTerminal}
|
||||
onNewTerminal={createNewTerminal}
|
||||
@@ -691,9 +698,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
|
||||
const [pullRequestDialogState, setPullRequestDialogState] =
|
||||
useState<PullRequestDialogState | null>(null);
|
||||
const [terminalLaunchContext, setTerminalLaunchContext] = useState<TerminalLaunchContext | null>(
|
||||
null,
|
||||
);
|
||||
const [terminalUiLaunchContext, setTerminalUiLaunchContext] =
|
||||
useState<TerminalLaunchContext | null>(null);
|
||||
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
|
||||
Record<string, string[]>
|
||||
>({});
|
||||
@@ -710,23 +716,24 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
|
||||
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
|
||||
const sendInFlightRef = useRef(false);
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
|
||||
const terminalState = useTerminalStateStore((state) =>
|
||||
selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef),
|
||||
const terminalUiState = useTerminalUiStateStore((state) =>
|
||||
selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef),
|
||||
);
|
||||
const openTerminalThreadKeys = useTerminalStateStore(
|
||||
const openTerminalThreadKeys = useTerminalUiStateStore(
|
||||
useShallow((state) =>
|
||||
Object.entries(state.terminalStateByThreadKey).flatMap(([nextThreadKey, nextTerminalState]) =>
|
||||
nextTerminalState.terminalOpen ? [nextThreadKey] : [],
|
||||
Object.entries(state.terminalUiStateByThreadKey).flatMap(
|
||||
([nextThreadKey, nextTerminalUiState]) =>
|
||||
nextTerminalUiState.terminalOpen ? [nextThreadKey] : [],
|
||||
),
|
||||
),
|
||||
);
|
||||
const storeSetTerminalOpen = useTerminalStateStore((s) => s.setTerminalOpen);
|
||||
const storeSplitTerminal = useTerminalStateStore((s) => s.splitTerminal);
|
||||
const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal);
|
||||
const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal);
|
||||
const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal);
|
||||
const storeSetTerminalOpen = useTerminalUiStateStore((s) => s.setTerminalOpen);
|
||||
const storeSplitTerminal = useTerminalUiStateStore((s) => s.splitTerminal);
|
||||
const storeNewTerminal = useTerminalUiStateStore((s) => s.newTerminal);
|
||||
const storeSetActiveTerminal = useTerminalUiStateStore((s) => s.setActiveTerminal);
|
||||
const storeCloseTerminal = useTerminalUiStateStore((s) => s.closeTerminal);
|
||||
const serverThreadKeys = useStore(
|
||||
useShallow((state) =>
|
||||
selectThreadsAcrossEnvironments(state).map((thread) =>
|
||||
@@ -734,12 +741,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
),
|
||||
),
|
||||
);
|
||||
const storeServerTerminalLaunchContext = useTerminalStateStore(
|
||||
(s) => s.terminalLaunchContextByThreadKey[scopedThreadKey(routeThreadRef)] ?? null,
|
||||
);
|
||||
const storeClearTerminalLaunchContext = useTerminalStateStore(
|
||||
(s) => s.clearTerminalLaunchContext,
|
||||
);
|
||||
const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey);
|
||||
const draftThreadKeys = useMemo(
|
||||
() =>
|
||||
@@ -792,6 +793,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const canCheckoutPullRequestIntoThread = isLocalDraftThread;
|
||||
const diffOpen = rawSearch.diff === "1";
|
||||
const activeThreadId = activeThread?.id ?? null;
|
||||
const runningTerminalIds = useThreadRunningTerminalIds({
|
||||
environmentId: activeThread?.environmentId ?? null,
|
||||
threadId: activeThreadId,
|
||||
});
|
||||
const activeThreadRef = useMemo(
|
||||
() => (activeThread ? scopeThreadRef(activeThread.environmentId, activeThread.id) : null),
|
||||
[activeThread],
|
||||
@@ -821,7 +826,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
currentThreadIds,
|
||||
openThreadIds: existingOpenTerminalThreadKeys,
|
||||
activeThreadId: activeThreadKey,
|
||||
activeThreadTerminalOpen: Boolean(activeThreadKey && terminalState.terminalOpen),
|
||||
activeThreadTerminalOpen: Boolean(activeThreadKey && terminalUiState.terminalOpen),
|
||||
maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
});
|
||||
return currentThreadIds.length === nextThreadIds.length &&
|
||||
@@ -829,7 +834,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
? currentThreadIds
|
||||
: nextThreadIds;
|
||||
});
|
||||
}, [activeThreadKey, existingOpenTerminalThreadKeys, terminalState.terminalOpen]);
|
||||
}, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]);
|
||||
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
|
||||
const activeProjectRef = activeThread
|
||||
? scopeProjectRef(activeThread.environmentId, activeThread.projectId)
|
||||
@@ -1431,28 +1436,26 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
|
||||
const activeTerminalLaunchContext =
|
||||
terminalLaunchContext?.threadId === activeThreadId
|
||||
? terminalLaunchContext
|
||||
: (storeServerTerminalLaunchContext ?? null);
|
||||
terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null;
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const terminalShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
context: {
|
||||
terminalFocus: true,
|
||||
terminalOpen: Boolean(terminalState.terminalOpen),
|
||||
terminalOpen: Boolean(terminalUiState.terminalOpen),
|
||||
},
|
||||
}),
|
||||
[terminalState.terminalOpen],
|
||||
[terminalUiState.terminalOpen],
|
||||
);
|
||||
const nonTerminalShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
context: {
|
||||
terminalFocus: false,
|
||||
terminalOpen: Boolean(terminalState.terminalOpen),
|
||||
terminalOpen: Boolean(terminalUiState.terminalOpen),
|
||||
},
|
||||
}),
|
||||
[terminalState.terminalOpen],
|
||||
[terminalUiState.terminalOpen],
|
||||
);
|
||||
const terminalToggleShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "terminal.toggle"),
|
||||
@@ -1519,11 +1522,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
);
|
||||
|
||||
const activeTerminalGroup =
|
||||
terminalState.terminalGroups.find(
|
||||
(group) => group.id === terminalState.activeTerminalGroupId,
|
||||
terminalUiState.terminalGroups.find(
|
||||
(group) => group.id === terminalUiState.activeTerminalGroupId,
|
||||
) ??
|
||||
terminalState.terminalGroups.find((group) =>
|
||||
group.terminalIds.includes(terminalState.activeTerminalId),
|
||||
terminalUiState.terminalGroups.find((group) =>
|
||||
group.terminalIds.includes(terminalUiState.activeTerminalId),
|
||||
) ??
|
||||
null;
|
||||
const hasReachedSplitLimit =
|
||||
@@ -1575,8 +1578,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
);
|
||||
const toggleTerminalVisibility = useCallback(() => {
|
||||
if (!activeThreadRef) return;
|
||||
setTerminalOpen(!terminalState.terminalOpen);
|
||||
}, [activeThreadRef, setTerminalOpen, terminalState.terminalOpen]);
|
||||
setTerminalOpen(!terminalUiState.terminalOpen);
|
||||
}, [activeThreadRef, setTerminalOpen, terminalUiState.terminalOpen]);
|
||||
const splitTerminal = useCallback(() => {
|
||||
if (!activeThreadRef || hasReachedSplitLimit) return;
|
||||
const terminalId = `terminal-${randomUUID()}`;
|
||||
@@ -1593,7 +1596,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
(terminalId: string) => {
|
||||
const api = readEnvironmentApi(environmentId);
|
||||
if (!activeThreadId || !api) return;
|
||||
const isFinalTerminal = terminalState.terminalIds.length <= 1;
|
||||
const isFinalTerminal = terminalUiState.terminalIds.length <= 1;
|
||||
const fallbackExitWrite = () =>
|
||||
api.terminal
|
||||
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
|
||||
@@ -1624,7 +1627,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
activeThreadRef,
|
||||
environmentId,
|
||||
storeCloseTerminal,
|
||||
terminalState.terminalIds.length,
|
||||
terminalUiState.terminalIds.length,
|
||||
],
|
||||
);
|
||||
const runProjectScript = useCallback(
|
||||
@@ -1648,10 +1651,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}
|
||||
const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd;
|
||||
const baseTerminalId =
|
||||
terminalState.activeTerminalId ||
|
||||
terminalState.terminalIds[0] ||
|
||||
terminalUiState.activeTerminalId ||
|
||||
terminalUiState.terminalIds[0] ||
|
||||
DEFAULT_THREAD_TERMINAL_ID;
|
||||
const isBaseTerminalBusy = terminalState.runningTerminalIds.includes(baseTerminalId);
|
||||
const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId);
|
||||
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
|
||||
const shouldCreateNewTerminal = wantsNewTerminal;
|
||||
const targetTerminalId = shouldCreateNewTerminal
|
||||
@@ -1659,7 +1662,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
: baseTerminalId;
|
||||
const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
|
||||
|
||||
setTerminalLaunchContext({
|
||||
setTerminalUiLaunchContext({
|
||||
threadId: activeThreadId,
|
||||
cwd: targetCwd,
|
||||
worktreePath: targetWorktreePath,
|
||||
@@ -1726,9 +1729,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
storeSetActiveTerminal,
|
||||
setLastInvokedScriptByProjectId,
|
||||
environmentId,
|
||||
terminalState.activeTerminalId,
|
||||
terminalState.runningTerminalIds,
|
||||
terminalState.terminalIds,
|
||||
runningTerminalIds,
|
||||
terminalUiState.activeTerminalId,
|
||||
terminalUiState.terminalIds,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2029,14 +2032,14 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id || terminalState.terminalOpen) return;
|
||||
if (!activeThread?.id || terminalUiState.terminalOpen) return;
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
focusComposer();
|
||||
});
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frame);
|
||||
};
|
||||
}, [activeThread?.id, focusComposer, terminalState.terminalOpen]);
|
||||
}, [activeThread?.id, focusComposer, terminalUiState.terminalOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
@@ -2121,22 +2124,21 @@ export default function ChatView(props: ChatViewProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) {
|
||||
setTerminalLaunchContext(null);
|
||||
storeClearTerminalLaunchContext(routeThreadRef);
|
||||
setTerminalUiLaunchContext(null);
|
||||
return;
|
||||
}
|
||||
setTerminalLaunchContext((current) => {
|
||||
setTerminalUiLaunchContext((current) => {
|
||||
if (!current) return current;
|
||||
if (current.threadId === activeThreadId) return current;
|
||||
return null;
|
||||
});
|
||||
}, [activeThreadId, routeThreadRef, storeClearTerminalLaunchContext]);
|
||||
}, [activeThreadId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || !activeProjectCwd) {
|
||||
return;
|
||||
}
|
||||
setTerminalLaunchContext((current) => {
|
||||
setTerminalUiLaunchContext((current) => {
|
||||
if (!current || current.threadId !== activeThreadId) {
|
||||
return current;
|
||||
}
|
||||
@@ -2148,72 +2150,32 @@ export default function ChatView(props: ChatViewProps) {
|
||||
settledCwd === current.cwd &&
|
||||
(activeThreadWorktreePath ?? null) === current.worktreePath
|
||||
) {
|
||||
if (activeThreadRef) {
|
||||
storeClearTerminalLaunchContext(activeThreadRef);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return current;
|
||||
});
|
||||
}, [
|
||||
activeProjectCwd,
|
||||
activeThreadId,
|
||||
activeThreadRef,
|
||||
activeThreadWorktreePath,
|
||||
storeClearTerminalLaunchContext,
|
||||
]);
|
||||
}, [activeProjectCwd, activeThreadId, activeThreadWorktreePath]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || !activeProjectCwd || !storeServerTerminalLaunchContext) {
|
||||
if (terminalUiState.terminalOpen) {
|
||||
return;
|
||||
}
|
||||
const settledCwd = projectScriptCwd({
|
||||
project: { cwd: activeProjectCwd },
|
||||
worktreePath: activeThreadWorktreePath,
|
||||
});
|
||||
if (
|
||||
settledCwd === storeServerTerminalLaunchContext.cwd &&
|
||||
(activeThreadWorktreePath ?? null) === storeServerTerminalLaunchContext.worktreePath
|
||||
) {
|
||||
if (activeThreadRef) {
|
||||
storeClearTerminalLaunchContext(activeThreadRef);
|
||||
}
|
||||
}
|
||||
}, [
|
||||
activeProjectCwd,
|
||||
activeThreadId,
|
||||
activeThreadRef,
|
||||
activeThreadWorktreePath,
|
||||
storeClearTerminalLaunchContext,
|
||||
storeServerTerminalLaunchContext,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (terminalState.terminalOpen) {
|
||||
return;
|
||||
}
|
||||
if (activeThreadRef) {
|
||||
storeClearTerminalLaunchContext(activeThreadRef);
|
||||
}
|
||||
setTerminalLaunchContext((current) => (current?.threadId === activeThreadId ? null : current));
|
||||
}, [
|
||||
activeThreadId,
|
||||
activeThreadRef,
|
||||
storeClearTerminalLaunchContext,
|
||||
terminalState.terminalOpen,
|
||||
]);
|
||||
setTerminalUiLaunchContext((current) =>
|
||||
current?.threadId === activeThreadId ? null : current,
|
||||
);
|
||||
}, [activeThreadId, terminalUiState.terminalOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadKey) return;
|
||||
const previous = terminalOpenByThreadRef.current[activeThreadKey] ?? false;
|
||||
const current = Boolean(terminalState.terminalOpen);
|
||||
const previous = terminalUiOpenByThreadRef.current[activeThreadKey] ?? false;
|
||||
const current = Boolean(terminalUiState.terminalOpen);
|
||||
|
||||
if (!previous && current) {
|
||||
terminalOpenByThreadRef.current[activeThreadKey] = current;
|
||||
terminalUiOpenByThreadRef.current[activeThreadKey] = current;
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
return;
|
||||
} else if (previous && !current) {
|
||||
terminalOpenByThreadRef.current[activeThreadKey] = current;
|
||||
terminalUiOpenByThreadRef.current[activeThreadKey] = current;
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
focusComposer();
|
||||
});
|
||||
@@ -2222,8 +2184,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
};
|
||||
}
|
||||
|
||||
terminalOpenByThreadRef.current[activeThreadKey] = current;
|
||||
}, [activeThreadKey, focusComposer, terminalState.terminalOpen]);
|
||||
terminalUiOpenByThreadRef.current[activeThreadKey] = current;
|
||||
}, [activeThreadKey, focusComposer, terminalUiState.terminalOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: globalThis.KeyboardEvent) => {
|
||||
@@ -2232,7 +2194,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}
|
||||
const shortcutContext = {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen: Boolean(terminalState.terminalOpen),
|
||||
terminalOpen: Boolean(terminalUiState.terminalOpen),
|
||||
};
|
||||
|
||||
const command = resolveShortcutCommand(event, keybindings, {
|
||||
@@ -2250,7 +2212,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
if (command === "terminal.split") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!terminalState.terminalOpen) {
|
||||
if (!terminalUiState.terminalOpen) {
|
||||
setTerminalOpen(true);
|
||||
}
|
||||
splitTerminal();
|
||||
@@ -2260,15 +2222,15 @@ export default function ChatView(props: ChatViewProps) {
|
||||
if (command === "terminal.close") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!terminalState.terminalOpen) return;
|
||||
closeTerminal(terminalState.activeTerminalId);
|
||||
if (!terminalUiState.terminalOpen) return;
|
||||
closeTerminal(terminalUiState.activeTerminalId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "terminal.new") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!terminalState.terminalOpen) {
|
||||
if (!terminalUiState.terminalOpen) {
|
||||
setTerminalOpen(true);
|
||||
}
|
||||
createNewTerminal();
|
||||
@@ -2294,8 +2256,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
return () => window.removeEventListener("keydown", handler, true);
|
||||
}, [
|
||||
activeProject,
|
||||
terminalState.terminalOpen,
|
||||
terminalState.activeTerminalId,
|
||||
terminalUiState.terminalOpen,
|
||||
terminalUiState.activeTerminalId,
|
||||
activeThreadId,
|
||||
closeTerminal,
|
||||
createNewTerminal,
|
||||
@@ -3232,7 +3194,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
keybindings={keybindings}
|
||||
availableEditors={availableEditors}
|
||||
terminalAvailable={activeProject !== undefined}
|
||||
terminalOpen={terminalState.terminalOpen}
|
||||
terminalOpen={terminalUiState.terminalOpen}
|
||||
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
|
||||
diffToggleShortcutLabel={diffPanelShortcutLabel}
|
||||
gitCwd={gitCwd}
|
||||
@@ -3436,7 +3398,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
key={mountedThreadKey}
|
||||
threadRef={mountedThreadRef}
|
||||
threadId={mountedThreadRef.threadId}
|
||||
visible={mountedThreadKey === activeThreadKey && terminalState.terminalOpen}
|
||||
visible={mountedThreadKey === activeThreadKey && terminalUiState.terminalOpen}
|
||||
launchContext={
|
||||
mountedThreadKey === activeThreadKey ? (activeTerminalLaunchContext ?? null) : null
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ import {
|
||||
selectSidebarThreadsAcrossEnvironments,
|
||||
useStore,
|
||||
} from "../store";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import {
|
||||
ADDON_ICON_CLASS,
|
||||
@@ -149,9 +149,9 @@ export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
|
||||
const terminalOpen = useTerminalStateStore((state) =>
|
||||
const terminalOpen = useTerminalUiStateStore((state) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef).terminalOpen
|
||||
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
|
||||
: false,
|
||||
);
|
||||
|
||||
|
||||
@@ -70,7 +70,8 @@ import {
|
||||
selectThreadByRef,
|
||||
useStore,
|
||||
} from "../store";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { useThreadRunningTerminalIds } from "../terminalSessionState";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import {
|
||||
resolveShortcutCommand,
|
||||
@@ -336,10 +337,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
|
||||
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
|
||||
const hasSelection = useThreadSelectionStore((state) => state.selectedThreadKeys.size > 0);
|
||||
const runningTerminalIds = useTerminalStateStore(
|
||||
(state) =>
|
||||
selectThreadTerminalState(state.terminalStateByThreadKey, threadRef).runningTerminalIds,
|
||||
);
|
||||
const runningTerminalIds = useThreadRunningTerminalIds({
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
});
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const isRemoteThread =
|
||||
primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId;
|
||||
@@ -351,7 +352,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
);
|
||||
const threadEnvironmentLabel = isRemoteThread
|
||||
? (remoteEnvLabel ?? remoteEnvSavedLabel ?? "Remote")
|
||||
: "Local";
|
||||
: null;
|
||||
// For grouped projects, the thread may belong to a different environment
|
||||
// than the representative project. Look up the thread's own project cwd
|
||||
// so git status (and thus PR detection) queries the correct path.
|
||||
@@ -670,16 +671,21 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
) : null}
|
||||
<span className={threadMetaClassName}>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span
|
||||
title={threadEnvironmentLabel}
|
||||
className={`inline-flex max-w-18 items-center truncate rounded-full border border-border/70 bg-background/85 px-1.5 py-0.5 text-[9px] font-medium tracking-[0.08em] ${
|
||||
isHighlighted
|
||||
? "text-foreground/72 dark:text-foreground/82"
|
||||
: "text-muted-foreground/60"
|
||||
}`}
|
||||
>
|
||||
{threadEnvironmentLabel}
|
||||
</span>
|
||||
{isRemoteThread && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
aria-label={threadEnvironmentLabel ?? "Remote"}
|
||||
className="inline-flex items-center justify-center"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<CloudIcon className="size-3 text-muted-foreground/40" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{jumpLabel ? (
|
||||
<span
|
||||
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
|
||||
@@ -2812,8 +2818,8 @@ export default function Sidebar() {
|
||||
() => ({
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen: routeThreadRef
|
||||
? selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
? selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
routeThreadRef,
|
||||
).terminalOpen
|
||||
: false,
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
} from "../environments/runtime";
|
||||
import { useGitStatus } from "../lib/gitStatusState";
|
||||
import { type AppState, selectProjectByRef, useStore } from "../store";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { useThreadRunningTerminalIds } from "../terminalSessionState";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
|
||||
import type { SidebarThreadSummary } from "../types";
|
||||
@@ -72,7 +72,7 @@ export function resolveThreadPr(
|
||||
}
|
||||
|
||||
export function terminalStatusFromRunningIds(
|
||||
runningTerminalIds: string[],
|
||||
runningTerminalIds: ReadonlyArray<string>,
|
||||
): TerminalStatusIndicator | null {
|
||||
if (runningTerminalIds.length === 0) {
|
||||
return null;
|
||||
@@ -186,11 +186,10 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
* environment indicator, matching the sidebar's trailing indicators.
|
||||
*/
|
||||
export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
|
||||
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
|
||||
const runningTerminalIds = useTerminalStateStore(
|
||||
(state) =>
|
||||
selectThreadTerminalState(state.terminalStateByThreadKey, threadRef).runningTerminalIds,
|
||||
);
|
||||
const runningTerminalIds = useThreadRunningTerminalIds({
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
});
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const isRemoteThread =
|
||||
primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId;
|
||||
|
||||
@@ -2,8 +2,6 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveTerminalSelectionActionPosition,
|
||||
selectPendingTerminalEventEntries,
|
||||
selectTerminalEventEntriesAfterSnapshot,
|
||||
shouldHandleTerminalSelectionMouseUp,
|
||||
terminalSelectionActionDelayForClickCount,
|
||||
} from "./ThreadTerminalDrawer";
|
||||
@@ -74,64 +72,4 @@ describe("resolveTerminalSelectionActionPosition", () => {
|
||||
expect(shouldHandleTerminalSelectionMouseUp(false, 0)).toBe(false);
|
||||
expect(shouldHandleTerminalSelectionMouseUp(true, 1)).toBe(false);
|
||||
});
|
||||
|
||||
it("replays only terminal events newer than the open snapshot", () => {
|
||||
expect(
|
||||
selectTerminalEventEntriesAfterSnapshot(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
event: {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
createdAt: "2026-04-02T20:00:00.000Z",
|
||||
type: "output",
|
||||
data: "before",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
event: {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
createdAt: "2026-04-02T20:00:01.000Z",
|
||||
type: "output",
|
||||
data: "after",
|
||||
},
|
||||
},
|
||||
],
|
||||
"2026-04-02T20:00:00.500Z",
|
||||
).map((entry) => entry.id),
|
||||
).toEqual([2]);
|
||||
});
|
||||
|
||||
it("applies only terminal events that have not already been consumed", () => {
|
||||
expect(
|
||||
selectPendingTerminalEventEntries(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
event: {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
createdAt: "2026-04-02T20:00:00.000Z",
|
||||
type: "output",
|
||||
data: "one",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
event: {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
createdAt: "2026-04-02T20:00:01.000Z",
|
||||
type: "output",
|
||||
data: "two",
|
||||
},
|
||||
},
|
||||
],
|
||||
1,
|
||||
).map((entry) => entry.id),
|
||||
).toEqual([2]);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "luci
|
||||
import {
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ScopedThreadRef,
|
||||
type TerminalEvent,
|
||||
type TerminalAttachStreamEvent,
|
||||
type TerminalSessionSnapshot,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -47,7 +47,7 @@ import {
|
||||
} from "../types";
|
||||
import { readEnvironmentApi } from "~/environmentApi";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { selectTerminalEventEntries, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { attachTerminalSession } from "../terminalSessionState";
|
||||
|
||||
const MIN_DRAWER_HEIGHT = 180;
|
||||
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
|
||||
@@ -75,20 +75,6 @@ function writeTerminalSnapshot(terminal: Terminal, snapshot: TerminalSessionSnap
|
||||
}
|
||||
}
|
||||
|
||||
export function selectTerminalEventEntriesAfterSnapshot(
|
||||
entries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
|
||||
snapshotUpdatedAt: string,
|
||||
): ReadonlyArray<{ id: number; event: TerminalEvent }> {
|
||||
return entries.filter((entry) => entry.event.createdAt > snapshotUpdatedAt);
|
||||
}
|
||||
|
||||
export function selectPendingTerminalEventEntries(
|
||||
entries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
|
||||
lastAppliedTerminalEventId: number,
|
||||
): ReadonlyArray<{ id: number; event: TerminalEvent }> {
|
||||
return entries.filter((entry) => entry.id > lastAppliedTerminalEventId);
|
||||
}
|
||||
|
||||
function normalizeComputedColor(value: string | null | undefined, fallback: string): string {
|
||||
const normalizedValue = value?.trim().toLowerCase();
|
||||
if (
|
||||
@@ -291,8 +277,6 @@ export function TerminalViewport({
|
||||
const selectionActionOpenRef = useRef(false);
|
||||
const selectionActionTimerRef = useRef<number | null>(null);
|
||||
const keybindingsRef = useRef(keybindings);
|
||||
const lastAppliedTerminalEventIdRef = useRef(0);
|
||||
const terminalHydratedRef = useRef(false);
|
||||
const handleSessionExited = useEffectEvent(() => {
|
||||
onSessionExited();
|
||||
});
|
||||
@@ -567,7 +551,7 @@ export function TerminalViewport({
|
||||
attributeFilter: ["class", "style"],
|
||||
});
|
||||
|
||||
const applyTerminalEvent = (event: TerminalEvent) => {
|
||||
const applyAttachEvent = (event: TerminalAttachStreamEvent) => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) {
|
||||
return;
|
||||
@@ -577,13 +561,20 @@ export function TerminalViewport({
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "snapshot") {
|
||||
hasHandledExitRef.current = false;
|
||||
clearSelectionAction();
|
||||
writeTerminalSnapshot(activeTerminal, event.snapshot);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "output") {
|
||||
activeTerminal.write(event.data);
|
||||
clearSelectionAction();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "started" || event.type === "restarted") {
|
||||
if (event.type === "restarted") {
|
||||
hasHandledExitRef.current = false;
|
||||
clearSelectionAction();
|
||||
writeTerminalSnapshot(activeTerminal, event.snapshot);
|
||||
@@ -628,54 +619,16 @@ export function TerminalViewport({
|
||||
handleSessionExited();
|
||||
}, 0);
|
||||
};
|
||||
const applyPendingTerminalEvents = (
|
||||
terminalEventEntries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
|
||||
) => {
|
||||
const pendingEntries = selectPendingTerminalEventEntries(
|
||||
terminalEventEntries,
|
||||
lastAppliedTerminalEventIdRef.current,
|
||||
);
|
||||
if (pendingEntries.length === 0) {
|
||||
return;
|
||||
}
|
||||
for (const entry of pendingEntries) {
|
||||
applyTerminalEvent(entry.event);
|
||||
}
|
||||
lastAppliedTerminalEventIdRef.current =
|
||||
pendingEntries.at(-1)?.id ?? lastAppliedTerminalEventIdRef.current;
|
||||
};
|
||||
|
||||
const unsubscribeTerminalEvents = useTerminalStateStore.subscribe((state, previousState) => {
|
||||
if (!terminalHydratedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const previousLastEntryId =
|
||||
selectTerminalEventEntries(
|
||||
previousState.terminalEventEntriesByKey,
|
||||
threadRef,
|
||||
terminalId,
|
||||
).at(-1)?.id ?? 0;
|
||||
const nextEntries = selectTerminalEventEntries(
|
||||
state.terminalEventEntriesByKey,
|
||||
threadRef,
|
||||
terminalId,
|
||||
);
|
||||
const nextLastEntryId = nextEntries.at(-1)?.id ?? 0;
|
||||
if (nextLastEntryId === previousLastEntryId) {
|
||||
return;
|
||||
}
|
||||
|
||||
applyPendingTerminalEvents(nextEntries);
|
||||
});
|
||||
|
||||
const openTerminal = async () => {
|
||||
try {
|
||||
const activeTerminal = terminalRef.current;
|
||||
const activeFitAddon = fitAddonRef.current;
|
||||
if (!activeTerminal || !activeFitAddon) return;
|
||||
activeFitAddon.fit();
|
||||
const snapshot = await api.terminal.open({
|
||||
let unsubscribeAttach: (() => void) | null = null;
|
||||
const attachTerminal = () => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
const activeFitAddon = fitAddonRef.current;
|
||||
if (!activeTerminal || !activeFitAddon) return;
|
||||
activeFitAddon.fit();
|
||||
unsubscribeAttach = attachTerminalSession({
|
||||
environmentId,
|
||||
client: api,
|
||||
terminal: {
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd,
|
||||
@@ -683,35 +636,20 @@ export function TerminalViewport({
|
||||
cols: activeTerminal.cols,
|
||||
rows: activeTerminal.rows,
|
||||
...(runtimeEnv ? { env: runtimeEnv } : {}),
|
||||
});
|
||||
if (disposed) return;
|
||||
writeTerminalSnapshot(activeTerminal, snapshot);
|
||||
const bufferedEntries = selectTerminalEventEntries(
|
||||
useTerminalStateStore.getState().terminalEventEntriesByKey,
|
||||
threadRef,
|
||||
terminalId,
|
||||
);
|
||||
const replayEntries = selectTerminalEventEntriesAfterSnapshot(
|
||||
bufferedEntries,
|
||||
snapshot.updatedAt,
|
||||
);
|
||||
for (const entry of replayEntries) {
|
||||
applyTerminalEvent(entry.event);
|
||||
}
|
||||
lastAppliedTerminalEventIdRef.current = bufferedEntries.at(-1)?.id ?? 0;
|
||||
terminalHydratedRef.current = true;
|
||||
if (autoFocus) {
|
||||
window.requestAnimationFrame(() => {
|
||||
activeTerminal.focus();
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
if (disposed) return;
|
||||
writeSystemMessage(
|
||||
terminal,
|
||||
err instanceof Error ? err.message : "Failed to open terminal",
|
||||
);
|
||||
}
|
||||
},
|
||||
onEvent: (event) => {
|
||||
if (disposed) return;
|
||||
applyAttachEvent(event);
|
||||
},
|
||||
onSnapshot: () => {
|
||||
if (disposed) return;
|
||||
if (autoFocus) {
|
||||
window.requestAnimationFrame(() => {
|
||||
activeTerminal.focus();
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const fitTimer = window.setTimeout(() => {
|
||||
@@ -733,13 +671,12 @@ export function TerminalViewport({
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 30);
|
||||
void openTerminal();
|
||||
attachTerminal();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
terminalHydratedRef.current = false;
|
||||
lastAppliedTerminalEventIdRef.current = 0;
|
||||
unsubscribeTerminalEvents();
|
||||
unsubscribeAttach?.();
|
||||
unsubscribeAttach = null;
|
||||
window.clearTimeout(fitTimer);
|
||||
inputDisposable.dispose();
|
||||
selectionDisposable.dispose();
|
||||
|
||||
@@ -9,12 +9,14 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
|
||||
return {
|
||||
terminal: {
|
||||
open: (input) => rpcClient.terminal.open(input as never),
|
||||
attach: (input, callback, options) =>
|
||||
rpcClient.terminal.attach(input as never, callback, options),
|
||||
write: (input) => rpcClient.terminal.write(input as never),
|
||||
resize: (input) => rpcClient.terminal.resize(input as never),
|
||||
clear: (input) => rpcClient.terminal.clear(input as never),
|
||||
restart: (input) => rpcClient.terminal.restart(input as never),
|
||||
close: (input) => rpcClient.terminal.close(input as never),
|
||||
onEvent: (callback) => rpcClient.terminal.onEvent(callback),
|
||||
onMetadata: (callback, options) => rpcClient.terminal.onMetadata(callback, options),
|
||||
},
|
||||
projects: {
|
||||
searchEntries: rpcClient.projects.searchEntries,
|
||||
|
||||
@@ -7,7 +7,6 @@ import type { WsRpcClient } from "~/rpc/wsRpcClient";
|
||||
function createTestClient() {
|
||||
const lifecycleListeners = new Set<(event: any) => void>();
|
||||
const configListeners = new Set<(event: any) => void>();
|
||||
const terminalListeners = new Set<(event: any) => void>();
|
||||
const shellListeners = new Set<(event: any) => void>();
|
||||
let shellResubscribe: (() => void) | undefined;
|
||||
|
||||
@@ -67,15 +66,13 @@ function createTestClient() {
|
||||
},
|
||||
terminal: {
|
||||
open: vi.fn(async () => undefined),
|
||||
attach: vi.fn(() => () => undefined),
|
||||
write: vi.fn(async () => undefined),
|
||||
resize: vi.fn(async () => undefined),
|
||||
clear: vi.fn(async () => undefined),
|
||||
restart: vi.fn(async () => undefined),
|
||||
close: vi.fn(async () => undefined),
|
||||
onEvent: (listener: (event: any) => void) => {
|
||||
terminalListeners.add(listener);
|
||||
return () => terminalListeners.delete(listener);
|
||||
},
|
||||
onMetadata: vi.fn(() => () => undefined),
|
||||
},
|
||||
projects: {
|
||||
searchEntries: vi.fn(async () => []),
|
||||
@@ -164,7 +161,6 @@ describe("createEnvironmentConnection", () => {
|
||||
client,
|
||||
applyShellEvent: vi.fn(),
|
||||
syncShellSnapshot,
|
||||
applyTerminalEvent: vi.fn(),
|
||||
});
|
||||
|
||||
await connection.ensureBootstrapped();
|
||||
@@ -196,7 +192,6 @@ describe("createEnvironmentConnection", () => {
|
||||
client,
|
||||
applyShellEvent: vi.fn(),
|
||||
syncShellSnapshot: vi.fn(),
|
||||
applyTerminalEvent: vi.fn(),
|
||||
});
|
||||
|
||||
expect(() => emitWelcome(EnvironmentId.make("env-2"))).toThrow(
|
||||
@@ -226,7 +221,6 @@ describe("createEnvironmentConnection", () => {
|
||||
client,
|
||||
applyShellEvent: vi.fn(),
|
||||
syncShellSnapshot,
|
||||
applyTerminalEvent: vi.fn(),
|
||||
});
|
||||
|
||||
await connection.ensureBootstrapped();
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { shouldApplyTerminalEvent } from "./service";
|
||||
|
||||
describe("shouldApplyTerminalEvent", () => {
|
||||
it("applies terminal events for draft-only threads", () => {
|
||||
expect(
|
||||
shouldApplyTerminalEvent({
|
||||
serverThreadArchivedAt: undefined,
|
||||
hasDraftThread: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("drops terminal events for unknown threads", () => {
|
||||
expect(
|
||||
shouldApplyTerminalEvent({
|
||||
serverThreadArchivedAt: undefined,
|
||||
hasDraftThread: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("drops terminal events for archived server threads even if a draft exists", () => {
|
||||
expect(
|
||||
shouldApplyTerminalEvent({
|
||||
serverThreadArchivedAt: "2026-04-09T00:00:00.000Z",
|
||||
hasDraftThread: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("applies terminal events for active server threads", () => {
|
||||
expect(
|
||||
shouldApplyTerminalEvent({
|
||||
serverThreadArchivedAt: null,
|
||||
hasDraftThread: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationShellStreamEvent,
|
||||
type ServerConfig,
|
||||
type TerminalEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { type QueryClient } from "@tanstack/react-query";
|
||||
@@ -24,7 +23,7 @@ import {
|
||||
useComposerDraftStore,
|
||||
} from "~/composerDraftStore";
|
||||
import { ensureLocalApi } from "~/localApi";
|
||||
import { collectActiveTerminalThreadIds } from "~/lib/terminalStateCleanup";
|
||||
import { collectActiveTerminalUiThreadKeys } from "~/lib/terminalUiStateCleanup";
|
||||
import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects";
|
||||
import { projectQueryKeys } from "~/lib/projectReactQuery";
|
||||
import { providerQueryKeys } from "~/lib/providerReactQuery";
|
||||
@@ -57,11 +56,12 @@ import {
|
||||
selectThreadByRef,
|
||||
selectThreadsAcrossEnvironments,
|
||||
} from "~/store";
|
||||
import { useTerminalStateStore } from "~/terminalStateStore";
|
||||
import { useTerminalUiStateStore } from "~/terminalUiStateStore";
|
||||
import { useUiStateStore } from "~/uiStateStore";
|
||||
import { WsTransport } from "../../rpc/wsTransport";
|
||||
import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient";
|
||||
import { derivePhysicalProjectKey } from "../../logicalProject";
|
||||
import { subscribeTerminalMetadata, terminalSessionManager } from "../../terminalSessionState";
|
||||
|
||||
type EnvironmentServiceState = {
|
||||
readonly queryClient: QueryClient;
|
||||
@@ -83,6 +83,7 @@ type ThreadDetailSubscriptionEntry = {
|
||||
const environmentConnections = new Map<EnvironmentId, EnvironmentConnection>();
|
||||
const environmentConnectionListeners = new Set<() => void>();
|
||||
const threadDetailSubscriptions = new Map<string, ThreadDetailSubscriptionEntry>();
|
||||
const terminalMetadataSubscriptions = new Map<EnvironmentId, () => void>();
|
||||
|
||||
let activeService: EnvironmentServiceState | null = null;
|
||||
let needsProviderInvalidation = false;
|
||||
@@ -494,7 +495,7 @@ function reconcileSnapshotDerivedState() {
|
||||
syncThreadUiFromStore();
|
||||
|
||||
const threads = selectThreadsAcrossEnvironments(useStore.getState());
|
||||
const activeThreadKeys = collectActiveTerminalThreadIds({
|
||||
const activeThreadKeys = collectActiveTerminalUiThreadKeys({
|
||||
snapshotThreads: threads.map((thread) => ({
|
||||
key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
|
||||
deletedAt: null,
|
||||
@@ -502,18 +503,7 @@ function reconcileSnapshotDerivedState() {
|
||||
})),
|
||||
draftThreadKeys: useComposerDraftStore.getState().listDraftThreadKeys(),
|
||||
});
|
||||
useTerminalStateStore.getState().removeOrphanedTerminalStates(activeThreadKeys);
|
||||
}
|
||||
|
||||
export function shouldApplyTerminalEvent(input: {
|
||||
serverThreadArchivedAt: string | null | undefined;
|
||||
hasDraftThread: boolean;
|
||||
}): boolean {
|
||||
if (input.serverThreadArchivedAt !== undefined) {
|
||||
return input.serverThreadArchivedAt === null;
|
||||
}
|
||||
|
||||
return input.hasDraftThread;
|
||||
useTerminalUiStateStore.getState().removeOrphanedTerminalUiStates(activeThreadKeys);
|
||||
}
|
||||
|
||||
function applyRecoveredEventBatch(
|
||||
@@ -577,8 +567,10 @@ function applyRecoveredEventBatch(
|
||||
draftStore.clearProjectDraftThreadId(scopeProjectRef(environmentId, event.payload.projectId));
|
||||
}
|
||||
}
|
||||
for (const threadId of batchEffects.removeTerminalStateThreadIds) {
|
||||
useTerminalStateStore.getState().removeTerminalState(scopeThreadRef(environmentId, threadId));
|
||||
for (const threadId of batchEffects.removeTerminalUiStateThreadIds) {
|
||||
useTerminalUiStateStore
|
||||
.getState()
|
||||
.removeTerminalUiState(scopeThreadRef(environmentId, threadId));
|
||||
}
|
||||
|
||||
reconcileThreadDetailSubscriptionEvictionForEnvironment(environmentId);
|
||||
@@ -614,7 +606,7 @@ function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: En
|
||||
markPromotedDraftThreadByRef(threadRef);
|
||||
}
|
||||
if (previousThread?.archivedAt === null && event.thread.archivedAt !== null && threadRef) {
|
||||
useTerminalStateStore.getState().removeTerminalState(threadRef);
|
||||
useTerminalUiStateStore.getState().removeTerminalUiState(threadRef);
|
||||
}
|
||||
reconcileThreadDetailSubscriptionEvictionForThread(environmentId, event.thread.id);
|
||||
evictIdleThreadDetailSubscriptionsToCapacity();
|
||||
@@ -624,7 +616,7 @@ function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: En
|
||||
disposeThreadDetailSubscriptionByKey(scopedThreadKey(threadRef));
|
||||
useComposerDraftStore.getState().clearDraftThread(threadRef);
|
||||
useUiStateStore.getState().clearThreadUi(scopedThreadKey(threadRef));
|
||||
useTerminalStateStore.getState().removeTerminalState(threadRef);
|
||||
useTerminalUiStateStore.getState().removeTerminalUiState(threadRef);
|
||||
}
|
||||
syncThreadUiFromStore();
|
||||
return;
|
||||
@@ -643,21 +635,6 @@ function createEnvironmentConnectionHandlers() {
|
||||
reconcileThreadDetailSubscriptionEvictionForEnvironment(environmentId);
|
||||
reconcileSnapshotDerivedState();
|
||||
},
|
||||
applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => {
|
||||
const threadRef = scopeThreadRef(environmentId, ThreadId.make(event.threadId));
|
||||
const serverThread = selectThreadByRef(useStore.getState(), threadRef);
|
||||
const hasDraftThread =
|
||||
useComposerDraftStore.getState().getDraftThreadByRef(threadRef) !== null;
|
||||
if (
|
||||
!shouldApplyTerminalEvent({
|
||||
serverThreadArchivedAt: serverThread?.archivedAt,
|
||||
hasDraftThread,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
useTerminalStateStore.getState().applyTerminalEvent(threadRef, event);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -739,6 +716,14 @@ function registerConnection(connection: EnvironmentConnection): EnvironmentConne
|
||||
throw new Error(`Environment ${connection.environmentId} already has an active connection.`);
|
||||
}
|
||||
environmentConnections.set(connection.environmentId, connection);
|
||||
terminalMetadataSubscriptions.get(connection.environmentId)?.();
|
||||
terminalMetadataSubscriptions.set(
|
||||
connection.environmentId,
|
||||
subscribeTerminalMetadata({
|
||||
environmentId: connection.environmentId,
|
||||
client: connection.client,
|
||||
}),
|
||||
);
|
||||
emitEnvironmentConnectionRegistryChange();
|
||||
return connection;
|
||||
}
|
||||
@@ -751,6 +736,9 @@ async function removeConnection(environmentId: EnvironmentId): Promise<boolean>
|
||||
|
||||
disposeThreadDetailSubscriptionsForEnvironment(environmentId);
|
||||
environmentConnections.delete(environmentId);
|
||||
terminalMetadataSubscriptions.get(environmentId)?.();
|
||||
terminalMetadataSubscriptions.delete(environmentId);
|
||||
terminalSessionManager.invalidateEnvironment(environmentId);
|
||||
emitEnvironmentConnectionRegistryChange();
|
||||
await connection.dispose();
|
||||
return true;
|
||||
@@ -1081,6 +1069,11 @@ export async function resetEnvironmentServiceForTests(): Promise<void> {
|
||||
for (const key of Array.from(threadDetailSubscriptions.keys())) {
|
||||
disposeThreadDetailSubscriptionByKey(key);
|
||||
}
|
||||
for (const unsubscribe of terminalMetadataSubscriptions.values()) {
|
||||
unsubscribe();
|
||||
}
|
||||
terminalMetadataSubscriptions.clear();
|
||||
terminalSessionManager.reset();
|
||||
await Promise.all(
|
||||
[...environmentConnections.keys()].map((environmentId) => removeConnection(environmentId)),
|
||||
);
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
selectThreadsForEnvironment,
|
||||
useStore,
|
||||
} from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { toastManager } from "../components/ui/toast";
|
||||
@@ -30,7 +30,7 @@ export function useThreadActions() {
|
||||
const clearProjectDraftThreadById = useComposerDraftStore(
|
||||
(store) => store.clearProjectDraftThreadById,
|
||||
);
|
||||
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
|
||||
const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
|
||||
const router = useRouter();
|
||||
const { handleNewThread } = useNewThreadHandler();
|
||||
// Keep a ref so archiveThread can call handleNewThread without appearing in
|
||||
@@ -180,7 +180,7 @@ export function useThreadActions() {
|
||||
scopeProjectRef(threadRef.environmentId, thread.projectId),
|
||||
threadRef,
|
||||
);
|
||||
clearTerminalState(threadRef);
|
||||
clearTerminalUiState(threadRef);
|
||||
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
@@ -235,7 +235,7 @@ export function useThreadActions() {
|
||||
[
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadById,
|
||||
clearTerminalState,
|
||||
clearTerminalUiState,
|
||||
getCurrentRouteThreadRef,
|
||||
router,
|
||||
queryClient,
|
||||
|
||||
+9
-9
@@ -2,15 +2,15 @@ import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { collectActiveTerminalThreadIds } from "./terminalStateCleanup";
|
||||
import { collectActiveTerminalUiThreadKeys } from "./terminalUiStateCleanup";
|
||||
|
||||
const threadId = (id: string): ThreadId => ThreadId.make(id);
|
||||
const threadKey = (environmentId: string, id: string): string =>
|
||||
scopedThreadKey(scopeThreadRef(environmentId as never, threadId(id)));
|
||||
|
||||
describe("collectActiveTerminalThreadIds", () => {
|
||||
describe("collectActiveTerminalUiThreadKeys", () => {
|
||||
it("retains non-deleted server threads", () => {
|
||||
const activeThreadIds = collectActiveTerminalThreadIds({
|
||||
const activeThreadKeys = collectActiveTerminalUiThreadKeys({
|
||||
snapshotThreads: [
|
||||
{ key: threadKey("env-a", "server-1"), deletedAt: null, archivedAt: null },
|
||||
{ key: threadKey("env-b", "server-2"), deletedAt: null, archivedAt: null },
|
||||
@@ -18,13 +18,13 @@ describe("collectActiveTerminalThreadIds", () => {
|
||||
draftThreadKeys: [],
|
||||
});
|
||||
|
||||
expect(activeThreadIds).toEqual(
|
||||
expect(activeThreadKeys).toEqual(
|
||||
new Set([threadKey("env-a", "server-1"), threadKey("env-b", "server-2")]),
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores deleted and archived server threads and keeps local draft threads", () => {
|
||||
const activeThreadIds = collectActiveTerminalThreadIds({
|
||||
const activeThreadKeys = collectActiveTerminalUiThreadKeys({
|
||||
snapshotThreads: [
|
||||
{ key: threadKey("env-a", "server-active"), deletedAt: null, archivedAt: null },
|
||||
{
|
||||
@@ -41,15 +41,15 @@ describe("collectActiveTerminalThreadIds", () => {
|
||||
draftThreadKeys: [threadKey("env-a", "local-draft")],
|
||||
});
|
||||
|
||||
expect(activeThreadIds).toEqual(
|
||||
expect(activeThreadKeys).toEqual(
|
||||
new Set([threadKey("env-a", "server-active"), threadKey("env-a", "local-draft")]),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not keep draft-linked terminal state for archived server threads", () => {
|
||||
it("does not keep draft-linked terminal UI state for archived server threads", () => {
|
||||
const archivedThreadId = threadKey("env-a", "server-archived");
|
||||
|
||||
const activeThreadIds = collectActiveTerminalThreadIds({
|
||||
const activeThreadKeys = collectActiveTerminalUiThreadKeys({
|
||||
snapshotThreads: [
|
||||
{
|
||||
key: archivedThreadId,
|
||||
@@ -60,6 +60,6 @@ describe("collectActiveTerminalThreadIds", () => {
|
||||
draftThreadKeys: [archivedThreadId, threadKey("env-a", "local-draft")],
|
||||
});
|
||||
|
||||
expect(activeThreadIds).toEqual(new Set([threadKey("env-a", "local-draft")]));
|
||||
expect(activeThreadKeys).toEqual(new Set([threadKey("env-a", "local-draft")]));
|
||||
});
|
||||
});
|
||||
+9
-9
@@ -1,23 +1,23 @@
|
||||
interface TerminalRetentionThread {
|
||||
interface TerminalUiRetentionThread {
|
||||
key: string;
|
||||
deletedAt: string | null;
|
||||
archivedAt: string | null;
|
||||
}
|
||||
|
||||
interface CollectActiveTerminalThreadIdsInput {
|
||||
snapshotThreads: readonly TerminalRetentionThread[];
|
||||
interface CollectActiveTerminalUiThreadKeysInput {
|
||||
snapshotThreads: readonly TerminalUiRetentionThread[];
|
||||
draftThreadKeys: Iterable<string>;
|
||||
}
|
||||
|
||||
export function collectActiveTerminalThreadIds(
|
||||
input: CollectActiveTerminalThreadIdsInput,
|
||||
export function collectActiveTerminalUiThreadKeys(
|
||||
input: CollectActiveTerminalUiThreadKeysInput,
|
||||
): Set<string> {
|
||||
const activeThreadIds = new Set<string>();
|
||||
const activeThreadKeys = new Set<string>();
|
||||
const snapshotThreadById = new Map(input.snapshotThreads.map((thread) => [thread.key, thread]));
|
||||
for (const thread of input.snapshotThreads) {
|
||||
if (thread.deletedAt !== null) continue;
|
||||
if (thread.archivedAt !== null) continue;
|
||||
activeThreadIds.add(thread.key);
|
||||
activeThreadKeys.add(thread.key);
|
||||
}
|
||||
for (const draftThreadKey of input.draftThreadKeys) {
|
||||
const snapshotThread = snapshotThreadById.get(draftThreadKey);
|
||||
@@ -27,7 +27,7 @@ export function collectActiveTerminalThreadIds(
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
activeThreadIds.add(draftThreadKey);
|
||||
activeThreadKeys.add(draftThreadKey);
|
||||
}
|
||||
return activeThreadIds;
|
||||
return activeThreadKeys;
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import {
|
||||
type OrchestrationShellStreamItem,
|
||||
type ServerConfig,
|
||||
type ServerProvider,
|
||||
type TerminalEvent,
|
||||
type TerminalAttachStreamEvent,
|
||||
type TerminalMetadataStreamEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -30,7 +31,8 @@ function registerListener<T>(listeners: Set<(event: T) => void>, listener: (even
|
||||
};
|
||||
}
|
||||
|
||||
const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
|
||||
const terminalAttachListeners = new Set<(event: TerminalAttachStreamEvent) => void>();
|
||||
const terminalMetadataListeners = new Set<(event: TerminalMetadataStreamEvent) => void>();
|
||||
const shellStreamListeners = new Set<(event: OrchestrationShellStreamItem) => void>();
|
||||
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
|
||||
|
||||
@@ -38,13 +40,16 @@ const rpcClientMock = {
|
||||
dispose: vi.fn(),
|
||||
terminal: {
|
||||
open: vi.fn(),
|
||||
attach: vi.fn((_input: unknown, listener: (event: TerminalAttachStreamEvent) => void) =>
|
||||
registerListener(terminalAttachListeners, listener),
|
||||
),
|
||||
write: vi.fn(),
|
||||
resize: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
restart: vi.fn(),
|
||||
close: vi.fn(),
|
||||
onEvent: vi.fn((listener: (event: TerminalEvent) => void) =>
|
||||
registerListener(terminalEventListeners, listener),
|
||||
onMetadata: vi.fn((listener: (event: TerminalMetadataStreamEvent) => void) =>
|
||||
registerListener(terminalMetadataListeners, listener),
|
||||
),
|
||||
},
|
||||
projects: {
|
||||
@@ -275,7 +280,8 @@ beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
showContextMenuFallbackMock.mockReset();
|
||||
terminalEventListeners.clear();
|
||||
terminalAttachListeners.clear();
|
||||
terminalMetadataListeners.clear();
|
||||
shellStreamListeners.clear();
|
||||
gitStatusListeners.clear();
|
||||
const testWindow = getWindowForTest();
|
||||
@@ -303,24 +309,42 @@ describe("wsApi", () => {
|
||||
expect(rpcClientMock.server.subscribeLifecycle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards terminal and shell stream events", async () => {
|
||||
it("forwards terminal attach, metadata, and shell stream events", async () => {
|
||||
const { createEnvironmentApi } = await import("./environmentApi");
|
||||
|
||||
const api = createEnvironmentApi(rpcClientMock as never);
|
||||
const onTerminalEvent = vi.fn();
|
||||
const onTerminalAttachEvent = vi.fn();
|
||||
const onTerminalMetadataEvent = vi.fn();
|
||||
const onShellEvent = vi.fn();
|
||||
|
||||
api.terminal.onEvent(onTerminalEvent);
|
||||
api.terminal.attach({ threadId: "thread-1", terminalId: "terminal-1" }, onTerminalAttachEvent);
|
||||
api.terminal.onMetadata(onTerminalMetadataEvent);
|
||||
api.orchestration.subscribeShell(onShellEvent);
|
||||
|
||||
const terminalEvent = {
|
||||
const terminalAttachEvent = {
|
||||
threadId: "thread-1",
|
||||
terminalId: "terminal-1",
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
type: "output",
|
||||
data: "hello",
|
||||
} as const;
|
||||
emitEvent(terminalEventListeners, terminalEvent);
|
||||
} satisfies TerminalAttachStreamEvent;
|
||||
emitEvent(terminalAttachListeners, terminalAttachEvent);
|
||||
|
||||
const terminalMetadataEvent = {
|
||||
type: "upsert",
|
||||
terminal: {
|
||||
threadId: "thread-1",
|
||||
terminalId: "terminal-1",
|
||||
cwd: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 123,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
hasRunningSubprocess: true,
|
||||
updatedAt: "2026-02-24T00:00:00.000Z",
|
||||
},
|
||||
} satisfies TerminalMetadataStreamEvent;
|
||||
emitEvent(terminalMetadataListeners, terminalMetadataEvent);
|
||||
|
||||
const shellEvent = {
|
||||
kind: "project-upserted" as const,
|
||||
@@ -340,7 +364,8 @@ describe("wsApi", () => {
|
||||
} satisfies OrchestrationShellStreamItem;
|
||||
emitEvent(shellStreamListeners, shellEvent);
|
||||
|
||||
expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
|
||||
expect(onTerminalAttachEvent).toHaveBeenCalledWith(terminalAttachEvent);
|
||||
expect(onTerminalMetadataEvent).toHaveBeenCalledWith(terminalMetadataEvent);
|
||||
expect(onShellEvent).toHaveBeenCalledWith(shellEvent);
|
||||
});
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ describe("deriveOrchestrationBatchEffects", () => {
|
||||
|
||||
expect(effects.promoteDraftThreadIds).toEqual([createdThreadId]);
|
||||
expect(effects.clearDeletedThreadIds).toEqual([deletedThreadId]);
|
||||
expect(effects.removeTerminalStateThreadIds).toEqual([deletedThreadId, archivedThreadId]);
|
||||
expect(effects.removeTerminalUiStateThreadIds).toEqual([deletedThreadId, archivedThreadId]);
|
||||
expect(effects.needsProviderInvalidation).toBe(false);
|
||||
});
|
||||
|
||||
@@ -108,7 +108,7 @@ describe("deriveOrchestrationBatchEffects", () => {
|
||||
|
||||
expect(effects.promoteDraftThreadIds).toEqual([threadId]);
|
||||
expect(effects.clearDeletedThreadIds).toEqual([]);
|
||||
expect(effects.removeTerminalStateThreadIds).toEqual([]);
|
||||
expect(effects.removeTerminalUiStateThreadIds).toEqual([]);
|
||||
expect(effects.needsProviderInvalidation).toBe(true);
|
||||
});
|
||||
|
||||
@@ -129,6 +129,6 @@ describe("deriveOrchestrationBatchEffects", () => {
|
||||
|
||||
expect(effects.promoteDraftThreadIds).toEqual([]);
|
||||
expect(effects.clearDeletedThreadIds).toEqual([]);
|
||||
expect(effects.removeTerminalStateThreadIds).toEqual([]);
|
||||
expect(effects.removeTerminalUiStateThreadIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import type { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
|
||||
export interface OrchestrationBatchEffects {
|
||||
promoteDraftThreadIds: ThreadId[];
|
||||
clearDeletedThreadIds: ThreadId[];
|
||||
removeTerminalStateThreadIds: ThreadId[];
|
||||
removeTerminalUiStateThreadIds: ThreadId[];
|
||||
needsProviderInvalidation: boolean;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export function deriveOrchestrationBatchEffects(
|
||||
{
|
||||
clearPromotedDraft: boolean;
|
||||
clearDeletedThread: boolean;
|
||||
removeTerminalState: boolean;
|
||||
removeTerminalUiState: boolean;
|
||||
}
|
||||
>();
|
||||
let needsProviderInvalidation = false;
|
||||
@@ -32,7 +32,7 @@ export function deriveOrchestrationBatchEffects(
|
||||
threadLifecycleEffects.set(event.payload.threadId, {
|
||||
clearPromotedDraft: true,
|
||||
clearDeletedThread: false,
|
||||
removeTerminalState: false,
|
||||
removeTerminalUiState: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
@@ -41,7 +41,7 @@ export function deriveOrchestrationBatchEffects(
|
||||
threadLifecycleEffects.set(event.payload.threadId, {
|
||||
clearPromotedDraft: false,
|
||||
clearDeletedThread: true,
|
||||
removeTerminalState: true,
|
||||
removeTerminalUiState: true,
|
||||
});
|
||||
break;
|
||||
}
|
||||
@@ -50,7 +50,7 @@ export function deriveOrchestrationBatchEffects(
|
||||
threadLifecycleEffects.set(event.payload.threadId, {
|
||||
clearPromotedDraft: false,
|
||||
clearDeletedThread: false,
|
||||
removeTerminalState: true,
|
||||
removeTerminalUiState: true,
|
||||
});
|
||||
break;
|
||||
}
|
||||
@@ -59,7 +59,7 @@ export function deriveOrchestrationBatchEffects(
|
||||
threadLifecycleEffects.set(event.payload.threadId, {
|
||||
clearPromotedDraft: false,
|
||||
clearDeletedThread: false,
|
||||
removeTerminalState: false,
|
||||
removeTerminalUiState: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
@@ -72,7 +72,7 @@ export function deriveOrchestrationBatchEffects(
|
||||
|
||||
const promoteDraftThreadIds: ThreadId[] = [];
|
||||
const clearDeletedThreadIds: ThreadId[] = [];
|
||||
const removeTerminalStateThreadIds: ThreadId[] = [];
|
||||
const removeTerminalUiStateThreadIds: ThreadId[] = [];
|
||||
for (const [threadId, effect] of threadLifecycleEffects) {
|
||||
if (effect.clearPromotedDraft) {
|
||||
promoteDraftThreadIds.push(threadId);
|
||||
@@ -80,15 +80,15 @@ export function deriveOrchestrationBatchEffects(
|
||||
if (effect.clearDeletedThread) {
|
||||
clearDeletedThreadIds.push(threadId);
|
||||
}
|
||||
if (effect.removeTerminalState) {
|
||||
removeTerminalStateThreadIds.push(threadId);
|
||||
if (effect.removeTerminalUiState) {
|
||||
removeTerminalUiStateThreadIds.push(threadId);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
promoteDraftThreadIds,
|
||||
clearDeletedThreadIds,
|
||||
removeTerminalStateThreadIds,
|
||||
removeTerminalUiStateThreadIds,
|
||||
needsProviderInvalidation,
|
||||
};
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
} from "../lib/chatThreadActions";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { resolveShortcutCommand } from "../keybindings";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic";
|
||||
import { useSettings } from "~/hooks/useSettings";
|
||||
@@ -21,9 +21,9 @@ function ChatRouteGlobalShortcuts() {
|
||||
const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =
|
||||
useHandleNewThread();
|
||||
const keybindings = useServerKeybindings();
|
||||
const terminalOpen = useTerminalStateStore((state) =>
|
||||
const terminalOpen = useTerminalUiStateStore((state) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef).terminalOpen
|
||||
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
|
||||
: false,
|
||||
);
|
||||
const appSettings = useSettings();
|
||||
|
||||
@@ -22,14 +22,20 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
|
||||
},
|
||||
terminal: {
|
||||
open: (input) => transport.request((client) => client[WS_METHODS.terminalOpen](input)),
|
||||
attach: (input, listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.terminalAttach](input),
|
||||
listener,
|
||||
options,
|
||||
),
|
||||
write: (input) => transport.request((client) => client[WS_METHODS.terminalWrite](input)),
|
||||
resize: (input) => transport.request((client) => client[WS_METHODS.terminalResize](input)),
|
||||
clear: (input) => transport.request((client) => client[WS_METHODS.terminalClear](input)),
|
||||
restart: (input) => transport.request((client) => client[WS_METHODS.terminalRestart](input)),
|
||||
close: (input) => transport.request((client) => client[WS_METHODS.terminalClose](input)),
|
||||
onEvent: (listener, options) =>
|
||||
onMetadata: (listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeTerminalEvents]({}),
|
||||
(client) => client[WS_METHODS.subscribeTerminalMetadata]({}),
|
||||
listener,
|
||||
options,
|
||||
),
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { TerminalEvent, TerminalSessionSnapshot } from "@t3tools/contracts";
|
||||
import { terminalRunningSubprocessFromEvent } from "./terminalActivity";
|
||||
|
||||
const snapshot: TerminalSessionSnapshot = {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
cwd: "/tmp",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 1234,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
function eventBase() {
|
||||
return {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("terminalRunningSubprocessFromEvent", () => {
|
||||
it("returns the subprocess flag for terminal activity events", () => {
|
||||
const active = terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "activity",
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
const idle = terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "activity",
|
||||
hasRunningSubprocess: false,
|
||||
});
|
||||
|
||||
expect(active).toBe(true);
|
||||
expect(idle).toBe(false);
|
||||
});
|
||||
|
||||
it("clears running state when a terminal session starts/restarts/exits", () => {
|
||||
const events: TerminalEvent[] = [
|
||||
{ ...eventBase(), type: "started", snapshot },
|
||||
{ ...eventBase(), type: "restarted", snapshot },
|
||||
{ ...eventBase(), type: "exited", exitCode: 0, exitSignal: null },
|
||||
];
|
||||
|
||||
for (const event of events) {
|
||||
expect(terminalRunningSubprocessFromEvent(event)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores non-activity terminal events", () => {
|
||||
expect(
|
||||
terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "output",
|
||||
data: "hello",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "error",
|
||||
message: "oops",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
import type { TerminalEvent } from "@t3tools/contracts";
|
||||
|
||||
export function terminalRunningSubprocessFromEvent(event: TerminalEvent): boolean | null {
|
||||
switch (event.type) {
|
||||
case "activity":
|
||||
return event.hasRunningSubprocess;
|
||||
case "started":
|
||||
case "restarted":
|
||||
case "exited":
|
||||
case "closed":
|
||||
return false;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
EMPTY_KNOWN_TERMINAL_SESSIONS_ATOM,
|
||||
EMPTY_TERMINAL_ID_LIST_ATOM,
|
||||
EMPTY_TERMINAL_SESSION_ATOM,
|
||||
createTerminalSessionManager,
|
||||
getKnownTerminalSessionTarget,
|
||||
getKnownTerminalSessionListFilter,
|
||||
knownTerminalSessionsAtom,
|
||||
runningTerminalIdsAtom,
|
||||
terminalSessionStateAtom,
|
||||
type KnownTerminalSession,
|
||||
type TerminalSessionTarget,
|
||||
type TerminalSessionState,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
TerminalAttachInput,
|
||||
TerminalSessionSnapshot,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { appAtomRegistry } from "./rpc/atomRegistry";
|
||||
|
||||
export const terminalSessionManager = createTerminalSessionManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
});
|
||||
|
||||
export function subscribeTerminalMetadata(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly client: Parameters<typeof terminalSessionManager.subscribeMetadata>[0]["client"];
|
||||
}) {
|
||||
return terminalSessionManager.subscribeMetadata(input);
|
||||
}
|
||||
|
||||
export function attachTerminalSession(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly client: Parameters<typeof terminalSessionManager.attach>[0]["client"];
|
||||
readonly terminal: TerminalAttachInput;
|
||||
readonly onSnapshot?: (snapshot: TerminalSessionSnapshot) => void;
|
||||
readonly onEvent?: Parameters<typeof terminalSessionManager.attach>[0]["onEvent"];
|
||||
}) {
|
||||
return terminalSessionManager.attach({
|
||||
environmentId: input.environmentId,
|
||||
client: input.client,
|
||||
terminal: input.terminal,
|
||||
...(input.onSnapshot ? { onSnapshot: input.onSnapshot } : {}),
|
||||
...(input.onEvent ? { onEvent: input.onEvent } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useTerminalSession(input: TerminalSessionTarget): TerminalSessionState {
|
||||
const target = getKnownTerminalSessionTarget(input);
|
||||
return useAtomValue(
|
||||
target !== null ? terminalSessionStateAtom(target) : EMPTY_TERMINAL_SESSION_ATOM,
|
||||
);
|
||||
}
|
||||
|
||||
export function useKnownTerminalSessions(input: {
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly threadId: ThreadId | null;
|
||||
}): ReadonlyArray<KnownTerminalSession> {
|
||||
const filter = getKnownTerminalSessionListFilter(input);
|
||||
return useAtomValue(
|
||||
filter !== null ? knownTerminalSessionsAtom(filter) : EMPTY_KNOWN_TERMINAL_SESSIONS_ATOM,
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadRunningTerminalIds(input: {
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly threadId: ThreadId | null;
|
||||
}): ReadonlyArray<string> {
|
||||
const filter = getKnownTerminalSessionListFilter(input);
|
||||
return useAtomValue(
|
||||
filter !== null ? runningTerminalIdsAtom(filter) : EMPTY_TERMINAL_ID_LIST_ATOM,
|
||||
);
|
||||
}
|
||||
@@ -1,398 +0,0 @@
|
||||
import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime";
|
||||
import { ThreadId, type TerminalEvent } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
migratePersistedTerminalStateStoreState,
|
||||
selectTerminalEventEntries,
|
||||
selectThreadTerminalState,
|
||||
useTerminalStateStore,
|
||||
} from "./terminalStateStore";
|
||||
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const THREAD_REF = scopeThreadRef("environment-a" as never, THREAD_ID);
|
||||
const OTHER_THREAD_REF = scopeThreadRef("environment-b" as never, THREAD_ID);
|
||||
|
||||
function makeTerminalEvent(
|
||||
type: TerminalEvent["type"],
|
||||
overrides: Partial<TerminalEvent> = {},
|
||||
): TerminalEvent {
|
||||
const base = {
|
||||
threadId: THREAD_ID,
|
||||
terminalId: "default",
|
||||
createdAt: "2026-04-02T20:00:00.000Z",
|
||||
};
|
||||
|
||||
switch (type) {
|
||||
case "output":
|
||||
return { ...base, type, data: "hello\n", ...overrides } as TerminalEvent;
|
||||
case "activity":
|
||||
return { ...base, type, hasRunningSubprocess: true, ...overrides } as TerminalEvent;
|
||||
case "error":
|
||||
return { ...base, type, message: "boom", ...overrides } as TerminalEvent;
|
||||
case "cleared":
|
||||
return { ...base, type, ...overrides } as TerminalEvent;
|
||||
case "exited":
|
||||
return { ...base, type, exitCode: 0, exitSignal: null, ...overrides } as TerminalEvent;
|
||||
case "closed":
|
||||
return { ...base, type, ...overrides } as TerminalEvent;
|
||||
case "started":
|
||||
case "restarted":
|
||||
return {
|
||||
...base,
|
||||
type,
|
||||
snapshot: {
|
||||
threadId: THREAD_ID,
|
||||
terminalId: "default",
|
||||
cwd: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 123,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-02T20:00:00.000Z",
|
||||
},
|
||||
...overrides,
|
||||
} as TerminalEvent;
|
||||
}
|
||||
}
|
||||
|
||||
describe("terminalStateStore actions", () => {
|
||||
beforeEach(() => {
|
||||
useTerminalStateStore.persist.clearStorage();
|
||||
useTerminalStateStore.setState({
|
||||
terminalStateByThreadKey: {},
|
||||
terminalLaunchContextByThreadKey: {},
|
||||
terminalEventEntriesByKey: {},
|
||||
nextTerminalEventId: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a closed default terminal state for unknown threads", () => {
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalState).toEqual({
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
});
|
||||
});
|
||||
|
||||
it("opens and splits terminals into the active group", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.setTerminalOpen(THREAD_REF, true);
|
||||
store.splitTerminal(THREAD_REF, "terminal-2");
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalState.terminalOpen).toBe(true);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("caps splits at four terminals per group", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_REF, "terminal-2");
|
||||
store.splitTerminal(THREAD_REF, "terminal-3");
|
||||
store.splitTerminal(THREAD_REF, "terminal-4");
|
||||
store.splitTerminal(THREAD_REF, "terminal-5");
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalState.terminalIds).toEqual([
|
||||
"default",
|
||||
"terminal-2",
|
||||
"terminal-3",
|
||||
"terminal-4",
|
||||
]);
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2", "terminal-3", "terminal-4"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates new terminals in a separate group", () => {
|
||||
useTerminalStateStore.getState().newTerminal(THREAD_REF, "terminal-2");
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.activeTerminalGroupId).toBe("group-terminal-2");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("ensures unknown server terminals are registered, opened, and activated", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.ensureTerminal(THREAD_REF, "setup-setup", { open: true, active: true });
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalState.terminalOpen).toBe(true);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "setup-setup"]);
|
||||
expect(terminalState.activeTerminalId).toBe("setup-setup");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-setup-setup", terminalIds: ["setup-setup"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps state isolated per environment when raw thread ids collide", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.setTerminalOpen(THREAD_REF, true);
|
||||
store.newTerminal(OTHER_THREAD_REF, "env-b-terminal");
|
||||
|
||||
expect(
|
||||
selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
).terminalOpen,
|
||||
).toBe(true);
|
||||
expect(
|
||||
selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
OTHER_THREAD_REF,
|
||||
).terminalIds,
|
||||
).toEqual(["default", "env-b-terminal"]);
|
||||
});
|
||||
|
||||
it("migrates v1 persisted terminal state using the stored version", () => {
|
||||
const migrated = migratePersistedTerminalStateStoreState(
|
||||
{
|
||||
terminalStateByThreadKey: {
|
||||
[scopedThreadKey(THREAD_REF)]: {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
},
|
||||
"legacy-thread-id": {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
},
|
||||
},
|
||||
},
|
||||
1,
|
||||
);
|
||||
|
||||
expect(migrated).toEqual({
|
||||
terminalStateByThreadKey: {
|
||||
[scopedThreadKey(THREAD_REF)]: {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks and clears terminal subprocess activity", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_REF, "terminal-2");
|
||||
store.setTerminalActivity(THREAD_REF, "terminal-2", true);
|
||||
expect(
|
||||
selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
).runningTerminalIds,
|
||||
).toEqual(["terminal-2"]);
|
||||
|
||||
store.setTerminalActivity(THREAD_REF, "terminal-2", false);
|
||||
expect(
|
||||
selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
).runningTerminalIds,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("resets to default and clears persisted entry when closing the last terminal", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.closeTerminal(THREAD_REF, "default");
|
||||
|
||||
expect(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey[scopedThreadKey(THREAD_REF)],
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
).terminalIds,
|
||||
).toEqual(["default"]);
|
||||
});
|
||||
|
||||
it("keeps a valid active terminal after closing an active split terminal", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_REF, "terminal-2");
|
||||
store.splitTerminal(THREAD_REF, "terminal-3");
|
||||
store.closeTerminal(THREAD_REF, "terminal-3");
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("buffers terminal events outside persisted terminal UI state", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.recordTerminalEvent(THREAD_REF, makeTerminalEvent("output"));
|
||||
store.recordTerminalEvent(THREAD_REF, makeTerminalEvent("activity"));
|
||||
|
||||
const entries = selectTerminalEventEntries(
|
||||
useTerminalStateStore.getState().terminalEventEntriesByKey,
|
||||
THREAD_REF,
|
||||
"default",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(2);
|
||||
expect(entries.map((entry) => entry.id)).toEqual([1, 2]);
|
||||
expect(entries.map((entry) => entry.event.type)).toEqual(["output", "activity"]);
|
||||
});
|
||||
|
||||
it("applies started terminal events to terminal state, launch context, and event buffer", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.applyTerminalEvent(
|
||||
THREAD_REF,
|
||||
makeTerminalEvent("started", {
|
||||
terminalId: "setup-bootstrap",
|
||||
snapshot: {
|
||||
threadId: THREAD_ID,
|
||||
terminalId: "setup-bootstrap",
|
||||
cwd: "/tmp/worktree",
|
||||
worktreePath: "/tmp/worktree",
|
||||
status: "running",
|
||||
pid: 123,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-02T20:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
const entries = selectTerminalEventEntries(
|
||||
useTerminalStateStore.getState().terminalEventEntriesByKey,
|
||||
THREAD_REF,
|
||||
"setup-bootstrap",
|
||||
);
|
||||
|
||||
expect(terminalState.terminalOpen).toBe(true);
|
||||
expect(terminalState.activeTerminalId).toBe("setup-bootstrap");
|
||||
expect(terminalState.terminalIds).toEqual(["default", "setup-bootstrap"]);
|
||||
expect(
|
||||
useTerminalStateStore.getState().terminalLaunchContextByThreadKey[
|
||||
scopedThreadKey(THREAD_REF)
|
||||
],
|
||||
).toEqual({
|
||||
cwd: "/tmp/worktree",
|
||||
worktreePath: "/tmp/worktree",
|
||||
});
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.event.type).toBe("started");
|
||||
});
|
||||
|
||||
it("applies activity and exited terminal events to subprocess state while buffering events", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.ensureTerminal(THREAD_REF, "terminal-2", { open: true, active: true });
|
||||
|
||||
store.applyTerminalEvent(
|
||||
THREAD_REF,
|
||||
makeTerminalEvent("activity", {
|
||||
terminalId: "terminal-2",
|
||||
hasRunningSubprocess: true,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
).runningTerminalIds,
|
||||
).toEqual(["terminal-2"]);
|
||||
|
||||
store.applyTerminalEvent(
|
||||
THREAD_REF,
|
||||
makeTerminalEvent("exited", {
|
||||
terminalId: "terminal-2",
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
const entries = selectTerminalEventEntries(
|
||||
useTerminalStateStore.getState().terminalEventEntriesByKey,
|
||||
THREAD_REF,
|
||||
"terminal-2",
|
||||
);
|
||||
|
||||
expect(terminalState.runningTerminalIds).toEqual([]);
|
||||
expect(entries.map((entry) => entry.event.type)).toEqual(["activity", "exited"]);
|
||||
});
|
||||
|
||||
it("clears buffered terminal events when a thread terminal state is removed", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.recordTerminalEvent(THREAD_REF, makeTerminalEvent("output"));
|
||||
store.removeTerminalState(THREAD_REF);
|
||||
|
||||
const entries = selectTerminalEventEntries(
|
||||
useTerminalStateStore.getState().terminalEventEntriesByKey,
|
||||
THREAD_REF,
|
||||
"default",
|
||||
);
|
||||
|
||||
expect(entries).toEqual([]);
|
||||
});
|
||||
|
||||
it("is a no-op when clearing terminal state for a thread with no state or buffered events", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
const before = useTerminalStateStore.getState();
|
||||
|
||||
store.clearTerminalState(THREAD_REF);
|
||||
|
||||
expect(useTerminalStateStore.getState()).toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -1,847 +0,0 @@
|
||||
/**
|
||||
* Single Zustand store for terminal UI state keyed by scoped thread identity.
|
||||
*
|
||||
* Terminal transition helpers are intentionally private to keep the public
|
||||
* API constrained to store actions/selectors.
|
||||
*/
|
||||
|
||||
import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime";
|
||||
import { type ScopedThreadRef, type TerminalEvent } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import { resolveStorage } from "./lib/storage";
|
||||
import { terminalRunningSubprocessFromEvent } from "./terminalActivity";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_TERMINALS_PER_GROUP,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
interface ThreadTerminalState {
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
}
|
||||
|
||||
export interface ThreadTerminalLaunchContext {
|
||||
cwd: string;
|
||||
worktreePath: string | null;
|
||||
}
|
||||
|
||||
export interface TerminalEventEntry {
|
||||
id: number;
|
||||
event: TerminalEvent;
|
||||
}
|
||||
|
||||
const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
|
||||
const EMPTY_TERMINAL_EVENT_ENTRIES: ReadonlyArray<TerminalEventEntry> = [];
|
||||
const MAX_TERMINAL_EVENT_BUFFER = 200;
|
||||
|
||||
interface PersistedTerminalStateStoreState {
|
||||
terminalStateByThreadKey?: Record<string, ThreadTerminalState>;
|
||||
}
|
||||
|
||||
export function migratePersistedTerminalStateStoreState(
|
||||
persistedState: unknown,
|
||||
version: number,
|
||||
): PersistedTerminalStateStoreState {
|
||||
if (version === 1 && persistedState && typeof persistedState === "object") {
|
||||
const candidate = persistedState as PersistedTerminalStateStoreState;
|
||||
const nextTerminalStateByThreadKey = Object.fromEntries(
|
||||
Object.entries(candidate.terminalStateByThreadKey ?? {}).filter(([threadKey]) =>
|
||||
parseScopedThreadKey(threadKey),
|
||||
),
|
||||
);
|
||||
return { terminalStateByThreadKey: nextTerminalStateByThreadKey };
|
||||
}
|
||||
return { terminalStateByThreadKey: {} };
|
||||
}
|
||||
|
||||
function createTerminalStateStorage() {
|
||||
return resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined);
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
function normalizeRunningTerminalIds(
|
||||
runningTerminalIds: string[],
|
||||
terminalIds: string[],
|
||||
): string[] {
|
||||
if (runningTerminalIds.length === 0) return [];
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): string {
|
||||
let candidate = baseId;
|
||||
let index = 2;
|
||||
while (usedGroupIds.has(candidate)) {
|
||||
candidate = `${baseId}-${index}`;
|
||||
index += 1;
|
||||
}
|
||||
usedGroupIds.add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function findGroupIndexByTerminalId(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalId: string,
|
||||
): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalIds: string[],
|
||||
): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const nextGroups: ThreadTerminalGroup[] = [];
|
||||
const usedGroupIds = new Set<string>();
|
||||
|
||||
for (const group of terminalGroups) {
|
||||
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (nextGroups.length === 0) {
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return nextGroups;
|
||||
}
|
||||
|
||||
function arraysEqual(a: string[], b: string[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let index = 0; index < a.length; index += 1) {
|
||||
if (a[index] !== b[index]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalGroup[]): boolean {
|
||||
if (left.length !== right.length) return false;
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
const leftGroup = left[index];
|
||||
const rightGroup = right[index];
|
||||
if (!leftGroup || !rightGroup) return false;
|
||||
if (leftGroup.id !== rightGroup.id) return false;
|
||||
if (!arraysEqual(leftGroup.terminalIds, rightGroup.terminalIds)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTerminalState): boolean {
|
||||
return (
|
||||
left.terminalOpen === right.terminalOpen &&
|
||||
left.terminalHeight === right.terminalHeight &&
|
||||
left.activeTerminalId === right.activeTerminalId &&
|
||||
left.activeTerminalGroupId === right.activeTerminalGroupId &&
|
||||
arraysEqual(left.terminalIds, right.terminalIds) &&
|
||||
arraysEqual(left.runningTerminalIds, right.runningTerminalIds) &&
|
||||
terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
|
||||
);
|
||||
}
|
||||
|
||||
const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
});
|
||||
|
||||
function createDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return {
|
||||
...DEFAULT_THREAD_TERMINAL_STATE,
|
||||
terminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.terminalIds],
|
||||
runningTerminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalIds],
|
||||
terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_STATE.terminalGroups),
|
||||
};
|
||||
}
|
||||
|
||||
function getDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
return DEFAULT_THREAD_TERMINAL_STATE;
|
||||
}
|
||||
|
||||
function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTerminalState {
|
||||
const terminalIds = normalizeTerminalIds(state.terminalIds);
|
||||
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const runningTerminalIds = normalizeRunningTerminalIds(state.runningTerminalIds, nextTerminalIds);
|
||||
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
|
||||
? state.activeTerminalId
|
||||
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
|
||||
const activeGroupIdFromState = terminalGroups.some(
|
||||
(group) => group.id === state.activeTerminalGroupId,
|
||||
)
|
||||
? state.activeTerminalGroupId
|
||||
: null;
|
||||
const activeGroupIdFromTerminal =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? null;
|
||||
|
||||
const normalized: ThreadTerminalState = {
|
||||
terminalOpen: state.terminalOpen,
|
||||
terminalHeight:
|
||||
Number.isFinite(state.terminalHeight) && state.terminalHeight > 0
|
||||
? state.terminalHeight
|
||||
: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: nextTerminalIds,
|
||||
runningTerminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId:
|
||||
activeGroupIdFromState ??
|
||||
activeGroupIdFromTerminal ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
};
|
||||
return threadTerminalStateEqual(state, normalized) ? state : normalized;
|
||||
}
|
||||
|
||||
function isDefaultThreadTerminalState(state: ThreadTerminalState): boolean {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
return threadTerminalStateEqual(normalized, DEFAULT_THREAD_TERMINAL_STATE);
|
||||
}
|
||||
|
||||
function isValidTerminalId(terminalId: string): boolean {
|
||||
return terminalId.trim().length > 0;
|
||||
}
|
||||
|
||||
function terminalThreadKey(threadRef: ScopedThreadRef): string {
|
||||
return scopedThreadKey(threadRef);
|
||||
}
|
||||
|
||||
function terminalEventBufferKey(threadRef: ScopedThreadRef, terminalId: string): string {
|
||||
return `${terminalThreadKey(threadRef)}\u0000${terminalId}`;
|
||||
}
|
||||
|
||||
function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[] {
|
||||
return groups.map((group) => ({
|
||||
id: group.id,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
}
|
||||
|
||||
function appendTerminalEventEntry(
|
||||
terminalEventEntriesByKey: Record<string, ReadonlyArray<TerminalEventEntry>>,
|
||||
nextTerminalEventId: number,
|
||||
threadRef: ScopedThreadRef,
|
||||
event: TerminalEvent,
|
||||
) {
|
||||
const key = terminalEventBufferKey(threadRef, event.terminalId);
|
||||
const currentEntries = terminalEventEntriesByKey[key] ?? EMPTY_TERMINAL_EVENT_ENTRIES;
|
||||
const nextEntry: TerminalEventEntry = {
|
||||
id: nextTerminalEventId,
|
||||
event,
|
||||
};
|
||||
const nextEntries =
|
||||
currentEntries.length >= MAX_TERMINAL_EVENT_BUFFER
|
||||
? [...currentEntries.slice(1), nextEntry]
|
||||
: [...currentEntries, nextEntry];
|
||||
|
||||
return {
|
||||
terminalEventEntriesByKey: {
|
||||
...terminalEventEntriesByKey,
|
||||
[key]: nextEntries,
|
||||
},
|
||||
nextTerminalEventId: nextTerminalEventId + 1,
|
||||
};
|
||||
}
|
||||
|
||||
function launchContextFromStartEvent(
|
||||
event: Extract<TerminalEvent, { type: "started" | "restarted" }>,
|
||||
): ThreadTerminalLaunchContext {
|
||||
return {
|
||||
cwd: event.snapshot.cwd,
|
||||
worktreePath: event.snapshot.worktreePath,
|
||||
};
|
||||
}
|
||||
|
||||
function upsertTerminalIntoGroups(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
mode: "split" | "new",
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!isValidTerminalId(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const isNewTerminal = !normalized.terminalIds.includes(terminalId);
|
||||
const terminalIds = isNewTerminal
|
||||
? [...normalized.terminalIds, terminalId]
|
||||
: normalized.terminalIds;
|
||||
const terminalGroups = copyTerminalGroups(normalized.terminalGroups);
|
||||
|
||||
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, terminalId);
|
||||
if (existingGroupIndex >= 0) {
|
||||
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
|
||||
existingGroupIndex
|
||||
]!.terminalIds.filter((id) => id !== terminalId);
|
||||
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
|
||||
terminalGroups.splice(existingGroupIndex, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === "new") {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [terminalId] });
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
let activeGroupIndex = terminalGroups.findIndex(
|
||||
(group) => group.id === normalized.activeTerminalGroupId,
|
||||
);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(
|
||||
fallbackGroupId(normalized.activeTerminalId),
|
||||
usedGroupIds,
|
||||
);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (
|
||||
isNewTerminal &&
|
||||
!destinationGroup.terminalIds.includes(terminalId) &&
|
||||
destinationGroup.terminalIds.length >= MAX_TERMINALS_PER_GROUP
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (!destinationGroup.terminalIds.includes(terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(terminalId);
|
||||
}
|
||||
}
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalOpen(state: ThreadTerminalState, open: boolean): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (normalized.terminalOpen === open) return normalized;
|
||||
return { ...normalized, terminalOpen: open };
|
||||
}
|
||||
|
||||
function setThreadTerminalHeight(state: ThreadTerminalState, height: number): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!Number.isFinite(height) || height <= 0 || normalized.terminalHeight === height) {
|
||||
return normalized;
|
||||
}
|
||||
return { ...normalized, terminalHeight: height };
|
||||
}
|
||||
|
||||
function splitThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "split");
|
||||
}
|
||||
|
||||
function newThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "new");
|
||||
}
|
||||
|
||||
function setThreadActiveTerminal(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const activeTerminalGroupId =
|
||||
normalized.terminalGroups.find((group) => group.terminalIds.includes(terminalId))?.id ??
|
||||
normalized.activeTerminalGroupId;
|
||||
if (
|
||||
normalized.activeTerminalId === terminalId &&
|
||||
normalized.activeTerminalGroupId === activeTerminalGroupId
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
return {
|
||||
...normalized,
|
||||
activeTerminalId: terminalId,
|
||||
activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
|
||||
function closeThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = normalized.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
return createDefaultThreadTerminalState();
|
||||
}
|
||||
|
||||
const closedTerminalIndex = normalized.terminalIds.indexOf(terminalId);
|
||||
const nextActiveTerminalId =
|
||||
normalized.activeTerminalId === terminalId
|
||||
? (remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: normalized.activeTerminalId;
|
||||
|
||||
const terminalGroups = normalized.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
const nextActiveTerminalGroupId =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(nextActiveTerminalId);
|
||||
|
||||
return normalizeThreadTerminalState({
|
||||
terminalOpen: normalized.terminalOpen,
|
||||
terminalHeight: normalized.terminalHeight,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: normalized.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextActiveTerminalGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalActivity(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const alreadyRunning = normalized.runningTerminalIds.includes(terminalId);
|
||||
if (hasRunningSubprocess === alreadyRunning) {
|
||||
return normalized;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalized.runningTerminalIds);
|
||||
if (hasRunningSubprocess) {
|
||||
runningTerminalIds.add(terminalId);
|
||||
} else {
|
||||
runningTerminalIds.delete(terminalId);
|
||||
}
|
||||
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
|
||||
}
|
||||
|
||||
export function selectThreadTerminalState(
|
||||
terminalStateByThreadKey: Record<string, ThreadTerminalState>,
|
||||
threadRef: ScopedThreadRef | null | undefined,
|
||||
): ThreadTerminalState {
|
||||
if (!threadRef || threadRef.threadId.length === 0) {
|
||||
return getDefaultThreadTerminalState();
|
||||
}
|
||||
return terminalStateByThreadKey[terminalThreadKey(threadRef)] ?? getDefaultThreadTerminalState();
|
||||
}
|
||||
|
||||
function updateTerminalStateByThreadKey(
|
||||
terminalStateByThreadKey: Record<string, ThreadTerminalState>,
|
||||
threadRef: ScopedThreadRef,
|
||||
updater: (state: ThreadTerminalState) => ThreadTerminalState,
|
||||
): Record<string, ThreadTerminalState> {
|
||||
if (threadRef.threadId.length === 0) {
|
||||
return terminalStateByThreadKey;
|
||||
}
|
||||
|
||||
const threadKey = terminalThreadKey(threadRef);
|
||||
const current = selectThreadTerminalState(terminalStateByThreadKey, threadRef);
|
||||
const next = updater(current);
|
||||
if (next === current) {
|
||||
return terminalStateByThreadKey;
|
||||
}
|
||||
|
||||
if (isDefaultThreadTerminalState(next)) {
|
||||
if (terminalStateByThreadKey[threadKey] === undefined) {
|
||||
return terminalStateByThreadKey;
|
||||
}
|
||||
const { [threadKey]: _removed, ...rest } = terminalStateByThreadKey;
|
||||
return rest;
|
||||
}
|
||||
|
||||
return {
|
||||
...terminalStateByThreadKey,
|
||||
[threadKey]: next,
|
||||
};
|
||||
}
|
||||
|
||||
export function selectTerminalEventEntries(
|
||||
terminalEventEntriesByKey: Record<string, ReadonlyArray<TerminalEventEntry>>,
|
||||
threadRef: ScopedThreadRef | null | undefined,
|
||||
terminalId: string,
|
||||
): ReadonlyArray<TerminalEventEntry> {
|
||||
if (!threadRef || threadRef.threadId.length === 0 || terminalId.trim().length === 0) {
|
||||
return EMPTY_TERMINAL_EVENT_ENTRIES;
|
||||
}
|
||||
return (
|
||||
terminalEventEntriesByKey[terminalEventBufferKey(threadRef, terminalId)] ??
|
||||
EMPTY_TERMINAL_EVENT_ENTRIES
|
||||
);
|
||||
}
|
||||
|
||||
interface TerminalStateStoreState {
|
||||
terminalStateByThreadKey: Record<string, ThreadTerminalState>;
|
||||
terminalLaunchContextByThreadKey: Record<string, ThreadTerminalLaunchContext>;
|
||||
terminalEventEntriesByKey: Record<string, ReadonlyArray<TerminalEventEntry>>;
|
||||
nextTerminalEventId: number;
|
||||
setTerminalOpen: (threadRef: ScopedThreadRef, open: boolean) => void;
|
||||
setTerminalHeight: (threadRef: ScopedThreadRef, height: number) => void;
|
||||
splitTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
newTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
ensureTerminal: (
|
||||
threadRef: ScopedThreadRef,
|
||||
terminalId: string,
|
||||
options?: { open?: boolean; active?: boolean },
|
||||
) => void;
|
||||
setActiveTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
closeTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
setTerminalLaunchContext: (
|
||||
threadRef: ScopedThreadRef,
|
||||
context: ThreadTerminalLaunchContext,
|
||||
) => void;
|
||||
clearTerminalLaunchContext: (threadRef: ScopedThreadRef) => void;
|
||||
setTerminalActivity: (
|
||||
threadRef: ScopedThreadRef,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
) => void;
|
||||
recordTerminalEvent: (threadRef: ScopedThreadRef, event: TerminalEvent) => void;
|
||||
applyTerminalEvent: (threadRef: ScopedThreadRef, event: TerminalEvent) => void;
|
||||
clearTerminalState: (threadRef: ScopedThreadRef) => void;
|
||||
removeTerminalState: (threadRef: ScopedThreadRef) => void;
|
||||
removeOrphanedTerminalStates: (activeThreadKeys: Set<string>) => void;
|
||||
}
|
||||
|
||||
export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
persist(
|
||||
(set) => {
|
||||
const updateTerminal = (
|
||||
threadRef: ScopedThreadRef,
|
||||
updater: (state: ThreadTerminalState) => ThreadTerminalState,
|
||||
) => {
|
||||
set((state) => {
|
||||
const nextTerminalStateByThreadKey = updateTerminalStateByThreadKey(
|
||||
state.terminalStateByThreadKey,
|
||||
threadRef,
|
||||
updater,
|
||||
);
|
||||
if (nextTerminalStateByThreadKey === state.terminalStateByThreadKey) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
terminalStateByThreadKey: nextTerminalStateByThreadKey,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
terminalStateByThreadKey: {},
|
||||
terminalLaunchContextByThreadKey: {},
|
||||
terminalEventEntriesByKey: {},
|
||||
nextTerminalEventId: 1,
|
||||
setTerminalOpen: (threadRef, open) =>
|
||||
updateTerminal(threadRef, (state) => setThreadTerminalOpen(state, open)),
|
||||
setTerminalHeight: (threadRef, height) =>
|
||||
updateTerminal(threadRef, (state) => setThreadTerminalHeight(state, height)),
|
||||
splitTerminal: (threadRef, terminalId) =>
|
||||
updateTerminal(threadRef, (state) => splitThreadTerminal(state, terminalId)),
|
||||
newTerminal: (threadRef, terminalId) =>
|
||||
updateTerminal(threadRef, (state) => newThreadTerminal(state, terminalId)),
|
||||
ensureTerminal: (threadRef, terminalId, options) =>
|
||||
updateTerminal(threadRef, (state) => {
|
||||
let nextState = state;
|
||||
if (!state.terminalIds.includes(terminalId)) {
|
||||
nextState = newThreadTerminal(nextState, terminalId);
|
||||
}
|
||||
if (options?.active === false) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
activeTerminalId: state.activeTerminalId,
|
||||
activeTerminalGroupId: state.activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
if (options?.active ?? true) {
|
||||
nextState = setThreadActiveTerminal(nextState, terminalId);
|
||||
}
|
||||
if (options?.open) {
|
||||
nextState = setThreadTerminalOpen(nextState, true);
|
||||
}
|
||||
return normalizeThreadTerminalState(nextState);
|
||||
}),
|
||||
setActiveTerminal: (threadRef, terminalId) =>
|
||||
updateTerminal(threadRef, (state) => setThreadActiveTerminal(state, terminalId)),
|
||||
closeTerminal: (threadRef, terminalId) =>
|
||||
updateTerminal(threadRef, (state) => closeThreadTerminal(state, terminalId)),
|
||||
setTerminalLaunchContext: (threadRef, context) =>
|
||||
set((state) => ({
|
||||
terminalLaunchContextByThreadKey: {
|
||||
...state.terminalLaunchContextByThreadKey,
|
||||
[terminalThreadKey(threadRef)]: context,
|
||||
},
|
||||
})),
|
||||
clearTerminalLaunchContext: (threadRef) =>
|
||||
set((state) => {
|
||||
const threadKey = terminalThreadKey(threadRef);
|
||||
if (!state.terminalLaunchContextByThreadKey[threadKey]) {
|
||||
return state;
|
||||
}
|
||||
const { [threadKey]: _removed, ...rest } = state.terminalLaunchContextByThreadKey;
|
||||
return { terminalLaunchContextByThreadKey: rest };
|
||||
}),
|
||||
setTerminalActivity: (threadRef, terminalId, hasRunningSubprocess) =>
|
||||
updateTerminal(threadRef, (state) =>
|
||||
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
|
||||
),
|
||||
recordTerminalEvent: (threadRef, event) =>
|
||||
set((state) =>
|
||||
appendTerminalEventEntry(
|
||||
state.terminalEventEntriesByKey,
|
||||
state.nextTerminalEventId,
|
||||
threadRef,
|
||||
event,
|
||||
),
|
||||
),
|
||||
applyTerminalEvent: (threadRef, event) =>
|
||||
set((state) => {
|
||||
const threadKey = terminalThreadKey(threadRef);
|
||||
let nextTerminalStateByThreadKey = state.terminalStateByThreadKey;
|
||||
let nextTerminalLaunchContextByThreadKey = state.terminalLaunchContextByThreadKey;
|
||||
|
||||
if (event.type === "started" || event.type === "restarted") {
|
||||
nextTerminalStateByThreadKey = updateTerminalStateByThreadKey(
|
||||
nextTerminalStateByThreadKey,
|
||||
threadRef,
|
||||
(current) => {
|
||||
let nextState = current;
|
||||
if (!current.terminalIds.includes(event.terminalId)) {
|
||||
nextState = newThreadTerminal(nextState, event.terminalId);
|
||||
}
|
||||
nextState = setThreadActiveTerminal(nextState, event.terminalId);
|
||||
nextState = setThreadTerminalOpen(nextState, true);
|
||||
return normalizeThreadTerminalState(nextState);
|
||||
},
|
||||
);
|
||||
nextTerminalLaunchContextByThreadKey = {
|
||||
...nextTerminalLaunchContextByThreadKey,
|
||||
[threadKey]: launchContextFromStartEvent(event),
|
||||
};
|
||||
}
|
||||
|
||||
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
|
||||
if (hasRunningSubprocess !== null) {
|
||||
nextTerminalStateByThreadKey = updateTerminalStateByThreadKey(
|
||||
nextTerminalStateByThreadKey,
|
||||
threadRef,
|
||||
(current) =>
|
||||
setThreadTerminalActivity(current, event.terminalId, hasRunningSubprocess),
|
||||
);
|
||||
}
|
||||
|
||||
const nextEventState = appendTerminalEventEntry(
|
||||
state.terminalEventEntriesByKey,
|
||||
state.nextTerminalEventId,
|
||||
threadRef,
|
||||
event,
|
||||
);
|
||||
|
||||
return {
|
||||
terminalStateByThreadKey: nextTerminalStateByThreadKey,
|
||||
terminalLaunchContextByThreadKey: nextTerminalLaunchContextByThreadKey,
|
||||
...nextEventState,
|
||||
};
|
||||
}),
|
||||
clearTerminalState: (threadRef) =>
|
||||
set((state) => {
|
||||
const threadKey = terminalThreadKey(threadRef);
|
||||
const nextTerminalStateByThreadKey = updateTerminalStateByThreadKey(
|
||||
state.terminalStateByThreadKey,
|
||||
threadRef,
|
||||
() => createDefaultThreadTerminalState(),
|
||||
);
|
||||
const hadLaunchContext =
|
||||
state.terminalLaunchContextByThreadKey[threadKey] !== undefined;
|
||||
const { [threadKey]: _removed, ...remainingLaunchContexts } =
|
||||
state.terminalLaunchContextByThreadKey;
|
||||
const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey };
|
||||
let removedEventEntries = false;
|
||||
for (const key of Object.keys(nextTerminalEventEntriesByKey)) {
|
||||
if (key.startsWith(`${threadKey}\u0000`)) {
|
||||
delete nextTerminalEventEntriesByKey[key];
|
||||
removedEventEntries = true;
|
||||
}
|
||||
}
|
||||
if (
|
||||
nextTerminalStateByThreadKey === state.terminalStateByThreadKey &&
|
||||
!hadLaunchContext &&
|
||||
!removedEventEntries
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
terminalStateByThreadKey: nextTerminalStateByThreadKey,
|
||||
terminalLaunchContextByThreadKey: remainingLaunchContexts,
|
||||
terminalEventEntriesByKey: nextTerminalEventEntriesByKey,
|
||||
};
|
||||
}),
|
||||
removeTerminalState: (threadRef) =>
|
||||
set((state) => {
|
||||
const threadKey = terminalThreadKey(threadRef);
|
||||
const hadTerminalState = state.terminalStateByThreadKey[threadKey] !== undefined;
|
||||
const hadLaunchContext =
|
||||
state.terminalLaunchContextByThreadKey[threadKey] !== undefined;
|
||||
const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey };
|
||||
let removedEventEntries = false;
|
||||
for (const key of Object.keys(nextTerminalEventEntriesByKey)) {
|
||||
if (key.startsWith(`${threadKey}\u0000`)) {
|
||||
delete nextTerminalEventEntriesByKey[key];
|
||||
removedEventEntries = true;
|
||||
}
|
||||
}
|
||||
if (!hadTerminalState && !hadLaunchContext && !removedEventEntries) {
|
||||
return state;
|
||||
}
|
||||
const nextTerminalStateByThreadKey = { ...state.terminalStateByThreadKey };
|
||||
delete nextTerminalStateByThreadKey[threadKey];
|
||||
const nextLaunchContexts = { ...state.terminalLaunchContextByThreadKey };
|
||||
delete nextLaunchContexts[threadKey];
|
||||
return {
|
||||
terminalStateByThreadKey: nextTerminalStateByThreadKey,
|
||||
terminalLaunchContextByThreadKey: nextLaunchContexts,
|
||||
terminalEventEntriesByKey: nextTerminalEventEntriesByKey,
|
||||
};
|
||||
}),
|
||||
removeOrphanedTerminalStates: (activeThreadKeys) =>
|
||||
set((state) => {
|
||||
const orphanedIds = Object.keys(state.terminalStateByThreadKey).filter(
|
||||
(key) => !activeThreadKeys.has(key),
|
||||
);
|
||||
const orphanedLaunchContextIds = Object.keys(
|
||||
state.terminalLaunchContextByThreadKey,
|
||||
).filter((key) => !activeThreadKeys.has(key));
|
||||
const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey };
|
||||
let removedEventEntries = false;
|
||||
for (const key of Object.keys(nextTerminalEventEntriesByKey)) {
|
||||
const [threadKey] = key.split("\u0000");
|
||||
if (threadKey && !activeThreadKeys.has(threadKey)) {
|
||||
delete nextTerminalEventEntriesByKey[key];
|
||||
removedEventEntries = true;
|
||||
}
|
||||
}
|
||||
if (
|
||||
orphanedIds.length === 0 &&
|
||||
orphanedLaunchContextIds.length === 0 &&
|
||||
!removedEventEntries
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
const next = { ...state.terminalStateByThreadKey };
|
||||
for (const id of orphanedIds) {
|
||||
delete next[id];
|
||||
}
|
||||
const nextLaunchContexts = { ...state.terminalLaunchContextByThreadKey };
|
||||
for (const id of orphanedLaunchContextIds) {
|
||||
delete nextLaunchContexts[id];
|
||||
}
|
||||
return {
|
||||
terminalStateByThreadKey: next,
|
||||
terminalLaunchContextByThreadKey: nextLaunchContexts,
|
||||
terminalEventEntriesByKey: nextTerminalEventEntriesByKey,
|
||||
};
|
||||
}),
|
||||
};
|
||||
},
|
||||
{
|
||||
name: TERMINAL_STATE_STORAGE_KEY,
|
||||
version: 2,
|
||||
storage: createJSONStorage(createTerminalStateStorage),
|
||||
migrate: migratePersistedTerminalStateStoreState,
|
||||
partialize: (state) => ({
|
||||
terminalStateByThreadKey: state.terminalStateByThreadKey,
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,208 @@
|
||||
import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
migratePersistedTerminalUiStateStoreState,
|
||||
selectThreadTerminalUiState,
|
||||
useTerminalUiStateStore,
|
||||
} from "./terminalUiStateStore";
|
||||
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const THREAD_REF = scopeThreadRef("environment-a" as never, THREAD_ID);
|
||||
const OTHER_THREAD_REF = scopeThreadRef("environment-b" as never, THREAD_ID);
|
||||
|
||||
describe("terminalUiStateStore actions", () => {
|
||||
beforeEach(() => {
|
||||
useTerminalUiStateStore.persist.clearStorage();
|
||||
useTerminalUiStateStore.setState({
|
||||
terminalUiStateByThreadKey: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a closed default terminal UI state for unknown threads", () => {
|
||||
const terminalUiState = selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState).toEqual({
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
});
|
||||
});
|
||||
|
||||
it("opens and splits terminals into the active group", () => {
|
||||
const store = useTerminalUiStateStore.getState();
|
||||
store.setTerminalOpen(THREAD_REF, true);
|
||||
store.splitTerminal(THREAD_REF, "terminal-2");
|
||||
|
||||
const terminalUiState = selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.terminalOpen).toBe(true);
|
||||
expect(terminalUiState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalUiState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("caps splits at four terminals per group", () => {
|
||||
const store = useTerminalUiStateStore.getState();
|
||||
store.splitTerminal(THREAD_REF, "terminal-2");
|
||||
store.splitTerminal(THREAD_REF, "terminal-3");
|
||||
store.splitTerminal(THREAD_REF, "terminal-4");
|
||||
store.splitTerminal(THREAD_REF, "terminal-5");
|
||||
|
||||
const terminalUiState = selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.terminalIds).toEqual([
|
||||
"default",
|
||||
"terminal-2",
|
||||
"terminal-3",
|
||||
"terminal-4",
|
||||
]);
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2", "terminal-3", "terminal-4"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates new terminals in a separate group", () => {
|
||||
useTerminalUiStateStore.getState().newTerminal(THREAD_REF, "terminal-2");
|
||||
|
||||
const terminalUiState = selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.terminalIds).toEqual(["default", "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"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("ensures unknown server terminals are registered, opened, and activated", () => {
|
||||
const store = useTerminalUiStateStore.getState();
|
||||
store.ensureTerminal(THREAD_REF, "setup-setup", { open: true, active: true });
|
||||
|
||||
const terminalUiState = selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.terminalOpen).toBe(true);
|
||||
expect(terminalUiState.terminalIds).toEqual(["default", "setup-setup"]);
|
||||
expect(terminalUiState.activeTerminalId).toBe("setup-setup");
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-setup-setup", terminalIds: ["setup-setup"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps state isolated per environment when raw thread ids collide", () => {
|
||||
const store = useTerminalUiStateStore.getState();
|
||||
store.setTerminalOpen(THREAD_REF, true);
|
||||
store.newTerminal(OTHER_THREAD_REF, "env-b-terminal");
|
||||
|
||||
expect(
|
||||
selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
).terminalOpen,
|
||||
).toBe(true);
|
||||
expect(
|
||||
selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
OTHER_THREAD_REF,
|
||||
).terminalIds,
|
||||
).toEqual(["default", "env-b-terminal"]);
|
||||
});
|
||||
|
||||
it("migrates legacy persisted terminal UI state using the stored version", () => {
|
||||
const migrated = migratePersistedTerminalUiStateStoreState(
|
||||
{
|
||||
terminalStateByThreadKey: {
|
||||
[scopedThreadKey(THREAD_REF)]: {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: ["default"],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
},
|
||||
"legacy-thread-id": {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: ["default"],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
},
|
||||
},
|
||||
},
|
||||
2,
|
||||
);
|
||||
|
||||
expect(migrated).toEqual({
|
||||
terminalUiStateByThreadKey: {
|
||||
[scopedThreadKey(THREAD_REF)]: {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: ["default"],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("resets to default and clears persisted entry when closing the last terminal", () => {
|
||||
const store = useTerminalUiStateStore.getState();
|
||||
store.closeTerminal(THREAD_REF, "default");
|
||||
|
||||
expect(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey[scopedThreadKey(THREAD_REF)],
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
).terminalIds,
|
||||
).toEqual(["default"]);
|
||||
});
|
||||
|
||||
it("keeps a valid active terminal after closing an active split terminal", () => {
|
||||
const store = useTerminalUiStateStore.getState();
|
||||
store.splitTerminal(THREAD_REF, "terminal-2");
|
||||
store.splitTerminal(THREAD_REF, "terminal-3");
|
||||
store.closeTerminal(THREAD_REF, "terminal-3");
|
||||
|
||||
const terminalUiState = selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
THREAD_REF,
|
||||
);
|
||||
expect(terminalUiState.activeTerminalId).toBe("terminal-2");
|
||||
expect(terminalUiState.terminalIds).toEqual(["default", "terminal-2"]);
|
||||
expect(terminalUiState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("is a no-op when clearing terminal UI state for a thread with no state", () => {
|
||||
const store = useTerminalUiStateStore.getState();
|
||||
const before = useTerminalUiStateStore.getState();
|
||||
|
||||
store.clearTerminalUiState(THREAD_REF);
|
||||
|
||||
expect(useTerminalUiStateStore.getState()).toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,611 @@
|
||||
/**
|
||||
* Single Zustand store for terminal UI state keyed by scoped thread identity.
|
||||
*
|
||||
* Terminal UI transition helpers are intentionally private to keep the public
|
||||
* API constrained to store actions/selectors.
|
||||
*/
|
||||
|
||||
import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime";
|
||||
import { type ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
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";
|
||||
|
||||
interface ThreadTerminalUiState {
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
}
|
||||
|
||||
// Keep the old storage key so existing drawer layout preferences migrate.
|
||||
const TERMINAL_UI_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
|
||||
|
||||
interface PersistedTerminalUiStateStoreState {
|
||||
terminalUiStateByThreadKey?: Record<string, ThreadTerminalUiState>;
|
||||
terminalStateByThreadKey?: Record<string, ThreadTerminalUiState>;
|
||||
}
|
||||
|
||||
export function migratePersistedTerminalUiStateStoreState(
|
||||
persistedState: unknown,
|
||||
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 };
|
||||
}
|
||||
return { terminalUiStateByThreadKey: {} };
|
||||
}
|
||||
|
||||
function createTerminalUiStateStorage() {
|
||||
return resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined);
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): string {
|
||||
let candidate = baseId;
|
||||
let index = 2;
|
||||
while (usedGroupIds.has(candidate)) {
|
||||
candidate = `${baseId}-${index}`;
|
||||
index += 1;
|
||||
}
|
||||
usedGroupIds.add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function findGroupIndexByTerminalId(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalId: string,
|
||||
): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalIds: string[],
|
||||
): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const nextGroups: ThreadTerminalGroup[] = [];
|
||||
const usedGroupIds = new Set<string>();
|
||||
|
||||
for (const group of terminalGroups) {
|
||||
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (nextGroups.length === 0) {
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return nextGroups;
|
||||
}
|
||||
|
||||
function arraysEqual(a: string[], b: string[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let index = 0; index < a.length; index += 1) {
|
||||
if (a[index] !== b[index]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalGroup[]): boolean {
|
||||
if (left.length !== right.length) return false;
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
const leftGroup = left[index];
|
||||
const rightGroup = right[index];
|
||||
if (!leftGroup || !rightGroup) return false;
|
||||
if (leftGroup.id !== rightGroup.id) return false;
|
||||
if (!arraysEqual(leftGroup.terminalIds, rightGroup.terminalIds)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function threadTerminalUiStateEqual(
|
||||
left: ThreadTerminalUiState,
|
||||
right: ThreadTerminalUiState,
|
||||
): boolean {
|
||||
return (
|
||||
left.terminalOpen === right.terminalOpen &&
|
||||
left.terminalHeight === right.terminalHeight &&
|
||||
left.activeTerminalId === right.activeTerminalId &&
|
||||
left.activeTerminalGroupId === right.activeTerminalGroupId &&
|
||||
arraysEqual(left.terminalIds, right.terminalIds) &&
|
||||
terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
|
||||
);
|
||||
}
|
||||
|
||||
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),
|
||||
});
|
||||
|
||||
function createDefaultThreadTerminalUiState(): ThreadTerminalUiState {
|
||||
return {
|
||||
...DEFAULT_THREAD_TERMINAL_UI_STATE,
|
||||
terminalIds: [...DEFAULT_THREAD_TERMINAL_UI_STATE.terminalIds],
|
||||
terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_UI_STATE.terminalGroups),
|
||||
};
|
||||
}
|
||||
|
||||
function getDefaultThreadTerminalUiState(): ThreadTerminalUiState {
|
||||
return DEFAULT_THREAD_TERMINAL_UI_STATE;
|
||||
}
|
||||
|
||||
function normalizeThreadTerminalUiState(state: ThreadTerminalUiState): ThreadTerminalUiState {
|
||||
const terminalIds = normalizeTerminalIds(state.terminalIds);
|
||||
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
|
||||
? state.activeTerminalId
|
||||
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
|
||||
const activeGroupIdFromState = terminalGroups.some(
|
||||
(group) => group.id === state.activeTerminalGroupId,
|
||||
)
|
||||
? state.activeTerminalGroupId
|
||||
: null;
|
||||
const activeGroupIdFromTerminal =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? null;
|
||||
|
||||
const normalized: ThreadTerminalUiState = {
|
||||
terminalOpen: state.terminalOpen,
|
||||
terminalHeight:
|
||||
Number.isFinite(state.terminalHeight) && state.terminalHeight > 0
|
||||
? state.terminalHeight
|
||||
: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: nextTerminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId:
|
||||
activeGroupIdFromState ??
|
||||
activeGroupIdFromTerminal ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
};
|
||||
return threadTerminalUiStateEqual(state, normalized) ? state : normalized;
|
||||
}
|
||||
|
||||
function isDefaultThreadTerminalUiState(state: ThreadTerminalUiState): boolean {
|
||||
const normalized = normalizeThreadTerminalUiState(state);
|
||||
return threadTerminalUiStateEqual(normalized, DEFAULT_THREAD_TERMINAL_UI_STATE);
|
||||
}
|
||||
|
||||
function isValidTerminalId(terminalId: string): boolean {
|
||||
return terminalId.trim().length > 0;
|
||||
}
|
||||
|
||||
function terminalThreadKey(threadRef: ScopedThreadRef): string {
|
||||
return scopedThreadKey(threadRef);
|
||||
}
|
||||
|
||||
function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[] {
|
||||
return groups.map((group) => ({
|
||||
id: group.id,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
}
|
||||
|
||||
function upsertTerminalIntoGroups(
|
||||
state: ThreadTerminalUiState,
|
||||
terminalId: string,
|
||||
mode: "split" | "new",
|
||||
): ThreadTerminalUiState {
|
||||
const normalized = normalizeThreadTerminalUiState(state);
|
||||
if (!isValidTerminalId(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const isNewTerminal = !normalized.terminalIds.includes(terminalId);
|
||||
const terminalIds = isNewTerminal
|
||||
? [...normalized.terminalIds, terminalId]
|
||||
: normalized.terminalIds;
|
||||
const terminalGroups = copyTerminalGroups(normalized.terminalGroups);
|
||||
|
||||
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, terminalId);
|
||||
if (existingGroupIndex >= 0) {
|
||||
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
|
||||
existingGroupIndex
|
||||
]!.terminalIds.filter((id) => id !== terminalId);
|
||||
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
|
||||
terminalGroups.splice(existingGroupIndex, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === "new") {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [terminalId] });
|
||||
return normalizeThreadTerminalUiState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
let activeGroupIndex = terminalGroups.findIndex(
|
||||
(group) => group.id === normalized.activeTerminalGroupId,
|
||||
);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
|
||||
const nextGroupId = assignUniqueGroupId(
|
||||
fallbackGroupId(normalized.activeTerminalId),
|
||||
usedGroupIds,
|
||||
);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (
|
||||
isNewTerminal &&
|
||||
!destinationGroup.terminalIds.includes(terminalId) &&
|
||||
destinationGroup.terminalIds.length >= MAX_TERMINALS_PER_GROUP
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (!destinationGroup.terminalIds.includes(terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(terminalId);
|
||||
}
|
||||
}
|
||||
|
||||
return normalizeThreadTerminalUiState({
|
||||
...normalized,
|
||||
terminalOpen: true,
|
||||
terminalIds,
|
||||
activeTerminalId: terminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
});
|
||||
}
|
||||
|
||||
function setThreadTerminalOpen(state: ThreadTerminalUiState, open: boolean): ThreadTerminalUiState {
|
||||
const normalized = normalizeThreadTerminalUiState(state);
|
||||
if (normalized.terminalOpen === open) return normalized;
|
||||
return { ...normalized, terminalOpen: open };
|
||||
}
|
||||
|
||||
function setThreadTerminalHeight(
|
||||
state: ThreadTerminalUiState,
|
||||
height: number,
|
||||
): ThreadTerminalUiState {
|
||||
const normalized = normalizeThreadTerminalUiState(state);
|
||||
if (!Number.isFinite(height) || height <= 0 || normalized.terminalHeight === height) {
|
||||
return normalized;
|
||||
}
|
||||
return { ...normalized, terminalHeight: height };
|
||||
}
|
||||
|
||||
function splitThreadTerminal(
|
||||
state: ThreadTerminalUiState,
|
||||
terminalId: string,
|
||||
): ThreadTerminalUiState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "split");
|
||||
}
|
||||
|
||||
function newThreadTerminal(
|
||||
state: ThreadTerminalUiState,
|
||||
terminalId: string,
|
||||
): ThreadTerminalUiState {
|
||||
return upsertTerminalIntoGroups(state, terminalId, "new");
|
||||
}
|
||||
|
||||
function setThreadActiveTerminal(
|
||||
state: ThreadTerminalUiState,
|
||||
terminalId: string,
|
||||
): ThreadTerminalUiState {
|
||||
const normalized = normalizeThreadTerminalUiState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const activeTerminalGroupId =
|
||||
normalized.terminalGroups.find((group) => group.terminalIds.includes(terminalId))?.id ??
|
||||
normalized.activeTerminalGroupId;
|
||||
if (
|
||||
normalized.activeTerminalId === terminalId &&
|
||||
normalized.activeTerminalGroupId === activeTerminalGroupId
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
return {
|
||||
...normalized,
|
||||
activeTerminalId: terminalId,
|
||||
activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
|
||||
function closeThreadTerminal(
|
||||
state: ThreadTerminalUiState,
|
||||
terminalId: string,
|
||||
): ThreadTerminalUiState {
|
||||
const normalized = normalizeThreadTerminalUiState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = normalized.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
return createDefaultThreadTerminalUiState();
|
||||
}
|
||||
|
||||
const closedTerminalIndex = normalized.terminalIds.indexOf(terminalId);
|
||||
const nextActiveTerminalId =
|
||||
normalized.activeTerminalId === terminalId
|
||||
? (remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: normalized.activeTerminalId;
|
||||
|
||||
const terminalGroups = normalized.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
const nextActiveTerminalGroupId =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(nextActiveTerminalId);
|
||||
|
||||
return normalizeThreadTerminalUiState({
|
||||
terminalOpen: normalized.terminalOpen,
|
||||
terminalHeight: normalized.terminalHeight,
|
||||
terminalIds: remainingTerminalIds,
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextActiveTerminalGroupId,
|
||||
});
|
||||
}
|
||||
|
||||
export function selectThreadTerminalUiState(
|
||||
terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>,
|
||||
threadRef: ScopedThreadRef | null | undefined,
|
||||
): ThreadTerminalUiState {
|
||||
if (!threadRef || threadRef.threadId.length === 0) {
|
||||
return getDefaultThreadTerminalUiState();
|
||||
}
|
||||
return (
|
||||
terminalUiStateByThreadKey[terminalThreadKey(threadRef)] ?? getDefaultThreadTerminalUiState()
|
||||
);
|
||||
}
|
||||
|
||||
function updateTerminalUiStateByThreadKey(
|
||||
terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>,
|
||||
threadRef: ScopedThreadRef,
|
||||
updater: (state: ThreadTerminalUiState) => ThreadTerminalUiState,
|
||||
): Record<string, ThreadTerminalUiState> {
|
||||
if (threadRef.threadId.length === 0) {
|
||||
return terminalUiStateByThreadKey;
|
||||
}
|
||||
|
||||
const threadKey = terminalThreadKey(threadRef);
|
||||
const current = selectThreadTerminalUiState(terminalUiStateByThreadKey, threadRef);
|
||||
const next = updater(current);
|
||||
if (next === current) {
|
||||
return terminalUiStateByThreadKey;
|
||||
}
|
||||
|
||||
if (isDefaultThreadTerminalUiState(next)) {
|
||||
if (terminalUiStateByThreadKey[threadKey] === undefined) {
|
||||
return terminalUiStateByThreadKey;
|
||||
}
|
||||
const { [threadKey]: _removed, ...rest } = terminalUiStateByThreadKey;
|
||||
return rest;
|
||||
}
|
||||
|
||||
return {
|
||||
...terminalUiStateByThreadKey,
|
||||
[threadKey]: next,
|
||||
};
|
||||
}
|
||||
|
||||
interface TerminalUiStateStoreState {
|
||||
terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>;
|
||||
setTerminalOpen: (threadRef: ScopedThreadRef, open: boolean) => void;
|
||||
setTerminalHeight: (threadRef: ScopedThreadRef, height: number) => void;
|
||||
splitTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
newTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
ensureTerminal: (
|
||||
threadRef: ScopedThreadRef,
|
||||
terminalId: string,
|
||||
options?: { open?: boolean; active?: boolean },
|
||||
) => void;
|
||||
setActiveTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
closeTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
|
||||
clearTerminalUiState: (threadRef: ScopedThreadRef) => void;
|
||||
removeTerminalUiState: (threadRef: ScopedThreadRef) => void;
|
||||
removeOrphanedTerminalUiStates: (activeThreadKeys: Set<string>) => void;
|
||||
}
|
||||
|
||||
export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
|
||||
persist(
|
||||
(set) => {
|
||||
const updateTerminal = (
|
||||
threadRef: ScopedThreadRef,
|
||||
updater: (state: ThreadTerminalUiState) => ThreadTerminalUiState,
|
||||
) => {
|
||||
set((state) => {
|
||||
const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey(
|
||||
state.terminalUiStateByThreadKey,
|
||||
threadRef,
|
||||
updater,
|
||||
);
|
||||
if (nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
terminalUiStateByThreadKey: {},
|
||||
setTerminalOpen: (threadRef, open) =>
|
||||
updateTerminal(threadRef, (state) => setThreadTerminalOpen(state, open)),
|
||||
setTerminalHeight: (threadRef, height) =>
|
||||
updateTerminal(threadRef, (state) => setThreadTerminalHeight(state, height)),
|
||||
splitTerminal: (threadRef, terminalId) =>
|
||||
updateTerminal(threadRef, (state) => splitThreadTerminal(state, terminalId)),
|
||||
newTerminal: (threadRef, terminalId) =>
|
||||
updateTerminal(threadRef, (state) => newThreadTerminal(state, terminalId)),
|
||||
ensureTerminal: (threadRef, terminalId, options) =>
|
||||
updateTerminal(threadRef, (state) => {
|
||||
let nextState = state;
|
||||
if (!state.terminalIds.includes(terminalId)) {
|
||||
nextState = newThreadTerminal(nextState, terminalId);
|
||||
}
|
||||
if (options?.active === false) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
activeTerminalId: state.activeTerminalId,
|
||||
activeTerminalGroupId: state.activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
if (options?.active ?? true) {
|
||||
nextState = setThreadActiveTerminal(nextState, terminalId);
|
||||
}
|
||||
if (options?.open) {
|
||||
nextState = setThreadTerminalOpen(nextState, true);
|
||||
}
|
||||
return normalizeThreadTerminalUiState(nextState);
|
||||
}),
|
||||
setActiveTerminal: (threadRef, terminalId) =>
|
||||
updateTerminal(threadRef, (state) => setThreadActiveTerminal(state, terminalId)),
|
||||
closeTerminal: (threadRef, terminalId) =>
|
||||
updateTerminal(threadRef, (state) => closeThreadTerminal(state, terminalId)),
|
||||
clearTerminalUiState: (threadRef) =>
|
||||
set((state) => {
|
||||
const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey(
|
||||
state.terminalUiStateByThreadKey,
|
||||
threadRef,
|
||||
() => createDefaultThreadTerminalUiState(),
|
||||
);
|
||||
if (nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
|
||||
};
|
||||
}),
|
||||
removeTerminalUiState: (threadRef) =>
|
||||
set((state) => {
|
||||
const threadKey = terminalThreadKey(threadRef);
|
||||
const hadTerminalUiState = state.terminalUiStateByThreadKey[threadKey] !== undefined;
|
||||
if (!hadTerminalUiState) {
|
||||
return state;
|
||||
}
|
||||
const nextTerminalUiStateByThreadKey = { ...state.terminalUiStateByThreadKey };
|
||||
delete nextTerminalUiStateByThreadKey[threadKey];
|
||||
return {
|
||||
terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
|
||||
};
|
||||
}),
|
||||
removeOrphanedTerminalUiStates: (activeThreadKeys) =>
|
||||
set((state) => {
|
||||
const orphanedIds = Object.keys(state.terminalUiStateByThreadKey).filter(
|
||||
(key) => !activeThreadKeys.has(key),
|
||||
);
|
||||
if (orphanedIds.length === 0) {
|
||||
return state;
|
||||
}
|
||||
const next = { ...state.terminalUiStateByThreadKey };
|
||||
for (const id of orphanedIds) {
|
||||
delete next[id];
|
||||
}
|
||||
return {
|
||||
terminalUiStateByThreadKey: next,
|
||||
};
|
||||
}),
|
||||
};
|
||||
},
|
||||
{
|
||||
name: TERMINAL_UI_STATE_STORAGE_KEY,
|
||||
version: 3,
|
||||
storage: createJSONStorage(createTerminalUiStateStorage),
|
||||
migrate: migratePersistedTerminalUiStateStoreState,
|
||||
partialize: (state) => ({
|
||||
terminalUiStateByThreadKey: state.terminalUiStateByThreadKey,
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -26,10 +26,13 @@ const STREAM_METHODS = new Set<string>([
|
||||
ORCHESTRATION_WS_METHODS.subscribeShell,
|
||||
ORCHESTRATION_WS_METHODS.subscribeThread,
|
||||
WS_METHODS.gitRunStackedAction,
|
||||
WS_METHODS.terminalAttach,
|
||||
WS_METHODS.subscribeGitStatus,
|
||||
WS_METHODS.subscribeTerminalEvents,
|
||||
WS_METHODS.subscribeTerminalMetadata,
|
||||
WS_METHODS.subscribeServerConfig,
|
||||
WS_METHODS.subscribeServerLifecycle,
|
||||
WS_METHODS.subscribeAuthAccess,
|
||||
]);
|
||||
|
||||
const ALL_RPC_METHODS = Array.from(WsRpcGroup.requests.keys());
|
||||
|
||||
@@ -297,7 +297,7 @@
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
"packages": {
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected].77", "", { "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-t+R1BW3ahCFMNM7/8WJq7+Gw9KPA9Cl7UUK8fWPokJZ75cf/xwEd9MqB+MVNoQT45dJiom/wxybT7tqYPkCqyg=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected].112", "", { "dependencies": { "@anthropic-ai/sdk": "^0.81.0", "@modelcontextprotocol/sdk": "^1.29.0" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-vMFoiDKlOive8p3tphpV1gQaaytOipwGJ+uw9mvvaLQUODSC2+fCdRDAY25i2Tsv+lOtxzXBKctmaDuWqZY7ig=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-D4K5PvEV6wPiRtVlVsJHIUhHAmOZ6IT/I9rKlTf84gR7GyyAurPJK7z9BOf/AZqC5d1DhYQGJNKRmV+q8dGhgw=="],
|
||||
|
||||
@@ -3243,8 +3243,6 @@
|
||||
|
||||
"svgo/css-tree": ["[email protected]", "", { "dependencies": { "mdn-data": "2.27.1", "source-map-js": "^1.2.1" } }, "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA=="],
|
||||
|
||||
"t3/@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "@anthropic-ai/sdk": "^0.81.0", "@modelcontextprotocol/sdk": "^1.29.0" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-vMFoiDKlOive8p3tphpV1gQaaytOipwGJ+uw9mvvaLQUODSC2+fCdRDAY25i2Tsv+lOtxzXBKctmaDuWqZY7ig=="],
|
||||
|
||||
"terser/commander": ["[email protected]", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="],
|
||||
|
||||
"test-exclude/glob": ["[email protected]", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="],
|
||||
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
OrchestrationShellStreamEvent,
|
||||
ServerConfig,
|
||||
ServerLifecycleWelcomePayload,
|
||||
TerminalEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { KnownEnvironment } from "./knownEnvironment.ts";
|
||||
@@ -29,7 +28,6 @@ interface OrchestrationHandlers {
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
environmentId: EnvironmentId,
|
||||
) => void;
|
||||
readonly applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => void;
|
||||
}
|
||||
|
||||
interface EnvironmentConnectionInput extends OrchestrationHandlers {
|
||||
@@ -137,14 +135,9 @@ export function createEnvironmentConnection(
|
||||
},
|
||||
);
|
||||
|
||||
const unsubTerminalEvent = input.client.terminal.onEvent((event) => {
|
||||
input.applyTerminalEvent(event, environmentId);
|
||||
});
|
||||
|
||||
const cleanup = () => {
|
||||
disposed = true;
|
||||
unsubShell();
|
||||
unsubTerminalEvent();
|
||||
unsubLifecycle();
|
||||
unsubConfig();
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createEnvironmentRuntimeManager } from "./environmentRuntimeState.ts";
|
||||
@@ -10,7 +11,7 @@ function resetAtomRegistry() {
|
||||
atomRegistry = AtomRegistry.make();
|
||||
}
|
||||
|
||||
const TARGET = { environmentId: "env-local" } as const;
|
||||
const TARGET = { environmentId: EnvironmentId.make("env-local") } as const;
|
||||
|
||||
describe("createEnvironmentRuntimeManager", () => {
|
||||
afterEach(() => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ServerConfig as T3ServerConfig } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ServerConfig as T3ServerConfig } from "@t3tools/contracts";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
export type EnvironmentConnectionState =
|
||||
@@ -15,7 +15,7 @@ export interface EnvironmentRuntimeState {
|
||||
}
|
||||
|
||||
export interface EnvironmentRuntimeTarget {
|
||||
readonly environmentId: string | null;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
}
|
||||
|
||||
export const EMPTY_ENVIRONMENT_RUNTIME_STATE = Object.freeze<EnvironmentRuntimeState>({
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type {
|
||||
GitActionProgressEvent,
|
||||
GitCreateBranchResult,
|
||||
GitCreateWorktreeResult,
|
||||
GitCheckoutResult,
|
||||
GitPullResult,
|
||||
GitRunStackedActionResult,
|
||||
GitStatusResult,
|
||||
import {
|
||||
EnvironmentId,
|
||||
type GitActionProgressEvent,
|
||||
type GitCreateBranchResult,
|
||||
type GitCreateWorktreeResult,
|
||||
type GitCheckoutResult,
|
||||
type GitPullResult,
|
||||
type GitRunStackedActionResult,
|
||||
type GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -33,7 +34,7 @@ function createDeferred<T>() {
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
const TARGET = { environmentId: "env-local", cwd: "/repo" } as const;
|
||||
const TARGET = { environmentId: EnvironmentId.make("env-local"), cwd: "/repo" } as const;
|
||||
|
||||
const BASE_STATUS: GitStatusResult = {
|
||||
isRepo: true,
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
GitRunStackedActionResult,
|
||||
GitStackedAction,
|
||||
GitStatusResult,
|
||||
EnvironmentId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -42,7 +43,7 @@ export interface GitActionState {
|
||||
}
|
||||
|
||||
export interface GitActionTarget {
|
||||
readonly environmentId: string | null;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly cwd: string | null;
|
||||
}
|
||||
|
||||
@@ -186,7 +187,7 @@ export function applyGitActionProgressEvent(
|
||||
|
||||
export interface GitActionManagerConfig {
|
||||
readonly getRegistry: () => AtomRegistry.AtomRegistry;
|
||||
readonly getClient: (environmentId: string) => GitActionClient | null;
|
||||
readonly getClient: (environmentId: EnvironmentId) => GitActionClient | null;
|
||||
readonly getActionId?: () => string;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitListBranchesResult } from "@t3tools/contracts";
|
||||
import { EnvironmentId, type GitListBranchesResult } from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -16,7 +16,7 @@ function resetAtomRegistry() {
|
||||
atomRegistry = AtomRegistry.make();
|
||||
}
|
||||
|
||||
const TARGET = { environmentId: "env-local", cwd: "/repo" } as const;
|
||||
const TARGET = { environmentId: EnvironmentId.make("env-local"), cwd: "/repo" } as const;
|
||||
|
||||
const FIRST_PAGE: GitListBranchesResult = {
|
||||
branches: [
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import type { GitBranch, GitListBranchesInput, GitListBranchesResult } from "@t3tools/contracts";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
GitBranch,
|
||||
GitListBranchesInput,
|
||||
GitListBranchesResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import type { WsRpcClient } from "./wsRpcClient.ts";
|
||||
|
||||
export interface GitBranchTarget {
|
||||
readonly environmentId: string | null;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly cwd: string | null;
|
||||
readonly query?: string | null;
|
||||
}
|
||||
@@ -76,7 +81,7 @@ function mergeBranches(
|
||||
|
||||
export interface GitBranchManagerConfig {
|
||||
readonly getRegistry: () => AtomRegistry.AtomRegistry;
|
||||
readonly getClient: (environmentId: string) => GitBranchClient | null;
|
||||
readonly getClient: (environmentId: EnvironmentId) => GitBranchClient | null;
|
||||
}
|
||||
|
||||
export function createGitBranchManager(config: GitBranchManagerConfig) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitStatusResult } from "@t3tools/contracts";
|
||||
import { EnvironmentId, type GitStatusResult } from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -60,9 +60,9 @@ function createMockClient(): {
|
||||
const PENDING = { data: null, error: null, cause: null, isPending: true };
|
||||
const EMPTY = { data: null, error: null, cause: null, isPending: false };
|
||||
|
||||
const TARGET = { environmentId: "env-local", cwd: "/repo" } as const;
|
||||
const FRESH_TARGET = { environmentId: "env-local", cwd: "/fresh" } as const;
|
||||
const OTHER_ENV_TARGET = { environmentId: "env-remote", cwd: "/repo" } as const;
|
||||
const TARGET = { environmentId: EnvironmentId.make("env-local"), cwd: "/repo" } as const;
|
||||
const FRESH_TARGET = { environmentId: EnvironmentId.make("env-local"), cwd: "/fresh" } as const;
|
||||
const OTHER_ENV_TARGET = { environmentId: EnvironmentId.make("env-remote"), cwd: "/repo" } as const;
|
||||
|
||||
/* ─── Tests ─────────────────────────────────────────────────────────── */
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitManagerServiceError, GitStatusResult } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, GitManagerServiceError, GitStatusResult } from "@t3tools/contracts";
|
||||
import type { Cause } from "effect";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
import type { WsRpcClient } from "./wsRpcClient.ts";
|
||||
@@ -13,7 +13,7 @@ export interface GitStatusState {
|
||||
}
|
||||
|
||||
export interface GitStatusTarget {
|
||||
readonly environmentId: string | null;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly cwd: string | null;
|
||||
}
|
||||
|
||||
@@ -76,13 +76,13 @@ export interface GitStatusManagerConfig {
|
||||
*/
|
||||
readonly getRegistry: () => AtomRegistry.AtomRegistry;
|
||||
/** Resolve a git client for an environment. */
|
||||
readonly getClient: (environmentId: string) => GitStatusClient | null;
|
||||
readonly getClient: (environmentId: EnvironmentId) => GitStatusClient | null;
|
||||
/**
|
||||
* Optional: get a stable identity for the current client.
|
||||
* Used to detect reconnections — when the identity changes the
|
||||
* manager tears down the old `onStatus` stream and subscribes anew.
|
||||
*/
|
||||
readonly getClientIdentity?: (environmentId: string) => string | null;
|
||||
readonly getClientIdentity?: (environmentId: EnvironmentId) => string | null;
|
||||
/**
|
||||
* Optional: subscribe to environment-connection changes.
|
||||
* When provided the manager reacts to client appear / disappear /
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ProjectId, ThreadId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationShellSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { createShellSnapshotManager } from "./shellSnapshotState.ts";
|
||||
|
||||
@@ -50,7 +55,7 @@ const BASE_SNAPSHOT: OrchestrationShellSnapshot = {
|
||||
],
|
||||
};
|
||||
|
||||
const TARGET = { environmentId: "env-local" } as const;
|
||||
const TARGET = { environmentId: EnvironmentId.make("env-local") } as const;
|
||||
|
||||
describe("createShellSnapshotManager", () => {
|
||||
afterEach(() => {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationShellStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import { applyShellStreamEvent } from "./shellSnapshotReducer.ts";
|
||||
@@ -10,7 +14,7 @@ export interface ShellSnapshotState {
|
||||
}
|
||||
|
||||
export interface ShellSnapshotTarget {
|
||||
readonly environmentId: string | null;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
}
|
||||
|
||||
export const EMPTY_SHELL_SNAPSHOT_STATE = Object.freeze<ShellSnapshotState>({
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { TerminalSessionSnapshot } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
TerminalAttachStreamEvent,
|
||||
TerminalMetadataStreamEvent,
|
||||
TerminalSessionSnapshot,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { createTerminalSessionManager } from "./terminalSessionState.ts";
|
||||
import {
|
||||
createTerminalSessionManager,
|
||||
getKnownTerminalSessionListFilter,
|
||||
knownTerminalSessionsAtom,
|
||||
runningTerminalIdsAtom,
|
||||
terminalSessionStateAtom,
|
||||
type KnownTerminalSessionTarget,
|
||||
} from "./terminalSessionState.ts";
|
||||
|
||||
let atomRegistry = AtomRegistry.make();
|
||||
|
||||
@@ -13,8 +26,8 @@ function resetAtomRegistry() {
|
||||
}
|
||||
|
||||
const TARGET = {
|
||||
environmentId: "env-local",
|
||||
threadId: "thread-1",
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: "default",
|
||||
} as const;
|
||||
|
||||
@@ -31,6 +44,48 @@ const BASE_SNAPSHOT: TerminalSessionSnapshot = {
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
type TerminalSessionManager = ReturnType<typeof createTerminalSessionManager>;
|
||||
|
||||
function applyAttachEvents(
|
||||
manager: TerminalSessionManager,
|
||||
target: KnownTerminalSessionTarget,
|
||||
events: ReadonlyArray<TerminalAttachStreamEvent>,
|
||||
): void {
|
||||
manager.attach({
|
||||
environmentId: target.environmentId,
|
||||
terminal: {
|
||||
threadId: target.threadId,
|
||||
terminalId: target.terminalId,
|
||||
},
|
||||
client: {
|
||||
terminal: {
|
||||
attach: (_input, listener) => {
|
||||
events.forEach(listener);
|
||||
return () => undefined;
|
||||
},
|
||||
},
|
||||
},
|
||||
})();
|
||||
}
|
||||
|
||||
function applyMetadataEvents(
|
||||
manager: TerminalSessionManager,
|
||||
environmentId: EnvironmentId,
|
||||
events: ReadonlyArray<TerminalMetadataStreamEvent>,
|
||||
): void {
|
||||
manager.subscribeMetadata({
|
||||
environmentId,
|
||||
client: {
|
||||
terminal: {
|
||||
onMetadata: (listener) => {
|
||||
events.forEach(listener);
|
||||
return () => undefined;
|
||||
},
|
||||
},
|
||||
},
|
||||
})();
|
||||
}
|
||||
|
||||
describe("createTerminalSessionManager", () => {
|
||||
afterEach(() => {
|
||||
resetAtomRegistry();
|
||||
@@ -41,27 +96,25 @@ describe("createTerminalSessionManager", () => {
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "started",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: BASE_SNAPSHOT.updatedAt,
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
});
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "output",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
data: " world",
|
||||
});
|
||||
applyAttachEvents(manager, TARGET, [
|
||||
{
|
||||
type: "snapshot",
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
},
|
||||
{
|
||||
type: "output",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
data: " world",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(manager.getSnapshot(TARGET)).toMatchObject({
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
summary: null,
|
||||
buffer: "hello world",
|
||||
status: "running",
|
||||
error: null,
|
||||
updatedAt: "2026-04-01T00:00:01.000Z",
|
||||
updatedAt: BASE_SNAPSHOT.updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -71,13 +124,14 @@ describe("createTerminalSessionManager", () => {
|
||||
maxBufferBytes: 5,
|
||||
});
|
||||
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "output",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
data: "abcdef",
|
||||
});
|
||||
applyAttachEvents(manager, TARGET, [
|
||||
{
|
||||
type: "output",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
data: "abcdef",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(manager.getSnapshot(TARGET).buffer).toBe("bcdef");
|
||||
});
|
||||
@@ -88,13 +142,14 @@ describe("createTerminalSessionManager", () => {
|
||||
maxBufferBytes: 4,
|
||||
});
|
||||
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "output",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
data: "🙂🙂",
|
||||
});
|
||||
applyAttachEvents(manager, TARGET, [
|
||||
{
|
||||
type: "output",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
data: "🙂🙂",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(manager.getSnapshot(TARGET).buffer).toBe("🙂");
|
||||
});
|
||||
@@ -104,19 +159,20 @@ describe("createTerminalSessionManager", () => {
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
const otherTarget = {
|
||||
environmentId: "env-remote",
|
||||
threadId: "thread-1",
|
||||
environmentId: EnvironmentId.make("env-remote"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
terminalId: "default",
|
||||
} as const;
|
||||
|
||||
for (const target of [TARGET, otherTarget]) {
|
||||
manager.applyEvent(target, {
|
||||
type: "output",
|
||||
threadId: target.threadId,
|
||||
terminalId: target.terminalId,
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
data: target.environmentId,
|
||||
});
|
||||
applyAttachEvents(manager, target, [
|
||||
{
|
||||
type: "output",
|
||||
threadId: target.threadId,
|
||||
terminalId: target.terminalId,
|
||||
data: target.environmentId,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
manager.invalidateEnvironment(TARGET.environmentId);
|
||||
@@ -130,29 +186,37 @@ describe("createTerminalSessionManager", () => {
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "started",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
});
|
||||
manager.applyEvent(
|
||||
applyMetadataEvents(manager, TARGET.environmentId, [
|
||||
{
|
||||
environmentId: TARGET.environmentId,
|
||||
type: "snapshot",
|
||||
terminals: [
|
||||
{
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
cwd: "/repo",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 123,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
hasRunningSubprocess: false,
|
||||
},
|
||||
{
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: "term-2",
|
||||
cwd: "/repo",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 124,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-01T00:00:02.000Z",
|
||||
hasRunningSubprocess: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "started",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: "term-2",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
snapshot: {
|
||||
...BASE_SNAPSHOT,
|
||||
terminalId: "term-2",
|
||||
updatedAt: "2026-04-01T00:00:02.000Z",
|
||||
},
|
||||
},
|
||||
);
|
||||
]);
|
||||
|
||||
expect(
|
||||
manager
|
||||
@@ -169,13 +233,14 @@ describe("createTerminalSessionManager", () => {
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "output",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
data: "hello",
|
||||
});
|
||||
applyAttachEvents(manager, TARGET, [
|
||||
{
|
||||
type: "output",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
data: "hello",
|
||||
},
|
||||
]);
|
||||
|
||||
manager.invalidateEnvironment(TARGET.environmentId);
|
||||
|
||||
@@ -192,20 +257,41 @@ describe("createTerminalSessionManager", () => {
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "started",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: BASE_SNAPSHOT.updatedAt,
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
});
|
||||
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "closed",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: "2026-04-01T00:00:04.000Z",
|
||||
});
|
||||
applyMetadataEvents(manager, TARGET.environmentId, [
|
||||
{
|
||||
type: "upsert",
|
||||
terminal: {
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
cwd: "/repo",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 123,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: BASE_SNAPSHOT.updatedAt,
|
||||
hasRunningSubprocess: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
applyAttachEvents(manager, TARGET, [
|
||||
{
|
||||
type: "snapshot",
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
},
|
||||
{
|
||||
type: "closed",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
},
|
||||
]);
|
||||
applyMetadataEvents(manager, TARGET.environmentId, [
|
||||
{
|
||||
type: "remove",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(
|
||||
manager.listSessions({
|
||||
@@ -216,8 +302,8 @@ describe("createTerminalSessionManager", () => {
|
||||
expect(manager.getSnapshot(TARGET)).toMatchObject({
|
||||
buffer: "hello",
|
||||
status: "closed",
|
||||
snapshot: null,
|
||||
updatedAt: "2026-04-01T00:00:04.000Z",
|
||||
summary: null,
|
||||
updatedAt: BASE_SNAPSHOT.updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -226,24 +312,22 @@ describe("createTerminalSessionManager", () => {
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "started",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: BASE_SNAPSHOT.updatedAt,
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
});
|
||||
manager.applyEvent(TARGET, {
|
||||
type: "closed",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
createdAt: "2026-04-01T00:00:04.000Z",
|
||||
});
|
||||
applyAttachEvents(manager, TARGET, [
|
||||
{
|
||||
type: "snapshot",
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
},
|
||||
{
|
||||
type: "closed",
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
},
|
||||
]);
|
||||
|
||||
manager.reset();
|
||||
|
||||
expect(manager.getSnapshot(TARGET)).toEqual({
|
||||
snapshot: null,
|
||||
summary: null,
|
||||
buffer: "",
|
||||
status: "closed",
|
||||
error: null,
|
||||
@@ -258,14 +342,16 @@ describe("createTerminalSessionManager", () => {
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
|
||||
manager.syncSnapshot(
|
||||
{ environmentId: TARGET.environmentId },
|
||||
applyAttachEvents(manager, TARGET, [
|
||||
{
|
||||
...BASE_SNAPSHOT,
|
||||
history: "prompt$ ",
|
||||
updatedAt: "2026-04-01T00:00:03.000Z",
|
||||
type: "snapshot",
|
||||
snapshot: {
|
||||
...BASE_SNAPSHOT,
|
||||
history: "prompt$ ",
|
||||
updatedAt: "2026-04-01T00:00:03.000Z",
|
||||
},
|
||||
},
|
||||
);
|
||||
]);
|
||||
|
||||
expect(manager.getSnapshot(TARGET)).toMatchObject({
|
||||
buffer: "prompt$ ",
|
||||
@@ -273,4 +359,178 @@ describe("createTerminalSessionManager", () => {
|
||||
updatedAt: "2026-04-01T00:00:03.000Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("syncs authoritative metadata snapshots and removes missing environment terminals", () => {
|
||||
const manager = createTerminalSessionManager({
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
|
||||
applyAttachEvents(manager, TARGET, [
|
||||
{
|
||||
type: "snapshot",
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
},
|
||||
]);
|
||||
applyAttachEvents(
|
||||
manager,
|
||||
{
|
||||
environmentId: TARGET.environmentId,
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: "term-2",
|
||||
},
|
||||
[
|
||||
{
|
||||
type: "snapshot",
|
||||
snapshot: {
|
||||
...BASE_SNAPSHOT,
|
||||
terminalId: "term-2",
|
||||
updatedAt: "2026-04-01T00:00:02.000Z",
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
applyMetadataEvents(manager, TARGET.environmentId, [
|
||||
{
|
||||
type: "snapshot",
|
||||
terminals: [
|
||||
{
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: "term-2",
|
||||
cwd: "/repo",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 123,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-01T00:00:05.000Z",
|
||||
hasRunningSubprocess: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(
|
||||
manager.listSessions({
|
||||
environmentId: TARGET.environmentId,
|
||||
threadId: TARGET.threadId,
|
||||
}),
|
||||
).toMatchObject([
|
||||
{
|
||||
target: {
|
||||
environmentId: TARGET.environmentId,
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: "term-2",
|
||||
},
|
||||
state: {
|
||||
summary: {
|
||||
terminalId: "term-2",
|
||||
cwd: "/repo",
|
||||
},
|
||||
hasRunningSubprocess: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("updates listed session metadata when existing session activity changes", () => {
|
||||
const manager = createTerminalSessionManager({
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
|
||||
applyMetadataEvents(manager, TARGET.environmentId, [
|
||||
{
|
||||
type: "upsert",
|
||||
terminal: {
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
cwd: "/repo",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 123,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: BASE_SNAPSHOT.updatedAt,
|
||||
hasRunningSubprocess: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
applyMetadataEvents(manager, TARGET.environmentId, [
|
||||
{
|
||||
type: "upsert",
|
||||
terminal: {
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
cwd: "/repo",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 123,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-01T00:00:05.000Z",
|
||||
hasRunningSubprocess: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(
|
||||
manager.listSessions({ environmentId: TARGET.environmentId, threadId: TARGET.threadId }),
|
||||
).toMatchObject([
|
||||
{
|
||||
state: {
|
||||
hasRunningSubprocess: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("derives session atoms from structurally equal target objects", () => {
|
||||
const manager = createTerminalSessionManager({
|
||||
getRegistry: () => atomRegistry,
|
||||
});
|
||||
|
||||
applyMetadataEvents(manager, TARGET.environmentId, [
|
||||
{
|
||||
type: "upsert",
|
||||
terminal: {
|
||||
threadId: TARGET.threadId,
|
||||
terminalId: TARGET.terminalId,
|
||||
cwd: "/repo",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 123,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: BASE_SNAPSHOT.updatedAt,
|
||||
hasRunningSubprocess: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
applyAttachEvents(manager, TARGET, [
|
||||
{
|
||||
type: "snapshot",
|
||||
snapshot: BASE_SNAPSHOT,
|
||||
},
|
||||
]);
|
||||
|
||||
const equalTarget = { ...TARGET };
|
||||
const filter = getKnownTerminalSessionListFilter({
|
||||
environmentId: TARGET.environmentId,
|
||||
threadId: TARGET.threadId,
|
||||
});
|
||||
expect(filter).not.toBeNull();
|
||||
if (filter === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(atomRegistry.get(terminalSessionStateAtom(equalTarget))).toMatchObject({
|
||||
buffer: BASE_SNAPSHOT.history,
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
expect(
|
||||
atomRegistry.get(knownTerminalSessionsAtom({ ...filter })).map((session) => session.target),
|
||||
).toEqual([TARGET]);
|
||||
expect(atomRegistry.get(runningTerminalIdsAtom({ ...filter }))).toEqual([TARGET.terminalId]);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,15 @@
|
||||
import type { TerminalEvent, TerminalSessionSnapshot } from "@t3tools/contracts";
|
||||
import type {
|
||||
TerminalAttachStreamEvent,
|
||||
TerminalMetadataStreamEvent,
|
||||
TerminalSessionSnapshot,
|
||||
TerminalSummary,
|
||||
EnvironmentId,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_TERMINAL_ID, ThreadId, type TerminalAttachInput } from "@t3tools/contracts";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
export interface TerminalSessionState {
|
||||
readonly snapshot: TerminalSessionSnapshot | null;
|
||||
readonly summary: TerminalSummary | null;
|
||||
readonly buffer: string;
|
||||
readonly status: TerminalSessionSnapshot["status"] | "closed";
|
||||
readonly error: string | null;
|
||||
@@ -11,15 +18,23 @@ export interface TerminalSessionState {
|
||||
readonly version: number;
|
||||
}
|
||||
|
||||
export interface TerminalBufferState {
|
||||
readonly buffer: string;
|
||||
readonly status: TerminalSessionSnapshot["status"] | "closed";
|
||||
readonly error: string | null;
|
||||
readonly updatedAt: string | null;
|
||||
readonly version: number;
|
||||
}
|
||||
|
||||
export interface TerminalSessionTarget {
|
||||
readonly environmentId: string | null;
|
||||
readonly threadId: string | null;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly threadId: ThreadId | null;
|
||||
readonly terminalId: string | null;
|
||||
}
|
||||
|
||||
export interface KnownTerminalSessionTarget {
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly terminalId: string;
|
||||
}
|
||||
|
||||
@@ -28,13 +43,57 @@ export interface KnownTerminalSession {
|
||||
readonly state: TerminalSessionState;
|
||||
}
|
||||
|
||||
export interface KnownTerminalMetadata {
|
||||
readonly target: KnownTerminalSessionTarget;
|
||||
readonly summary: TerminalSummary;
|
||||
}
|
||||
|
||||
export interface TerminalSessionListFilter {
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly threadId?: ThreadId | null;
|
||||
readonly terminalId?: string | null;
|
||||
}
|
||||
|
||||
export interface KnownTerminalSessionListFilter {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId | null;
|
||||
readonly terminalId: string | null;
|
||||
}
|
||||
|
||||
export interface TerminalSessionManagerConfig {
|
||||
readonly getRegistry: () => AtomRegistry.AtomRegistry;
|
||||
readonly maxBufferBytes?: number;
|
||||
}
|
||||
|
||||
export interface TerminalMetadataClient {
|
||||
readonly terminal: {
|
||||
readonly onMetadata: (
|
||||
listener: (event: TerminalMetadataStreamEvent) => void,
|
||||
options?: { readonly onResubscribe?: () => void },
|
||||
) => () => void;
|
||||
};
|
||||
}
|
||||
|
||||
export interface TerminalAttachClient {
|
||||
readonly terminal: {
|
||||
readonly attach: (
|
||||
input: TerminalAttachInput & { readonly terminalId: string },
|
||||
listener: (event: TerminalAttachStreamEvent) => void,
|
||||
options?: { readonly onResubscribe?: () => void },
|
||||
) => () => void;
|
||||
};
|
||||
}
|
||||
|
||||
export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze<TerminalBufferState>({
|
||||
buffer: "",
|
||||
status: "closed",
|
||||
error: null,
|
||||
updatedAt: null,
|
||||
version: 0,
|
||||
});
|
||||
|
||||
export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze<TerminalSessionState>({
|
||||
snapshot: null,
|
||||
summary: null,
|
||||
buffer: "",
|
||||
status: "closed",
|
||||
error: null,
|
||||
@@ -43,56 +102,94 @@ export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze<TerminalSessionState>(
|
||||
version: 0,
|
||||
});
|
||||
|
||||
const EMPTY_KNOWN_TERMINAL_SESSIONS = Object.freeze<Array<KnownTerminalSession>>([]);
|
||||
const EMPTY_TERMINAL_ID_LIST = Object.freeze<Array<string>>([]);
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 512 * 1024;
|
||||
const knownTerminalSessionKeys = new Set<string>();
|
||||
const knownTerminalMetadataEnvironmentIds = new Set<EnvironmentId>();
|
||||
const knownTerminalBufferTargets = new Map<string, KnownTerminalSessionTarget>();
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
export const terminalSessionStateAtom = Atom.family((key: string) => {
|
||||
knownTerminalSessionKeys.add(key);
|
||||
return Atom.make(EMPTY_TERMINAL_SESSION_STATE).pipe(
|
||||
export const terminalSessionMetadataAtom = Atom.family((environmentId: EnvironmentId) => {
|
||||
knownTerminalMetadataEnvironmentIds.add(environmentId);
|
||||
return Atom.make<Record<string, KnownTerminalMetadata>>({}).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`terminal-session:${key}`),
|
||||
Atom.withLabel(`terminal-session:metadata:${environmentId}`),
|
||||
);
|
||||
});
|
||||
|
||||
export const EMPTY_TERMINAL_SESSION_ATOM = Atom.make(EMPTY_TERMINAL_SESSION_STATE).pipe(
|
||||
export const terminalSessionBufferAtom = Atom.family((target: KnownTerminalSessionTarget) => {
|
||||
const key = keyFromKnownTarget(target);
|
||||
knownTerminalBufferTargets.set(key, target);
|
||||
return Atom.make(EMPTY_TERMINAL_BUFFER_STATE).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`terminal-session:buffer:${key}`),
|
||||
);
|
||||
});
|
||||
|
||||
export const EMPTY_TERMINAL_BUFFER_ATOM = Atom.make(EMPTY_TERMINAL_BUFFER_STATE).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("terminal-session:null"),
|
||||
Atom.withLabel("terminal-session:buffer:null"),
|
||||
);
|
||||
|
||||
export const knownTerminalSessionsAtom = Atom.make<Record<string, KnownTerminalSessionTarget>>(
|
||||
{},
|
||||
).pipe(Atom.keepAlive, Atom.withLabel("terminal-session:index"));
|
||||
export const EMPTY_TERMINAL_SESSION_ATOM = Atom.make(EMPTY_TERMINAL_SESSION_STATE).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("terminal-session:state:null"),
|
||||
);
|
||||
|
||||
export function getTerminalSessionTargetKey(target: TerminalSessionTarget): string | null {
|
||||
export const EMPTY_KNOWN_TERMINAL_SESSIONS_ATOM = Atom.make(EMPTY_KNOWN_TERMINAL_SESSIONS).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("terminal-session:known:null"),
|
||||
);
|
||||
|
||||
export const EMPTY_TERMINAL_ID_LIST_ATOM = Atom.make(EMPTY_TERMINAL_ID_LIST).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("terminal-session:running-terminal-ids:null"),
|
||||
);
|
||||
|
||||
export function getKnownTerminalSessionTarget(
|
||||
target: TerminalSessionTarget,
|
||||
): KnownTerminalSessionTarget | null {
|
||||
if (target.environmentId === null || target.threadId === null || target.terminalId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return `${target.environmentId}:${target.threadId}:${target.terminalId}`;
|
||||
return {
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
terminalId: target.terminalId,
|
||||
};
|
||||
}
|
||||
|
||||
function toKnownTarget(target: TerminalSessionTarget): KnownTerminalSessionTarget | null {
|
||||
const targetKey = getTerminalSessionTargetKey(target);
|
||||
if (targetKey === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const environmentId = target.environmentId;
|
||||
const threadId = target.threadId;
|
||||
const terminalId = target.terminalId;
|
||||
if (environmentId === null || threadId === null || terminalId === null) {
|
||||
export function getKnownTerminalSessionListFilter(
|
||||
filter: TerminalSessionListFilter,
|
||||
): KnownTerminalSessionListFilter | null {
|
||||
if (filter.environmentId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
environmentId,
|
||||
threadId,
|
||||
terminalId,
|
||||
environmentId: filter.environmentId,
|
||||
threadId: filter.threadId ?? null,
|
||||
terminalId: filter.terminalId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function knownTargetFromSummary(
|
||||
environmentId: EnvironmentId,
|
||||
summary: TerminalSummary,
|
||||
): KnownTerminalSessionTarget {
|
||||
return {
|
||||
environmentId,
|
||||
threadId: ThreadId.make(summary.threadId),
|
||||
terminalId: summary.terminalId,
|
||||
};
|
||||
}
|
||||
|
||||
function keyFromKnownTarget(target: KnownTerminalSessionTarget): string {
|
||||
return `${target.environmentId}:${target.threadId}:${target.terminalId}`;
|
||||
}
|
||||
|
||||
function trimBufferToBytes(buffer: string, maxBufferBytes: number): string {
|
||||
if (maxBufferBytes <= 0) {
|
||||
return "";
|
||||
@@ -115,246 +212,326 @@ function trimBufferToBytes(buffer: string, maxBufferBytes: number): string {
|
||||
return textDecoder.decode(encoded.subarray(start));
|
||||
}
|
||||
|
||||
function stateFromSnapshot(
|
||||
function bufferFromSnapshot(
|
||||
snapshot: TerminalSessionSnapshot,
|
||||
maxBufferBytes: number,
|
||||
): TerminalSessionState {
|
||||
): TerminalBufferState {
|
||||
return {
|
||||
snapshot,
|
||||
buffer: trimBufferToBytes(snapshot.history, maxBufferBytes),
|
||||
status: snapshot.status,
|
||||
error: null,
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: snapshot.updatedAt,
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
function latestTimestamp(left: string | null, right: string | null): string | null {
|
||||
if (left === null) return right;
|
||||
if (right === null) return left;
|
||||
return Date.parse(left) >= Date.parse(right) ? left : right;
|
||||
}
|
||||
|
||||
function combineSessionState(
|
||||
summary: TerminalSummary | null,
|
||||
buffer: TerminalBufferState,
|
||||
): TerminalSessionState {
|
||||
return {
|
||||
summary,
|
||||
buffer: buffer.buffer,
|
||||
status: summary?.status ?? buffer.status,
|
||||
error: buffer.error,
|
||||
hasRunningSubprocess: summary?.hasRunningSubprocess ?? false,
|
||||
updatedAt: latestTimestamp(summary?.updatedAt ?? null, buffer.updatedAt),
|
||||
version: buffer.version,
|
||||
};
|
||||
}
|
||||
|
||||
function listKnownSessionsFromMetadata(
|
||||
metadata: Record<string, KnownTerminalMetadata>,
|
||||
getBuffer: (target: KnownTerminalSessionTarget) => TerminalBufferState,
|
||||
filter?: Partial<KnownTerminalSessionTarget>,
|
||||
): ReadonlyArray<KnownTerminalSession> {
|
||||
return Object.values(metadata)
|
||||
.filter(({ target }) => {
|
||||
if (filter?.environmentId && target.environmentId !== filter.environmentId) {
|
||||
return false;
|
||||
}
|
||||
if (filter?.threadId && target.threadId !== filter.threadId) {
|
||||
return false;
|
||||
}
|
||||
if (filter?.terminalId && target.terminalId !== filter.terminalId) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map(({ target, summary }) => ({
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
export const terminalSessionStateAtom = Atom.family((target: KnownTerminalSessionTarget) =>
|
||||
Atom.make((get) => {
|
||||
const targetKey = keyFromKnownTarget(target);
|
||||
return combineSessionState(
|
||||
get(terminalSessionMetadataAtom(target.environmentId))[targetKey]?.summary ?? null,
|
||||
get(terminalSessionBufferAtom(target)),
|
||||
);
|
||||
}).pipe(Atom.keepAlive, Atom.withLabel(`terminal-session:state:${keyFromKnownTarget(target)}`)),
|
||||
);
|
||||
|
||||
export const knownTerminalSessionsAtom = Atom.family((filter: KnownTerminalSessionListFilter) =>
|
||||
Atom.make((get) =>
|
||||
listKnownSessionsFromMetadata(
|
||||
get(terminalSessionMetadataAtom(filter.environmentId)),
|
||||
(target) => get(terminalSessionBufferAtom(target)),
|
||||
{
|
||||
environmentId: filter.environmentId,
|
||||
...(filter.threadId !== null ? { threadId: filter.threadId } : {}),
|
||||
...(filter.terminalId !== null ? { terminalId: filter.terminalId } : {}),
|
||||
},
|
||||
),
|
||||
).pipe(Atom.keepAlive, Atom.withLabel(`terminal-session:known:${JSON.stringify(filter)}`)),
|
||||
);
|
||||
|
||||
export const runningTerminalIdsAtom = Atom.family((filter: KnownTerminalSessionListFilter) =>
|
||||
Atom.make((get) => {
|
||||
return Object.values(get(terminalSessionMetadataAtom(filter.environmentId)))
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.target.environmentId === filter.environmentId &&
|
||||
(filter.threadId === null || entry.target.threadId === filter.threadId) &&
|
||||
(filter.terminalId === null || entry.target.terminalId === filter.terminalId) &&
|
||||
entry.summary.hasRunningSubprocess,
|
||||
)
|
||||
.map((entry) => entry.target.terminalId)
|
||||
.sort();
|
||||
}).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`terminal-session:running-terminal-ids:${JSON.stringify(filter)}`),
|
||||
),
|
||||
);
|
||||
|
||||
export function createTerminalSessionManager(config: TerminalSessionManagerConfig) {
|
||||
const maxBufferBytes = config.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
|
||||
const closedSessionStates = new Map<string, TerminalSessionState>();
|
||||
|
||||
function clearKnownSessionAtomState(targetKey: string): void {
|
||||
knownTerminalSessionKeys.delete(targetKey);
|
||||
config.getRegistry().set(terminalSessionStateAtom(targetKey), EMPTY_TERMINAL_SESSION_STATE);
|
||||
function getMetadata(environmentId: EnvironmentId): Record<string, KnownTerminalMetadata> {
|
||||
return config.getRegistry().get(terminalSessionMetadataAtom(environmentId));
|
||||
}
|
||||
|
||||
function rememberTarget(target: TerminalSessionTarget): string | null {
|
||||
const targetKey = getTerminalSessionTargetKey(target);
|
||||
const knownTarget = toKnownTarget(target);
|
||||
if (targetKey === null || knownTarget === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
closedSessionStates.delete(targetKey);
|
||||
|
||||
const current = config.getRegistry().get(knownTerminalSessionsAtom);
|
||||
const existing = current[targetKey];
|
||||
if (
|
||||
existing?.environmentId === knownTarget.environmentId &&
|
||||
existing.threadId === knownTarget.threadId &&
|
||||
existing.terminalId === knownTarget.terminalId
|
||||
) {
|
||||
return targetKey;
|
||||
}
|
||||
|
||||
config.getRegistry().set(knownTerminalSessionsAtom, {
|
||||
...current,
|
||||
[targetKey]: knownTarget,
|
||||
});
|
||||
return targetKey;
|
||||
function setMetadata(
|
||||
environmentId: EnvironmentId,
|
||||
next: Record<string, KnownTerminalMetadata>,
|
||||
): void {
|
||||
config.getRegistry().set(terminalSessionMetadataAtom(environmentId), next);
|
||||
}
|
||||
|
||||
function removeTargets(
|
||||
match: (target: KnownTerminalSessionTarget) => boolean,
|
||||
): ReadonlyArray<string> {
|
||||
const current = config.getRegistry().get(knownTerminalSessionsAtom);
|
||||
const removedKeys: string[] = [];
|
||||
const next = Object.fromEntries(
|
||||
Object.entries(current).filter(([key, target]) => {
|
||||
const shouldRemove = match(target);
|
||||
if (shouldRemove) {
|
||||
removedKeys.push(key);
|
||||
}
|
||||
return !shouldRemove;
|
||||
}),
|
||||
) as Record<string, KnownTerminalSessionTarget>;
|
||||
if (Object.keys(next).length === Object.keys(current).length) {
|
||||
return removedKeys;
|
||||
}
|
||||
function getBuffer(target: KnownTerminalSessionTarget): TerminalBufferState {
|
||||
return config.getRegistry().get(terminalSessionBufferAtom(target));
|
||||
}
|
||||
|
||||
config.getRegistry().set(knownTerminalSessionsAtom, next);
|
||||
return removedKeys;
|
||||
function setBuffer(target: KnownTerminalSessionTarget, next: TerminalBufferState): void {
|
||||
config.getRegistry().set(terminalSessionBufferAtom(target), next);
|
||||
}
|
||||
|
||||
function getSnapshot(target: TerminalSessionTarget): TerminalSessionState {
|
||||
const targetKey = getTerminalSessionTargetKey(target);
|
||||
if (targetKey === null) {
|
||||
const knownTarget = getKnownTerminalSessionTarget(target);
|
||||
if (knownTarget === null) {
|
||||
return EMPTY_TERMINAL_SESSION_STATE;
|
||||
}
|
||||
|
||||
const closedState = closedSessionStates.get(targetKey);
|
||||
if (closedState) {
|
||||
return closedState;
|
||||
}
|
||||
|
||||
const rememberedTargetKey = rememberTarget(target);
|
||||
if (rememberedTargetKey === null) {
|
||||
return EMPTY_TERMINAL_SESSION_STATE;
|
||||
}
|
||||
|
||||
return config.getRegistry().get(terminalSessionStateAtom(rememberedTargetKey));
|
||||
}
|
||||
|
||||
function setState(targetKey: string, nextState: TerminalSessionState): void {
|
||||
config.getRegistry().set(terminalSessionStateAtom(targetKey), nextState);
|
||||
return combineSessionState(
|
||||
getMetadata(knownTarget.environmentId)[keyFromKnownTarget(knownTarget)]?.summary ?? null,
|
||||
getBuffer(knownTarget),
|
||||
);
|
||||
}
|
||||
|
||||
function syncSnapshot(
|
||||
target: Pick<TerminalSessionTarget, "environmentId">,
|
||||
snapshot: TerminalSessionSnapshot,
|
||||
): void {
|
||||
const targetKey = rememberTarget({
|
||||
const knownTarget = getKnownTerminalSessionTarget({
|
||||
environmentId: target.environmentId,
|
||||
threadId: snapshot.threadId,
|
||||
threadId: ThreadId.make(snapshot.threadId),
|
||||
terminalId: snapshot.terminalId,
|
||||
});
|
||||
if (targetKey === null) {
|
||||
if (knownTarget === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(targetKey, stateFromSnapshot(snapshot, maxBufferBytes));
|
||||
setBuffer(knownTarget, bufferFromSnapshot(snapshot, maxBufferBytes));
|
||||
}
|
||||
|
||||
function applyEvent(
|
||||
function applyMetadataEvent(
|
||||
target: Pick<TerminalSessionTarget, "environmentId">,
|
||||
event: TerminalEvent,
|
||||
event: TerminalMetadataStreamEvent,
|
||||
): void {
|
||||
const targetKey = rememberTarget({
|
||||
environmentId: target.environmentId,
|
||||
threadId: event.threadId,
|
||||
terminalId: event.terminalId,
|
||||
});
|
||||
if (targetKey === null) {
|
||||
const environmentId = target.environmentId;
|
||||
if (environmentId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const current = config.getRegistry().get(terminalSessionStateAtom(targetKey));
|
||||
if (event.type === "snapshot") {
|
||||
const retainedKeys = new Set<string>();
|
||||
const next = { ...getMetadata(environmentId) };
|
||||
|
||||
for (const terminal of event.terminals) {
|
||||
const knownTarget = knownTargetFromSummary(environmentId, terminal);
|
||||
const targetKey = keyFromKnownTarget(knownTarget);
|
||||
retainedKeys.add(targetKey);
|
||||
next[targetKey] = {
|
||||
target: knownTarget,
|
||||
summary: terminal,
|
||||
};
|
||||
}
|
||||
|
||||
for (const key of Object.keys(next)) {
|
||||
if (!retainedKeys.has(key)) {
|
||||
delete next[key];
|
||||
}
|
||||
}
|
||||
|
||||
setMetadata(environmentId, next);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "upsert") {
|
||||
const knownTarget = knownTargetFromSummary(environmentId, event.terminal);
|
||||
const targetKey = keyFromKnownTarget(knownTarget);
|
||||
setMetadata(environmentId, {
|
||||
...getMetadata(environmentId),
|
||||
[targetKey]: {
|
||||
target: knownTarget,
|
||||
summary: event.terminal,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const knownTarget = getKnownTerminalSessionTarget({
|
||||
environmentId,
|
||||
threadId: ThreadId.make(event.threadId),
|
||||
terminalId: event.terminalId,
|
||||
});
|
||||
if (knownTarget === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const next = { ...getMetadata(environmentId) };
|
||||
delete next[keyFromKnownTarget(knownTarget)];
|
||||
setMetadata(environmentId, next);
|
||||
}
|
||||
|
||||
function applyAttachEvent(
|
||||
target: Pick<TerminalSessionTarget, "environmentId">,
|
||||
event: TerminalAttachStreamEvent,
|
||||
): void {
|
||||
if (event.type === "snapshot") {
|
||||
syncSnapshot(target, event.snapshot);
|
||||
return;
|
||||
}
|
||||
|
||||
const knownTarget = getKnownTerminalSessionTarget({
|
||||
environmentId: target.environmentId,
|
||||
threadId: ThreadId.make(event.threadId),
|
||||
terminalId: event.terminalId,
|
||||
});
|
||||
if (knownTarget === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const current = getBuffer(knownTarget);
|
||||
switch (event.type) {
|
||||
case "started":
|
||||
case "restarted":
|
||||
setState(targetKey, stateFromSnapshot(event.snapshot, maxBufferBytes));
|
||||
setBuffer(knownTarget, bufferFromSnapshot(event.snapshot, maxBufferBytes));
|
||||
return;
|
||||
case "output":
|
||||
setState(targetKey, {
|
||||
setBuffer(knownTarget, {
|
||||
...current,
|
||||
buffer: trimBufferToBytes(`${current.buffer}${event.data}`, maxBufferBytes),
|
||||
status: current.status === "closed" ? "running" : current.status,
|
||||
error: null,
|
||||
updatedAt: event.createdAt,
|
||||
version: current.version + 1,
|
||||
});
|
||||
return;
|
||||
case "cleared":
|
||||
setState(targetKey, {
|
||||
setBuffer(knownTarget, {
|
||||
...current,
|
||||
buffer: "",
|
||||
error: null,
|
||||
updatedAt: event.createdAt,
|
||||
version: current.version + 1,
|
||||
});
|
||||
return;
|
||||
case "exited":
|
||||
setState(targetKey, {
|
||||
setBuffer(knownTarget, {
|
||||
...current,
|
||||
snapshot: current.snapshot
|
||||
? {
|
||||
...current.snapshot,
|
||||
status: "exited",
|
||||
exitCode: event.exitCode,
|
||||
exitSignal: event.exitSignal,
|
||||
updatedAt: event.createdAt,
|
||||
}
|
||||
: null,
|
||||
status: "exited",
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: event.createdAt,
|
||||
error: null,
|
||||
version: current.version + 1,
|
||||
});
|
||||
return;
|
||||
case "closed":
|
||||
closedSessionStates.set(targetKey, {
|
||||
setBuffer(knownTarget, {
|
||||
...current,
|
||||
snapshot: null,
|
||||
status: "closed",
|
||||
error: null,
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: event.createdAt,
|
||||
version: current.version + 1,
|
||||
});
|
||||
clearKnownSessionAtomState(targetKey);
|
||||
removeTargets(
|
||||
(knownTarget) =>
|
||||
knownTarget.environmentId === target.environmentId &&
|
||||
knownTarget.threadId === event.threadId &&
|
||||
knownTarget.terminalId === event.terminalId,
|
||||
);
|
||||
return;
|
||||
case "error":
|
||||
setState(targetKey, {
|
||||
setBuffer(knownTarget, {
|
||||
...current,
|
||||
status: "error",
|
||||
error: event.message,
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: event.createdAt,
|
||||
version: current.version + 1,
|
||||
});
|
||||
return;
|
||||
case "activity":
|
||||
setState(targetKey, {
|
||||
...current,
|
||||
hasRunningSubprocess: event.hasRunningSubprocess,
|
||||
updatedAt: event.createdAt,
|
||||
version: current.version + 1,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function invalidate(target?: TerminalSessionTarget): void {
|
||||
if (target) {
|
||||
const targetKey = getTerminalSessionTargetKey(target);
|
||||
if (targetKey !== null) {
|
||||
closedSessionStates.delete(targetKey);
|
||||
setState(targetKey, EMPTY_TERMINAL_SESSION_STATE);
|
||||
const knownTarget = getKnownTerminalSessionTarget(target);
|
||||
if (knownTarget !== null) {
|
||||
const targetKey = keyFromKnownTarget(knownTarget);
|
||||
const next = { ...getMetadata(knownTarget.environmentId) };
|
||||
delete next[targetKey];
|
||||
setMetadata(knownTarget.environmentId, next);
|
||||
setBuffer(knownTarget, EMPTY_TERMINAL_BUFFER_STATE);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (const key of knownTerminalSessionKeys) {
|
||||
setState(key, EMPTY_TERMINAL_SESSION_STATE);
|
||||
for (const environmentId of knownTerminalMetadataEnvironmentIds) {
|
||||
setMetadata(environmentId, {});
|
||||
}
|
||||
closedSessionStates.clear();
|
||||
knownTerminalSessionKeys.clear();
|
||||
config.getRegistry().set(knownTerminalSessionsAtom, {});
|
||||
knownTerminalMetadataEnvironmentIds.clear();
|
||||
for (const target of knownTerminalBufferTargets.values()) {
|
||||
setBuffer(target, EMPTY_TERMINAL_BUFFER_STATE);
|
||||
}
|
||||
knownTerminalBufferTargets.clear();
|
||||
}
|
||||
|
||||
function invalidateEnvironment(environmentId: string): void {
|
||||
function invalidateEnvironment(environmentId: EnvironmentId): void {
|
||||
setMetadata(environmentId, {});
|
||||
knownTerminalMetadataEnvironmentIds.delete(environmentId);
|
||||
|
||||
const prefix = `${environmentId}:`;
|
||||
for (const key of knownTerminalSessionKeys) {
|
||||
for (const [key, target] of knownTerminalBufferTargets) {
|
||||
if (key.startsWith(prefix)) {
|
||||
setState(key, EMPTY_TERMINAL_SESSION_STATE);
|
||||
setBuffer(target, EMPTY_TERMINAL_BUFFER_STATE);
|
||||
}
|
||||
}
|
||||
for (const key of closedSessionStates.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
closedSessionStates.delete(key);
|
||||
}
|
||||
}
|
||||
for (const key of removeTargets((target) => target.environmentId === environmentId)) {
|
||||
closedSessionStates.delete(key);
|
||||
clearKnownSessionAtomState(key);
|
||||
}
|
||||
}
|
||||
|
||||
function reset(): void {
|
||||
@@ -364,41 +541,58 @@ export function createTerminalSessionManager(config: TerminalSessionManagerConfi
|
||||
function listSessions(
|
||||
filter?: Partial<KnownTerminalSessionTarget>,
|
||||
): ReadonlyArray<KnownTerminalSession> {
|
||||
const knownTargets = Object.values(config.getRegistry().get(knownTerminalSessionsAtom));
|
||||
return knownTargets
|
||||
.filter((target) => {
|
||||
if (filter?.environmentId && target.environmentId !== filter.environmentId) {
|
||||
return false;
|
||||
if (filter?.environmentId) {
|
||||
return listKnownSessionsFromMetadata(getMetadata(filter.environmentId), getBuffer, filter);
|
||||
}
|
||||
|
||||
return [...knownTerminalMetadataEnvironmentIds].flatMap((environmentId) =>
|
||||
listKnownSessionsFromMetadata(getMetadata(environmentId), getBuffer, filter),
|
||||
);
|
||||
}
|
||||
|
||||
function subscribeMetadata(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly client: TerminalMetadataClient;
|
||||
readonly options?: { readonly onResubscribe?: () => void };
|
||||
}): () => void {
|
||||
return input.client.terminal.onMetadata(
|
||||
(event) => applyMetadataEvent({ environmentId: input.environmentId }, event),
|
||||
input.options,
|
||||
);
|
||||
}
|
||||
|
||||
function attach(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly client: TerminalAttachClient;
|
||||
readonly terminal: TerminalAttachInput;
|
||||
readonly onSnapshot?: (snapshot: TerminalSessionSnapshot) => void;
|
||||
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,
|
||||
(event) => {
|
||||
applyAttachEvent({ environmentId: input.environmentId }, event);
|
||||
input.onEvent?.(event);
|
||||
if (event.type === "snapshot") {
|
||||
input.onSnapshot?.(event.snapshot);
|
||||
}
|
||||
if (filter?.threadId && target.threadId !== filter.threadId) {
|
||||
return false;
|
||||
}
|
||||
if (filter?.terminalId && target.terminalId !== filter.terminalId) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map((target) => ({
|
||||
target,
|
||||
state: getSnapshot(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);
|
||||
});
|
||||
},
|
||||
input.options,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
applyEvent,
|
||||
attach,
|
||||
getSnapshot,
|
||||
invalidate,
|
||||
invalidateEnvironment,
|
||||
listSessions,
|
||||
syncSnapshot,
|
||||
subscribeMetadata,
|
||||
reset,
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
EventId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -56,7 +57,10 @@ const BASE_THREAD: OrchestrationThread = {
|
||||
session: null,
|
||||
};
|
||||
|
||||
const TARGET = { environmentId: "env-local", threadId: "thread-1" } as const;
|
||||
const TARGET = {
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
} as const;
|
||||
|
||||
function createMockClient(): {
|
||||
client: ThreadDetailClient;
|
||||
|
||||
@@ -4,9 +4,9 @@ import * as Arr from "effect/Array";
|
||||
import type {
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadStreamItem,
|
||||
EnvironmentId,
|
||||
ThreadId as ThreadIdType,
|
||||
} from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
@@ -24,8 +24,8 @@ export interface ThreadDetailState {
|
||||
}
|
||||
|
||||
export interface ThreadDetailTarget {
|
||||
readonly environmentId: string | null;
|
||||
readonly threadId: string | null;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly threadId: ThreadIdType | null;
|
||||
}
|
||||
|
||||
export type ThreadDetailClient = Pick<WsRpcClient["orchestration"], "subscribeThread">;
|
||||
@@ -34,15 +34,15 @@ export interface ThreadDetailRetentionPolicy {
|
||||
readonly idleTtlMs: number;
|
||||
readonly maxRetainedEntries: number;
|
||||
readonly shouldKeepWarm?: (
|
||||
target: { readonly environmentId: string; readonly threadId: string },
|
||||
target: { readonly environmentId: EnvironmentId; readonly threadId: ThreadIdType },
|
||||
state: ThreadDetailState,
|
||||
) => boolean;
|
||||
}
|
||||
|
||||
interface ThreadDetailEntry {
|
||||
readonly target: {
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadIdType;
|
||||
};
|
||||
watcherCount: number;
|
||||
retainCount: number;
|
||||
@@ -99,8 +99,8 @@ export function getThreadDetailTargetKey(target: ThreadDetailTarget): string | n
|
||||
|
||||
export interface ThreadDetailManagerConfig {
|
||||
readonly getRegistry: () => AtomRegistry.AtomRegistry;
|
||||
readonly getClient: (environmentId: string) => ThreadDetailClient | null;
|
||||
readonly getClientIdentity?: (environmentId: string) => string | null;
|
||||
readonly getClient: (environmentId: EnvironmentId) => ThreadDetailClient | null;
|
||||
readonly getClientIdentity?: (environmentId: EnvironmentId) => string | null;
|
||||
readonly subscribeClientChanges?: (listener: () => void) => () => void;
|
||||
readonly limits?: ThreadDetailRetentionLimits;
|
||||
readonly retention?: ThreadDetailRetentionPolicy;
|
||||
@@ -272,13 +272,13 @@ export function createThreadDetailManager(config: ThreadDetailManagerConfig) {
|
||||
|
||||
function subscribeStream(
|
||||
targetKey: string,
|
||||
target: { readonly environmentId: string; readonly threadId: string },
|
||||
target: { readonly environmentId: EnvironmentId; readonly threadId: ThreadIdType },
|
||||
client: ThreadDetailClient,
|
||||
): () => void {
|
||||
markPending(targetKey);
|
||||
return client.subscribeThread(
|
||||
{ threadId: ThreadId.make(target.threadId) },
|
||||
(item) => applyStreamItem(targetKey, item, ThreadId.make(target.threadId)),
|
||||
{ threadId: target.threadId },
|
||||
(item) => applyStreamItem(targetKey, item, target.threadId),
|
||||
{
|
||||
onResubscribe: () => markPending(targetKey),
|
||||
},
|
||||
@@ -287,7 +287,7 @@ export function createThreadDetailManager(config: ThreadDetailManagerConfig) {
|
||||
|
||||
function createDynamicSubscription(
|
||||
targetKey: string,
|
||||
target: { readonly environmentId: string; readonly threadId: string },
|
||||
target: { readonly environmentId: EnvironmentId; readonly threadId: ThreadIdType },
|
||||
): () => void {
|
||||
let currentIdentity: string | null = null;
|
||||
let currentUnsub = NOOP;
|
||||
|
||||
@@ -56,12 +56,13 @@ export interface WsRpcClient {
|
||||
readonly reconnect: () => Promise<void>;
|
||||
readonly terminal: {
|
||||
readonly open: RpcUnaryMethod<typeof WS_METHODS.terminalOpen>;
|
||||
readonly attach: RpcInputStreamMethod<typeof WS_METHODS.terminalAttach>;
|
||||
readonly write: RpcUnaryMethod<typeof WS_METHODS.terminalWrite>;
|
||||
readonly resize: RpcUnaryMethod<typeof WS_METHODS.terminalResize>;
|
||||
readonly clear: RpcUnaryMethod<typeof WS_METHODS.terminalClear>;
|
||||
readonly restart: RpcUnaryMethod<typeof WS_METHODS.terminalRestart>;
|
||||
readonly close: RpcUnaryMethod<typeof WS_METHODS.terminalClose>;
|
||||
readonly onEvent: RpcStreamMethod<typeof WS_METHODS.subscribeTerminalEvents>;
|
||||
readonly onMetadata: RpcStreamMethod<typeof WS_METHODS.subscribeTerminalMetadata>;
|
||||
};
|
||||
readonly projects: {
|
||||
readonly searchEntries: RpcUnaryMethod<typeof WS_METHODS.projectsSearchEntries>;
|
||||
@@ -127,14 +128,20 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
|
||||
reconnect: () => transport.reconnect(),
|
||||
terminal: {
|
||||
open: (input) => transport.request((client) => client[WS_METHODS.terminalOpen](input)),
|
||||
attach: (input, listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.terminalAttach](input),
|
||||
listener,
|
||||
options,
|
||||
),
|
||||
write: (input) => transport.request((client) => client[WS_METHODS.terminalWrite](input)),
|
||||
resize: (input) => transport.request((client) => client[WS_METHODS.terminalResize](input)),
|
||||
clear: (input) => transport.request((client) => client[WS_METHODS.terminalClear](input)),
|
||||
restart: (input) => transport.request((client) => client[WS_METHODS.terminalRestart](input)),
|
||||
close: (input) => transport.request((client) => client[WS_METHODS.terminalClose](input)),
|
||||
onEvent: (listener, options) =>
|
||||
onMetadata: (listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeTerminalEvents]({}),
|
||||
(client) => client[WS_METHODS.subscribeTerminalMetadata]({}),
|
||||
listener,
|
||||
options,
|
||||
),
|
||||
|
||||
@@ -33,9 +33,11 @@ import type {
|
||||
ServerUpsertKeybindingResult,
|
||||
} from "./server.ts";
|
||||
import type {
|
||||
TerminalAttachInput,
|
||||
TerminalAttachStreamEvent,
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
TerminalEvent,
|
||||
TerminalMetadataStreamEvent,
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalRestartInput,
|
||||
@@ -236,12 +238,24 @@ export interface LocalApi {
|
||||
export interface EnvironmentApi {
|
||||
terminal: {
|
||||
open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;
|
||||
attach: (
|
||||
input: typeof TerminalAttachInput.Encoded,
|
||||
callback: (event: TerminalAttachStreamEvent) => void,
|
||||
options?: {
|
||||
onResubscribe?: () => void;
|
||||
},
|
||||
) => () => void;
|
||||
write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;
|
||||
resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;
|
||||
clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;
|
||||
restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;
|
||||
close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;
|
||||
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
|
||||
onMetadata: (
|
||||
callback: (event: TerminalMetadataStreamEvent) => void,
|
||||
options?: {
|
||||
onResubscribe?: () => void;
|
||||
},
|
||||
) => () => void;
|
||||
};
|
||||
projects: {
|
||||
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
|
||||
|
||||
@@ -59,10 +59,13 @@ import {
|
||||
ProjectWriteFileResult,
|
||||
} from "./project.ts";
|
||||
import {
|
||||
TerminalAttachInput,
|
||||
TerminalAttachStreamEvent,
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
TerminalError,
|
||||
TerminalEvent,
|
||||
TerminalMetadataStreamEvent,
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalRestartInput,
|
||||
@@ -109,6 +112,7 @@ export const WS_METHODS = {
|
||||
|
||||
// Terminal methods
|
||||
terminalOpen: "terminal.open",
|
||||
terminalAttach: "terminal.attach",
|
||||
terminalWrite: "terminal.write",
|
||||
terminalResize: "terminal.resize",
|
||||
terminalClear: "terminal.clear",
|
||||
@@ -125,6 +129,7 @@ export const WS_METHODS = {
|
||||
// Streaming subscriptions
|
||||
subscribeGitStatus: "subscribeGitStatus",
|
||||
subscribeTerminalEvents: "subscribeTerminalEvents",
|
||||
subscribeTerminalMetadata: "subscribeTerminalMetadata",
|
||||
subscribeServerConfig: "subscribeServerConfig",
|
||||
subscribeServerLifecycle: "subscribeServerLifecycle",
|
||||
subscribeAuthAccess: "subscribeAuthAccess",
|
||||
@@ -266,6 +271,13 @@ export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {
|
||||
error: TerminalError,
|
||||
});
|
||||
|
||||
export const WsTerminalAttachRpc = Rpc.make(WS_METHODS.terminalAttach, {
|
||||
payload: TerminalAttachInput,
|
||||
success: TerminalAttachStreamEvent,
|
||||
error: TerminalError,
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsTerminalWriteRpc = Rpc.make(WS_METHODS.terminalWrite, {
|
||||
payload: TerminalWriteInput,
|
||||
error: TerminalError,
|
||||
@@ -345,6 +357,12 @@ export const WsSubscribeTerminalEventsRpc = Rpc.make(WS_METHODS.subscribeTermina
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsSubscribeTerminalMetadataRpc = Rpc.make(WS_METHODS.subscribeTerminalMetadata, {
|
||||
payload: Schema.Struct({}),
|
||||
success: TerminalMetadataStreamEvent,
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsSubscribeServerConfigRpc = Rpc.make(WS_METHODS.subscribeServerConfig, {
|
||||
payload: Schema.Struct({}),
|
||||
success: ServerConfigStreamEvent,
|
||||
@@ -388,12 +406,14 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsGitInitRpc,
|
||||
WsGitGetReviewDiffsRpc,
|
||||
WsTerminalOpenRpc,
|
||||
WsTerminalAttachRpc,
|
||||
WsTerminalWriteRpc,
|
||||
WsTerminalResizeRpc,
|
||||
WsTerminalClearRpc,
|
||||
WsTerminalRestartRpc,
|
||||
WsTerminalCloseRpc,
|
||||
WsSubscribeTerminalEventsRpc,
|
||||
WsSubscribeTerminalMetadataRpc,
|
||||
WsSubscribeServerConfigRpc,
|
||||
WsSubscribeServerLifecycleRpc,
|
||||
WsSubscribeAuthAccessRpc,
|
||||
|
||||
@@ -178,7 +178,6 @@ describe("TerminalEvent", () => {
|
||||
type: "output",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
data: "line\n",
|
||||
}),
|
||||
).toBe(true);
|
||||
@@ -190,7 +189,6 @@ describe("TerminalEvent", () => {
|
||||
type: "exited",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
}),
|
||||
@@ -203,7 +201,6 @@ describe("TerminalEvent", () => {
|
||||
type: "closed",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -214,7 +211,6 @@ describe("TerminalEvent", () => {
|
||||
type: "activity",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
hasRunningSubprocess: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
@@ -226,7 +222,6 @@ describe("TerminalEvent", () => {
|
||||
type: "started",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
snapshot: {
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
|
||||
@@ -44,6 +44,16 @@ export const TerminalOpenInput = Schema.Struct({
|
||||
});
|
||||
export type TerminalOpenInput = Schema.Codec.Encoded<typeof TerminalOpenInput>;
|
||||
|
||||
export const TerminalAttachInput = Schema.Struct({
|
||||
...TerminalSessionInput.fields,
|
||||
cwd: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
|
||||
cols: Schema.optional(TerminalColsSchema),
|
||||
rows: Schema.optional(TerminalRowsSchema),
|
||||
env: Schema.optional(TerminalEnvSchema),
|
||||
});
|
||||
export type TerminalAttachInput = Schema.Codec.Encoded<typeof TerminalAttachInput>;
|
||||
|
||||
export const TerminalWriteInput = Schema.Struct({
|
||||
...TerminalSessionInput.fields,
|
||||
data: Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)),
|
||||
@@ -91,13 +101,51 @@ export const TerminalSessionSnapshot = Schema.Struct({
|
||||
exitCode: Schema.NullOr(Schema.Int),
|
||||
exitSignal: Schema.NullOr(Schema.Int),
|
||||
updatedAt: Schema.String,
|
||||
sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
|
||||
});
|
||||
export type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type;
|
||||
|
||||
export const TerminalSummary = Schema.Struct({
|
||||
threadId: Schema.String.check(Schema.isNonEmpty()),
|
||||
terminalId: Schema.String.check(Schema.isNonEmpty()),
|
||||
cwd: Schema.String.check(Schema.isNonEmpty()),
|
||||
worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
status: TerminalSessionStatus,
|
||||
pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
|
||||
exitCode: Schema.NullOr(Schema.Int),
|
||||
exitSignal: Schema.NullOr(Schema.Int),
|
||||
hasRunningSubprocess: Schema.Boolean,
|
||||
updatedAt: Schema.String,
|
||||
});
|
||||
export type TerminalSummary = typeof TerminalSummary.Type;
|
||||
|
||||
const TerminalMetadataSnapshotEvent = Schema.Struct({
|
||||
type: Schema.Literal("snapshot"),
|
||||
terminals: Schema.Array(TerminalSummary),
|
||||
});
|
||||
|
||||
const TerminalMetadataUpsertEvent = Schema.Struct({
|
||||
type: Schema.Literal("upsert"),
|
||||
terminal: TerminalSummary,
|
||||
});
|
||||
|
||||
const TerminalMetadataRemoveEvent = Schema.Struct({
|
||||
type: Schema.Literal("remove"),
|
||||
threadId: Schema.String.check(Schema.isNonEmpty()),
|
||||
terminalId: Schema.String.check(Schema.isNonEmpty()),
|
||||
});
|
||||
|
||||
export const TerminalMetadataStreamEvent = Schema.Union([
|
||||
TerminalMetadataSnapshotEvent,
|
||||
TerminalMetadataUpsertEvent,
|
||||
TerminalMetadataRemoveEvent,
|
||||
]);
|
||||
export type TerminalMetadataStreamEvent = typeof TerminalMetadataStreamEvent.Type;
|
||||
|
||||
const TerminalEventBaseSchema = Schema.Struct({
|
||||
threadId: Schema.String.check(Schema.isNonEmpty()),
|
||||
terminalId: Schema.String.check(Schema.isNonEmpty()),
|
||||
createdAt: Schema.String,
|
||||
sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
|
||||
});
|
||||
|
||||
const TerminalStartedEvent = Schema.Struct({
|
||||
@@ -159,6 +207,23 @@ export const TerminalEvent = Schema.Union([
|
||||
]);
|
||||
export type TerminalEvent = typeof TerminalEvent.Type;
|
||||
|
||||
const TerminalAttachSnapshotEvent = Schema.Struct({
|
||||
type: Schema.Literal("snapshot"),
|
||||
snapshot: TerminalSessionSnapshot,
|
||||
});
|
||||
|
||||
export const TerminalAttachStreamEvent = Schema.Union([
|
||||
TerminalAttachSnapshotEvent,
|
||||
TerminalOutputEvent,
|
||||
TerminalExitedEvent,
|
||||
TerminalClosedEvent,
|
||||
TerminalErrorEvent,
|
||||
TerminalClearedEvent,
|
||||
TerminalRestartedEvent,
|
||||
TerminalActivityEvent,
|
||||
]);
|
||||
export type TerminalAttachStreamEvent = typeof TerminalAttachStreamEvent.Type;
|
||||
|
||||
export class TerminalCwdError extends Schema.TaggedErrorClass<TerminalCwdError>()(
|
||||
"TerminalCwdError",
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user