Compare commits

..
Author SHA1 Message Date
Mohamed Boudra f694d0eab3 fix(app): return the previous pane to its last active tab when splitting or moving
Detaching a pane's active tab via splitPane or moveTabToPane previously dropped focusedTabId and fell back to the rightmost remaining tab in the strip, so dragging a file tab out after coming from tab A left the previous pane on tab B instead of putting A and the file side by side.

Track per-pane tab focus recency in memory and route both close and relocate focus transitions through one explicit policy table. Closing a tab keeps its existing parent-then-neighbor order, while splitting or moving a focused tab out of a pane returns the source pane to its most recently focused remaining tab (falling back to a same-pane parent tab and then an adjacent neighbor). Keeping the focus history in memory avoids adding a new key to the strict persisted layout schema.
2026-11-24 15:21:33 +01:00
62 changed files with 1313 additions and 3385 deletions
+2
View File
@@ -422,6 +422,7 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/headers/screen-header.tsx",
"packages/app/src/components/host-status-dot.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/icons/paseo-logo.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/plan-card.tsx",
@@ -553,6 +554,7 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/highlighted-code-block.tsx",
"packages/app/src/components/hosts/host-filter.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/import-session-sheet.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/markdown/fence/mermaid/host.native.tsx",
@@ -4,12 +4,15 @@
// never swallow entity tabs or lose the user's focus, and
// 2) splitting a tab out of a pane leaves a New tab behind, and the app must stay
// interactive in the [agent | New | explorer] state.
import { writeFileSync } from "node:fs";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { gotoWorkspace } from "../support/helpers/launcher";
import { seedCorruptedWorkspaceLayout } from "../support/helpers/workspace-layout";
import {
openChangesTreePanel,
openFilesPanel,
waitForWorkspaceTabsVisible,
} from "../support/helpers/workspace-tabs";
@@ -317,3 +320,75 @@ test("reloading a saved hidden generated Explorer recovers a usable workspace",
await gotoWorkspace(page, otherWorkspace.workspaceId);
await expect(draftTabChip(page)).toHaveCount(1);
});
test("dragging a file tab into a split returns the previous pane to the tab you came from", async ({
page,
withWorkspace,
e2eWorkerClient,
}) => {
const workspace = await withWorkspace({ prefix: "split-prev-tab-focus-" });
writeFileSync(path.join(workspace.repoPath, "notes.md"), "# Notes\nhello\n");
const agentA = await e2eWorkerClient.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Agent A",
});
const agentB = await e2eWorkerClient.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Agent B",
});
await gotoWorkspace(page, workspace.workspaceId);
await waitForWorkspaceTabsVisible(page);
const mainPane = page.getByTestId("workspace-pane-main");
await expect(mainPane.getByTestId(`workspace-tab-agent_${agentA.id}`)).toBeVisible({
timeout: 30_000,
});
await expect(mainPane.getByTestId(`workspace-tab-agent_${agentB.id}`)).toBeVisible({
timeout: 30_000,
});
const initialTabs = await mainPane
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-context-"])')
.evaluateAll((els) => els.map((el) => el.getAttribute("data-testid")));
const firstTab = mainPane.getByTestId(initialTabs[0]!);
const secondTab = mainPane.getByTestId(initialTabs[1]!);
// Open FILE while on B so B is the birth parent, then navigate A -> FILE before splitting.
await secondTab.click({ position: { x: 12, y: 13 } });
await expect(secondTab).toHaveAttribute("aria-selected", "true");
await openFilesPanel(page);
await page
.getByTestId("file-explorer-tree-scroll")
.getByText("notes.md", { exact: true })
.click();
const fileTab = mainPane
.locator('[data-testid^="workspace-tab-file_"]:not([data-testid^="workspace-tab-context-"])')
.first();
await expect(fileTab).toBeVisible({ timeout: 15_000 });
await firstTab.click({ position: { x: 12, y: 13 } });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
await fileTab.click({ position: { x: 12, y: 13 } });
await expect(fileTab).toHaveAttribute("aria-selected", "true");
const mainBox = await mainPane.boundingBox();
if (!mainBox) throw new Error("mainPane has no bounding box");
await dragChipTo(page, fileTab, {
x: mainBox.x + mainBox.width * 0.92,
y: mainBox.y + mainBox.height * 0.5,
});
await expect(
page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true }),
).toHaveCount(2, { timeout: 10_000 });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
await expect(secondTab).toHaveAttribute("aria-selected", "false");
});
@@ -4,7 +4,6 @@ import {
addConnectedHostAndReload,
chooseHostBadgeDisplay,
chooseHostColor,
chooseHostIcon,
expectHostAppearancePreview,
expectHostBadgeIconOnly,
expectHostBadgeName,
@@ -116,21 +115,12 @@ test("customizes a host badge and preserves its appearance after reload", async
expect(widths.content).toBeLessThanOrEqual(widths.client);
});
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
await test.step("preview a color and apply it to the sidebar badge", async () => {
await openHostAppearanceSettings(page, badge.serverId);
await chooseHostColor(page, "Teal");
await chooseHostIcon(page, "Laptop");
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
await leaveHostAppearanceSettings(page);
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
await page.getByTestId("sidebar-hosts-trigger").click();
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
await expect(hostRow).toBeVisible();
await expect(hostRow).toContainText("Direct");
await expect(hostRow).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/);
await expect(hostRow).not.toContainText(/agents?/i);
await page.keyboard.press("Escape");
});
await test.step("keep the icon-only preference through reload", async () => {
@@ -155,30 +145,3 @@ test("customizes a host badge and preserves its appearance after reload", async
});
});
});
base(
"activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter",
async ({ page }) => {
await gotoAppShell(page);
const trigger = page.getByTestId("sidebar-hosts-trigger");
await expect(trigger).toBeVisible();
// Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host.
const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" });
await trigger.click();
const addHostButton = page.getByRole("button", { name: "Add host", exact: true });
await expect(addHostButton).toBeVisible();
await addHostButton.focus();
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
await page.keyboard.press("Escape");
await expect(addConnectionDialog).toBeHidden();
// ArrowDown + Enter must also reach Add host from the host list.
await trigger.click();
await expect(addHostButton).toBeVisible();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
},
);
@@ -65,7 +65,8 @@ import {
openSettingsHostSection,
removeCurrentHostFromSettings,
openSidebarHostPicker,
sidebarHostRowButton,
sidebarHostSettingsButton,
expectStandaloneSidebarHostSettingsButton,
activateSidebarHostSettingsWithKeyboard,
bindCommandCenterToEnter,
} from "../support/helpers/settings";
@@ -191,16 +192,17 @@ test.describe("Settings sidebar scroll position", () => {
});
test.describe("Settings sidebar navigation", () => {
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
await openWorkspace(page, workspace);
await openSidebarHostPicker(page);
await sidebarHostRowButton(page).click();
await expectStandaloneSidebarHostSettingsButton(page);
await sidebarHostSettingsButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
});
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
await bindCommandCenterToEnter(page);
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
await openWorkspace(page, workspace);
@@ -564,7 +566,7 @@ test.describe("Settings — compact master-detail", () => {
await openWorkspace(page, workspace);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
await page.getByTestId("sidebar-hosts-trigger").click();
await sidebarHostRowButton(page).click();
await page.getByRole("button", { name: /Open .* settings/ }).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
+1 -10
View File
@@ -132,10 +132,7 @@ export async function waitForConnectedHost(
): Promise<void> {
await page.getByTestId("sidebar-hosts-trigger").click();
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
const escapedEndpoint = input.endpoint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Local daemons render "Local" without repeating localhost:<port>; remote hosts render the endpoint.
await expect(host).toContainText(new RegExp(`${escapedEndpoint}|Local`), { timeout: 30_000 });
await expect(host).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/, { timeout: 30_000 });
await expect(host).toContainText(input.endpoint, { timeout: 30_000 });
await page.keyboard.press("Escape");
await expect(host).not.toBeVisible();
}
@@ -198,12 +195,6 @@ export async function chooseHostColor(page: Page, colorName: string): Promise<vo
await expect(page.getByRole("button", { name: `Color, ${colorName}` })).toBeVisible();
}
export async function chooseHostIcon(page: Page, iconName: string): Promise<void> {
await page.getByTestId("host-appearance-icon").click();
await page.getByRole("menuitem", { name: iconName, exact: true }).click();
await expect(page.getByRole("button", { name: `Icon, ${iconName}` })).toBeVisible();
}
export async function chooseHostBadgeDisplay(
page: Page,
option: "Name" | "Icon only" | "Hidden",
+14 -4
View File
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
await page.getByRole("button", { name: "Hosts", exact: true }).click();
}
export function sidebarHostRowButton(page: Page) {
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
export function sidebarHostSettingsButton(page: Page) {
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
}
export async function bindCommandCenterToEnter(page: Page) {
@@ -32,10 +32,20 @@ export async function bindCommandCenterToEnter(page: Page) {
});
}
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
const gear = sidebarHostSettingsButton(page);
await expect(gear).toBeVisible();
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
true,
);
}
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
const host = sidebarHostRowButton(page);
await expect(host).toBeVisible();
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
await expect(host).toBeFocused();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Tab");
await expect(sidebarHostSettingsButton(page)).toBeFocused();
await page.keyboard.press("Enter");
}
+133 -301
View File
@@ -1,28 +1,11 @@
import {
useCallback,
useEffect,
useMemo,
useState,
type ReactElement,
type ReactNode,
} from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Check, Plus, Server } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
import { Pressable, View } from "react-native";
import { Plus, Server, Settings } from "lucide-react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { HostStatusDot } from "@/components/host-status-dot";
import { Combobox, type ComboboxProps } from "@/components/ui/combobox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { defaultHostAppearance, resolveHostIcon, type HostAppearance } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import {
getHostRuntimeStore,
useHostRuntimeConnectionStatus,
useHosts,
} from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime";
import { orderHostsLocalFirst } from "@/types/host-connection";
import {
ADD_HOST_OPTION_ID,
@@ -39,16 +22,7 @@ export {
};
const SEARCHABLE_THRESHOLD = 10;
const DEFAULT_DESKTOP_MIN_WIDTH = 328;
const LEADING_RAIL_SIZE = 16;
const HOST_ROW_ICON_SIZE = 14;
type RenderHostOption = NonNullable<ComboboxProps["renderOption"]>;
const ThemedCheck = withUnistyles(Check);
const ThemedPlus = withUnistyles(Plus);
const ThemedServer = withUnistyles(Server);
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
export interface HostPickerHost {
serverId: string;
label: string;
@@ -62,166 +36,122 @@ export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElem
);
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
// Socket/pipe transports have no host:port — their endpoint is a filesystem
// path, so they read as "Local". TCP and relay show the address being used.
function formatActiveConnectionLabel(connection: ActiveConnection): string {
if (connection.type === "directSocket" || connection.type === "directPipe") {
return "Local";
}
return formatConnectionEndpoint(connection.endpoint);
}
export interface HostPickerOptionProps {
serverId: string;
label: string;
appearance: HostAppearance;
showActiveConnection: boolean;
selected?: boolean;
active: boolean;
onPress: () => void;
onOpenHostSettings?: (serverId: string) => void;
testID?: string;
}
export function HostPickerOption({
serverId,
label,
appearance,
showActiveConnection,
selected,
active,
onPress,
onOpenHostSettings,
testID,
}: HostPickerOptionProps): ReactElement {
const status = useHostRuntimeConnectionStatus(serverId);
const detectedMachineKind = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const isOffline = status === "offline" || status === "error";
const { theme } = useUnistyles();
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
const connectionLabel =
showActiveConnection && activeConnection
? formatActiveConnectionLabel(activeConnection)
: undefined;
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
const handleSettingsPress = useCallback(() => {
onOpenHostSettings?.(serverId);
}, [onOpenHostSettings, serverId]);
const trailingAction = useMemo(() => {
if (!onOpenHostSettings) return undefined;
return (
<Pressable
onPress={handleSettingsPress}
style={styles.settingsAction}
accessibilityRole="button"
accessibilityLabel={`Open ${label} settings`}
>
<Settings size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
);
}, [
handleSettingsPress,
label,
onOpenHostSettings,
theme.colors.foregroundMuted,
theme.iconSize.sm,
]);
return (
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.hostRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<HostStatusDot serverId={serverId} />
</View>
<View style={styles.hostBody}>
<View style={styles.hostHeaderRow}>
<HostIconGlyph
icon={resolvedIcon}
color={appearance.color}
size={HOST_ROW_ICON_SIZE}
style={styles.hostGlyph}
/>
<Text style={[styles.hostName, isOffline && styles.hostNameMuted]} numberOfLines={1}>
{label}
</Text>
</View>
<HostConnectionLine serverId={serverId} />
</View>
<View style={styles.hostTrailing}>
<HostLatencyLabel serverId={serverId} />
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</View>
</PressHighlight>
</View>
<ComboboxItem
label={label}
description={connectionLabel}
leadingSlot={leadingSlot}
trailingAction={trailingAction}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
);
}
function AllHostsOption({
const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = {
add: "Add host",
all: "All hosts",
enableBuiltInDaemon: "Enable built-in daemon",
};
function SystemHostPickerOption({
active,
selected,
onPress,
kind,
testID,
}: {
active: boolean;
selected?: boolean;
onPress: () => void;
kind: "add" | "all" | "enableBuiltInDaemon";
testID?: string;
}): ReactElement {
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = t("sidebar.display.hostFilter.all");
return (
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</PressHighlight>
</View>
const { theme } = useUnistyles();
const Icon = kind === "add" ? Plus : Server;
const label = SYSTEM_HOST_PICKER_OPTION_LABELS[kind];
const leadingSlot = useMemo(
() => <Icon size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />,
[Icon, theme.colors.foregroundMuted, theme.iconSize.sm],
);
}
function ActionOptionRow({
kind,
active,
showDivider,
onPress,
testID,
}: {
kind: "add" | "enableBuiltInDaemon";
active: boolean;
showDivider: boolean;
onPress: () => void;
testID?: string;
}): ReactElement {
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = kind === "add" ? t("settings.addHost") : t("settings.enableBuiltInDaemon");
return (
<View>
{showDivider ? <View style={styles.actionSectionDivider} /> : null}
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
{kind === "add" ? (
<ThemedPlus size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
) : (
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
)}
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
</PressHighlight>
</View>
</View>
<ComboboxItem
label={label}
leadingSlot={leadingSlot}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
);
}
@@ -238,6 +168,7 @@ export interface HostPickerProps {
includeEnableBuiltInDaemon?: boolean;
onEnableBuiltInDaemon?: () => void;
showActiveConnection?: boolean;
onOpenHostSettings?: (serverId: string) => void;
searchable?: boolean;
title?: string;
desktopPlacement?: ComboboxProps["desktopPlacement"];
@@ -259,85 +190,74 @@ export function HostPicker({
onAddHost,
includeEnableBuiltInDaemon,
onEnableBuiltInDaemon,
showActiveConnection,
onOpenHostSettings,
searchable,
title,
desktopPlacement = "bottom-start",
desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH,
desktopMinWidth,
addHostTestID,
hostOptionTestID,
children,
}: HostPickerProps): ReactElement {
const { t } = useTranslation();
const localServerId = useLocalDaemonServerId();
const allHostProfiles = useHosts();
const orderedHosts = useMemo(
() => orderHostsLocalFirst(hosts, localServerId),
[hosts, localServerId],
);
const appearanceByServerId = useMemo(() => {
const map = new Map<string, HostAppearance>();
for (const profile of allHostProfiles) {
map.set(profile.serverId, profile.appearance);
}
return map;
}, [allHostProfiles]);
useEffect(() => {
if (!open) return;
getHostRuntimeStore().refreshActiveLatencies(orderedHosts.map((host) => host.serverId));
}, [open, orderedHosts]);
const options = useMemo(() => {
const hostOptions = orderedHosts.map((host) => ({ id: host.serverId, label: host.label }));
if (includeAllHost) {
hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: t("sidebar.display.hostFilter.all") });
}
if (includeAddHost) {
hostOptions.push({ id: ADD_HOST_OPTION_ID, label: t("settings.addHost") });
}
if (includeEnableBuiltInDaemon) {
if (includeAllHost) hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: "All hosts" });
if (includeAddHost) hostOptions.push({ id: ADD_HOST_OPTION_ID, label: "Add host" });
if (includeEnableBuiltInDaemon)
hostOptions.push({
id: ENABLE_BUILT_IN_DAEMON_OPTION_ID,
label: t("settings.enableBuiltInDaemon"),
label: "Enable built-in daemon",
});
}
return hostOptions;
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon, t]);
let firstActionOptionId: string | null = null;
if (includeAddHost) {
firstActionOptionId = ADD_HOST_OPTION_ID;
} else if (includeEnableBuiltInDaemon) {
firstActionOptionId = ENABLE_BUILT_IN_DAEMON_OPTION_ID;
}
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]);
const isSearchable = searchable === true && orderedHosts.length > SEARCHABLE_THRESHOLD;
const resolvedTitle = title ?? t("sidebar.actions.hosts");
const handleSelect = useCallback(
(id: string) => {
if (id === ADD_HOST_OPTION_ID) {
onOpenChange(false);
onAddHost?.();
return;
}
if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onOpenChange(false);
} else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onEnableBuiltInDaemon?.();
return;
} else {
onSelect(id);
}
onSelect(id);
onOpenChange(false);
},
[onAddHost, onEnableBuiltInDaemon, onOpenChange, onSelect],
);
const handleOpenHostSettings = useCallback(
(serverId: string) => {
onOpenHostSettings?.(serverId);
onOpenChange(false);
},
[onOpenHostSettings, onOpenChange],
);
const renderOption = useCallback<RenderHostOption>(
({ option, selected, active, onPress }) => {
if (option.id === ADD_HOST_OPTION_ID) {
return (
<SystemHostPickerOption
kind="add"
active={active}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ALL_HOSTS_OPTION_ID) {
return (
<AllHostsOption
<SystemHostPickerOption
kind="all"
active={active}
selected={selected}
onPress={onPress}
@@ -345,48 +265,30 @@ export function HostPicker({
/>
);
}
if (option.id === ADD_HOST_OPTION_ID) {
return (
<ActionOptionRow
kind="add"
active={active}
showDivider={firstActionOptionId === ADD_HOST_OPTION_ID && orderedHosts.length > 0}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
return (
<ActionOptionRow
kind="enableBuiltInDaemon"
active={active}
showDivider={
firstActionOptionId === ENABLE_BUILT_IN_DAEMON_OPTION_ID && orderedHosts.length > 0
}
onPress={onPress}
/>
<SystemHostPickerOption kind="enableBuiltInDaemon" active={active} onPress={onPress} />
);
}
const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance();
return (
<HostPickerOption
serverId={option.id}
label={option.label}
appearance={appearance}
showActiveConnection={showActiveConnection === true}
selected={selected}
active={active}
onPress={onPress}
onOpenHostSettings={onOpenHostSettings ? handleOpenHostSettings : undefined}
testID={hostOptionTestID?.(option.id)}
/>
);
},
[
addHostTestID,
appearanceByServerId,
firstActionOptionId,
hostOptionTestID,
orderedHosts.length,
onOpenHostSettings,
showActiveConnection,
handleOpenHostSettings,
],
);
@@ -399,8 +301,8 @@ export function HostPicker({
onSelect={handleSelect}
renderOption={renderOption}
searchable={isSearchable}
searchPlaceholder={t("sidebar.host.searchPlaceholder")}
title={resolvedTitle}
searchPlaceholder="Search hosts"
title={title ?? "Host"}
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
@@ -412,86 +314,16 @@ export function HostPicker({
}
const styles = StyleSheet.create((theme) => ({
settingsAction: {
flex: 1,
justifyContent: "center",
paddingLeft: theme.spacing[1],
paddingRight: theme.spacing[3],
},
statusDotSlot: {
width: theme.iconSize.sm,
height: theme.iconSize.sm,
alignItems: "center",
justifyContent: "center",
},
rowEnvelope: {
position: "relative",
},
// Shared leading rail: the status dot on host rows and the '+' / All hosts glyph share one
// centered 16px column aligned to the first line's 18px line-height.
leadingRailSlot: {
width: LEADING_RAIL_SIZE,
height: 18,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
hostRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
rowHighlighted: {
backgroundColor: theme.colors.surface1,
},
hostBody: {
flex: 1,
minWidth: 0,
gap: 2,
},
hostHeaderRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
hostGlyph: {
flexShrink: 0,
},
hostName: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
hostNameMuted: {
color: theme.colors.foregroundMuted,
},
hostTrailing: {
flexDirection: "row",
alignItems: "center",
height: 18,
gap: theme.spacing[2],
flexShrink: 0,
},
actionSectionDivider: {
height: theme.borderWidth[1],
backgroundColor: theme.colors.border,
marginVertical: theme.spacing[1],
},
actionRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
actionLabel: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
}));
@@ -1,32 +0,0 @@
import Svg, { Circle } from "react-native-svg";
const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) =>
[3, 12, 21].map((cx, column) => ({
cx,
cy,
// The Tailscale mark is a 3x3 dot grid with a solid T (middle row + bottom center).
solid: row === 1 || (row === 2 && column === 1),
})),
);
export interface TailscaleIconProps {
size?: number;
color?: string;
}
export function TailscaleIcon({ size = 12, color = "currentColor" }: TailscaleIconProps) {
return (
<Svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
{TAILSCALE_DOTS.map((dot) => (
<Circle
key={`${dot.cx}:${dot.cy}`}
cx={dot.cx}
cy={dot.cy}
r={3}
fill={color}
opacity={dot.solid ? 1 : 0.3}
/>
))}
</Svg>
);
}
+2 -2
View File
@@ -388,10 +388,10 @@ function SidebarHostPicker({
includeAddHost
onAddHost={onAddHost}
showActiveConnection
onOpenHostSettings={onOpenHostSettings}
searchable
title={label}
desktopPlacement="top-start"
desktopMinWidth={328}
desktopMinWidth={240}
addHostTestID="sidebar-host-add"
hostOptionTestID={sidebarHostOptionTestID}
>
+14 -60
View File
@@ -73,9 +73,6 @@ export { buildDesktopFrameStyle } from "./combobox-frame-style";
const IS_WEB = isWeb;
const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true };
const FOOTER_DATASET = { comboboxFooter: true };
const FOCUSED_COMBOBOX_ACTION_SELECTOR =
'[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]';
export type ComboboxOption = ComboboxOptionModel;
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
@@ -405,7 +402,6 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme
type RenderOptionFn = NonNullable<ComboboxProps["renderOption"]>;
interface OptionRowProps {
index: number;
option: ComboboxOption;
selected: boolean;
active: boolean;
@@ -413,27 +409,20 @@ interface OptionRowProps {
renderOption: RenderOptionFn | undefined;
}
function OptionRow({ index, option, selected, active, onSelect, renderOption }: OptionRowProps) {
function OptionRow({ option, selected, active, onSelect, renderOption }: OptionRowProps) {
const handlePress = useCallback(() => onSelect(option.id), [onSelect, option.id]);
const optionDataset = useMemo(() => ({ comboboxOptionIndex: String(index) }), [index]);
if (renderOption) {
return (
<View dataSet={optionDataset}>
{renderOption({ option, selected, active, onPress: handlePress })}
</View>
);
return <View>{renderOption({ option, selected, active, onPress: handlePress })}</View>;
}
return (
<View dataSet={optionDataset}>
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
</View>
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
);
}
@@ -462,7 +451,6 @@ function OptionsList({
{options.map((opt, index) => (
<OptionRow
key={opt.id}
index={index}
option={opt}
selected={opt.id === value}
active={index === activeIndex}
@@ -964,9 +952,8 @@ function dispatchDesktopKey(
return true;
}
if (key === "Enter") {
// Consume the shortcut but keep the browser's default button activation when the user moved
// keyboard focus onto a trailing action or footer button inside the combobox.
if (isWeb && document.activeElement?.matches(FOCUSED_COMBOBOX_ACTION_SELECTOR)) {
// Consume the shortcut but keep the browser's default button activation.
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
return true;
}
if (input.orderedVisibleOptions.length === 0) return false;
@@ -1140,12 +1127,7 @@ function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children
[safeAreaBottom],
);
const footerView = useMemo(
() =>
footer ? (
<View style={footerStyle} dataSet={FOOTER_DATASET}>
{footer}
</View>
) : undefined,
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
[footer, footerStyle],
);
return (
@@ -1359,11 +1341,7 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
renderOption={props.renderOption}
/>
)}
{props.footer ? (
<View style={styles.footer} dataSet={FOOTER_DATASET}>
{props.footer}
</View>
) : null}
{props.footer ? <View style={styles.footer}>{props.footer}</View> : null}
</FloatingSurface>
</View>
</OverlayLayerProvider>
@@ -1619,30 +1597,6 @@ export function Combobox({
setActiveIndex,
);
// Keep activeIndex aligned when a keyboard user Tabs onto a specific option button on web.
useEffect(() => {
if (!IS_WEB || !isOpen || isMobile) return;
const handleFocusIn = (event: FocusEvent) => {
const target = event.target;
if (!(target instanceof Element)) return;
const optionEl = target.closest("[data-combobox-option-index]");
if (!optionEl) return;
const nextIndex = Number.parseInt(
optionEl.getAttribute("data-combobox-option-index") ?? "",
10,
);
if (
Number.isInteger(nextIndex) &&
nextIndex >= 0 &&
nextIndex < orderedVisibleOptions.length
) {
setActiveIndex(nextIndex);
}
};
document.addEventListener("focusin", handleFocusIn);
return () => document.removeEventListener("focusin", handleFocusIn);
}, [isMobile, isOpen, orderedVisibleOptions.length]);
const handleSelect = useCallback(
(id: string) => {
onSelect(id);
+7 -93
View File
@@ -4,7 +4,6 @@ import {
defaultHostAppearance,
normalizeStoredHostAppearance,
resolveHostBadgeDisplay,
resolveHostIcon,
selectHostBadges,
} from "@/hosts/appearance";
@@ -17,7 +16,7 @@ function host(
}
describe("normalizeStoredHostAppearance", () => {
it("defaults without writing an icon field so untouched records stay downgrade-safe", () => {
it("defaults when the stored registry predates the field or holds junk", () => {
const expected = { color: "none", badgeDisplay: null };
expect(normalizeStoredHostAppearance(undefined)).toEqual(expected);
expect(normalizeStoredHostAppearance(null)).toEqual(expected);
@@ -25,82 +24,16 @@ describe("normalizeStoredHostAppearance", () => {
expect(normalizeStoredHostAppearance({})).toEqual(expected);
expect(normalizeStoredHostAppearance({ color: "chartreuse" })).toEqual(expected);
expect(normalizeStoredHostAppearance({ badgeDisplay: "loud" })).toEqual(expected);
expect("icon" in defaultHostAppearance()).toBe(false);
});
it("preserves an unknown stored icon on disk while falling back at render time", () => {
const normalized = normalizeStoredHostAppearance({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(normalized).toEqual({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(resolveHostIcon({ appearance: normalized })).toBe("server");
expect(resolveHostIcon({ appearance: normalized, detectedMachineKind: "laptop" })).toBe(
"laptop",
);
});
it("keeps icon absent on stored entries that predate host icons", () => {
const normalized = normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" });
expect(normalized).toEqual({
color: "teal",
badgeDisplay: "icon",
});
expect("icon" in normalized).toBe(false);
});
it("round-trips a value the user actually chose", () => {
expect(
normalizeStoredHostAppearance({ color: "teal", icon: "laptop", badgeDisplay: "icon" }),
).toEqual({
expect(normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" })).toEqual({
color: "teal",
icon: "laptop",
badgeDisplay: "icon",
});
});
});
describe("resolveHostIcon", () => {
it("prefers an explicit user icon over daemon auto-detection", () => {
expect(
resolveHostIcon({
appearance: { color: "none", icon: "workstation", badgeDisplay: null },
detectedMachineKind: "laptop",
}),
).toBe("workstation");
});
it("uses the daemon-detected machine kind while the user icon is auto (null)", () => {
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "laptop",
}),
).toBe("laptop");
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "container",
}),
).toBe("container");
});
it("falls back to server when the detected machine kind is absent or unknown", () => {
expect(resolveHostIcon({ appearance: defaultHostAppearance() })).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: null }),
).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: "future-kind" }),
).toBe("server");
});
});
describe("resolveHostBadgeDisplay", () => {
it("hides the badge for the local host until the user chooses", () => {
expect(
@@ -117,13 +50,13 @@ describe("resolveHostBadgeDisplay", () => {
it("prefers an explicit choice over either default", () => {
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
appearance: { color: "none", badgeDisplay: "icon" },
isLocalHost: true,
}),
).toBe("icon");
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", icon: "server", badgeDisplay: "hidden" },
appearance: { color: "none", badgeDisplay: "hidden" },
isLocalHost: false,
}),
).toBe("hidden");
@@ -139,7 +72,7 @@ describe("resolveHostBadgeDisplay", () => {
).toBeNull();
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
appearance: { color: "none", badgeDisplay: "icon" },
isLocalHost: false,
localHostResolutionPending: true,
}),
@@ -160,7 +93,7 @@ describe("selectHostBadges", () => {
it("omits a host the user hid and keeps its sibling", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha", { color: "none", icon: "server", badgeDisplay: "hidden" }),
host("alpha", "Alpha", { color: "none", badgeDisplay: "hidden" }),
host("beta", "Beta"),
],
localServerId: null,
@@ -171,14 +104,13 @@ describe("selectHostBadges", () => {
serverId: "beta",
label: "Beta",
color: "none",
icon: "server",
showLabel: true,
});
});
it("keeps an icon-only host in the map without its label", () => {
const badges = selectHostBadges({
hosts: [host("alpha", "Alpha", { color: "teal", icon: "mini", badgeDisplay: "icon" })],
hosts: [host("alpha", "Alpha", { color: "teal", badgeDisplay: "icon" })],
localServerId: null,
enabled: true,
});
@@ -186,7 +118,6 @@ describe("selectHostBadges", () => {
serverId: "alpha",
label: "Alpha",
color: "teal",
icon: "mini",
showLabel: false,
});
});
@@ -219,21 +150,4 @@ describe("selectHostBadges", () => {
});
expect(badges.size).toBe(0);
});
it("applies daemon-detected machine kind for auto icons while respecting explicit overrides", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha"),
host("beta", "Beta", { color: "sky", icon: "workstation", badgeDisplay: "name" }),
],
localServerId: null,
detectedMachineKindByServerId: new Map([
["alpha", "laptop"],
["beta", "cloud"],
]),
enabled: true,
});
expect(badges.get("alpha")?.icon).toBe("laptop");
expect(badges.get("beta")?.icon).toBe("workstation");
});
});
+4 -65
View File
@@ -6,69 +6,25 @@ export type HostColor = "none" | IdentityColorName;
export const HOST_COLORS: readonly HostColor[] = ["none", ...IDENTITY_COLOR_NAMES];
export const HOST_ICONS = [
"server",
"laptop",
"desktop",
"mini",
"workstation",
"cloud",
"container",
"board",
"terminal",
] as const;
export type HostIcon = (typeof HOST_ICONS)[number];
export const DEFAULT_HOST_ICON: HostIcon = "server";
const HOST_ICON_SET = new Set<string>(HOST_ICONS);
export function normalizeDetectedHostIcon(value: string | null | undefined): HostIcon | null {
const trimmed = value?.trim();
if (trimmed && HOST_ICON_SET.has(trimmed)) {
return trimmed as HostIcon;
}
return null;
}
export type HostBadgeDisplay = "name" | "icon" | "hidden";
export const HOST_BADGE_DISPLAYS: readonly HostBadgeDisplay[] = ["name", "icon", "hidden"];
/**
* Per-device host presentation.
* - `icon` is omitted while untouched ("Auto") so existing records stay byte-for-byte compatible
* with older builds whose stored appearance schema is strict. An unknown icon string written by
* a newer build is preserved on disk and falls back at render time via `resolveHostIcon`.
* - `badgeDisplay` is null while untouched so runtime defaults apply (hidden for local / name for
* remote) without baking runtime facts at parse time.
* Per-device host presentation. `badgeDisplay` is null while the user has not chosen,
* because the default differs by host (local hides, remote shows) and local-ness is only
* knowable from a desktop-only async query — never at parse time.
*/
export interface HostAppearance {
color: HostColor;
icon?: string;
badgeDisplay: HostBadgeDisplay | null;
}
const StoredHostAppearanceSchema = z.strictObject({
export const HostAppearanceSchema: z.ZodType<HostAppearance> = z.strictObject({
color: z.enum(["none", ...IDENTITY_COLOR_NAMES]),
// Optional loose string on disk so untouched hosts stay readable after a downgrade and an icon
// added by a newer build survives read/write instead of being dropped or overwritten.
icon: z.string().nullable().optional(),
badgeDisplay: z.enum(["name", "icon", "hidden"]).nullable(),
});
export const HostAppearanceSchema = StoredHostAppearanceSchema.transform(
(value): HostAppearance => {
const icon = value.icon?.trim();
return {
color: value.color,
...(icon ? { icon } : {}),
badgeDisplay: value.badgeDisplay,
};
},
);
export function defaultHostAppearance(): HostAppearance {
return { color: "none", badgeDisplay: null };
}
@@ -78,17 +34,6 @@ export function normalizeStoredHostAppearance(value: unknown): HostAppearance {
return result.success ? result.data : defaultHostAppearance();
}
export function resolveHostIcon(input: {
appearance: HostAppearance;
detectedMachineKind?: string | null;
}): HostIcon {
return (
normalizeDetectedHostIcon(input.appearance.icon) ??
normalizeDetectedHostIcon(input.detectedMachineKind) ??
DEFAULT_HOST_ICON
);
}
export function resolveHostBadgeDisplay(input: {
appearance: HostAppearance;
isLocalHost: boolean;
@@ -107,7 +52,6 @@ export interface HostBadgeModel {
serverId: string;
label: string;
color: HostColor;
icon: HostIcon;
showLabel: boolean;
}
@@ -122,7 +66,6 @@ export function selectHostBadges(input: {
hosts: readonly HostAppearanceSource[];
localServerId: string | null;
localHostResolutionPending?: boolean;
detectedMachineKindByServerId?: ReadonlyMap<string, string | null>;
enabled: boolean;
}): ReadonlyMap<string, HostBadgeModel> {
const badges = new Map<string, HostBadgeModel>();
@@ -142,10 +85,6 @@ export function selectHostBadges(input: {
serverId: host.serverId,
label: host.label.trim() || host.serverId,
color: host.appearance.color,
icon: resolveHostIcon({
appearance: host.appearance,
detectedMachineKind: input.detectedMachineKindByServerId?.get(host.serverId) ?? null,
}),
showLabel: display === "name",
});
}
@@ -1,134 +0,0 @@
import { describe, expect, it } from "vitest";
import {
describeActiveConnection,
describeHostConnection,
formatConnectionEndpoint,
isTailscaleEndpoint,
} from "./connection-display";
describe("isTailscaleEndpoint", () => {
it("recognizes MagicDNS .ts.net hostnames with or without ports", () => {
expect(isTailscaleEndpoint("mac-mini.tail123.ts.net:6767")).toBe(true);
expect(isTailscaleEndpoint("Mac-Mini.Tail123.TS.NET:443")).toBe(true);
expect(isTailscaleEndpoint("devbox.tailnet.ts.net")).toBe(true);
expect(isTailscaleEndpoint(".ts.net")).toBe(false);
});
it("recognizes Tailscale IPv4 CGNAT (100.64.0.0/10) and IPv6 ULA addresses", () => {
expect(isTailscaleEndpoint("100.64.0.1:6767")).toBe(true);
expect(isTailscaleEndpoint("100.100.42.9:6767")).toBe(true);
expect(isTailscaleEndpoint("100.127.255.254:6767")).toBe(true);
expect(isTailscaleEndpoint("100.63.255.255:6767")).toBe(false);
expect(isTailscaleEndpoint("100.128.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("[fd7a:115c:a1e0::1]:6767")).toBe(true);
});
it("does not misclassify LAN, localhost, or ordinary domains", () => {
expect(isTailscaleEndpoint("localhost:6767")).toBe(false);
expect(isTailscaleEndpoint("127.0.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("192.168.1.25:6767")).toBe(false);
expect(isTailscaleEndpoint("relay.paseo.sh:443")).toBe(false);
expect(isTailscaleEndpoint("not-ts.net.example.com:6767")).toBe(false);
});
});
describe("describeActiveConnection", () => {
it("describes local socket and pipe connections without exposing paths", () => {
expect(
describeActiveConnection({
type: "directSocket",
endpoint: "/tmp/paseo.sock",
display: "socket",
}),
).toEqual({ kind: "local" });
expect(
describeActiveConnection({
type: "directPipe",
endpoint: "\\\\.\\pipe\\paseo",
display: "pipe",
}),
).toEqual({ kind: "local" });
});
it("describes loopback TCP on the local host as local, and remote loopback as direct", () => {
const loopback = {
type: "directTcp",
endpoint: "localhost:6767",
display: "localhost:6767",
} as const;
expect(describeActiveConnection(loopback, { isLocalHost: true })).toEqual({ kind: "local" });
expect(describeActiveConnection(loopback, { isLocalHost: false })).toEqual({
kind: "direct",
endpoint: "localhost:6767",
});
});
it("strips standard web ports on relay, tailscale, and direct connections", () => {
expect(
describeActiveConnection({ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" }),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
display: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "devbox.example.com:443",
display: "devbox.example.com:443",
}),
).toEqual({ kind: "direct", endpoint: "devbox.example.com" });
});
it("preserves SSH and routed targets", () => {
expect(
describeActiveConnection({
type: "remoteSsh",
endpoint: "mo@workstation",
display: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
expect(
describeActiveConnection({
type: "routed",
endpoint: "srv_origin",
display: "via srv_origin",
}),
).toEqual({ kind: "routed", endpoint: "srv_origin" });
});
it("strips default HTTP/HTTPS ports only", () => {
expect(formatConnectionEndpoint("relay.paseo.sh:443")).toBe("relay.paseo.sh");
expect(formatConnectionEndpoint("example.com:80")).toBe("example.com");
expect(formatConnectionEndpoint("127.0.0.1:6767")).toBe("127.0.0.1:6767");
});
it("describes configured host connections before an active connection is online", () => {
expect(
describeHostConnection({
id: "direct:mac-mini.tail123.ts.net:6767",
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeHostConnection({
id: "relay:wss:relay.paseo.sh:443",
type: "relay",
relayEndpoint: "relay.paseo.sh:443",
useTls: true,
daemonPublicKeyB64: "key",
}),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeHostConnection({
id: "ssh:mo%40workstation::",
type: "remoteSsh",
host: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
});
});
@@ -1,120 +0,0 @@
import type { ActiveConnection } from "@/runtime/host-runtime";
import type { HostConnection } from "@/types/host-connection";
export type HostConnectionKind = "local" | "relay" | "tailscale" | "ssh" | "direct" | "routed";
export interface HostConnectionDisplay {
kind: HostConnectionKind;
/** Address shown beside the connection kind. Omitted for local transports. */
endpoint?: string;
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
export function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
function extractEndpointHost(endpoint: string): string {
const trimmed = endpoint.trim().toLowerCase();
if (!trimmed) return "";
const withoutScheme = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
const authority = withoutScheme.split("/")[0] ?? "";
const hostPort = authority.includes("@")
? authority.slice(authority.lastIndexOf("@") + 1)
: authority;
if (hostPort.startsWith("[")) {
const closeBracket = hostPort.indexOf("]");
return closeBracket > 1 ? hostPort.slice(1, closeBracket) : hostPort;
}
const firstColon = hostPort.indexOf(":");
const lastColon = hostPort.lastIndexOf(":");
if (firstColon !== -1 && firstColon === lastColon) {
return hostPort.slice(0, firstColon);
}
return hostPort;
}
function isTailscaleIpv4(host: string): boolean {
const parts = host.split(".");
if (parts.length !== 4) return false;
const octets = parts.map((part) => (/^\d+$/.test(part) ? Number(part) : Number.NaN));
if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
return false;
}
// Tailscale assigns addresses from the RFC 6598 CGNAT range 100.64.0.0/10.
return octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127;
}
function isTailscaleIpv6(host: string): boolean {
return host.startsWith("fd7a:115c:a1e0:");
}
export function isTailscaleEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
if (!host) return false;
if (host.endsWith(".ts.net") && host.length > ".ts.net".length) {
return true;
}
return isTailscaleIpv4(host) || isTailscaleIpv6(host);
}
export function isLoopbackEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
return host === "localhost" || host === "127.0.0.1" || host === "::1";
}
export function describeActiveConnection(
connection: ActiveConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.endpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.endpoint };
case "routed":
return { kind: "routed", endpoint: connection.endpoint };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
export function describeHostConnection(
connection: HostConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.relayEndpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.host };
case "routed":
return { kind: "routed", endpoint: connection.originServerId };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
+29 -8
View File
@@ -1,8 +1,9 @@
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Server } from "lucide-react-native";
import { HOST_COLORS, type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
/**
* The glyph size the badge draws at. Rows that place the badge alongside their own glyphs
@@ -10,9 +11,30 @@ import { identityForeground } from "@/styles/identity-colors";
*/
export const HOST_BADGE_ICON_SIZE = 12;
const ThemedServer = withUnistyles(Server);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable mapping per host color for the life of the module — a fresh `uniProps` identity
// on every render makes withUnistyles re-subscribe each pass. The scheme is read inside the
// mapping rather than baked in, so a theme change repaints the glyph without a React render.
//
// Glyph and label share one color, so a badge reads as one object rather than a colored icon
// with an unrelated grey word beside it.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
/**
* Which machine something lives on, drawn the same way everywhere it appears: the host's device
* glyph and, when the host is configured to show one, its name — both in the host's identity color.
* Which machine something lives on, drawn the same way everywhere it appears: a server glyph
* and, when the host is configured to show one, its name — both in the host's identity color.
*
* A hostname is the least interesting thing on any line that carries it and the only one whose
* length nobody chose, so the badge yields space before its neighbours rather than alongside
@@ -25,11 +47,10 @@ export function HostBadge({ badge }: { badge: HostBadgeModel }) {
testID={`host-badge-${badge.serverId}`}
accessibilityLabel={badge.label}
>
<HostIconGlyph
icon={badge.icon}
color={badge.color}
<ThemedServer
size={HOST_BADGE_ICON_SIZE}
style={styles.icon}
uniProps={HOST_ICON_MAPPINGS[badge.color]}
/>
{badge.showLabel ? (
<Text style={[styles.label, labelColorStyle(badge.color)]} numberOfLines={1}>
+27 -66
View File
@@ -7,16 +7,14 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { Server } from "lucide-react-native";
import { create } from "zustand";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { HostStatusDot } from "@/components/host-status-dot";
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
import { isWeb } from "@/constants/platform";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { resolveHostIcon } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root";
import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { useHosts } from "@/runtime/host-runtime";
import { orderHostsLocalFirst, type HostProfile } from "@/types/host-connection";
type HostFilter = (host: HostProfile) => boolean;
@@ -103,52 +101,36 @@ function HostChooserRow({
active: boolean;
onChooseHost: (serverId: string) => void;
}) {
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const { theme } = useUnistyles();
const handlePress = useCallback(() => onChooseHost(host.serverId), [host.serverId, onChooseHost]);
const rowStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [
({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.row,
(active || hovered || pressed) && styles.rowActive,
],
[active, hovered],
[active],
);
return (
<View onPointerEnter={handlePointerEnter} onPointerLeave={handlePointerLeave}>
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<View style={styles.rowHeader}>
<HostIconGlyph
icon={resolvedIcon}
color={host.appearance.color}
size={14}
style={styles.rowGlyph}
/>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
</View>
<HostConnectionLine serverId={host.serverId} />
</View>
<View style={styles.rowTrailing}>
<HostLatencyLabel serverId={host.serverId} />
</View>
</Pressable>
</View>
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDotSlot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
<Text style={styles.rowSubtitle} numberOfLines={1}>
{host.serverId}
</Text>
</View>
<Server size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
);
}
@@ -179,7 +161,6 @@ export function HostChooserModal() {
useEffect(() => {
if (!request) return;
getHostRuntimeStore().refreshActiveLatencies(request.serverIds);
inputRef.current?.replaceText("");
setQuery("");
setActiveIndex(0);
@@ -347,7 +328,7 @@ const styles = StyleSheet.create((theme) => ({
},
row: {
flexDirection: "row",
alignItems: "flex-start",
alignItems: "center",
gap: theme.spacing[3],
minHeight: 56,
paddingHorizontal: theme.spacing[4],
@@ -356,39 +337,19 @@ const styles = StyleSheet.create((theme) => ({
rowActive: {
backgroundColor: theme.colors.surface1,
},
rowTrailing: {
flexDirection: "row",
alignItems: "center",
height: 20,
flexShrink: 0,
},
rowIconSlot: {
width: 16,
height: 20,
width: 18,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
rowText: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
rowHeader: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
rowGlyph: {
flexShrink: 0,
},
rowTitle: {
flex: 1,
minWidth: 0,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
lineHeight: 20,
},
rowSubtitle: {
color: theme.colors.foregroundMuted,
@@ -1,77 +0,0 @@
import type { ReactElement } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import {
Cloud,
Computer,
Container,
Cpu,
Laptop,
Monitor,
PcCase,
Server,
Terminal,
} from "lucide-react-native";
import { withUnistyles } from "react-native-unistyles";
import { DEFAULT_HOST_ICON, HOST_COLORS, type HostColor, type HostIcon } from "@/hosts/appearance";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
const ThemedServer = withUnistyles(Server);
const ThemedLaptop = withUnistyles(Laptop);
const ThemedMonitor = withUnistyles(Monitor);
const ThemedComputer = withUnistyles(Computer);
const ThemedPcCase = withUnistyles(PcCase);
const ThemedCloud = withUnistyles(Cloud);
const ThemedContainer = withUnistyles(Container);
const ThemedCpu = withUnistyles(Cpu);
const ThemedTerminal = withUnistyles(Terminal);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable uniProps mapping per host color for the life of the module — a fresh identity on
// every render makes withUnistyles re-subscribe each pass. Reading `theme.colorScheme` inside the
// mapping keeps theme switches off React's render path.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
export function HostIconGlyph({
icon = DEFAULT_HOST_ICON,
color = "none",
size = 16,
style,
}: {
icon?: HostIcon;
color?: HostColor;
size?: number;
style?: StyleProp<ViewStyle>;
}): ReactElement {
const uniProps = HOST_ICON_MAPPINGS[color];
switch (icon) {
case "laptop":
return <ThemedLaptop size={size} style={style} uniProps={uniProps} />;
case "desktop":
return <ThemedMonitor size={size} style={style} uniProps={uniProps} />;
case "mini":
return <ThemedComputer size={size} style={style} uniProps={uniProps} />;
case "workstation":
return <ThemedPcCase size={size} style={style} uniProps={uniProps} />;
case "cloud":
return <ThemedCloud size={size} style={style} uniProps={uniProps} />;
case "container":
return <ThemedContainer size={size} style={style} uniProps={uniProps} />;
case "board":
return <ThemedCpu size={size} style={style} uniProps={uniProps} />;
case "terminal":
return <ThemedTerminal size={size} style={style} uniProps={uniProps} />;
case "server":
return <ThemedServer size={size} style={style} uniProps={uniProps} />;
}
}
-215
View File
@@ -1,215 +0,0 @@
import { useMemo, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Globe, Monitor, Network, Terminal, Waypoints } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { TailscaleIcon } from "@/components/icons/tailscale-icon";
import {
describeActiveConnection,
describeHostConnection,
type HostConnectionKind,
} from "@/hosts/connection-display";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import type { HostProfile } from "@/types/host-connection";
import { formatLatency } from "@/utils/latency";
export { HostIconGlyph };
const CONNECTION_GLYPH_SIZE = 11;
const ThemedMonitor = withUnistyles(Monitor);
const ThemedTerminal = withUnistyles(Terminal);
const ThemedGlobe = withUnistyles(Globe);
const ThemedNetwork = withUnistyles(Network);
const ThemedWaypoints = withUnistyles(Waypoints);
const ThemedTailscale = withUnistyles(TailscaleIcon);
const extraMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundExtraMuted });
function ConnectionKindGlyph({ kind }: { kind: HostConnectionKind }): ReactElement {
switch (kind) {
case "local":
return (
<ThemedMonitor
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "relay":
return (
<ThemedGlobe
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "tailscale":
return <ThemedTailscale size={CONNECTION_GLYPH_SIZE} uniProps={extraMutedMapping} />;
case "ssh":
return (
<ThemedTerminal
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "routed":
return (
<ThemedWaypoints
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "direct":
return (
<ThemedNetwork
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
}
}
function resolvePreferredConnection(host: HostProfile | undefined) {
if (!host || host.connections.length === 0) return null;
if (host.preferredConnectionId) {
const preferred = host.connections.find(
(connection) => connection.id === host.preferredConnectionId,
);
if (preferred) return preferred;
}
return host.connections[0] ?? null;
}
export function HostConnectionLine({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const localServerId = useLocalDaemonServerId();
const hosts = useHosts();
const activeConnection = snapshot?.activeConnection ?? null;
const hostProfile = useMemo(
() => hosts.find((candidate) => candidate.serverId === serverId),
[hosts, serverId],
);
const fallbackConnection = useMemo(
() => (activeConnection ? null : resolvePreferredConnection(hostProfile)),
[activeConnection, hostProfile],
);
const described = useMemo(() => {
const options = { isLocalHost: serverId === localServerId };
if (activeConnection) {
return describeActiveConnection(activeConnection, options);
}
if (fallbackConnection) {
return describeHostConnection(fallbackConnection, options);
}
return null;
}, [activeConnection, fallbackConnection, localServerId, serverId]);
if (!described) {
return null;
}
const endpoint =
described.kind === "routed" && described.endpoint
? (hosts.find((host) => host.serverId === described.endpoint)?.label ?? described.endpoint)
: described.endpoint;
return (
<View style={styles.connectionRow}>
<View style={styles.linkIconSlot}>
<ConnectionKindGlyph kind={described.kind} />
</View>
<Text style={styles.connectionKind} numberOfLines={1}>
{t(`settings.host.connectionKinds.${described.kind}`)}
</Text>
{endpoint ? (
<Text style={styles.connectionEndpoint} numberOfLines={1}>
{endpoint}
</Text>
) : null}
</View>
);
}
export function HostLatencyLabel({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const status = snapshot?.connectionStatus;
const activeConnectionId = snapshot?.activeConnectionId;
const activeProbe = activeConnectionId
? snapshot?.probeByConnectionId.get(activeConnectionId)
: undefined;
const latencyMs =
status === "online" && activeProbe?.status === "available" ? activeProbe.latencyMs : null;
if (latencyMs !== null) {
return (
<Text style={styles.latency} numberOfLines={1}>
{formatLatency(latencyMs)}
</Text>
);
}
if (status === "offline" || status === "error") {
return (
<Text style={styles.statusText} numberOfLines={1}>
{t("common.connectionStatus.offline")}
</Text>
);
}
return null;
}
const styles = StyleSheet.create((theme) => ({
connectionRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
// Matches the 14px host icon width on the row above so connection text aligns on the same rail.
linkIconSlot: {
width: 14,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
linkIcon: {
flexShrink: 0,
},
connectionKind: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
flexShrink: 0,
},
connectionEndpoint: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 1,
minWidth: 0,
},
latency: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
flexShrink: 0,
},
statusText: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 0,
},
}));
+11 -24
View File
@@ -1,13 +1,11 @@
import { useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import { useHosts } from "@/runtime/host-runtime";
import { useLocalDaemonServerId, useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { selectHostBadges, type HostBadgeModel } from "@/hosts/appearance";
import { useSessionStore } from "@/stores/session-store";
/**
* Every host's badge, resolved from the host registry, local-host detection, daemon-reported
* machine kind, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* Every host's badge, resolved from the three things that decide one: the host registry, which
* host is local, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* that has its own reason to hide badges passes false rather than filtering the result, so the
* per-host setting stays the only thing that decides name vs icon vs hidden.
*/
@@ -19,25 +17,14 @@ export function useHostBadges({
const hosts = useHosts();
const localServerId = useLocalDaemonServerId();
const localDaemon = useLocalDaemonServerIdState();
const detectedMachineKinds = useSessionStore(
useShallow((state) => {
const result: Record<string, string | null> = {};
for (const host of hosts) {
result[host.serverId] = state.sessions[host.serverId]?.serverInfo?.machineKind ?? null;
}
return result;
}),
return useMemo(
() =>
selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
enabled,
}),
[hosts, localDaemon.status, localServerId, enabled],
);
return useMemo(() => {
const detectedMachineKindByServerId = new Map<string, string | null>(
Object.entries(detectedMachineKinds),
);
return selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
detectedMachineKindByServerId,
enabled,
});
}, [hosts, localDaemon.status, localServerId, detectedMachineKinds, enabled]);
}
-25
View File
@@ -2841,23 +2841,6 @@ export const ar: TranslationResources = {
name: {
label: "الاسم",
},
icon: {
label: "الأيقونة",
accessibilityLabel: "الأيقونة، {{value}}",
auto: "تلقائي",
autoDetected: "تلقائي ({{icon}})",
options: {
server: "خادم",
laptop: "حاسوب محمول",
desktop: "حاسوب مكتبي",
mini: "حاسوب مصغّر",
workstation: "محطة عمل",
cloud: "سحابي",
container: "حاوية",
board: "حاسوب أحادي اللوحة",
terminal: "طرفية",
},
},
color: {
label: "اللون",
accessibilityLabel: "اللون، {{value}}",
@@ -2894,14 +2877,6 @@ export const ar: TranslationResources = {
local: "محلي",
remoteSsh: "SSH عن بُعد",
},
connectionKinds: {
local: "محلي",
relay: "تتابع",
tailscale: "Tailscale",
ssh: "SSH",
direct: "مباشر",
routed: "عبر",
},
connections: {
title: "اتصالات",
removeTitle: "إزالة الاتصال",
-25
View File
@@ -2936,23 +2936,6 @@ export const en = {
name: {
label: "Name",
},
icon: {
label: "Icon",
accessibilityLabel: "Icon, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Server",
laptop: "Laptop",
desktop: "Desktop",
mini: "Mini",
workstation: "Workstation",
cloud: "Cloud",
container: "Container",
board: "Single-board PC",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2989,14 +2972,6 @@ export const en = {
local: "Local",
remoteSsh: "Remote SSH",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connections",
removeTitle: "Remove connection",
-25
View File
@@ -2865,23 +2865,6 @@ export const es: TranslationResources = {
name: {
label: "Nombre",
},
icon: {
label: "Icono",
accessibilityLabel: "Icono, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Portátil",
desktop: "Escritorio",
mini: "Mini",
workstation: "Estación de trabajo",
cloud: "Nube",
container: "Contenedor",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2918,14 +2901,6 @@ export const es: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relé",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Directo",
routed: "Vía",
},
connections: {
title: "Conexiones",
removeTitle: "Quitar conexión",
-25
View File
@@ -2867,23 +2867,6 @@ export const fr: TranslationResources = {
name: {
label: "Nom",
},
icon: {
label: "Icône",
accessibilityLabel: "Icône, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Serveur",
laptop: "Portable",
desktop: "Bureau",
mini: "Mini",
workstation: "Station de travail",
cloud: "Cloud",
container: "Conteneur",
board: "Ordinateur monocarte",
terminal: "Terminal",
},
},
color: {
label: "Couleur",
accessibilityLabel: "Couleur, {{value}}",
@@ -2920,14 +2903,6 @@ export const fr: TranslationResources = {
local: "Local",
remoteSsh: "SSH distant",
},
connectionKinds: {
local: "Local",
relay: "Relais",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connexions",
removeTitle: "Supprimer la connexion",
-25
View File
@@ -2833,23 +2833,6 @@ export const ja: TranslationResources = {
name: {
label: "名前",
},
icon: {
label: "アイコン",
accessibilityLabel: "アイコン、{{value}}",
auto: "自動",
autoDetected: "自動 ({{icon}})",
options: {
server: "サーバー",
laptop: "ノート PC",
desktop: "デスクトップ",
mini: "ミニ PC",
workstation: "ワークステーション",
cloud: "クラウド",
container: "コンテナ",
board: "シングルボード PC",
terminal: "ターミナル",
},
},
color: {
label: "色",
accessibilityLabel: "色、{{value}}",
@@ -2886,14 +2869,6 @@ export const ja: TranslationResources = {
local: "ローカル",
remoteSsh: "リモート SSH",
},
connectionKinds: {
local: "ローカル",
relay: "リレー",
tailscale: "Tailscale",
ssh: "SSH",
direct: "ダイレクト",
routed: "経由",
},
connections: {
title: "接続",
removeTitle: "接続を削除",
-25
View File
@@ -2819,23 +2819,6 @@ export const ko: TranslationResources = {
name: {
label: "이름",
},
icon: {
label: "아이콘",
accessibilityLabel: "아이콘, {{value}}",
auto: "자동",
autoDetected: "자동 ({{icon}})",
options: {
server: "서버",
laptop: "노트북",
desktop: "데스크톱",
mini: "미니",
workstation: "워크스테이션",
cloud: "클라우드",
container: "컨테이너",
board: "싱글보드 PC",
terminal: "터미널",
},
},
color: {
label: "색상",
accessibilityLabel: "색상, {{value}}",
@@ -2872,14 +2855,6 @@ export const ko: TranslationResources = {
local: "로컬",
remoteSsh: "원격 SSH",
},
connectionKinds: {
local: "로컬",
relay: "릴레이",
tailscale: "Tailscale",
ssh: "SSH",
direct: "직접 연결",
routed: "경유",
},
connections: {
title: "연결",
removeTitle: "연결 제거",
-25
View File
@@ -2846,23 +2846,6 @@ export const ptBR: TranslationResources = {
name: {
label: "Nome",
},
icon: {
label: "Ícone",
accessibilityLabel: "Ícone, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Notebook",
desktop: "Desktop",
mini: "Mini",
workstation: "Estação de trabalho",
cloud: "Nuvem",
container: "Contêiner",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Cor",
accessibilityLabel: "Cor, {{value}}",
@@ -2899,14 +2882,6 @@ export const ptBR: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direto",
routed: "Via",
},
connections: {
title: "Conexões",
removeTitle: "Remover conexão",
-25
View File
@@ -2854,23 +2854,6 @@ export const ru: TranslationResources = {
name: {
label: "Имя",
},
icon: {
label: "Значок",
accessibilityLabel: "Значок, {{value}}",
auto: "Авто",
autoDetected: "Авто ({{icon}})",
options: {
server: "Сервер",
laptop: "Ноутбук",
desktop: "Компьютер",
mini: "Мини-ПК",
workstation: "Рабочая станция",
cloud: "Облако",
container: "Контейнер",
board: "Одноплатный ПК",
terminal: "Терминал",
},
},
color: {
label: "Цвет",
accessibilityLabel: "Цвет, {{value}}",
@@ -2907,14 +2890,6 @@ export const ru: TranslationResources = {
local: "Локальный",
remoteSsh: "Удалённый SSH",
},
connectionKinds: {
local: "Локальный",
relay: "Ретранслятор",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Прямой",
routed: "Через",
},
connections: {
title: "Подключения",
removeTitle: "Удалить подключение",
-25
View File
@@ -2775,23 +2775,6 @@ export const zhCN: TranslationResources = {
name: {
label: "名称",
},
icon: {
label: "图标",
accessibilityLabel: "图标,{{value}}",
auto: "自动",
autoDetected: "自动 ({{icon}})",
options: {
server: "服务器",
laptop: "笔记本电脑",
desktop: "台式机",
mini: "迷你主机",
workstation: "工作站",
cloud: "云端",
container: "容器",
board: "单板机",
terminal: "终端",
},
},
color: {
label: "颜色",
accessibilityLabel: "颜色,{{value}}",
@@ -2828,14 +2811,6 @@ export const zhCN: TranslationResources = {
local: "本地",
remoteSsh: "远程 SSH",
},
connectionKinds: {
local: "本地",
relay: "中继",
tailscale: "Tailscale",
ssh: "SSH",
direct: "直连",
routed: "经由",
},
connections: {
title: "连接",
removeTitle: "移除连接",
+6 -175
View File
@@ -1114,106 +1114,6 @@ describe("HostRuntimeController", () => {
expect(activeClient.latencyMeasurements()).toEqual([]);
});
it("measures active latency on demand when an online host has no sample yet", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const controller = new HostRuntimeController({
host: makeHost({
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
preferredConnectionId: "direct:lan:6767",
}),
deps: makeDeps({ "direct:lan:6767": 14 }, []),
});
await controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "pending",
latencyMs: null,
});
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
});
it("keeps an on-demand active latency sample when a slower probe on another connection finishes", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const relayProbeStarted = createDeferred<void>();
const slowRelayProbe = createDeferred<{
client: DaemonClient;
serverId: string;
hostname: string | null;
}>();
const relayClient = new FakeDaemonClient();
relayClient.setConnectionState({ status: "connected" });
relayClient.ping = async () => ({ rttMs: 90 });
const controller = new HostRuntimeController({
host: makeHost(),
deps: {
...makeDeps({}, []),
connectToDaemon: async ({ host, connection }) => {
if (connection.id === "relay:relay.paseo.sh:443") {
relayProbeStarted.resolve();
return slowRelayProbe.promise;
}
return {
client: initialClient as unknown as DaemonClient,
serverId: host.serverId,
hostname: null,
};
},
},
});
// Startup runs the first probe cycle immediately; wait until the slower relay probe is in
// flight, then measure active latency on demand before the relay probe resolves.
const startPromise = controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
await relayProbeStarted.promise;
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
slowRelayProbe.resolve({
client: relayClient as unknown as DaemonClient,
serverId: "srv_test",
hostname: null,
});
await startPromise;
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
expect(controller.getSnapshot().probeByConnectionId.get("relay:relay.paseo.sh:443")).toEqual({
status: "available",
latencyMs: 90,
});
});
it.each([12, null])(
"falls back to relay when the direct client disconnects with heartbeat RTT %s",
async (heartbeatRtt) => {
@@ -3466,11 +3366,7 @@ describe("HostRuntimeStore", () => {
store.boot();
await registryLoaded;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "none",
badgeDisplay: null,
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
expect(store.getHosts()[0]?.appearance).toEqual({ color: "none", badgeDisplay: null });
store.syncHosts([]);
});
@@ -3495,7 +3391,6 @@ describe("HostRuntimeStore", () => {
const updated = store.getHosts()[0];
expect(updated?.appearance).toEqual({ color: "teal", badgeDisplay: null });
expect("icon" in (updated?.appearance ?? {})).toBe(false);
expect(updated?.updatedAt).not.toBe(host.updatedAt);
const persisted = await storage.getItem("@paseo:daemon-registry");
@@ -3507,60 +3402,10 @@ describe("HostRuntimeStore", () => {
store.syncHosts([]);
});
it("records a chosen host icon and resets to auto without disturbing color or badge display", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "violet", badgeDisplay: "icon" },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
await storage.setItem("@paseo:e2e", "1");
const store = createAppearanceStore(storage);
const registryLoaded = onceHostListMatches(store, () => store.isHostRegistryLoaded());
store.boot();
await registryLoaded;
const hostListChanged = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === "laptop",
);
await store.setHostIcon("srv_appearance", "laptop");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const resetToAuto = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === undefined,
);
await store.setHostIcon("srv_appearance", null);
await resetToAuto;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
badgeDisplay: "icon",
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
store.syncHosts([]);
});
it("records a chosen badge display without disturbing the color", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "amber", icon: "server", badgeDisplay: null },
appearance: { color: "amber", badgeDisplay: null },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
@@ -3578,16 +3423,11 @@ describe("HostRuntimeStore", () => {
await store.setHostBadgeDisplay("srv_appearance", "icon");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
expect(store.getHosts()[0]?.appearance).toEqual({ color: "amber", badgeDisplay: "icon" });
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
@@ -3636,25 +3476,16 @@ describe("HostRuntimeStore", () => {
};
const color = store.setHostColor("srv_appearance", "teal");
const icon = store.setHostIcon("srv_appearance", "mini");
const display = store.setHostBadgeDisplay("srv_appearance", "icon");
await Promise.resolve();
expect(writeCount).toBe(1);
firstWrite.resolve();
await Promise.all([color, icon, display]);
await Promise.all([color, display]);
expect(store.getHosts()[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
expect(store.getHosts()[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
const persistedHosts = JSON.parse((await storage.getItem("@paseo:daemon-registry")) ?? "[]");
expect(persistedHosts[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
expect(persistedHosts[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
store.syncHosts([]);
});
+15 -91
View File
@@ -28,12 +28,7 @@ import {
type HostProfile,
type UnreadableHostEntries,
} from "@/types/host-connection";
import {
defaultHostAppearance,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
import {
buildDaemonWebSocketUrl,
buildRelayWebSocketUrl,
@@ -950,56 +945,6 @@ export class HostRuntimeController {
await this.switchToConnection(input);
}
/**
* Measures the active connection's round-trip time when the host is online and no sample has
* landed yet (for example right after connecting, before the first heartbeat interval fires).
*/
async refreshActiveLatency(): Promise<void> {
const activeConnectionId = this.snapshot.activeConnectionId;
const activeClient = this.snapshot.client;
if (
this.snapshot.connectionStatus !== "online" ||
!activeConnectionId ||
!activeClient ||
activeClient.getConnectionState().status !== "connected"
) {
return;
}
const existing = this.snapshot.probeByConnectionId.get(activeConnectionId);
if (existing?.status === "available") {
return;
}
const existingRtt = activeClient.getLastLivenessRttMs();
if (existingRtt !== null) {
this.recordActiveLatencySample(activeConnectionId, existingRtt);
return;
}
try {
const rttMs = await activeClient.measureLatency({ timeoutMs: 3_000 });
if (
this.snapshot.activeConnectionId !== activeConnectionId ||
this.snapshot.client !== activeClient ||
this.snapshot.connectionStatus !== "online"
) {
return;
}
this.recordActiveLatencySample(activeConnectionId, rttMs);
} catch {
// A latency probe never drives teardown; the heartbeat owns liveness.
}
}
private setConnectionProbe(connectionId: string, probe: ConnectionProbeState): void {
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
probeByConnectionId.set(connectionId, probe);
this.updateSnapshot({ probeByConnectionId });
}
private recordActiveLatencySample(connectionId: string, rttMs: number): void {
this.recordActiveRttSample(rttMs, performance.now());
this.setConnectionProbe(connectionId, { status: "available", latencyMs: rttMs });
}
async runProbeCycleNow(): Promise<void> {
if (this.probeCycleInFlight) {
return this.probeCycleInFlight;
@@ -1056,32 +1001,30 @@ export class HostRuntimeController {
return;
}
const initialProbes = new Map(this.snapshot.probeByConnectionId);
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
for (const connection of connectionsToProbe) {
this.connectionLastProbedAt.set(connection.id, performance.now());
const existingProbe = initialProbes.get(connection.id);
const existingProbe = probeByConnectionId.get(connection.id);
const shouldPreserveActiveLatency =
isOnline && connection.id === activeConnectionId && existingProbe?.status === "available";
if (!shouldPreserveActiveLatency) {
initialProbes.set(connection.id, {
probeByConnectionId.set(connection.id, {
status: "pending",
latencyMs: null,
});
}
}
this.updateSnapshot({ probeByConnectionId: initialProbes });
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
let remaining = connectionsToProbe.length;
let probeAuthFailure: "password_required" | "incorrect_password" | null = null;
let activationLock: Promise<void> | null = null;
// Merge each connection result into the live snapshot map so a slow probe on another
// connection cannot overwrite a fresher sample (e.g. from refreshActiveLatency) on the active one.
const publishConnectionProbe = (connectionId: string, probe: ConnectionProbeState): void => {
const publishProbeState = (): void => {
if (!this.isCurrentProbeRequest(requestVersion)) {
return;
}
this.setConnectionProbe(connectionId, probe);
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
};
const maybeActivateFirstAvailable = async (
@@ -1110,7 +1053,6 @@ export class HostRuntimeController {
return;
}
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
const currentActiveConnectionId = this.snapshot.activeConnectionId;
if (currentActiveConnectionId) {
this.reconcileActiveProbeWithClient(currentActiveConnectionId, probeByConnectionId);
@@ -1266,10 +1208,11 @@ export class HostRuntimeController {
if (activeClient) {
if (activeClient.getConnectionState().status !== "connected") {
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
return;
}
const rttMs = activeClient.getLastLivenessRttMs();
@@ -1278,10 +1221,11 @@ export class HostRuntimeController {
}
if (rttMs !== null) {
this.recordActiveRttSample(rttMs, performance.now());
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
}
return;
}
@@ -1291,10 +1235,11 @@ export class HostRuntimeController {
return;
}
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
} catch (error) {
if (this.isCurrentProbeRequest(requestVersion)) {
const authFailure = getConnectionAuthFailureReason(error);
@@ -1302,10 +1247,11 @@ export class HostRuntimeController {
this.authRejectedConnectionIds.add(connection.id);
probeAuthFailure = authFailure;
}
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
}
} finally {
if (connectedClient && shouldCloseClient) {
@@ -2490,16 +2436,6 @@ export class HostRuntimeStore {
}));
}
async setHostIcon(serverId: string, icon: HostIcon | null): Promise<void> {
await this.updateHostAppearance(serverId, (host) => {
const { icon: _previousIcon, ...rest } = host.appearance;
return {
...host,
appearance: icon ? { ...rest, icon } : rest,
};
});
}
async setHostBadgeDisplay(serverId: string, badgeDisplay: HostBadgeDisplay): Promise<void> {
await this.updateHostAppearance(serverId, (host) => ({
...host,
@@ -2507,16 +2443,6 @@ export class HostRuntimeStore {
}));
}
refreshActiveLatencies(serverIds?: readonly string[]): void {
const targets = serverIds ?? this.hosts.map((host) => host.serverId);
for (const serverId of targets) {
const controller = this.controllers.get(serverId);
if (controller) {
void controller.refreshActiveLatency();
}
}
}
private updateHostAppearance(
serverId: string,
apply: (host: HostProfile) => HostProfile,
@@ -3370,7 +3296,6 @@ export interface HostMutations {
beginLinkPairing: () => LinkPairing;
renameHost: (serverId: string, label: string) => Promise<void>;
setHostColor: (serverId: string, color: HostColor) => Promise<void>;
setHostIcon: (serverId: string, icon: HostIcon | null) => Promise<void>;
setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise<void>;
removeHost: (serverId: string) => Promise<void>;
removeConnection: (serverId: string, connectionId: string) => Promise<void>;
@@ -3386,7 +3311,6 @@ export function useHostMutations(): HostMutations {
beginLinkPairing: () => store.beginLinkPairing(),
renameHost: (serverId, label) => store.renameHost(serverId, label),
setHostColor: (serverId, color) => store.setHostColor(serverId, color),
setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon),
setHostBadgeDisplay: (serverId, badgeDisplay) =>
store.setHostBadgeDisplay(serverId, badgeDisplay),
removeHost: (serverId) => store.removeHost(serverId),
@@ -438,7 +438,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
title={t("newWorkspace.fields.host")}
desktopPlacement="bottom-start"
desktopMinWidth={320}
desktopMinWidth={200}
hostOptionTestID={hostOptionTestID}
>
<FieldTrigger
+1 -1
View File
@@ -907,7 +907,7 @@ function HostPicker({
showActiveConnection
searchable={false}
title={t("settings.hostPicker.switchHost")}
desktopMinWidth={328}
desktopMinWidth={240}
addHostTestID="settings-add-host"
hostOptionTestID={hostOptionTestID}
>
@@ -4,12 +4,7 @@ import { useTranslation } from "react-i18next";
import { Pressable, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Pencil } from "lucide-react-native";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
import { AdaptiveRenameModal } from "@/components/rename-modal";
import { WorkspaceMetaRow } from "@/components/sidebar/workspace-meta-row";
@@ -18,18 +13,12 @@ import { SettingsSection } from "@/components/settings/headings/settings-section
import {
HOST_BADGE_DISPLAYS,
HOST_COLORS,
HOST_ICONS,
normalizeDetectedHostIcon,
resolveHostBadgeDisplay,
resolveHostIcon,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { useHostMutations } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { identityColor } from "@/styles/identity-colors";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
@@ -87,112 +76,10 @@ function colorLabel(t: TFunction, color: HostColor): string {
return t(`settings.host.appearance.color.options.${color}`);
}
function iconLabel(t: TFunction, icon: HostIcon): string {
return t(`settings.host.appearance.icon.options.${icon}`);
}
function autoIconLabel(t: TFunction, detectedIcon: HostIcon | null): string {
if (detectedIcon) {
return t("settings.host.appearance.icon.autoDetected", {
icon: iconLabel(t, detectedIcon),
});
}
return t("settings.host.appearance.icon.auto");
}
function badgeDisplayLabel(t: TFunction, display: HostBadgeDisplay): string {
return t(`settings.host.appearance.badge.options.${display}`);
}
function IconMenuItem({
icon,
color,
selected,
onChange,
}: {
icon: HostIcon;
color: HostColor;
selected: boolean;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const handleSelect = useCallback(() => onChange(icon), [icon, onChange]);
const leading = useMemo(
() => <HostIconGlyph icon={icon} color={color} size={ICON_SIZE.sm} />,
[color, icon],
);
return (
<DropdownMenuItem selected={selected} onSelect={handleSelect} leading={leading}>
{iconLabel(t, icon)}
</DropdownMenuItem>
);
}
function IconRow({
icon,
detectedIcon,
resolvedIcon,
color,
onChange,
}: {
icon: HostIcon | null;
detectedIcon: HostIcon | null;
resolvedIcon: HostIcon;
color: HostColor;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const autoLabel = autoIconLabel(t, detectedIcon);
const selectedLabel = icon ? iconLabel(t, icon) : autoLabel;
const handleSelectAuto = useCallback(() => onChange(null), [onChange]);
const triggerLeading = useMemo(
() => <HostIconGlyph icon={resolvedIcon} color={color} size={ICON_SIZE.sm} />,
[color, resolvedIcon],
);
const autoLeading = useMemo(
() => <HostIconGlyph icon={detectedIcon ?? "server"} color={color} size={ICON_SIZE.sm} />,
[color, detectedIcon],
);
return (
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.host.appearance.icon.label")}</Text>
</View>
<DropdownMenu>
<DropdownTrigger
testID="host-appearance-icon"
accessibilityRole="button"
accessibilityLabel={t("settings.host.appearance.icon.accessibilityLabel", {
value: selectedLabel,
})}
leading={triggerLeading}
>
{selectedLabel}
</DropdownTrigger>
<DropdownMenuContent side="bottom" align="end" width={220}>
<DropdownMenuItem
selected={icon === null}
onSelect={handleSelectAuto}
leading={autoLeading}
>
{autoLabel}
</DropdownMenuItem>
<DropdownMenuSeparator />
{HOST_ICONS.map((option) => (
<IconMenuItem
key={option}
icon={option}
color={color}
selected={option === icon}
onChange={onChange}
/>
))}
</DropdownMenuContent>
</DropdownMenu>
</View>
);
}
function ColorSwatch({ color }: { color: HostColor }) {
const swatchStyle = useMemo(
() => [styles.swatch, color === "none" ? null : { backgroundColor: identityColor(color) }],
@@ -318,11 +205,9 @@ function BadgeDisplayMenuItem({
*/
function BadgePreview({
host,
resolvedIcon,
badgeDisplay,
}: {
host: HostProfile;
resolvedIcon: HostIcon;
badgeDisplay: HostBadgeDisplay;
}) {
const { t } = useTranslation();
@@ -334,10 +219,9 @@ function BadgePreview({
serverId: host.serverId,
label: host.label,
color: host.appearance.color,
icon: resolvedIcon,
showLabel: badgeDisplay === "name",
},
[badgeDisplay, host.serverId, host.label, host.appearance.color, resolvedIcon],
[badgeDisplay, host.serverId, host.label, host.appearance.color],
);
// The real sidebar row, so the preview can't drift from what the setting actually does.
return (
@@ -360,14 +244,8 @@ function BadgePreview({
export function HostAppearanceSection({ host }: { host: HostProfile }) {
const { t } = useTranslation();
const toast = useToast();
const { setHostColor, setHostIcon, setHostBadgeDisplay } = useHostMutations();
const { setHostColor, setHostBadgeDisplay } = useHostMutations();
const localDaemon = useLocalDaemonServerIdState();
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const detectedIcon = normalizeDetectedHostIcon(detectedMachineKind);
const selectedIcon = normalizeDetectedHostIcon(host.appearance.icon);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const isLocalHost = localDaemon.status === "resolved" && localDaemon.serverId === host.serverId;
const badgeDisplay = resolveHostBadgeDisplay({
appearance: host.appearance,
@@ -385,16 +263,6 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
},
[host.serverId, setHostColor, t, toast],
);
const handleIconChange = useCallback(
async (icon: HostIcon | null) => {
try {
await setHostIcon(host.serverId, icon);
} catch {
toast.error(t("errors.unableToSave"));
}
},
[host.serverId, setHostIcon, t, toast],
);
const handleBadgeDisplayChange = useCallback(
async (next: HostBadgeDisplay) => {
try {
@@ -420,18 +288,11 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
<HostRenameButton host={host} />
</View>
</View>
<IconRow
icon={selectedIcon}
detectedIcon={detectedIcon}
resolvedIcon={resolvedIcon}
color={host.appearance.color}
onChange={handleIconChange}
/>
<ColorRow color={host.appearance.color} onChange={handleColorChange} />
{badgeDisplay === null ? null : (
<>
<BadgeDisplayRow badgeDisplay={badgeDisplay} onChange={handleBadgeDisplayChange} />
<BadgePreview host={host} resolvedIcon={resolvedIcon} badgeDisplay={badgeDisplay} />
<BadgePreview host={host} badgeDisplay={badgeDisplay} />
</>
)}
</View>
-9
View File
@@ -293,7 +293,6 @@ export interface DaemonServerInfo {
serverId: string;
hostname: string | null;
version: string | null;
machineKind?: string | null;
desktopManaged?: boolean;
capabilities?: ServerCapabilities;
features?: ServerInfoStatusPayload["features"];
@@ -304,7 +303,6 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS
serverId: serverInfo.serverId,
hostname: serverInfo.hostname ?? null,
version: serverInfo.version ?? null,
...(serverInfo.machineKind !== undefined ? { machineKind: serverInfo.machineKind } : {}),
...(serverInfo.desktopManaged !== undefined
? { desktopManaged: serverInfo.desktopManaged }
: {}),
@@ -788,7 +786,6 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo: SessionState["serverInfo"] | undefined;
nextHostname: string | null;
nextVersion: string | null;
nextMachineKind: string | null;
nextDesktopManaged: boolean | undefined;
nextCapabilities: ServerCapabilities | undefined;
nextFeatures: ServerInfoStatusPayload["features"] | undefined;
@@ -798,19 +795,16 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
} = input;
const prevHostname = currentServerInfo?.hostname?.trim() || null;
const prevVersion = currentServerInfo?.version?.trim() || null;
const prevMachineKind = currentServerInfo?.machineKind?.trim() || null;
return (
currentServerInfo?.serverId === input.nextServerId &&
prevHostname === nextHostname &&
prevVersion === nextVersion &&
prevMachineKind === nextMachineKind &&
currentServerInfo?.desktopManaged === nextDesktopManaged &&
areServerCapabilitiesEqual(currentServerInfo?.capabilities, nextCapabilities) &&
areServerInfoFeaturesEqual(currentServerInfo?.features, nextFeatures)
@@ -948,7 +942,6 @@ export const useSessionStore = create<SessionStore>()(
const nextHostname = info.hostname?.trim() || null;
const nextVersion = info.version?.trim() || null;
const nextMachineKind = info.machineKind?.trim() || null;
const nextDesktopManaged = info.desktopManaged;
const nextCapabilities = info.capabilities;
const nextFeatures = info.features;
@@ -958,7 +951,6 @@ export const useSessionStore = create<SessionStore>()(
currentServerInfo: session.serverInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
@@ -978,7 +970,6 @@ export const useSessionStore = create<SessionStore>()(
serverId: info.serverId,
hostname: nextHostname,
version: nextVersion,
...(nextMachineKind !== null ? { machineKind: nextMachineKind } : {}),
...(nextDesktopManaged !== undefined
? { desktopManaged: nextDesktopManaged }
: {}),
@@ -11,6 +11,10 @@ import {
workspaceTabTargetsEqual,
} from "@/workspace-tabs/identity";
import { createNewWorkspaceTab } from "@/workspace-tabs/new-tab";
import {
resolveTabDepartureSuccessor,
type PaneTabFocusHistory,
} from "@/stores/workspace-tab-focus-policy";
export interface SplitPane {
id: string;
@@ -75,6 +79,7 @@ interface InsertChildIntoGroupInput {
interface DetachTabFromTreeInput {
tabId: string;
preserveEmptyPaneId?: string | null;
replacementFocusedTabId?: string | null;
}
interface DetachTabFromTreeResult {
@@ -96,6 +101,7 @@ interface InsertSplitInternalInput {
tabId: string;
position: "left" | "right" | "top" | "bottom";
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
replacementFocusedTabId?: string | null;
}
interface InsertSplitInternalResult {
@@ -139,6 +145,7 @@ interface OpenTabInLayoutInput {
explorerSidebarPaneId: string | null;
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
reservedTabIds?: ReadonlySet<string>;
paneFocusHistory?: PaneTabFocusHistory;
}
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
@@ -207,6 +214,7 @@ interface SplitPaneInLayoutInput {
position: "left" | "right" | "top" | "bottom";
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
maxTreeDepth: number;
paneFocusHistory?: PaneTabFocusHistory;
}
interface SplitPaneInLayoutResult {
@@ -233,6 +241,7 @@ interface MoveTabToPaneInLayoutInput {
tabId: string;
toPaneId: string;
explorerSidebarPaneId?: string | null;
paneFocusHistory?: PaneTabFocusHistory;
}
interface FocusTabInLayoutInput {
@@ -815,6 +824,10 @@ function detachTabFromTree(
const nextPane = normalizePaneAfterTabChange({
...paneNode.pane,
tabs: paneNode.pane.tabs.filter((entry) => entry.tabId !== input.tabId),
focusedTabId:
paneNode.pane.focusedTabId === input.tabId
? (input.replacementFocusedTabId ?? paneNode.pane.focusedTabId)
: paneNode.pane.focusedTabId,
});
const nextRoot = replaceNodeAtPath(root, panePath, () => ({ kind: "pane", pane: nextPane }));
@@ -970,6 +983,7 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
const detached = detachTabFromTree(input.root, {
tabId: input.tabId,
preserveEmptyPaneId: input.targetPaneId,
replacementFocusedTabId: input.replacementFocusedTabId,
});
invariant(detached.tab, `Tab not found: ${input.tabId}`);
@@ -1165,6 +1179,14 @@ export function collectAllPanes(root: SplitNode): SplitPane[] {
return internalRoot.group.children.flatMap((child) => collectAllPanes(child));
}
export function collectAllPanesIncludingHidden(root: SplitNode): SplitPane[] {
const internalRoot = asInternalNode(root);
if (internalRoot.kind === "pane") {
return [internalRoot.pane];
}
return internalRoot.group.children.flatMap((child) => collectAllPanesIncludingHidden(child));
}
function isEphemeralTab(tab: WorkspaceTab): boolean {
return tab.target.kind === "commit_diff" || tab.target.kind === "new_tab";
}
@@ -1508,6 +1530,7 @@ export function openTabInLayoutFocused(input: OpenTabInLayoutInput): OpenTabInLa
layout: nextLayout,
tabId: existingTab.tabId,
placement: input.placement,
paneFocusHistory: input.paneFocusHistory,
}),
};
}
@@ -1534,6 +1557,7 @@ export function revealTargetInLayout(input: CreateTabInLayoutInput): OpenTabInLa
layout: updateExistingTabTarget(input.layout, existingTab, input.target),
tabId: existingTab.tabId,
placement: input.placement,
paneFocusHistory: input.paneFocusHistory,
}),
};
}
@@ -1551,6 +1575,7 @@ function revealExistingTab(input: {
layout: WorkspaceLayout;
tabId: string;
placement: WorkspaceTabPlacement;
paneFocusHistory?: PaneTabFocusHistory;
}): WorkspaceLayout {
if (input.placement.mode === "pane") {
const currentPane = findPaneContainingTab(asInternalNode(input.layout.root), input.tabId);
@@ -1559,6 +1584,7 @@ function revealExistingTab(input: {
layout: input.layout,
tabId: input.tabId,
toPaneId: input.placement.paneId,
paneFocusHistory: input.paneFocusHistory,
});
if (moved) {
return moved;
@@ -1600,9 +1626,9 @@ export function closeTabInLayout(input: CloseTabInLayoutInput): WorkspaceLayout
? pane.id
: null;
const closeSuccessorTabId = getCloseSuccessorTabId({
const closeSuccessorTabId = resolveTabDepartureSuccessor("close", {
pane,
tabId: input.tabId,
departingTabId: input.tabId,
openTabIds: new Set(collectAllTabs(internalLayout.root).map((tab) => tab.tabId)),
parentTabIdByTabId: input.layout.parentTabIdByTabId,
});
@@ -1986,16 +2012,26 @@ export function splitPaneInLayout(input: SplitPaneInLayoutInput): SplitPaneInLay
if (!findPaneById(layout.root, input.targetPaneId)) {
return null;
}
if (!findPaneContainingTab(layout.root, input.tabId)) {
const sourcePane = findPaneContainingTab(layout.root, input.tabId);
if (!sourcePane) {
return null;
}
const replacementFocusedTabId = resolveTabDepartureSuccessor("relocate", {
pane: sourcePane,
departingTabId: input.tabId,
openTabIds: new Set(collectAllTabs(layout.root).map((tab) => tab.tabId)),
parentTabIdByTabId: input.layout.parentTabIdByTabId,
paneFocusHistory: input.paneFocusHistory,
});
const result = insertSplitInternal({
root: layout.root,
targetPaneId: input.targetPaneId,
tabId: input.tabId,
position: input.position,
createNodeId: input.createNodeId,
replacementFocusedTabId,
});
if (getTreeDepth(result.root) > input.maxTreeDepth) {
return null;
@@ -2115,6 +2151,17 @@ export function moveTabToPaneInLayout(input: MoveTabToPaneInLayoutInput): Worksp
});
}
const replacementFocusedTabId =
sourcePane.id === input.toPaneId
? null
: resolveTabDepartureSuccessor("relocate", {
pane: sourcePane,
departingTabId: input.tabId,
openTabIds: new Set(collectAllTabs(layout.root).map((tab) => tab.tabId)),
parentTabIdByTabId: input.layout.parentTabIdByTabId,
paneFocusHistory: input.paneFocusHistory,
});
const detached = detachTabFromTree(layout.root, {
tabId: input.tabId,
// Crossing into or out of Explorer cannot remove either host shell.
@@ -2124,6 +2171,7 @@ export function moveTabToPaneInLayout(input: MoveTabToPaneInLayoutInput): Worksp
input.toPaneId === input.explorerSidebarPaneId
? sourcePane.id
: null,
replacementFocusedTabId,
});
if (!detached.tab) {
return null;
@@ -2280,29 +2328,6 @@ function withNormalizedParentTabMap(layout: WorkspaceLayout): WorkspaceLayout {
: { root: layout.root, focusedPaneId: layout.focusedPaneId };
}
function getCloseSuccessorTabId(input: {
pane: SplitPane;
tabId: string;
openTabIds: ReadonlySet<string>;
parentTabIdByTabId?: Record<string, string>;
}): string | null {
if (input.pane.focusedTabId !== input.tabId) {
return null;
}
const tabIndex = input.pane.tabIds.indexOf(input.tabId);
const parentTabId = input.parentTabIdByTabId?.[input.tabId] ?? null;
if (parentTabId && input.openTabIds.has(parentTabId)) {
return parentTabId;
}
return (
input.pane.tabIds[tabIndex + 1] ??
(tabIndex > 0 ? input.pane.tabIds[tabIndex - 1] : null) ??
null
);
}
function getFocusedPaneIdAfterTabClose(input: {
root: SplitNode;
focusedPaneId: string | null;
@@ -5496,3 +5496,245 @@ it("reentering a workspace restores its suspended pane without choosing another
expect(store.getState().layoutByWorkspace[workspaceKey]!.focusedPaneId).toBe(paneId);
expect(store.getState().focusRequest).toEqual({ workspaceKey, tabId });
});
describe("tab departure focus policy", () => {
it("splitPane returns the source pane to the most recently focused tab instead of the rightmost tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:split-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
const tabB = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
})!;
// Open FILE while B is active (parentTabId = B) to prove focus recency wins over birth parent.
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
parentTabId: tabB,
})!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
const newPaneId = store.getState().splitPane(workspaceKey, {
tabId: tabFile,
targetPaneId: "main",
position: "right",
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(newPaneId).toBeTruthy();
expect(layout.focusedPaneId).toBe(newPaneId);
expect(findPaneById(layout.root, newPaneId)?.focusedTabId).toBe(tabFile);
expect(findPaneById(layout.root, "main")?.tabIds).toEqual([tabA, tabB]);
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabA);
});
it("moveTabToPane returns the source pane to the most recently focused remaining tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:move-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
const tabB = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
})!;
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
})!;
const sidePaneId = store.getState().splitPaneEmpty(workspaceKey, {
targetPaneId: "main",
position: "right",
})!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
store.getState().moveTabToPane(workspaceKey, tabFile, sidePaneId);
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(layout.focusedPaneId).toBe(sidePaneId);
expect(findPaneById(layout.root, sidePaneId)?.focusedTabId).toBe(tabFile);
expect(findPaneById(layout.root, "main")?.tabIds).toEqual([tabA, tabB]);
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabA);
});
it("explicit pane-local reveal returns the source pane to its most recently focused tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:pane-reveal-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
});
const fileTarget = { kind: "file", path: "/repo/notes.md" } as const;
const tabFile = store.getState().openTab({
workspaceKey,
target: fileTarget,
intent: "reveal",
})!;
const sidePaneId = store.getState().ensureSidePane(workspaceKey, { focus: false })!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
store.getState().openTab({
workspaceKey,
target: fileTarget,
intent: "reveal",
placement: { mode: "pane", paneId: sidePaneId },
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabA);
expect(findPaneById(layout.root, sidePaneId)?.focusedTabId).toBe(tabFile);
});
it("seeds focus recency from a hydrated layout on the first tab switch", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:hydrated-recency";
store.setState((state) => ({
...state,
layoutByWorkspace: {
...state.layoutByWorkspace,
[workspaceKey]: {
root: createPane({
id: "main",
tabIds: ["agent_a", "agent_b", "file_/repo/notes.md"],
focusedTabId: "agent_a",
}),
focusedPaneId: "main",
},
},
}));
store.getState().focusTab(workspaceKey, "file_/repo/notes.md");
store.getState().splitPane(workspaceKey, {
tabId: "file_/repo/notes.md",
targetPaneId: "main",
position: "right",
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("agent_a");
});
it("falls back to a same-pane parent tab when relocating immediately after hydration", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:hydrated-parent-fallback";
store.setState((state) => ({
...state,
layoutByWorkspace: {
...state.layoutByWorkspace,
[workspaceKey]: {
root: createPane({
id: "main",
tabIds: ["agent_a", "agent_b", "file_/repo/notes.md"],
focusedTabId: "file_/repo/notes.md",
}),
focusedPaneId: "main",
parentTabIdByTabId: { "file_/repo/notes.md": "agent_a" },
},
},
}));
store.getState().splitPane(workspaceKey, {
tabId: "file_/repo/notes.md",
targetPaneId: "main",
position: "right",
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("agent_a");
});
it("tracks multi-step recency and preserves history across convertDraftToAgent", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:multi-step-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "draft", draftId: "draft-a" },
intent: "reveal",
})!;
const tabB = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
})!;
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
})!;
store.getState().focusTab(workspaceKey, tabB);
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
const convertedA = store.getState().convertDraftToAgent(workspaceKey, tabA, "agent-a")!;
store.getState().splitPane(workspaceKey, {
tabId: tabFile,
targetPaneId: "main",
position: "right",
});
expect(
findPaneById(store.getState().layoutByWorkspace[workspaceKey]!.root, "main")?.focusedTabId,
).toBe(convertedA);
store.getState().focusTab(workspaceKey, convertedA);
store.getState().splitPane(workspaceKey, {
tabId: convertedA,
targetPaneId: "main",
position: "bottom",
});
expect(
findPaneById(store.getState().layoutByWorkspace[workspaceKey]!.root, "main")?.focusedTabId,
).toBe(tabB);
});
it("keeps the source pane focused tab unchanged when dragging an unfocused tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:unfocused-drag";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
});
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
})!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().splitPane(workspaceKey, {
tabId: tabFile,
targetPaneId: "main",
position: "right",
});
expect(
findPaneById(store.getState().layoutByWorkspace[workspaceKey]!.root, "main")?.focusedTabId,
).toBe(tabA);
});
});
+103 -105
View File
@@ -18,6 +18,7 @@ import {
closePaneInLayout,
closeTabInLayout,
collectAllPanes,
collectAllPanesIncludingHidden,
collectAllTabs,
convertDraftToAgentInLayout,
createTabInLayout,
@@ -69,6 +70,10 @@ import { isSheetTabModified, resolveCompactSheetPolicy } from "@/workspace-tabs/
import { panelResourceKey, type CompactSheetPolicy } from "@/panels/panel-manifest";
import { createValidatedPersistStorage } from "@/storage/validated-persist-storage";
import { panelTargetSupportsHostForWorkspaceKey } from "@/plugins/workspace-panels/locations";
import {
syncPaneTabFocusHistory,
type PaneTabFocusHistory,
} from "@/stores/workspace-tab-focus-policy";
export {
AMBIENT_PLACEMENT,
@@ -153,6 +158,7 @@ interface WorkspaceLayoutStore {
pinnedAgentIdsByWorkspace: Record<string, Set<string>>;
hiddenAgentIdsByWorkspace: Record<string, Set<string>>;
focusRestorationByWorkspace: Record<string, WorkspaceFocusRestorationState>;
paneTabFocusHistoryByWorkspace: Record<string, PaneTabFocusHistory>;
explorerSidebarPaneIdByWorkspace: Record<string, string | null>;
sidePaneIdByWorkspace: Record<string, string | null>;
/** Workspaces where PR detection already added its tab once; a closed tab never returns. */
@@ -689,6 +695,35 @@ function withoutFocusRestoration(
return { focusRestorationByWorkspace };
}
function withUpdatedWorkspaceLayout(
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "paneTabFocusHistoryByWorkspace">,
workspaceKey: string,
nextLayout: WorkspaceLayout,
renamedTab?: { from: string; to: string } | null,
): Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "paneTabFocusHistoryByWorkspace"> {
const previousLayout = state.layoutByWorkspace[workspaceKey] ?? null;
const previousHistory = state.paneTabFocusHistoryByWorkspace[workspaceKey];
const nextHistory = syncPaneTabFocusHistory({
previousHistory,
previousPanes: previousLayout ? collectAllPanesIncludingHidden(previousLayout.root) : [],
nextPanes: collectAllPanesIncludingHidden(nextLayout.root),
renamedTab,
});
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[workspaceKey]: nextLayout,
},
paneTabFocusHistoryByWorkspace:
nextHistory === previousHistory
? state.paneTabFocusHistoryByWorkspace
: {
...state.paneTabFocusHistoryByWorkspace,
[workspaceKey]: nextHistory,
},
};
}
function reconcileRememberedSidePane(
state: WorkspaceLayoutStore,
workspaceKey: string,
@@ -873,6 +908,7 @@ function promoteSheetToTab(
now: tab.createdAt,
createTabId: () => tab.tabId,
state: tab.state,
paneFocusHistory: state.paneTabFocusHistoryByWorkspace[workspaceKey],
};
const result = isTargetOpenAsTab(placement.layout, tab.target)
? revealTargetInLayout(input)
@@ -900,7 +936,7 @@ function promoteSheetToTab(
tab.target.agentId,
)
: state.hiddenAgentIdsByWorkspace,
layoutByWorkspace: { ...state.layoutByWorkspace, [workspaceKey]: nextLayout },
...withUpdatedWorkspaceLayout(state, workspaceKey, nextLayout),
},
};
}
@@ -1109,6 +1145,7 @@ export function createWorkspaceLayoutStore(
pinnedAgentIdsByWorkspace: {},
hiddenAgentIdsByWorkspace: {},
focusRestorationByWorkspace: {},
paneTabFocusHistoryByWorkspace: {},
explorerSidebarPaneIdByWorkspace: {},
sidePaneIdByWorkspace: {},
pullRequestTabAutoOpenedByWorkspace: {},
@@ -1199,6 +1236,7 @@ export function createWorkspaceLayoutStore(
target: normalizedTarget,
now: Date.now(),
createTabId: createWorkspaceTabInstanceId,
paneFocusHistory: get().paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
});
}
if (!result) {
@@ -1220,6 +1258,13 @@ export function createWorkspaceLayoutStore(
placement.layout.focusedPaneId,
);
const shouldPinAgent = input.pin === true && normalizedTarget.kind === "agent";
const finalLayout = parentTabId
? attachParentTab({
layout: nextLayout,
childTabId: result.tabId,
parentTabId,
})
: nextLayout;
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...advancePanelRevision(state, normalizedWorkspaceKey, result.tabId, normalizedTarget),
@@ -1243,16 +1288,7 @@ export function createWorkspaceLayoutStore(
normalizedTarget.agentId,
)
: state.pinnedAgentIdsByWorkspace,
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: parentTabId
? attachParentTab({
layout: nextLayout,
childTabId: result.tabId,
parentTabId,
})
: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, finalLayout),
}));
return result.tabId;
},
@@ -1304,14 +1340,15 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey,
);
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: keepWorkspaceFocusOutOfExplorerSidebar(
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
keepWorkspaceFocusOutOfExplorerSidebar(
currentLayout,
paneId,
currentLayout.focusedPaneId,
),
},
),
explorerSidebarPaneIdByWorkspace: {
...state.explorerSidebarPaneIdByWorkspace,
[normalizedWorkspaceKey]: paneId,
@@ -1326,9 +1363,7 @@ export function createWorkspaceLayoutStore(
set((state) => {
const layout = state.layoutByWorkspace[workspaceKey];
const next = setPaneHiddenInLayout({ layout, paneId, hidden: false });
return next
? { layoutByWorkspace: { ...state.layoutByWorkspace, [workspaceKey]: next } }
: state;
return next ? withUpdatedWorkspaceLayout(state, workspaceKey, next) : state;
});
return paneId;
},
@@ -1351,12 +1386,7 @@ export function createWorkspaceLayoutStore(
return state;
}
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
};
return withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout);
});
},
ensureSidePane: (workspaceKey, options) => {
@@ -1388,13 +1418,13 @@ export function createWorkspaceLayoutStore(
}
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]:
options?.focus === false
? { ...result.layout, focusedPaneId: layout.focusedPaneId }
: result.layout,
},
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
options?.focus === false
? { ...result.layout, focusedPaneId: layout.focusedPaneId }
: result.layout,
),
sidePaneIdByWorkspace: {
...state.sidePaneIdByWorkspace,
[normalizedWorkspaceKey]: result.paneId,
@@ -1441,10 +1471,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...reconcileRememberedSidePane(state, normalizedWorkspaceKey, nextLayout),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
}
const closedLayout = closeTabInLayout({
@@ -1476,10 +1503,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...reconcileRememberedSidePane(state, normalizedWorkspaceKey, nextLayout),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
});
},
@@ -1541,9 +1565,9 @@ export function createWorkspaceLayoutStore(
...withoutFocusRestoration(state, normalizedWorkspaceKey),
// Choosing a tab dismisses the sheets that cover it.
...dismissSheets(state, normalizedWorkspaceKey),
layoutByWorkspace: nextLayout
? { ...state.layoutByWorkspace, [normalizedWorkspaceKey]: nextLayout }
: state.layoutByWorkspace,
...(nextLayout
? withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout)
: {}),
};
});
},
@@ -1567,10 +1591,11 @@ export function createWorkspaceLayoutStore(
focusRequest: { workspaceKey: normalizedWorkspaceKey, tabId: normalizedTabId },
// Choosing a tab dismisses the sheets that cover it.
...dismissSheets(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout ?? layout,
},
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
nextLayout ?? layout,
),
}
: state;
});
@@ -1622,6 +1647,8 @@ export function createWorkspaceLayoutStore(
state: tabState,
});
if (!result) return null;
const renamedTab =
result.tabId !== normalizedTabId ? { from: normalizedTabId, to: result.tabId } : null;
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...advancePanelRevision(state, normalizedWorkspaceKey, result.tabId, normalizedTarget),
@@ -1633,10 +1660,7 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey,
normalizedTarget.agentId,
),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout, renamedTab),
}));
return result.tabId;
},
@@ -1660,12 +1684,7 @@ export function createWorkspaceLayoutStore(
state: tabState,
});
if (!layout) return state;
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: layout,
},
};
return withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, layout);
});
},
convertDraftToAgent: (workspaceKey, tabId, agentId) => {
@@ -1690,6 +1709,8 @@ export function createWorkspaceLayoutStore(
return null;
}
const renamedTab =
result.tabId !== normalizedTabId ? { from: normalizedTabId, to: result.tabId } : null;
set((state) => ({
...(result.layout.focusedPaneId !== null
? (withoutFocusRestoration(state, normalizedWorkspaceKey) ?? {})
@@ -1699,10 +1720,7 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey,
normalizedAgentId,
),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout, renamedTab),
}));
return result.tabId;
@@ -1766,10 +1784,7 @@ export function createWorkspaceLayoutStore(
return {
...(sheetAgentGone ? withSheets(state, normalizedWorkspaceKey, fittingSheets) : {}),
pinnedAgentIdsByWorkspace,
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
});
},
@@ -1788,12 +1803,7 @@ export function createWorkspaceLayoutStore(
return state;
}
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
};
return withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout);
});
},
getWorkspaceTabs: (workspaceKey) => {
@@ -1842,6 +1852,7 @@ export function createWorkspaceLayoutStore(
position: input.position,
maxTreeDepth: MAX_TREE_DEPTH,
createNodeId: ids.createNodeId,
paneFocusHistory: get().paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
});
if (!result) {
return null;
@@ -1849,10 +1860,7 @@ export function createWorkspaceLayoutStore(
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout),
}));
return result.paneId;
@@ -1886,10 +1894,7 @@ export function createWorkspaceLayoutStore(
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout),
}));
return result.paneId;
@@ -1928,6 +1933,7 @@ export function createWorkspaceLayoutStore(
tabId: normalizedTabId,
toPaneId: normalizedToPaneId,
explorerSidebarPaneId,
paneFocusHistory: state.paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
});
if (!nextLayout) {
return state;
@@ -1945,10 +1951,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: normalizedNextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, normalizedNextLayout),
sidePaneIdByWorkspace:
rememberedSidePaneId &&
!findPaneById(normalizedNextLayout.root, rememberedSidePaneId)
@@ -1986,10 +1989,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
sidePaneIdByWorkspace:
state.sidePaneIdByWorkspace[normalizedWorkspaceKey] === normalizedPaneId
? {
@@ -2035,9 +2035,9 @@ export function createWorkspaceLayoutStore(
? { workspaceKey: normalizedWorkspaceKey, tabId: pane.focusedTabId }
: null,
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: nextLayout
? { ...state.layoutByWorkspace, [normalizedWorkspaceKey]: nextLayout }
: state.layoutByWorkspace,
...(nextLayout
? withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout)
: {}),
};
});
},
@@ -2061,11 +2061,11 @@ export function createWorkspaceLayoutStore(
tokens: [...(currentRestoration?.tokens ?? []), token],
},
},
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]:
layout.focusedPaneId === null ? layout : { ...layout, focusedPaneId: null },
},
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
layout.focusedPaneId === null ? layout : { ...layout, focusedPaneId: null },
),
};
});
return token;
@@ -2116,13 +2116,10 @@ export function createWorkspaceLayoutStore(
return {
focusRestorationByWorkspace: remainingRestorations,
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: {
...layout,
focusedPaneId: restorePaneId,
},
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, {
...layout,
focusedPaneId: restorePaneId,
}),
};
});
},
@@ -2175,10 +2172,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
});
},
@@ -2276,6 +2270,7 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey in state.pinnedAgentIdsByWorkspace ||
normalizedWorkspaceKey in state.hiddenAgentIdsByWorkspace ||
normalizedWorkspaceKey in state.focusRestorationByWorkspace ||
normalizedWorkspaceKey in state.paneTabFocusHistoryByWorkspace ||
normalizedWorkspaceKey in state.explorerSidebarPaneIdByWorkspace ||
normalizedWorkspaceKey in state.sidePaneIdByWorkspace ||
normalizedWorkspaceKey in state.pullRequestTabAutoOpenedByWorkspace ||
@@ -2303,6 +2298,8 @@ export function createWorkspaceLayoutStore(
state.hiddenAgentIdsByWorkspace;
const { [normalizedWorkspaceKey]: _restoration, ...focusRestorationByWorkspace } =
state.focusRestorationByWorkspace;
const { [normalizedWorkspaceKey]: _focusHistory, ...paneTabFocusHistoryByWorkspace } =
state.paneTabFocusHistoryByWorkspace;
const {
[normalizedWorkspaceKey]: _explorerSidebarPane,
...explorerSidebarPaneIdByWorkspace
@@ -2319,6 +2316,7 @@ export function createWorkspaceLayoutStore(
pinnedAgentIdsByWorkspace,
hiddenAgentIdsByWorkspace,
focusRestorationByWorkspace,
paneTabFocusHistoryByWorkspace,
explorerSidebarPaneIdByWorkspace,
sidePaneIdByWorkspace,
};
@@ -0,0 +1,115 @@
import { describe, expect, it } from "vitest";
import {
resolveTabDepartureSuccessor,
syncPaneTabFocusHistory,
} from "./workspace-tab-focus-policy";
describe("workspace tab departure focus policy", () => {
it("relocate prefers most recently focused remaining tab over parent and neighbor", () => {
const successor = resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
parentTabIdByTabId: { file: "b" },
paneFocusHistory: { main: ["file", "a", "b"] },
});
expect(successor).toBe("a");
});
it("relocate falls back to same-pane parent when focus history has no remaining tab", () => {
const successor = resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
parentTabIdByTabId: { file: "a" },
});
expect(successor).toBe("a");
});
it("relocate ignores a parent tab in another pane and falls back to source-pane neighbor", () => {
const successor = resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["other-pane-parent", "a", "b", "file"]),
parentTabIdByTabId: { file: "other-pane-parent" },
});
expect(successor).toBe("b");
});
it("close prefers open parent tab anywhere, then right neighbor, then left neighbor", () => {
expect(
resolveTabDepartureSuccessor("close", {
pane: { id: "main", tabIds: ["a", "file", "b"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["other-parent", "a", "file", "b"]),
parentTabIdByTabId: { file: "other-parent" },
paneFocusHistory: { main: ["file", "a", "b"] },
}),
).toBe("other-parent");
expect(
resolveTabDepartureSuccessor("close", {
pane: { id: "main", tabIds: ["a", "file", "b"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "file", "b"]),
paneFocusHistory: { main: ["file", "a", "b"] },
}),
).toBe("b");
expect(
resolveTabDepartureSuccessor("close", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
paneFocusHistory: { main: ["file", "a", "b"] },
}),
).toBe("b");
});
it("returns null when the departing tab is not focused", () => {
expect(
resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "a" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
}),
).toBeNull();
});
it("syncPaneTabFocusHistory seeds from prior focused tab, renames tabs, prunes closed tabs, and preserves identity when unchanged", () => {
const initial = syncPaneTabFocusHistory({
previousHistory: undefined,
previousPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "a" }],
nextPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
});
expect(initial).toEqual({ main: ["file", "a"] });
const unchanged = syncPaneTabFocusHistory({
previousHistory: initial,
previousPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
nextPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
});
expect(unchanged).toBe(initial);
const renamed = syncPaneTabFocusHistory({
previousHistory: initial,
previousPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
nextPanes: [{ id: "main", tabIds: ["agent-a", "b", "file"], focusedTabId: "file" }],
renamedTab: { from: "a", to: "agent-a" },
});
expect(renamed).toEqual({ main: ["file", "agent-a"] });
const pruned = syncPaneTabFocusHistory({
previousHistory: renamed,
previousPanes: [{ id: "main", tabIds: ["agent-a", "b", "file"], focusedTabId: "file" }],
nextPanes: [
{ id: "main", tabIds: ["agent-a", "b"], focusedTabId: "agent-a" },
{ id: "split", tabIds: ["file"], focusedTabId: "file" },
],
});
expect(pruned).toEqual({ main: ["agent-a"], split: ["file"] });
});
});
@@ -0,0 +1,145 @@
/**
* Per-pane tab focus recency, ordered most-recently-focused first.
* Kept in memory rather than persisted so strict layout storage stays unchanged.
*/
export type PaneTabFocusHistory = Record<string, readonly string[]>;
/**
* Why a pane is losing its currently focused tab:
* - "close": browser-style close returns to the tab's parent (if still open anywhere),
* otherwise steps to the adjacent neighbor (right, then left).
* - "relocate": split or move keeps the user's working context visible in the source pane
* by returning to the most recently focused remaining tab in that pane, then a same-pane
* parent tab (for example immediately after reload), then the adjacent neighbor.
*/
export type TabDepartureReason = "close" | "relocate";
export interface PaneFocusSnapshot {
id: string;
tabIds: readonly string[];
focusedTabId: string | null;
}
export interface TabDepartureContext {
pane: PaneFocusSnapshot;
departingTabId: string;
openTabIds: ReadonlySet<string>;
parentTabIdByTabId?: Record<string, string>;
paneFocusHistory?: PaneTabFocusHistory;
}
type TabSuccessorRule = (context: TabDepartureContext) => string | null;
function isRemainingInSourcePane(context: TabDepartureContext, tabId: string | null): boolean {
return Boolean(tabId && tabId !== context.departingTabId && context.pane.tabIds.includes(tabId));
}
const mostRecentlyFocusedInSourcePane: TabSuccessorRule = (context) => {
const recent = context.paneFocusHistory?.[context.pane.id];
return recent?.find((tabId) => isRemainingInSourcePane(context, tabId)) ?? null;
};
const openParentTabAnywhere: TabSuccessorRule = (context) => {
const parentTabId = context.parentTabIdByTabId?.[context.departingTabId] ?? null;
return parentTabId &&
parentTabId !== context.departingTabId &&
context.openTabIds.has(parentTabId)
? parentTabId
: null;
};
const parentTabInSourcePane: TabSuccessorRule = (context) => {
const parentTabId = context.parentTabIdByTabId?.[context.departingTabId] ?? null;
return isRemainingInSourcePane(context, parentTabId) ? parentTabId : null;
};
const adjacentNeighborInSourcePane: TabSuccessorRule = (context) => {
const tabIndex = context.pane.tabIds.indexOf(context.departingTabId);
if (tabIndex < 0) {
return null;
}
return (
context.pane.tabIds[tabIndex + 1] ??
(tabIndex > 0 ? context.pane.tabIds[tabIndex - 1] : null) ??
null
);
};
export const TAB_DEPARTURE_POLICIES: Record<TabDepartureReason, readonly TabSuccessorRule[]> = {
close: [openParentTabAnywhere, adjacentNeighborInSourcePane],
relocate: [mostRecentlyFocusedInSourcePane, parentTabInSourcePane, adjacentNeighborInSourcePane],
};
export function resolveTabDepartureSuccessor(
reason: TabDepartureReason,
context: TabDepartureContext,
): string | null {
if (context.pane.focusedTabId !== context.departingTabId) {
return null;
}
for (const rule of TAB_DEPARTURE_POLICIES[reason]) {
const candidate = rule(context);
if (candidate) {
return candidate;
}
}
return null;
}
function mapRenamedTabId(
tabId: string | null | undefined,
renamedTab: { from: string; to: string } | null | undefined,
): string | null {
if (!tabId) {
return null;
}
return renamedTab && tabId === renamedTab.from ? renamedTab.to : tabId;
}
export function syncPaneTabFocusHistory(input: {
previousHistory: PaneTabFocusHistory | undefined;
previousPanes: readonly PaneFocusSnapshot[];
nextPanes: readonly PaneFocusSnapshot[];
renamedTab?: { from: string; to: string } | null;
}): PaneTabFocusHistory {
const previous = input.previousHistory ?? {};
const previousFocusedByPaneId = new Map(
input.previousPanes.map((pane) => [pane.id, pane.focusedTabId]),
);
const next: Record<string, readonly string[]> = {};
let changed = Object.keys(previous).length !== input.nextPanes.length;
for (const pane of input.nextPanes) {
const openInPane = new Set(pane.tabIds);
const priorEntries = previous[pane.id] ?? [];
const updated: string[] = [];
const seen = new Set<string>();
const pushIfOpen = (tabId: string | null | undefined) => {
if (!tabId || seen.has(tabId) || !openInPane.has(tabId)) {
return;
}
seen.add(tabId);
updated.push(tabId);
};
pushIfOpen(pane.focusedTabId);
// Seed from the pane's prior focused tab so the first switch after hydration remembers it.
pushIfOpen(mapRenamedTabId(previousFocusedByPaneId.get(pane.id), input.renamedTab));
for (const entry of priorEntries) {
pushIfOpen(mapRenamedTabId(entry, input.renamedTab));
}
if (
!changed &&
(priorEntries.length !== updated.length ||
priorEntries.some((entry, index) => entry !== updated[index]))
) {
changed = true;
}
next[pane.id] = updated;
}
return changed ? next : previous;
}
+5 -27
View File
@@ -152,7 +152,7 @@ describe("normalizeStoredHostProfile", () => {
});
});
it("gives a host stored before appearance existed the default appearance without an icon key", () => {
it("gives a host stored before appearance existed the default appearance", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_old",
connections: [
@@ -161,35 +161,18 @@ describe("normalizeStoredHostProfile", () => {
});
expect(profile?.appearance).toEqual({ color: "none", badgeDisplay: null });
expect(profile && "icon" in profile.appearance).toBe(false);
});
it("loads a stored appearance the user chose", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_new",
appearance: { color: "teal", icon: "laptop", badgeDisplay: "icon" },
appearance: { color: "teal", badgeDisplay: "icon" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({ color: "teal", icon: "laptop", badgeDisplay: "icon" });
});
it("preserves an unknown stored icon intact without dropping the saved host", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_future_icon",
appearance: { color: "violet", icon: "future-device", badgeDisplay: "name" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({
color: "violet",
icon: "future-device",
badgeDisplay: "name",
});
expect(profile?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
});
it("normalizes stored Remote SSH connection parameters", () => {
@@ -357,13 +340,12 @@ describe("upsertHostConnectionInProfiles", () => {
});
expect(profile.appearance).toEqual({ color: "none", badgeDisplay: null });
expect("icon" in profile.appearance).toBe(false);
});
it("keeps the appearance the user chose when the host reconnects", () => {
const existing: HostProfile = {
...makeHost("srv_known"),
appearance: { color: "amber", icon: "workstation", badgeDisplay: "hidden" },
appearance: { color: "amber", badgeDisplay: "hidden" },
connections: [],
};
@@ -373,11 +355,7 @@ describe("upsertHostConnectionInProfiles", () => {
connection,
});
expect(profile.appearance).toEqual({
color: "amber",
icon: "workstation",
badgeDisplay: "hidden",
});
expect(profile.appearance).toEqual({ color: "amber", badgeDisplay: "hidden" });
});
it("replaces a direct connection when its settings change", () => {
@@ -143,11 +143,3 @@ export const Minimize = StubIcon;
export const Rows2 = StubIcon;
export const Gauge = StubIcon;
export const GripVertical = StubIcon;
export const Cloud = StubIcon;
export const Computer = StubIcon;
export const Container = StubIcon;
export const Cpu = StubIcon;
export const Laptop = StubIcon;
export const Network = StubIcon;
export const PcCase = StubIcon;
export const Waypoints = StubIcon;
+1 -14
View File
@@ -754,14 +754,13 @@ class DaemonClientSession {
private readonly daemon = new FakeDaemon();
private readonly client: DaemonClient;
constructor(options: { livenessHeartbeat?: boolean } = {}) {
constructor() {
this.client = new DaemonClient({
url: "ws://test",
clientId: "clsk_heartbeat_test",
logger: noopLogger,
reconnect: { enabled: false },
transportFactory: () => this.daemon.transport,
...options,
});
clients.push(this.client);
}
@@ -3396,18 +3395,6 @@ test("starts pinging one interval after connecting and holds the cadence", async
expect(session.pingTimestamps()).toEqual(["10s", "20s", "30s"]);
});
test("a client with the liveness heartbeat off never pings on its own", async () => {
useHeartbeatClock();
const session = new DaemonClientSession({ livenessHeartbeat: false });
session.daemonAnswersPingsAfter("fast");
await session.connect();
await session.advance(60_000);
expect(session.state()).toEqual({ status: "connected" });
expect(session.pingTimestamps()).toEqual([]);
});
test("stops pinging once the connection is gone", async () => {
useHeartbeatClock();
const session = new DaemonClientSession();
+1 -12
View File
@@ -473,13 +473,6 @@ export interface DaemonClientConfig {
runtimeMetricsWindowMs?: number;
trace?: DaemonClientTrace;
capabilities?: Partial<Record<ClientCapability, unknown>>;
/**
* Ping the daemon every 10 s and reconnect after missed replies (default true). Turn it off
* only where the transport reports its own loss (a plugin's IPC channel, an in-process
* channel): there a ping cannot find a dead link the channel would not, and it costs both
* processes a wakeup per client every 10 s.
*/
livenessHeartbeat?: boolean;
}
export interface DaemonClientTrace {
@@ -2749,11 +2742,7 @@ export class DaemonClient {
}
private scheduleNextLivenessHeartbeat(): void {
if (
this.config.livenessHeartbeat === false ||
this.connectionState.status !== "connected" ||
this.livenessHeartbeatTimer
) {
if (this.connectionState.status !== "connected" || this.livenessHeartbeatTimer) {
return;
}
this.livenessHeartbeatTimer = setTimeout(() => {
-3
View File
@@ -3970,9 +3970,6 @@ export const ServerInfoStatusPayloadSchema = z
serverId: z.string().trim().min(1),
hostname: ServerInfoHostnameSchema.optional(),
version: ServerInfoVersionSchema.optional(),
// Best-effort machine kind detected by the daemon (e.g. "laptop", "mini", "cloud").
// Loose string so unknown future kinds stay parseable across versions.
machineKind: z.string().nullable().optional(),
// Authenticated producer for host registration ownership, separate from admission authority.
sourceId: z.string().optional(),
// COMPAT(sessionPermissions): optional while clients support older daemons.
@@ -236,34 +236,6 @@ describe("wire schema compatibility", () => {
});
});
test("server info accepts optional machineKind and older clients drop it cleanly", () => {
const legacyServerInfo = z.object({
status: z.literal("server_info"),
serverId: z.string().trim().min(1),
hostname: z.string().nullable().optional(),
version: z.string().nullable().optional(),
});
const withKind = {
status: "server_info",
serverId: "macbook-server",
hostname: "mbp.local",
version: "0.9.5",
machineKind: "laptop",
};
expect(ServerInfoStatusPayloadSchema.parse(withKind).machineKind).toBe("laptop");
expect(
ServerInfoStatusPayloadSchema.parse({ ...withKind, machineKind: null }).machineKind,
).toBeNull();
expect(
ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "older-server",
}).machineKind,
).toBeUndefined();
expect(legacyServerInfo.parse(withKind)).not.toHaveProperty("machineKind");
});
test("assistant timeline message ids are optional on the wire", () => {
expect(
AgentTimelineItemPayloadSchema.parse({
@@ -1,12 +1,9 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import type { ChildProcess } from "node:child_process";
import {
query as sdkQuery,
type Options,
type Query,
type SpawnOptions as ClaudeSpawnOptions,
type SpawnedProcess,
import type {
Options,
Query,
SpawnOptions as ClaudeSpawnOptions,
} from "@anthropic-ai/claude-agent-sdk";
import { afterEach, describe, expect, test, vi } from "vitest";
@@ -105,72 +102,4 @@ describe("Claude spawn override", () => {
const spawnOptions = claudeSpawnCall?.[2];
expect(spawnOptions?.shell).toBe(false);
});
test("keeps the Paseo MCP bearer token off the Claude Code command line", async () => {
let capturedOptions: Options | undefined;
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
capturedOptions = options;
return createQueryMock([]);
});
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => "2.1.326",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
mcpServers: {
paseo: {
type: "http",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: { Authorization: "Bearer secret-token" },
},
},
});
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
await session.close();
if (!capturedOptions) {
throw new Error("Claude query options were not captured");
}
// Feed Paseo's options to the real SDK and record the argv it would launch with.
let launchArgs: string[] | undefined;
let stdinText = "";
const stdin = new PassThrough();
stdin.on("data", (chunk: Buffer) => {
stdinText += chunk.toString("utf8");
});
const abortController = new AbortController();
const sdk = sdkQuery({
prompt: "hello",
options: {
...capturedOptions,
abortController,
spawnClaudeCodeProcess: (spawnOptions: ClaudeSpawnOptions): SpawnedProcess => {
launchArgs = spawnOptions.args;
const child = new EventEmitter() as EventEmitter & SpawnedProcess;
Object.assign(child, {
stdin,
stdout: new PassThrough(),
killed: false,
exitCode: null,
kill: () => true,
});
return child;
},
},
});
// The fake process never answers, so the first message never arrives; only the launch matters.
void sdk.next().catch(() => undefined);
await vi.waitFor(() => {
expect(stdinText).toContain("secret-token");
});
abortController.abort();
expect(launchArgs).toBeDefined();
expect(launchArgs?.join(" ")).not.toContain("secret-token");
expect(launchArgs).not.toContain("--mcp-config");
});
});
@@ -449,12 +449,12 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
describe("a background subagent", () => {
// Shapes recorded from Claude Code 2.1.x: the launch returns at once with an async result,
// and a child stopped by an interrupt ends on the interrupt placeholder, not an end_turn.
function backgroundLaunch({ toolUseId = TOOL_USE_ID, agentId = AGENT_ID } = {}): string[] {
function backgroundLaunch(): string[] {
return [
parentEntry([
{
type: "tool_use",
id: toolUseId,
id: TOOL_USE_ID,
name: "Agent",
input: {
subagent_type: "general-purpose",
@@ -472,17 +472,17 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
content: [
{
type: "tool_result",
tool_use_id: toolUseId,
tool_use_id: TOOL_USE_ID,
content: [
{
type: "text",
text: `Async agent launched successfully.\nagentId: ${agentId}`,
text: `Async agent launched successfully.\nagentId: ${AGENT_ID}`,
},
],
},
],
},
toolUseResult: { isAsync: true, status: "async_launched", agentId },
toolUseResult: { isAsync: true, status: "async_launched", agentId: AGENT_ID },
}),
];
}
@@ -607,35 +607,17 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
expect(statuses).toContain("running");
});
function taskNotification({
status,
form = "user",
includeToolUseId = true,
taskIds = [AGENT_ID],
quoted = false,
}: {
status: string;
form?: string;
includeToolUseId?: boolean;
taskIds?: string[];
quoted?: boolean;
}): string {
const toolUseTag = includeToolUseId ? `<tool-use-id>${TOOL_USE_ID}</tool-use-id>\n` : "";
const taskTags = taskIds.map((id) => `<task-id>${id}</task-id>`).join("\n");
const notification = `<task-notification>\n${taskTags}\n${toolUseTag}<status>${status}</status>\n<summary>Background task ended</summary>\n</task-notification>`;
const text = quoted ? `Explain this log.\n${notification}` : notification;
function taskNotification(status: string, form = "user"): string {
const text = `<task-notification>\n<task-id>${AGENT_ID}</task-id>\n<tool-use-id>${TOOL_USE_ID}</tool-use-id>\n<status>${status}</status>\n<summary>Background task ended</summary>\n</task-notification>`;
const records = {
user: {
...(quoted ? {} : { origin: { kind: "task-notification" } }),
message: { role: "user", content: [{ type: "text", text }] },
},
user: { message: { role: "user", content: [{ type: "text", text }] } },
system: {
subtype: "task_notification",
task_id: AGENT_ID,
...(includeToolUseId ? { tool_use_id: TOOL_USE_ID } : {}),
tool_use_id: TOOL_USE_ID,
status,
},
"queue-operation": { operation: quoted ? "remove" : "enqueue", content: text },
"queue-operation": { operation: "enqueue", content: text },
};
return JSON.stringify({
type: form,
@@ -654,7 +636,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
`restores a %s task notification from ${form} when the child stop_reason is null`,
async (status, expected) => {
writeSession({
parentLines: [...backgroundLaunch(), taskNotification({ status, form })],
parentLines: [...backgroundLaunch(), taskNotification(status, form)],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: null })],
});
@@ -666,160 +648,9 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
);
}
for (const form of ["user", "system", "queue-operation"]) {
test.each([
["completed", "completed"],
["failed", "failed"],
["stopped", "canceled"],
["unknown", "running"],
])(`restores a task-id-only %s notification from ${form}`, async (status, expected) => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status, form, includeToolUseId: false }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({
id: TOOL_USE_ID,
status: expected,
});
});
}
test.each([
["user", false, "canceled"],
["queue-operation", false, "canceled"],
["user", true, "running"],
])(
"restores a shared %s notification with explicit tool-use ID present = %s",
async (form, includeToolUseId, secondStatus) => {
const secondAgentId = "a2222222222222222";
const secondToolUseId = "toolu_second";
const subagentDir = writeParentSession([
...backgroundLaunch(),
...backgroundLaunch({ agentId: secondAgentId, toolUseId: secondToolUseId }),
taskNotification({
status: "stopped",
form,
includeToolUseId,
taskIds: [AGENT_ID, "unrelated-task", secondAgentId],
}),
]);
writeSubagent({
subagentDir,
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
writeSubagent({
subagentDir,
agentId: secondAgentId,
sidechainLines: [sidechainEntry({ agentId: secondAgentId, stopReason: "tool_use" })],
});
const statuses = new Map();
for (const { id, status } of upserts(await replayDescriptors())) {
statuses.set(id, status);
}
expect(statuses).toEqual(
new Map([
[TOOL_USE_ID, "canceled"],
[secondToolUseId, secondStatus],
]),
);
},
);
test("keeps the latest outcome across task-only and tool-linked notifications", async () => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "stopped", form: "queue-operation", includeToolUseId: false }),
taskNotification({ status: "stopped", form: "user", includeToolUseId: false }),
taskNotification({ status: "completed" }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" });
});
test("honors a later task-only stopped notification after a tool-linked completion", async () => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "completed" }),
taskNotification({ status: "stopped", form: "user", includeToolUseId: false }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "canceled" });
});
test.each(["user", "queue-operation"])(
"keeps a completed child when a later %s record quotes a stopped notification",
async (form) => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "completed" }),
taskNotification({ status: "stopped", form, includeToolUseId: false, quoted: true }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" });
},
);
test("does not apply an unrelated task's stopped outcome to a child", async () => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "stopped", form: "user", includeToolUseId: false }).replace(
AGENT_ID,
"unrelated-task",
),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "running" });
});
test("restores a stopped child after a Bash result echoes its launch log", async () => {
const bashToolUseId = "toolu_bash";
writeSession({
parentLines: [
...backgroundLaunch(),
parentEntry([{ type: "tool_use", id: bashToolUseId, name: "Bash", input: {} }]),
JSON.stringify({
type: "user",
message: {
content: [
{
type: "tool_result",
tool_use_id: bashToolUseId,
content: `Async agent launched successfully.\nagentId: ${AGENT_ID}`,
},
],
},
}),
taskNotification({ status: "stopped", includeToolUseId: false }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({
id: TOOL_USE_ID,
status: "canceled",
});
});
test("prefers a stopped notification over the child's end_turn", async () => {
writeSession({
parentLines: [...backgroundLaunch(), taskNotification({ status: "stopped" })],
parentLines: [...backgroundLaunch(), taskNotification("stopped")],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "end_turn" })],
});
@@ -828,7 +659,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
test("does not invent an outcome for an unknown notification status", async () => {
writeSession({
parentLines: [...backgroundLaunch(), taskNotification({ status: "unknown" })],
parentLines: [...backgroundLaunch(), taskNotification("unknown")],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: null })],
});
@@ -1094,153 +1094,6 @@ describe("ClaudeAgentSession features", () => {
await session.close();
});
test.each([
{ claudeCodeVersion: "2.1.326", expected: "initialize" },
{ claudeCodeVersion: "2.2.0", expected: "initialize" },
{ claudeCodeVersion: "2.1.325", expected: "argv" },
{ claudeCodeVersion: undefined, expected: "argv" },
])(
"delivers MCP servers by $expected for Claude Code $claudeCodeVersion",
async ({ claudeCodeVersion, expected }) => {
const { queryFactory } = createQueryMock();
const client = new ClaudeAgentClient({
logger,
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => {
if (claudeCodeVersion === undefined) {
throw new Error("Unable to parse Claude Code version from --version output");
}
return claudeCodeVersion;
},
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
mcpServers: {
paseo: {
type: "http",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: { Authorization: "Bearer secret-token" },
},
},
});
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
expect(queryFactory.mock.calls[0]?.[0].options.mcpServersDelivery).toBe(expected);
await session.close();
},
);
test("probes the configured Claude command in the workspace with the session environment", async () => {
const { queryFactory, launches } = createQueryMock();
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "claude-mcp-workspace-"));
const versionProbe = `
const workspace = process.cwd().endsWith(${JSON.stringify(path.basename(cwd))});
const selected = workspace && process.env.TEST_CLAUDE_WORKSPACE_VERSION;
console.log((selected || "2.1.326") + " (Claude Code)");
`;
const client = new ClaudeAgentClient({
logger,
queryFactory,
runtimeSettings: {
command: { mode: "replace", argv: [process.execPath, "-e", versionProbe, "--"] },
},
});
try {
const session = await client.createSession(
{
provider: "claude",
cwd,
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
},
{ env: { TEST_CLAUDE_WORKSPACE_VERSION: "2.1.325" } },
);
try {
await session.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual(["argv"]);
} finally {
await session.close();
}
} finally {
await fs.rm(cwd, { recursive: true, force: true });
}
});
test("uses stdin on new launches and relaunches after Claude Code upgrades", async () => {
const { queryFactory, launches } = createQueryMock();
let version = "2.1.325";
const client = new ClaudeAgentClient({
logger,
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => version,
});
const config = {
provider: "claude",
cwd: process.cwd(),
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
} as const;
const existing = await client.createSession(config);
try {
await existing.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual(["argv"]);
version = "2.1.326";
const fresh = await client.createSession(config);
try {
await fresh.setModel?.("claude-sonnet-4-6");
await existing.setThinkingOption?.("high");
await existing.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual([
"argv",
"initialize",
"initialize",
]);
} finally {
await fresh.close();
}
} finally {
await existing.close();
}
});
test("warns about argv delivery only on launches with MCP servers", async () => {
const messages: string[] = [];
const { queryFactory } = createQueryMock();
const client = new ClaudeAgentClient({
logger: pino({}, { write: (message: string) => messages.push(JSON.parse(message).msg) }),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => "2.1.325",
});
const warnings = () => messages.filter((message) => message.includes("MCP server headers"));
const config = { provider: "claude", cwd: process.cwd() } as const;
const launch = async (sessionConfig: Parameters<typeof client.createSession>[0]) => {
const session = await client.createSession(sessionConfig);
try {
await session.setModel?.("claude-sonnet-4-6");
} finally {
await session.close();
}
};
await launch(config);
await launch({ ...config, mcpServers: {} });
expect(warnings()).toEqual([]);
const withMcp = {
...config,
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
} as const;
await launch(withMcp);
await launch(withMcp);
expect(warnings()).toEqual([
"Claude Code is too old or reports no version; MCP server headers go on its command line",
]);
});
test("passes extra Claude Code CLI arguments to the SDK", async () => {
const { queryFactory, launches } = createQueryMock();
const client = new ClaudeAgentClient({
@@ -39,7 +39,7 @@ import {
mapTaskNotificationSystemRecordToToolCall,
mapTaskNotificationUserContentToToolCall,
readTaskNotificationToolUseIdFromHistoryRecord,
readTaskNotificationOutcomeFromHistoryRecord,
readTaskNotificationFromHistoryRecord,
} from "./task-notification-tool-call.js";
import { isClaudeInterruptPlaceholderText } from "./interrupt-placeholder.js";
import {
@@ -54,7 +54,6 @@ import {
claudeManifestModelSupportsUltracode,
parseClaudeCodeVersion,
resolveClaudeDisabledThinkingForModel,
supportsClaudeMcpServersViaInitialize,
supportsIndependentClaudeUltracode,
} from "./model-manifest.js";
import { expandTilde } from "../../../../utils/path.js";
@@ -89,13 +88,7 @@ import {
} from "./options.js";
import { renderPromptAttachmentAsText } from "../../prompt-attachments.js";
import { discoverClaudeModels, killExitingClaudeModelDiscoveries } from "./model-discovery.js";
import {
claudeQuery,
probeClaudeLaunchVersion,
type ClaudeLaunchVersionProbe,
type ClaudeOptions,
type ClaudeQueryFactory,
} from "./query.js";
import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js";
import {
findSteeredMessageParent,
realClaudeRewindSdk,
@@ -520,14 +513,9 @@ interface ClaudeAgentSessionOptions {
queryFactory?: ClaudeQueryFactory;
resolveBinary: () => Promise<string>;
independentUltracode: boolean;
resolveMcpServersDelivery: (
launch: ClaudeLaunchVersionProbe,
) => Promise<ClaudeMcpServersDelivery>;
rewindSdk?: ClaudeRewindSdk;
}
type ClaudeMcpServersDelivery = NonNullable<ClaudeOptions["mcpServersDelivery"]>;
type ClaudeThinkingEffort = "low" | "medium" | "high" | "xhigh" | "max";
type ClaudeThinkingOption =
| ClaudeThinkingEffort
@@ -1658,11 +1646,7 @@ export class ClaudeAgentClient implements AgentClient {
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly resolveVersion: (signal?: AbortSignal) => Promise<string>;
private readonly resolveLaunchVersion: (
launch: ClaudeLaunchVersionProbe,
) => Promise<string | null>;
private version: Promise<string | undefined> | undefined;
private warnedMcpServersOnArgv = false;
private readonly lookupLatestRelease: LatestReleaseLookup;
private readonly rewindSdk: ClaudeRewindSdk;
private readonly scheduleImportDescriptors = createImportDescriptorScheduler(
@@ -1685,9 +1669,6 @@ export class ClaudeAgentClient implements AgentClient {
this.resolveVersion =
options.resolveVersion ??
((signal) => resolveClaudeCodeVersion(this.runtimeSettings, signal));
this.resolveLaunchVersion = options.resolveVersion
? () => this.resolveVersion()
: async (launch) => parseReportedClaudeVersion(await probeClaudeLaunchVersion(launch));
this.lookupLatestRelease =
options.lookupLatestRelease ??
((input) =>
@@ -1718,7 +1699,6 @@ export class ClaudeAgentClient implements AgentClient {
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
rewindSdk: this.rewindSdk,
});
}
@@ -1749,7 +1729,6 @@ export class ClaudeAgentClient implements AgentClient {
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
rewindSdk: this.rewindSdk,
});
await session.ensureHistoryReady();
@@ -1847,25 +1826,6 @@ export class ClaudeAgentClient implements AgentClient {
return supportsIndependentClaudeUltracode(await this.version);
}
private async resolveMcpServersDelivery(
launch: ClaudeLaunchVersionProbe,
): Promise<ClaudeMcpServersDelivery> {
// The installed version can change between SDK launches in the same session.
const version = (await this.resolveLaunchVersion(launch).catch(() => null)) ?? undefined;
if (supportsClaudeMcpServersViaInitialize(version)) {
return "initialize";
}
if (this.warnedMcpServersOnArgv) {
return "argv";
}
this.warnedMcpServersOnArgv = true;
this.logger.warn(
{ claudeCodeVersion: version ?? null },
"Claude Code is too old or reports no version; MCP server headers go on its command line",
);
return "argv";
}
async listImportableSessions(
options?: ListImportableSessionsOptions & { signal?: AbortSignal },
): Promise<ImportableProviderSession[]> {
@@ -2099,23 +2059,22 @@ async function readClaudeCodeVersion(
const installed = await resolveInstalledClaude(runtimeSettings);
if (!installed) return { status: "not_installed" };
const { executable } = installed;
const output = await execCommand(executable, [...installed.args, "--version"], {
const { stdout, stderr } = await execCommand(executable, [...installed.args, "--version"], {
...createProviderEnvSpec({ runtimeSettings }),
timeout: 5_000,
signal,
});
return { status: "installed", version: parseReportedClaudeVersion(output) };
}
function parseReportedClaudeVersion({ stdout, stderr }: { stdout: string; stderr: string }) {
// A wrapper command (the `command` provider setting) may print its own version here
// A wrapper command (the `command` provider setting) prints its own version here
// instead of Claude Code's. Only trust output that identifies itself as Claude Code,
// so a wrapper's version can't mis-gate models behind a minimumClaudeCodeVersion.
const rawVersionOutput = `${stdout}\n${stderr}`;
const version = /\d+\.\d+\.\d+\s+\(Claude Code\)/i.test(rawVersionOutput)
? parseClaudeCodeVersion(rawVersionOutput)
: null;
return version ? version.join(".") : null;
return {
status: "installed",
version: version ? version.join(".") : null,
};
}
async function resolveClaudeAuth(
@@ -2465,7 +2424,6 @@ class ClaudeAgentSession implements AgentSession {
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly independentUltracode: boolean;
private readonly resolveMcpServersDelivery: ClaudeAgentSessionOptions["resolveMcpServersDelivery"];
private query: Query | null = null;
private readonly runtimeSafety = new ClaudeRuntimeSafety();
private readonly backgroundStops = new Map<string, (outcome: string) => void>();
@@ -2605,7 +2563,6 @@ class ClaudeAgentSession implements AgentSession {
this.queryFactory = options.queryFactory;
this.resolveBinary = options.resolveBinary;
this.independentUltracode = options.independentUltracode;
this.resolveMcpServersDelivery = options.resolveMcpServersDelivery;
this.rewindSdk = options.rewindSdk ?? realClaudeRewindSdk;
this.contextUsage = new ClaudeContextUsageState(
getClaudeContextWindowMaxTokens(this.config.model),
@@ -4091,15 +4048,6 @@ class ClaudeAgentSession implements AgentSession {
if (this.config.mcpServers) {
base.mcpServers = this.normalizeMcpServers(this.config.mcpServers);
if (Object.keys(base.mcpServers).length > 0) {
base.mcpServersDelivery = await this.resolveMcpServersDelivery({
executable: claudeBinary,
cwd: this.config.cwd,
env: sdkEnv,
runtimeSettings: this.runtimeSettings,
launchEnv: this.launchEnv,
});
}
}
if (this.config.model) {
@@ -6821,8 +6769,10 @@ async function readClaudeReplayParentFacts(
const linksByAgentId = new Map<string, { toolCallId: string }>();
const outcomes: Map<string, { status: ProviderSubagentStatus }> = new Map();
for await (const entry of entries) {
for (const notificationOutcome of readClaudeReplayNotificationOutcomes(entry, linksByAgentId)) {
outcomes.set(notificationOutcome.toolCallId, { status: notificationOutcome.status });
const notification = readTaskNotificationFromHistoryRecord(entry);
const status = mapTaskStatus(notification?.status ?? undefined);
if (notification?.toolUseId && status) {
outcomes.set(notification.toolUseId, { status });
}
const content = toObjectRecord(entry.message)?.content;
if (!Array.isArray(content)) continue;
@@ -6840,7 +6790,6 @@ async function readClaudeReplayParentFacts(
outcomes.set(block.tool_use_id, {
status: block.is_error === true ? "failed" : "completed",
});
if (!toolCalls.has(block.tool_use_id)) continue;
const agentId = readLegacyClaudeSubagentId(block.content);
if (agentId)
linksByAgentId.set(agentId, {
@@ -6855,26 +6804,6 @@ async function readClaudeReplayParentFacts(
};
}
function* readClaudeReplayNotificationOutcomes(
entry: ClaudeHistoryEntry,
linksByAgentId: ReadonlyMap<string, { toolCallId: string }>,
): Generator<{ toolCallId: string; status: ProviderSubagentStatus }> {
const notification = readTaskNotificationOutcomeFromHistoryRecord(entry);
if (!notification) return;
const status = mapTaskStatus(notification.status ?? undefined);
if (!status) return;
if (notification.toolUseId) {
yield { toolCallId: notification.toolUseId, status };
return;
}
// Stopped tasks can omit tool-use-id; their launch results already link the native IDs.
for (const taskId of notification.taskIds) {
const link = linksByAgentId.get(taskId);
if (link) yield { toolCallId: link.toolCallId, status };
}
}
function readClaudeReplayTaskDeclaration(
entryType: unknown,
block: Record<string, unknown> | undefined,
@@ -347,27 +347,6 @@ export function supportsIndependentClaudeUltracode(version: string | undefined):
return version === undefined || compareVersions(version, "2.1.284") >= 0;
}
/**
* The Claude Code version bundled with the Agent SDK release that documents
* `mcpServersDelivery: "initialize"`. The SDK only guarantees that delivery for
* the bundled Claude Code or newer: an older binary exits on an unknown flag or
* has its session ended by the SDK.
*/
export const CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION = "2.1.326";
/**
* Whether MCP servers can reach Claude Code over stdin instead of `--mcp-config`
* on its command line, where any local user can read their headers and env.
* An unknown version (a wrapper command) stays on the command line so the
* session still starts.
*/
export function supportsClaudeMcpServersViaInitialize(version: string | undefined): boolean {
return (
version !== undefined &&
compareVersions(version, CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION) >= 0
);
}
export interface ClaudeDisabledThinkingResolution {
supported: boolean;
fallbackThinkingOptionId: string | undefined;
@@ -6,7 +6,7 @@ import {
type ProviderRuntimeSettings,
} from "../../provider-launch-config.js";
import { buildSelfNodeCommand, createExternalProcessEnv } from "../../../paseo-env.js";
import { execCommand, spawnProcess } from "../../../../utils/spawn.js";
import { spawnProcess } from "../../../../utils/spawn.js";
// Keep the raw SDK query import in this module only. Claude process launch behavior
// must stay shared between production and tests so Windows .cmd/.bat handling cannot
@@ -29,7 +29,7 @@ function isChildProcessWithStreams(child: ChildProcess): child is ChildProcessWi
}
function resolveClaudeSpawnCommand(
spawnOptions: Pick<SpawnOptions, "command" | "args">,
spawnOptions: SpawnOptions,
runtimeSettings?: ProviderRuntimeSettings,
): { command: string; args: string[] } {
const commandConfig = runtimeSettings?.command;
@@ -53,44 +53,11 @@ function resolveClaudeSpawnCommand(
};
}
type ClaudeLaunchEnvironment = Pick<ClaudeQueryContext, "runtimeSettings" | "launchEnv">;
function createClaudeSpawnEnvSpec(
baseEnv: SpawnOptions["env"],
{ runtimeSettings, launchEnv }: ClaudeLaunchEnvironment,
) {
const spec = createProviderEnvSpec({ baseEnv, runtimeSettings, overlays: [launchEnv] });
// Session-open hooks may supply a client identity. Clear inherited SDK/parent identities.
spec.envOverlay.CLAUDE_CODE_ENTRYPOINT = launchEnv?.CLAUDE_CODE_ENTRYPOINT;
return spec;
}
export interface ClaudeLaunchVersionProbe extends ClaudeLaunchEnvironment {
executable: string;
cwd: string;
env: SpawnOptions["env"];
}
export function probeClaudeLaunchVersion(
launch: ClaudeLaunchVersionProbe,
): Promise<{ stdout: string; stderr: string }> {
const { command, args } = resolveClaudeSpawnCommand(
{ command: launch.executable, args: ["--version"] },
launch.runtimeSettings,
);
return execCommand(command, args, {
...createClaudeSpawnEnvSpec(launch.env, launch),
cwd: launch.cwd,
shell: false,
timeout: 5_000,
});
}
function applyRuntimeSettingsToClaudeOptions(
options: ClaudeOptions,
context: ClaudeQueryContext,
): ClaudeOptions {
const { runtimeSettings, onChildProcess } = context;
const { runtimeSettings, launchEnv, onChildProcess } = context;
return {
...options,
spawnClaudeCodeProcess: (spawnOptions) => {
@@ -101,7 +68,14 @@ function applyRuntimeSettingsToClaudeOptions(
// When the SDK passes a native binary path (from pathToClaudeCodeExecutable)
// or the user overrides the command via runtime settings, use that directly.
const isDefaultRuntime = resolved.command === "node" || resolved.command === "bun";
const providerEnvSpec = createClaudeSpawnEnvSpec(spawnOptions.env, context);
const providerEnvSpec = createProviderEnvSpec({
baseEnv: spawnOptions.env,
runtimeSettings,
overlays: [launchEnv],
});
// Session-open hooks may explicitly supply a client identity. Keep inherited
// SDK/parent identities cleared while honoring this launch-only contribution.
providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = launchEnv?.CLAUDE_CODE_ENTRYPOINT;
const providerEnv = createExternalProcessEnv(spawnOptions.env, providerEnvSpec.envOverlay);
const selfNodeCommand = isDefaultRuntime
? buildSelfNodeCommand(resolved.args, providerEnv)
@@ -14,7 +14,7 @@ const OptionalNonEmptyTrimmedStringSchema = z.preprocess(
const TaskNotificationEnvelopeSchema = z.object({
notificationId: z.string().optional(),
messageId: z.string().nullable(),
taskIds: z.array(z.string()),
taskId: z.string().nullable(),
toolUseId: z.string().nullable(),
status: z.string().nullable(),
summary: z.string().nullable(),
@@ -44,10 +44,6 @@ const TaskNotificationHistoryRecordSchema = z
message_id: z.string().optional(),
task_id: z.string().optional(),
tool_use_id: z.string().optional(),
origin: z
.object({ kind: z.literal("task-notification") })
.optional()
.catch(undefined),
status: z.string().optional(),
summary: z.string().optional(),
output_file: z.string().optional(),
@@ -149,19 +145,6 @@ function readTaskNotificationTagValue(input: ReadTaskNotificationTagInput): stri
return toNonEmptyString(match[1]);
}
function readTaskNotificationTaskIds(rawText: string | null, structuredTaskId?: string): string[] {
const taskIds = [];
const taskId = toNonEmptyString(structuredTaskId);
if (taskId) taskIds.push(taskId);
if (rawText) {
for (const match of rawText.matchAll(/<task-id>([\s\S]*?)<\/task-id>/gi)) {
const taggedTaskId = toNonEmptyString(match[1]);
if (taggedTaskId) taskIds.push(taggedTaskId);
}
}
return [...new Set(taskIds)];
}
function parseTaskNotificationFromUserContent(
input: MapTaskNotificationUserContentToToolCallInput,
): TaskNotificationEnvelope | null {
@@ -178,7 +161,7 @@ function parseTaskNotificationFromUserContent(
return TaskNotificationEnvelopeSchema.parse({
notificationId: parsedInput.data.notificationId,
messageId: toNonEmptyString(parsedInput.data.messageId),
taskIds: readTaskNotificationTaskIds(rawText),
taskId: readTaskNotificationTagValue({ text: rawText, tagName: "task-id" }),
toolUseId:
readTaskNotificationTagValue({ text: rawText, tagName: "tool-use-id" }) ??
readTaskNotificationTagValue({ text: rawText, tagName: "tool_use_id" }),
@@ -210,7 +193,9 @@ function parseTaskNotificationFromSystemRecord(record: unknown): TaskNotificatio
return TaskNotificationEnvelopeSchema.parse({
notificationId: systemRecord.notificationId,
messageId: toNonEmptyString(systemRecord.uuid) ?? toNonEmptyString(systemRecord.message_id),
taskIds: readTaskNotificationTaskIds(rawText, systemRecord.task_id),
taskId:
toNonEmptyString(systemRecord.task_id) ??
(rawText ? readTaskNotificationTagValue({ text: rawText, tagName: "task-id" }) : null),
toolUseId:
toNonEmptyString(systemRecord.tool_use_id) ??
(rawText
@@ -251,7 +236,7 @@ export async function* assignTaskNotificationReplayIds<T>(
data.type === "user"
? parseTaskNotificationFromUserContent({ content: data.message?.content })
: parseTaskNotificationFromSystemRecord(data);
if (!envelope?.taskIds.length || !data.type) {
if (!envelope?.taskId || !data.type) {
yield entry;
continue;
}
@@ -278,7 +263,7 @@ function taskNotificationReplaySignature(envelope: TaskNotificationEnvelope): st
return createHash("sha1")
.update(
JSON.stringify([
envelope.taskIds.length > 1 ? envelope.taskIds : (envelope.taskIds[0] ?? null),
envelope.taskId,
envelope.toolUseId,
envelope.status,
envelope.summary,
@@ -301,8 +286,9 @@ function buildTaskNotificationCallId(envelope: TaskNotificationEnvelope): string
: null;
if (messageSegment) return `task_notification_${messageSegment}`;
const [taskId] = envelope.taskIds;
const taskSegment = taskId ? normalizeTaskNotificationCallIdSegment(taskId) : null;
const taskSegment = envelope.taskId
? normalizeTaskNotificationCallIdSegment(envelope.taskId)
: null;
if (taskSegment) return `task_notification_${taskSegment}`;
const seed =
@@ -348,11 +334,10 @@ function toTaskNotificationToolCall(
});
const label = buildTaskNotificationLabel(envelope);
const detailText = envelope.rawText ?? envelope.summary ?? undefined;
const [taskId] = envelope.taskIds;
const metadata: Record<string, unknown> = {
synthetic: true,
source: "claude_task_notification",
...(taskId ? { taskId } : {}),
...(envelope.taskId ? { taskId: envelope.taskId } : {}),
...(envelope.toolUseId ? { toolUseId: envelope.toolUseId } : {}),
...(envelope.status ? { status: envelope.status } : {}),
...(envelope.outputFile ? { outputFile: envelope.outputFile } : {}),
@@ -422,38 +407,18 @@ export function mapTaskNotificationSystemRecordToToolCall(
}
export function readTaskNotificationToolUseIdFromHistoryRecord(record: unknown): string | null {
const parsedRecord = TaskNotificationHistoryRecordSchema.safeParse(record);
return parsedRecord.success
? (parseTaskNotificationHistoryRecord(parsedRecord.data)?.toolUseId ?? null)
: null;
return readTaskNotificationFromHistoryRecord(record)?.toolUseId ?? null;
}
export function readTaskNotificationOutcomeFromHistoryRecord(
export function readTaskNotificationFromHistoryRecord(
record: unknown,
): TaskNotificationEnvelope | null {
const parsedRecord = TaskNotificationHistoryRecordSchema.safeParse(record);
if (!parsedRecord.success) return null;
const entry = parsedRecord.data;
if (entry.type === "user" && entry.origin?.kind !== "task-notification") return null;
if (entry.type === "queue-operation") {
const content = entry.content?.trim();
if (
!content?.startsWith(TASK_NOTIFICATION_MARKER) ||
!content.endsWith("</task-notification>")
) {
return null;
}
}
return parseTaskNotificationHistoryRecord(entry);
}
function parseTaskNotificationHistoryRecord(
record: TaskNotificationHistoryRecord,
): TaskNotificationEnvelope | null {
if (record.type === "user" && record.message) {
if (parsedRecord.data.type === "user" && parsedRecord.data.message) {
return parseTaskNotificationFromUserContent({
content: record.message.content,
messageId: record.uuid ?? record.message_id,
content: parsedRecord.data.message.content,
messageId: parsedRecord.data.uuid ?? parsedRecord.data.message_id,
});
}
return parseTaskNotificationFromSystemRecord(record);
@@ -477,12 +442,11 @@ export function coerceTaskNotificationHistoryRecordToSystemMessage(
status = "completed";
}
const [taskId] = parsed.taskIds;
return {
type: "system",
subtype: "task_notification",
...(parsed.messageId ? { uuid: parsed.messageId } : {}),
...(taskId ? { task_id: taskId } : {}),
...(parsed.taskId ? { task_id: parsed.taskId } : {}),
status,
...(parsed.summary ? { summary: parsed.summary } : {}),
...(parsed.outputFile ? { output_file: parsed.outputFile } : {}),
+1 -20
View File
@@ -16,7 +16,6 @@ import { createServer as createHTTPServer, type IncomingMessage, type ServerResp
import { constants, existsSync, unlinkSync } from "fs";
import { open, rm, stat } from "fs/promises";
import { randomUUID } from "node:crypto";
import { getCachedHostMachineKind, primeHostMachineKind } from "./host-machine-kind.js";
import { getHostName } from "./host-name.js";
import path from "node:path";
import { createMcpHandler } from "@modelcontextprotocol/server";
@@ -637,9 +636,6 @@ export async function createPaseoDaemon(
rootLogger: Logger,
dependencies: PaseoDaemonDependencies = {},
): Promise<PaseoDaemon> {
// Start hardware detection at the beginning of bootstrap so it overlaps with disk/registry init
// and does not hold up the listener when probes are slow.
const hostMachineKindReady = primeHostMachineKind();
configureGitProcessPolicy(config.git ?? resolveGitProcessPolicy({ env: process.env }));
const logger = rootLogger.child({ module: "bootstrap" });
const obsoleteTimelineDirectory = path.join(config.paseoHome, "agent-timelines");
@@ -878,13 +874,11 @@ export async function createPaseoDaemon(
});
app.get("/api/status", (_req, res) => {
const machineKind = getCachedHostMachineKind();
res.json({
status: "server_info",
serverId,
hostname: getHostName(),
version: daemonVersion,
...(machineKind ? { machineKind } : {}),
listen: formatListenTarget(boundListenTarget ?? listenTarget),
});
});
@@ -1815,20 +1809,7 @@ export async function createPaseoDaemon(
const start = async () => {
let mainStarted = false;
try {
let machineKindTimeout: ReturnType<typeof setTimeout> | null = null;
const [nextLocalCredential] = await Promise.all([
writeLocalCredential(config.paseoHome),
Promise.race([
hostMachineKindReady,
new Promise<void>((resolve) => {
machineKindTimeout = setTimeout(resolve, 150);
machineKindTimeout.unref();
}),
]).finally(() => {
if (machineKindTimeout) clearTimeout(machineKindTimeout);
}),
]);
localCredential = nextLocalCredential;
localCredential = await writeLocalCredential(config.paseoHome);
if (serviceProxyListenTarget) {
const boundServiceProxyTarget = await serviceProxy.startStandalone({
listenTarget: serviceProxyListenTarget,
@@ -1,94 +0,0 @@
import { describe, expect, it } from "vitest";
import {
classifyLinuxMachine,
classifyMacModel,
parseMacIoregProductName,
type LinuxMachineProbeInput,
} from "./host-machine-kind";
function linuxProbe(overrides: Partial<LinuxMachineProbeInput> = {}): LinuxMachineProbeInput {
return {
hasContainerMarker: false,
procVersion: null,
deviceTreeModel: null,
sysVendor: null,
productName: null,
biosVendor: null,
boardVendor: null,
chassisType: null,
...overrides,
};
}
describe("classifyMacModel", () => {
it.each([
["MacBookPro18,3", "laptop"],
["MacBookAir10,1", "laptop"],
["Macmini9,1", "mini"],
["iMac21,1", "desktop"],
["MacStudio1,1", "workstation"],
["MacPro7,1", "workstation"],
["Mac15,6", null],
["", null],
[null, null],
] as const)("maps %s to %s", (model, expected) => {
expect(classifyMacModel(model)).toBe(expected);
});
it("extracts Apple Silicon product-name from ioreg output", () => {
const ioreg = `
"model" = <"Mac15,6">
"product-name" = <"MacBook Pro">
`;
expect(classifyMacModel(parseMacIoregProductName(ioreg))).toBe("laptop");
});
});
describe("classifyLinuxMachine", () => {
it("detects containers before VM or chassis markers", () => {
expect(
classifyLinuxMachine(
linuxProbe({ hasContainerMarker: true, sysVendor: "Hetzner", chassisType: "17" }),
),
).toBe("container");
});
it("detects WSL as desktop", () => {
expect(
classifyLinuxMachine(
linuxProbe({ procVersion: "Linux version 5.15.153.1-microsoft-standard-WSL2" }),
),
).toBe("desktop");
});
it("detects single-board PCs from device-tree model", () => {
expect(
classifyLinuxMachine(linuxProbe({ deviceTreeModel: "Raspberry Pi 5 Model B Rev 1.0" })),
).toBe("board");
});
it("detects cloud VMs and hypervisors from DMI metadata", () => {
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Hetzner", productName: "vServer" }))).toBe(
"cloud",
);
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Amazon EC2" }))).toBe("cloud");
expect(classifyLinuxMachine(linuxProbe({ biosVendor: "QEMU" }))).toBe("cloud");
});
it("classifies bare-metal Linux machines by SMBIOS chassis type", () => {
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "LENOVO", chassisType: "10" }))).toBe(
"laptop",
);
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "ASUS", chassisType: "35" }))).toBe("mini");
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Dell Inc.", chassisType: "3" }))).toBe(
"desktop",
);
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Supermicro", chassisType: "23" }))).toBe(
"server",
);
});
it("returns null when no marker matches", () => {
expect(classifyLinuxMachine(linuxProbe())).toBeNull();
});
});
@@ -1,251 +0,0 @@
import { execFile } from "node:child_process";
import { access, readFile } from "node:fs/promises";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
export type HostMachineKind =
| "laptop"
| "desktop"
| "mini"
| "workstation"
| "cloud"
| "container"
| "board"
| "server";
const PROBE_TIMEOUT_MS = 1_500;
export function classifyMacModel(model: string | null | undefined): HostMachineKind | null {
const normalized = model?.trim().toLowerCase() ?? "";
if (!normalized) return null;
if (normalized.includes("macbook")) return "laptop";
if (normalized.includes("macmini") || normalized.includes("mac mini")) return "mini";
if (normalized.includes("imac")) return "desktop";
if (
normalized.includes("macstudio") ||
normalized.includes("mac studio") ||
normalized.includes("macpro") ||
normalized.includes("mac pro")
) {
return "workstation";
}
return null;
}
export interface LinuxMachineProbeInput {
hasContainerMarker: boolean;
procVersion: string | null;
deviceTreeModel: string | null;
sysVendor: string | null;
productName: string | null;
biosVendor: string | null;
boardVendor: string | null;
chassisType: string | null;
}
const BOARD_PATTERNS = [
"raspberry pi",
"orange pi",
"banana pi",
"rock pi",
"jetson",
"beaglebone",
"odroid",
"pine64",
"radxa",
] as const;
const CLOUD_OR_VM_MARKERS = [
"amazon",
"aws",
"ec2",
"google",
"gce",
"digitalocean",
"hetzner",
"linode",
"akamai",
"vultr",
"ovh",
"scaleway",
"oracle",
"qemu",
"kvm",
"vmware",
"virtualbox",
"xen",
"bochs",
"parallels",
"proxmox",
"hyper-v",
"virtual machine",
"openstack",
"upcloud",
"fly.io",
] as const;
const LAPTOP_CHASSIS_TYPES = new Set([8, 9, 10, 11, 14, 30, 31, 32]);
const DESKTOP_CHASSIS_TYPES = new Set([3, 4, 5, 6, 7, 13, 15, 16]);
const SERVER_CHASSIS_TYPES = new Set([17, 23, 25, 28, 29]);
export function classifyLinuxMachine(input: LinuxMachineProbeInput): HostMachineKind | null {
if (input.hasContainerMarker) {
return "container";
}
const procVersion = input.procVersion?.toLowerCase() ?? "";
if (procVersion.includes("microsoft") || procVersion.includes("wsl")) {
return "desktop";
}
const deviceTree = input.deviceTreeModel?.toLowerCase() ?? "";
if (deviceTree && BOARD_PATTERNS.some((pattern) => deviceTree.includes(pattern))) {
return "board";
}
const dmiText = [input.sysVendor, input.productName, input.biosVendor, input.boardVendor]
.filter((value): value is string => Boolean(value))
.join(" ")
.toLowerCase();
if (dmiText && CLOUD_OR_VM_MARKERS.some((marker) => dmiText.includes(marker))) {
return "cloud";
}
const chassis = Number.parseInt(input.chassisType?.trim() ?? "", 10);
if (Number.isInteger(chassis)) {
if (LAPTOP_CHASSIS_TYPES.has(chassis)) return "laptop";
if (chassis === 35) return "mini";
if (DESKTOP_CHASSIS_TYPES.has(chassis)) return "desktop";
if (SERVER_CHASSIS_TYPES.has(chassis)) return "server";
}
return null;
}
async function fileExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
async function readTrimmedFile(path: string): Promise<string | null> {
try {
const content = (await readFile(path, "utf8")).replaceAll("\u0000", "").trim();
return content.length > 0 ? content : null;
} catch {
return null;
}
}
export function parseMacIoregProductName(output: string): string | null {
const productMatch = output.match(/"product-name"\s*=\s*<"([^"]+)">/i);
if (productMatch?.[1]?.trim()) {
return productMatch[1].trim();
}
const modelMatch = output.match(/"model"\s*=\s*<"([^"]+)">/i);
return modelMatch?.[1]?.trim() ?? null;
}
async function readMacModel(): Promise<string | null> {
// Apple Silicon Macs report generic "Mac15,6" in sysctl hw.model, while IOPlatformExpertDevice
// exposes the human product name ("MacBook Pro", "Mac mini", "Mac Studio", etc.).
try {
const { stdout } = await execFileAsync(
"/usr/sbin/ioreg",
["-rd1", "-c", "IOPlatformExpertDevice"],
{
encoding: "utf8",
timeout: PROBE_TIMEOUT_MS,
},
);
const parsed = parseMacIoregProductName(stdout);
if (parsed && classifyMacModel(parsed)) {
return parsed;
}
} catch {
// Fall back to sysctl below.
}
try {
const { stdout } = await execFileAsync("/usr/sbin/sysctl", ["-n", "hw.model"], {
encoding: "utf8",
timeout: PROBE_TIMEOUT_MS,
});
const trimmed = stdout.trim();
return trimmed || null;
} catch {
return null;
}
}
export async function detectHostMachineKind(
platform: NodeJS.Platform = process.platform,
): Promise<HostMachineKind | null> {
if (platform === "darwin") {
return classifyMacModel(await readMacModel());
}
if (platform === "linux") {
const [
hasDockerEnv,
hasContainerEnv,
procVersion,
deviceTreeModel,
sysVendor,
productName,
biosVendor,
boardVendor,
chassisType,
] = await Promise.all([
fileExists("/.dockerenv"),
fileExists("/run/.containerenv"),
readTrimmedFile("/proc/version"),
readTrimmedFile("/proc/device-tree/model"),
readTrimmedFile("/sys/class/dmi/id/sys_vendor"),
readTrimmedFile("/sys/class/dmi/id/product_name"),
readTrimmedFile("/sys/class/dmi/id/bios_vendor"),
readTrimmedFile("/sys/class/dmi/id/board_vendor"),
readTrimmedFile("/sys/class/dmi/id/chassis_type"),
]);
return classifyLinuxMachine({
hasContainerMarker: hasDockerEnv || hasContainerEnv,
procVersion,
deviceTreeModel,
sysVendor,
productName,
biosVendor,
boardVendor,
chassisType,
});
}
return null;
}
let cachedMachineKind: HostMachineKind | null | undefined;
let pendingMachineKind: Promise<HostMachineKind | null> | null = null;
export function primeHostMachineKind(): Promise<HostMachineKind | null> {
if (cachedMachineKind !== undefined) {
return Promise.resolve(cachedMachineKind);
}
if (!pendingMachineKind) {
pendingMachineKind = detectHostMachineKind()
.then((kind) => {
cachedMachineKind = kind;
return kind;
})
.catch(() => {
cachedMachineKind = null;
return null;
});
}
return pendingMachineKind;
}
export function getCachedHostMachineKind(): HostMachineKind | null {
return cachedMachineKind ?? null;
}
@@ -16,7 +16,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import pino from "pino";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { DaemonConfigStore } from "../daemon-config-store.js";
import { PluginService } from "./index.js";
import { BuiltinPluginLoader } from "./builtin/index.js";
@@ -1905,229 +1905,210 @@ export default function contribute() {
]);
}, 120_000);
let home: string;
let service: PluginService;
let openService: () => PluginService;
let previousConfig: string | undefined;
let previousPath: string | undefined;
beforeEach(async () => {
home = await mkdtemp(path.join(tmpdir(), "paseo-npm-service-"));
previousConfig = process.env.npm_config_userconfig;
previousPath = process.env.PATH;
it("preserves dependencies and metadata, and reloads without npm", async () => {
const home = await mkdtemp(path.join(tmpdir(), "paseo-npm-service-"));
roots.push(home);
const previousConfig = process.env.npm_config_userconfig;
const previousPath = process.env.PATH;
process.env.npm_config_userconfig = registry.userconfig;
const store = createStore(home);
openService = () =>
const open = () =>
bindTestSessionHost(
new PluginService(pino({ level: "silent" }), store, "0.8.0", {
managedSources: new ManagedPluginSources(home),
}),
);
service = openService();
await service.start();
});
afterEach(async () => {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
if (previousConfig === undefined) delete process.env.npm_config_userconfig;
else process.env.npm_config_userconfig = previousConfig;
registry.setTag("paseo-fixture-plugin", "latest", "1.1.0");
await service.stopAllPlugins();
await rm(home, { recursive: true, force: true });
});
afterAll(async () => {
await registry?.close();
});
it("preserves dependencies and metadata, and reloads without npm", async () => {
const installed = await service.installSource({ source: "npm:paseo-fixture-plugin@^1.0.0" });
expect(installed).toMatchObject({
id: "npm-review",
status: "running",
installation: {
identity: { kind: "npm", packageName: "paseo-fixture-plugin", pluginPath: "." },
currentRevision: "1.1.0",
},
});
expect(installed.commit).toBeUndefined();
expect(installed.remote).toBeUndefined();
expect(
service
.getLogs("npm-review")
.map((entry) => entry.message)
.join("\n"),
).toContain("dependency loaded");
const installRoot = path.dirname(path.dirname(installed.path));
expect(
JSON.parse(await readFile(path.join(home, "plugins", "sources.json"), "utf8"))["npm-review"],
).toEqual({ kind: "npm" });
expect(
JSON.parse(await readFile(path.join(installRoot, "package-lock.json"), "utf8")).packages[
"node_modules/paseo-fixture-dependency"
].version,
).toBe("1.0.0");
expect(
await service.installSource({ source: "npm:@paseo-fixture/review", id: "scoped" }),
).toMatchObject({
id: "scoped",
status: "running",
installation: { currentRevision: "2.0.0" },
});
expect(registry.requests).not.toContain("/@getpaseo/plugin");
await expect(service.installSource({ source: "npm:paseo-fixture-plugin" })).rejects.toThrow(
"already configured",
);
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
await service.disablePlugin("scoped");
await service.stopAllPlugins();
const recordsPath = path.join(home, "plugins", "sources.json");
const oldRecords = JSON.parse(await readFile(recordsPath, "utf8"));
Object.assign(oldRecords["npm-review"], {
requestedSpec: "0.0.1",
version: "0.0.1",
packageName: "obsolete",
installRoot: "/obsolete",
integrity: "obsolete",
});
await writeFile(recordsPath, JSON.stringify(oldRecords));
process.env.PATH = path.join(home, "no-executables");
service = openService();
await service.start();
expect(await service.listPlugins()).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
id: "npm-review",
let service = open();
try {
await service.start();
const installed = await service.installSource({ source: "npm:paseo-fixture-plugin@^1.0.0" });
expect(installed).toMatchObject({
id: "npm-review",
status: "running",
installation: {
identity: { kind: "npm", packageName: "paseo-fixture-plugin", pluginPath: "." },
currentRevision: "1.1.0",
},
});
expect(installed.commit).toBeUndefined();
expect(installed.remote).toBeUndefined();
expect(
service
.getLogs("npm-review")
.map((entry) => entry.message)
.join("\n"),
).toContain("dependency loaded");
const installRoot = path.dirname(path.dirname(installed.path));
expect(
JSON.parse(await readFile(path.join(home, "plugins", "sources.json"), "utf8"))[
"npm-review"
],
).toEqual({ kind: "npm" });
expect(
JSON.parse(await readFile(path.join(installRoot, "package-lock.json"), "utf8")).packages[
"node_modules/paseo-fixture-dependency"
].version,
).toBe("1.0.0");
for (const [source, id, version] of [
["npm:paseo-fixture-plugin@1.0.0", "exact", "1.0.0"],
["paseo-fixture-plugin@stable", "tag", "1.0.0"],
["npm:@paseo-fixture/review", "scoped", "2.0.0"],
]) {
expect(await service.installSource({ source, id })).toMatchObject({
id,
status: "running",
installation: installed.installation,
}),
expect.objectContaining({ id: "scoped", enabled: false, status: "disabled" }),
]),
);
expect(await service.reloadPlugin("npm-review")).toMatchObject({
status: "running",
installation: installed.installation,
});
await expect(
service.installSource({ source: "npm:paseo-fixture-plugin", id: "missing-npm" }),
).rejects.toThrow("npm is required on the daemon host");
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
const packagePath = path.join(installed.path, "package.json");
const packageJson = await readFile(packagePath, "utf8");
await writeFile(packagePath, JSON.stringify({ ...JSON.parse(packageJson), version: "99.0.0" }));
const corrupt = (await service.listPlugins()).find((plugin) => plugin.id === "npm-review")!;
expect(corrupt.status).toBe("running");
expect(corrupt.installation).toEqual({ identity: installed.installation!.identity });
expect((await service.previewUpdates({ pluginId: "npm-review" }))[0]).toMatchObject({
outcome: "error",
error: expect.stringContaining("Installed revision is unavailable"),
});
expect(await service.reloadPlugin("npm-review")).toMatchObject({ status: "running" });
await writeFile(packagePath, packageJson);
await service.removePlugin("npm-review");
await expect(stat(installRoot)).rejects.toMatchObject({ code: "ENOENT" });
expect(
JSON.parse(await readFile(path.join(home, "plugins", "sources.json"), "utf8"))["npm-review"],
).toBeUndefined();
}, 120_000);
it("applies reviewed npm updates and downgrades", async () => {
expect(
await service.installSource({ source: "npm:paseo-fixture-plugin@1.0.0", id: "exact" }),
).toMatchObject({
id: "exact",
status: "running",
installation: { currentRevision: "1.0.0" },
});
const [preview] = await service.previewUpdates({ pluginId: "exact" });
expect(preview).toMatchObject({
outcome: "update",
current: { currentRevision: "1.0.0" },
target: { version: "1.1.0" },
});
const before = (await service.listPlugins()).find((item) => item.id === "exact")!;
await service.disablePlugin("exact");
registry.setTag("paseo-fixture-plugin", "latest", "2.0.0");
const results = await service.applyUpdates([
{ ...preview!.proposal!, id: "missing-plugin" },
preview!.proposal!,
]);
expect(results).toMatchObject([
{ outcome: "error" },
{
outcome: "updated",
plugin: { enabled: false, installation: { currentRevision: "1.1.0" } },
},
]);
expect(results[1]?.plugin?.installation?.identity).toEqual(before.installation?.identity);
registry.setTag("paseo-fixture-plugin", "latest", "1.1.0");
expect(await service.applyUpdates([preview!.proposal!])).toMatchObject([
{ outcome: "error", error: expect.stringContaining("changed since review") },
]);
await service.enablePlugin("exact");
const [future] = await service.previewUpdates({
pluginId: "exact",
target: { kind: "npm", version: "future" },
});
expect(await service.applyUpdates([future!.proposal!])).toMatchObject([
{ outcome: "updated", plugin: { installation: { currentRevision: "2.0.0" } } },
]);
const [newer] = await service.previewUpdates({ pluginId: "exact" });
expect(newer).toMatchObject({
outcome: "installed-newer",
current: { currentRevision: "2.0.0" },
target: { version: "1.1.0" },
});
expect(newer?.proposal).toBeUndefined();
const [downgrade] = await service.previewUpdates({
pluginId: "exact",
target: { kind: "npm", version: "1.0.0" },
});
const wrongArtifact = {
...downgrade!.proposal!,
target: { ...downgrade!.proposal!.target, integrity: "sha512-invalid" },
};
expect(await service.applyUpdates([wrongArtifact])).toMatchObject([{ outcome: "error" }]);
expect(await service.applyUpdates([downgrade!.proposal!])).toMatchObject([
{ outcome: "updated", plugin: { installation: { currentRevision: "1.0.0" } } },
]);
expect((await service.previewUpdates({ pluginId: "exact" }))[0]?.outcome).toBe("update");
await expect(service.updateSources("exact")).rejects.toThrow("Update the client");
}, 120_000);
it("prepares npm plugins and cleans up rejected installations", async () => {
expect(
await service.installSource({ source: "paseo-fixture-plugin@stable", id: "tag" }),
).toMatchObject({
id: "tag",
status: "running",
installation: { currentRevision: "1.0.0" },
});
const prepared = await service.installSource({
source: "npm:paseo-prepared-plugin@1.0.0:nested",
});
expect(prepared).toMatchObject({ id: "prepared", status: "running" });
expect(await readFile(path.join(prepared.path, "server/generated.js"), "utf8")).toBe(
"export default 42;",
);
expect(prepared.installation).toMatchObject({ identity: { pluginPath: "nested" } });
await service.removePlugin("prepared");
await expect(service.installSource({ source: "npm:missing-plugin" })).rejects.toThrow();
await expect(
service.installSource({ source: "npm:paseo-fixture-plugin", ref: "main" }),
).rejects.toThrow("--ref is only valid for Git");
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
for (const name of [
"bad-manifest",
"bad-build",
"bad-requirements",
"bad-code",
"bad-activation",
]) {
await expect(service.installSource({ source: `npm:${name}`, id: name })).rejects.toThrow();
expect((await service.listPlugins()).map((plugin) => plugin.id)).toEqual(["tag"]);
installation: { currentRevision: version },
});
}
const [preview] = await service.previewUpdates({ pluginId: "exact" });
expect(preview).toMatchObject({
outcome: "update",
current: { currentRevision: "1.0.0" },
target: { version: "1.1.0" },
});
const before = (await service.listPlugins()).find((item) => item.id === "exact")!;
await service.disablePlugin("exact");
registry.setTag("paseo-fixture-plugin", "latest", "2.0.0");
const results = await service.applyUpdates([
{ ...preview!.proposal!, id: "missing-plugin" },
preview!.proposal!,
]);
expect(results).toMatchObject([
{ outcome: "error" },
{
outcome: "updated",
plugin: { enabled: false, installation: { currentRevision: "1.1.0" } },
},
]);
expect(results[1]?.plugin?.installation?.identity).toEqual(before.installation?.identity);
registry.setTag("paseo-fixture-plugin", "latest", "1.1.0");
expect(await service.applyUpdates([preview!.proposal!])).toMatchObject([
{ outcome: "error", error: expect.stringContaining("changed since review") },
]);
await service.enablePlugin("exact");
const [future] = await service.previewUpdates({
pluginId: "exact",
target: { kind: "npm", version: "future" },
});
expect(await service.applyUpdates([future!.proposal!])).toMatchObject([
{ outcome: "updated", plugin: { installation: { currentRevision: "2.0.0" } } },
]);
const [newer] = await service.previewUpdates({ pluginId: "exact" });
expect(newer).toMatchObject({
outcome: "installed-newer",
current: { currentRevision: "2.0.0" },
target: { version: "1.1.0" },
});
expect(newer?.proposal).toBeUndefined();
const [downgrade] = await service.previewUpdates({
pluginId: "exact",
target: { kind: "npm", version: "1.0.0" },
});
const wrongArtifact = {
...downgrade!.proposal!,
target: { ...downgrade!.proposal!.target, integrity: "sha512-invalid" },
};
expect(await service.applyUpdates([wrongArtifact])).toMatchObject([{ outcome: "error" }]);
expect(await service.applyUpdates([downgrade!.proposal!])).toMatchObject([
{ outcome: "updated", plugin: { installation: { currentRevision: "1.0.0" } } },
]);
expect((await service.previewUpdates({ pluginId: "exact" }))[0]?.outcome).toBe("update");
await expect(service.updateSources("exact")).rejects.toThrow("Update the client");
const prepared = await service.installSource({
source: "npm:paseo-prepared-plugin@1.0.0:nested",
});
expect(prepared).toMatchObject({ id: "prepared", status: "running" });
expect(await readFile(path.join(prepared.path, "server/generated.js"), "utf8")).toBe(
"export default 42;",
);
expect(prepared.installation).toMatchObject({ identity: { pluginPath: "nested" } });
await service.removePlugin("prepared");
expect(registry.requests).not.toContain("/@getpaseo/plugin");
await expect(service.installSource({ source: "npm:missing-plugin" })).rejects.toThrow();
await expect(
service.installSource({ source: "npm:paseo-fixture-plugin", ref: "main" }),
).rejects.toThrow("--ref is only valid for Git");
await expect(service.installSource({ source: "npm:paseo-fixture-plugin" })).rejects.toThrow(
"already configured",
);
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
for (const name of [
"bad-manifest",
"bad-build",
"bad-requirements",
"bad-code",
"bad-activation",
]) {
await expect(service.installSource({ source: `npm:${name}`, id: name })).rejects.toThrow();
expect((await service.listPlugins()).map((plugin) => plugin.id)).toEqual([
"exact",
"npm-review",
"scoped",
"tag",
]);
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
}
await service.disablePlugin("scoped");
await service.stopAllPlugins();
const recordsPath = path.join(home, "plugins", "sources.json");
const oldRecords = JSON.parse(await readFile(recordsPath, "utf8"));
Object.assign(oldRecords["npm-review"], {
requestedSpec: "0.0.1",
version: "0.0.1",
packageName: "obsolete",
installRoot: "/obsolete",
integrity: "obsolete",
});
await writeFile(recordsPath, JSON.stringify(oldRecords));
process.env.PATH = path.join(home, "no-executables");
service = open();
await service.start();
expect(await service.listPlugins()).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
id: "npm-review",
status: "running",
installation: installed.installation,
}),
expect.objectContaining({ id: "scoped", enabled: false, status: "disabled" }),
]),
);
expect(await service.reloadPlugin("npm-review")).toMatchObject({
status: "running",
installation: installed.installation,
});
await expect(
service.installSource({ source: "npm:paseo-fixture-plugin", id: "missing-npm" }),
).rejects.toThrow("npm is required on the daemon host");
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
const packagePath = path.join(installed.path, "package.json");
const packageJson = await readFile(packagePath, "utf8");
await writeFile(
packagePath,
JSON.stringify({ ...JSON.parse(packageJson), version: "99.0.0" }),
);
const corrupt = (await service.listPlugins()).find((plugin) => plugin.id === "npm-review")!;
expect(corrupt.status).toBe("running");
expect(corrupt.installation).toEqual({ identity: installed.installation!.identity });
expect((await service.previewUpdates({ pluginId: "npm-review" }))[0]).toMatchObject({
outcome: "error",
error: expect.stringContaining("Installed revision is unavailable"),
});
expect(await service.reloadPlugin("npm-review")).toMatchObject({ status: "running" });
await writeFile(packagePath, packageJson);
await service.removePlugin("npm-review");
await expect(stat(installRoot)).rejects.toMatchObject({ code: "ENOENT" });
expect(
JSON.parse(await readFile(path.join(home, "plugins", "sources.json"), "utf8"))[
"npm-review"
],
).toBeUndefined();
} finally {
process.env.PATH = previousPath;
if (previousConfig === undefined) delete process.env.npm_config_userconfig;
else process.env.npm_config_userconfig = previousConfig;
await service.stopAllPlugins();
await registry.close();
}
}, 120_000);
});
@@ -466,9 +466,6 @@ export function createPluginWorker(options: {
// The runtime re-attaches a session when the daemon drops this socket.
reconnect: { enabled: true },
transportFactory,
// The channel is a pipe to the daemon (or an in-process queue for built-in plugins); its
// loss is reported directly, so a 10 s ping would only wake both sides.
livenessHeartbeat: false,
});
paseo = createPaseoApi(daemonClient);
await daemonClient.connect();
@@ -916,7 +913,6 @@ export function createPluginWorker(options: {
if (process.argv[1] === fileURLToPath(import.meta.url)) {
let worker: ReturnType<typeof createPluginWorker> | null = null;
let closedByShutdown = false;
const handlers = new Set<(message: PluginProcessRequest) => void>();
const channel: PluginWorkerChannel = {
send(message, callback) {
@@ -930,17 +926,9 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
};
},
disconnect() {
closedByShutdown = true;
process.disconnect();
},
};
// The daemon worker owns this process through the IPC channel. When the channel closes without
// this process closing it (the worker crashed or was killed), nothing can reach the plugin any
// more, so exit instead of running on as an orphan. A normal shutdown closes the channel itself
// and lets work still in flight finish.
process.once("disconnect", () => {
if (!closedByShutdown) process.exit(0);
});
process.on("message", (raw) => {
const parsed = PluginProcessRequestSchema.safeParse(raw);
if (!worker && parsed.success && parsed.data.type === "initialize") {
@@ -7,7 +7,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import pino from "pino";
import type { ProviderEvent, ProviderRegistration } from "@getpaseo/plugin/server/provider";
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { AgentStreamEvent } from "../agent/agent-sdk-types.js";
import { PluginAgentClientRegistry } from "../agent/plugin-provider.js";
import { PluginRuntime } from "./runtime.js";
@@ -1982,40 +1982,6 @@ export default function contribute(plugin: any) {
);
});
it("exits a plugin process when its channel to the daemon closes without a shutdown", async () => {
const directory = await createPlugin(
"orphaned",
// A timer keeps the process alive the way a polling plugin does.
`export default function contribute(plugin: unknown) {
void plugin;
const timer = setInterval(() => undefined, 1_000);
return () => clearInterval(timer);
}`,
);
const spawned: Array<ReturnType<typeof spawnObservedPluginProcess>> = [];
const exits: Array<Promise<number | null>> = [];
const runtime = createTestRuntime({
spawnChild: () => {
const child = spawnObservedPluginProcess(() => undefined);
exits.push(new Promise((resolve) => child.once("exit", resolve)));
spawned.push(child);
return child;
},
});
// If the process never exits (the failure this test catches), do not leave it running.
onTestFinished(() => {
for (const child of spawned) if (child.exitCode === null) child.kill("SIGKILL");
});
await runtime.startPlugin("orphaned", directory);
expect(spawned).toHaveLength(1);
// What the plugin sees when its daemon worker dies: the IPC channel closes, no shutdown request.
spawned[0]!.disconnect();
// In a real crash the daemon side is gone, so there is no runtime state left to stop here.
await expect(exits[0]).resolves.toBe(0);
});
it("reports and removes a plugin it terminated for an invalid message", async () => {
const directory = await createPlugin(
"invalid-message",
@@ -26,7 +26,6 @@ import { MessageReceipts } from "./message-receipts/index.js";
import { WebSocket, WebSocketServer } from "ws";
import type { IncomingMessage, Server as HTTPServer } from "http";
import { join } from "path";
import { getCachedHostMachineKind } from "./host-machine-kind.js";
import { getHostName } from "./host-name.js";
import { randomUUID } from "node:crypto";
import { monitorEventLoopDelay } from "node:perf_hooks";
@@ -2061,14 +2060,12 @@ export class VoiceAssistantWebSocketServer {
}
private buildServerInfoStatusPayload(session: Session): ServerInfoStatusPayload {
const machineKind = getCachedHostMachineKind();
return {
status: "server_info",
protocolVersion: WS_PROTOCOL_VERSION,
serverId: this.serverId,
hostname: getHostName(),
version: this.daemonVersion,
...(machineKind ? { machineKind } : {}),
sourceId: session.getHostSourceId(),
permissions: session.getPermissions(),
// COMPAT(desktopManaged): added in v0.1.X, remove optional parsing after 2027-01-16.
@@ -1,4 +1,4 @@
import { Computer, Globe, Laptop, Monitor, PcCase, Plus, Server, Terminal } from "lucide-react";
import { Computer, Globe, Laptop, Monitor, PcCase, Plus, Server, Terminal, X } from "lucide-react";
import type * as React from "react";
import { useTranslation } from "react-i18next";
import { TailscaleMark } from "./icons";
@@ -53,6 +53,7 @@ interface ConnectedHost {
endpoint?: string;
/** Round trip time, formatted as the app's `formatLatency` prints it. */
latency: string;
agents: number;
}
const CONNECTED_HOSTS: ConnectedHost[] = [
@@ -62,6 +63,7 @@ const CONNECTED_HOSTS: ConnectedHost[] = [
tone: "text-mock-fg-muted",
link: "local",
latency: "1ms",
agents: 4,
},
{
name: "devbox",
@@ -70,6 +72,7 @@ const CONNECTED_HOSTS: ConnectedHost[] = [
link: "relay",
endpoint: "relay.paseo.sh",
latency: "38ms",
agents: 6,
},
{
name: "mac-mini",
@@ -78,6 +81,7 @@ const CONNECTED_HOSTS: ConnectedHost[] = [
link: "tailscale",
endpoint: "mac-mini:6767",
latency: "12ms",
agents: 3,
},
{
name: "workstation",
@@ -86,41 +90,39 @@ const CONNECTED_HOSTS: ConnectedHost[] = [
link: "ssh",
endpoint: "mo@workstation",
latency: "24ms",
agents: 2,
},
];
function HostRow({ host, highlighted }: { host: ConnectedHost; highlighted?: boolean }) {
function HostRow({ host }: { host: ConnectedHost }) {
const { t } = useTranslation();
const Device = host.device;
const LinkIcon = LINK_ICON[host.link];
return (
<div
className={`mx-[4px] flex items-start gap-[8px] rounded-[6px] px-[8px] py-[8px] ${highlighted ? "bg-mock-surface2" : ""}`}
>
<span className="flex h-[18px] w-[16px] shrink-0 items-center justify-center">
<span className="size-[8px] rounded-full bg-mock-dot-success" />
<div className="flex items-center gap-[13px] border-t border-mock-border px-[18px] py-[13px]">
<span
className={`relative flex size-[36px] shrink-0 items-center justify-center rounded-[9px] bg-mock-surface2 ${host.tone}`}
>
<Device size={18} />
<span className="absolute -right-[2px] -bottom-[2px] size-[9px] rounded-full bg-mock-dot-success ring-2 ring-mock-surface1" />
</span>
<span className="min-w-0 flex-1">
<span className="flex items-center gap-[6px]">
<span className={`shrink-0 ${host.tone}`}>
<Device size={14} />
</span>
<span className="min-w-0 flex-1 truncate text-[13.5px] leading-[18px] text-mock-fg">
{host.name}
</span>
<span className="block truncate text-[13.5px] leading-[18px] text-mock-fg">
{host.name}
</span>
<span className="mt-[2px] flex items-center gap-[6px] text-[12px] leading-[16px] text-mock-fg-muted">
<span className="flex w-[14px] shrink-0 items-center justify-center">
<LinkIcon size={11} className="shrink-0 opacity-70" />
</span>
<span className="shrink-0">{t(`landing.mockup.app.hostLinks.${host.link}`)}</span>
{host.endpoint ? (
<span className="min-w-0 truncate opacity-70">{host.endpoint}</span>
) : null}
<span className="mt-[3px] flex items-center gap-[6px] text-[12px] leading-[16px] text-mock-fg-muted">
<LinkIcon size={12} className="shrink-0" />
<span className="text-mock-fg">{t(`landing.mockup.app.hostLinks.${host.link}`)}</span>
{host.endpoint ? <span className="min-w-0 truncate">{host.endpoint}</span> : null}
</span>
</span>
<span className="flex h-[18px] shrink-0 items-center text-right text-[12px] leading-[16px] text-mock-fg-muted tabular-nums">
{host.latency}
<span className="shrink-0 text-right">
<span className="block text-[13px] leading-[18px] text-mock-fg tabular-nums">
{host.latency}
</span>
<span className="mt-[3px] block text-[12px] leading-[16px] text-mock-fg-muted">
{t("landing.mockup.app.agentCount", { count: host.agents })}
</span>
</span>
</div>
);
@@ -128,23 +130,25 @@ function HostRow({ host, highlighted }: { host: ConnectedHost; highlighted?: boo
/**
* Every machine this window is connected to: what kind of machine it is, how the app reaches it,
* and its round trip time.
* the round trip time, and how many agents it runs.
*/
export function HostsModal() {
const { t } = useTranslation();
return (
<div className="w-[348px] overflow-hidden rounded-[10px] border border-mock-border-accent bg-mock-surface1 py-[4px] shadow-[0_24px_64px_rgba(0,0,0,0.55)]">
<div className="px-[12px] pt-[4px] pb-[2px] text-[11.5px] font-medium text-mock-fg-muted">
{t("landing.mockup.app.hosts")}
<div className="w-[468px] overflow-hidden rounded-[14px] border border-mock-border-accent bg-mock-surface1 shadow-[0_24px_64px_rgba(0,0,0,0.55)]">
<div className="flex h-[46px] items-center justify-between px-[18px]">
<span className="text-[14px] font-medium text-mock-fg">
{t("landing.mockup.app.hosts")}
</span>
<X size={15} className="text-mock-fg-muted" />
</div>
{CONNECTED_HOSTS.map((host, index) => (
<HostRow key={host.name} host={host} highlighted={index === 1} />
{CONNECTED_HOSTS.map((host) => (
<HostRow key={host.name} host={host} />
))}
<div className="my-[4px] border-t border-mock-border" />
<div className="mx-[4px] flex items-center gap-[8px] rounded-[6px] px-[8px] py-[8px] text-[13px] text-mock-fg">
{/* The plus sits on the center line of the status dots above it. */}
<span className="flex size-[16px] shrink-0 items-center justify-center">
<Plus size={16} className="text-mock-fg-muted" />
<div className="flex h-[46px] items-center gap-[13px] border-t border-mock-border px-[18px] text-[13px] text-mock-fg">
{/* The plus sits on the center line of the device tiles above it. */}
<span className="flex w-[36px] shrink-0 justify-center">
<Plus size={15} className="text-mock-fg-muted" />
</span>
{t("landing.mockup.app.addHost")}
</div>
@@ -498,6 +498,7 @@
"addProject": "Add project",
"addHost": "Add host",
"hosts": "Hosts",
"agentCount": "{{count}} agents",
"hostLinks": {
"local": "Local",
"relay": "Relay",
@@ -498,6 +498,7 @@
"addProject": "添加 project",
"addHost": "添加主机",
"hosts": "主机",
"agentCount": "{{count}} 个 Agent",
"hostLinks": {
"local": "本地",
"relay": "中继",