mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 09:46:05 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42a7cf0a16 | ||
|
|
e504877752 | ||
|
|
096de6a1f6 | ||
|
|
7ee7c2adbf | ||
|
|
2531ba2542 | ||
|
|
ed21847121 | ||
|
|
8ad8c40d67 | ||
|
|
685a4f2ad2 | ||
|
|
b8516bb2c1 | ||
|
|
0d0aa27584 | ||
|
|
e06bfbb94c | ||
|
|
7bcd598f09 | ||
|
|
c626bf3707 |
@@ -422,7 +422,6 @@
|
||||
"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",
|
||||
@@ -554,7 +553,6 @@
|
||||
"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,6 +4,7 @@ import {
|
||||
addConnectedHostAndReload,
|
||||
chooseHostBadgeDisplay,
|
||||
chooseHostColor,
|
||||
chooseHostIcon,
|
||||
expectHostAppearancePreview,
|
||||
expectHostBadgeIconOnly,
|
||||
expectHostBadgeName,
|
||||
@@ -115,12 +116,21 @@ 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 apply it to the sidebar badge", async () => {
|
||||
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", 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 () => {
|
||||
@@ -145,3 +155,30 @@ 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();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -4,10 +4,15 @@ import { copyFile, mkdir, rm, utimes, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { TestInfo } from "@playwright/test";
|
||||
import type { FetchRecentProviderSessionsRequestMessage } from "@getpaseo/protocol/messages";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { addConnectedHostAndReload } from "../support/helpers/hosts";
|
||||
import { ImportSessionFlow } from "../support/helpers/import-session";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import {
|
||||
connectNewWorkspaceDaemonClient,
|
||||
loadSessionMessageReaders,
|
||||
openProjectViaDaemon,
|
||||
type OpenedProject,
|
||||
} from "../support/helpers/new-workspace";
|
||||
@@ -20,16 +25,22 @@ const SCREENSHOT_DIRECTORY = path.join(
|
||||
const claudeConfigDirectory = mkdtempSync(path.join(tmpdir(), "paseo-import-flow-claude-"));
|
||||
const brokenProvider = "broken-acp";
|
||||
|
||||
const disabledProviders = {
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
antigravity: { enabled: false },
|
||||
muse: { enabled: false },
|
||||
};
|
||||
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
...disabledProviders,
|
||||
[brokenProvider]: {
|
||||
extends: "acp",
|
||||
label: "Broken ACP",
|
||||
@@ -136,6 +147,120 @@ test("an open Import Session row keeps its age current", async ({ page }) => {
|
||||
await expect(row).toContainText("4m ago");
|
||||
});
|
||||
|
||||
test("shows listing failure details beside healthy sessions and retries the failed provider", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const frames = await loadSessionMessageReaders();
|
||||
const requests: FetchRecentProviderSessionsRequestMessage[] = [];
|
||||
const completed = new Set<string>();
|
||||
page.on("websocket", (socket) => {
|
||||
socket.on("framesent", ({ payload }) => {
|
||||
const request = frames.client(payload);
|
||||
if (request?.type === "fetch_recent_provider_sessions_request") {
|
||||
requests.push(request);
|
||||
}
|
||||
});
|
||||
socket.on("framereceived", ({ payload }) => {
|
||||
const response = frames.server(payload);
|
||||
if (response?.type === "fetch_recent_provider_sessions_response") {
|
||||
completed.add(response.payload.requestId);
|
||||
}
|
||||
});
|
||||
});
|
||||
const flow = new ImportSessionFlow(page);
|
||||
for (const width of [1280, 390]) {
|
||||
await flow.openWorkspace(scenario.project.workspaceId, { width, height: 844 });
|
||||
await flow.openGlobally();
|
||||
await flow.expectProviderError("Broken ACP");
|
||||
const healthySession = page.getByTestId(
|
||||
`import-session-session-claude-${scenario.importSessionId}`,
|
||||
);
|
||||
await expect(healthySession).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath(`listing-failure-${width}.png`) });
|
||||
await expect(page.getByTestId("import-session-provider-errors")).toContainText(
|
||||
"missing-agent-command",
|
||||
);
|
||||
|
||||
const requestOffset = requests.length;
|
||||
await flow.retryProvider(brokenProvider, "Broken ACP");
|
||||
await expect
|
||||
.poll(() => requests.slice(requestOffset).map((request) => request.providers))
|
||||
.toEqual([[brokenProvider]]);
|
||||
const retriedRequest = requests[requestOffset];
|
||||
if (!retriedRequest) throw new Error("Retry did not send a provider listing request");
|
||||
await expect.poll(() => completed.has(retriedRequest.requestId)).toBe(true);
|
||||
await expect(page.getByTestId(`import-session-retry-${brokenProvider}`)).toBeEnabled();
|
||||
await expect(page.getByTestId("import-session-provider-errors")).toContainText(
|
||||
"missing-agent-command",
|
||||
);
|
||||
await expect(healthySession).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath(`listing-failure-retry-${width}.png`) });
|
||||
await flow.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("Import Session keeps listings tied to their host during a switch and a pending import", async ({
|
||||
page,
|
||||
}) => {
|
||||
const secondaryHost = await startIsolatedHostDaemon("import-session-secondary", {
|
||||
config: {
|
||||
agents: {
|
||||
providers: {
|
||||
...disabledProviders,
|
||||
claude: { enabled: false },
|
||||
[brokenProvider]: {
|
||||
extends: "acp",
|
||||
label: "Broken ACP",
|
||||
command: ["missing-secondary-command", "acp"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
try {
|
||||
const gate = await installDaemonWebSocketGate(page);
|
||||
const flow = new ImportSessionFlow(page);
|
||||
await flow.openWorkspace(scenario.project.workspaceId, { width: 1280, height: 844 });
|
||||
await addConnectedHostAndReload(page, {
|
||||
serverId: secondaryHost.serverId,
|
||||
port: secondaryHost.port,
|
||||
label: "Second import host",
|
||||
primaryLabel: "First import host",
|
||||
});
|
||||
|
||||
await flow.chooseHostForImport("First import host");
|
||||
await expect(page.getByText(/missing-agent-command/)).toBeVisible();
|
||||
await flow.close();
|
||||
|
||||
await flow.chooseHostForImport("Second import host");
|
||||
await expect(page.getByText(/missing-secondary-command/)).toBeVisible();
|
||||
await expect(page.getByText(/missing-agent-command/)).toHaveCount(0);
|
||||
await flow.close();
|
||||
|
||||
await test.step("returning to the original host omits the session imported during the switch", async () => {
|
||||
const sessionId = "fixture-root-04";
|
||||
await flow.chooseHostForImport("First import host");
|
||||
gate.holdNextClientRequest("import_agent_request");
|
||||
await flow.startImport(sessionId);
|
||||
await gate.waitForHeldClientRequest();
|
||||
|
||||
await flow.close();
|
||||
await flow.chooseHostForImport("Second import host");
|
||||
await flow.expectProviderError("Broken ACP");
|
||||
gate.releaseHeldClientRequest();
|
||||
await flow.expectClosed();
|
||||
|
||||
await flow.chooseHostForImport("First import host");
|
||||
await flow.revealSession("fixture-worktree");
|
||||
await flow.expectSessionUnavailable(sessionId);
|
||||
await flow.close();
|
||||
await flow.expectTranscript("Review fixture item 4", "Fixture response 4");
|
||||
});
|
||||
} finally {
|
||||
await secondaryHost.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("captures the compact import-session journey", async ({ page }, testInfo) => {
|
||||
const flow = new ImportSessionFlow(page);
|
||||
await flow.openWorkspace(scenario.project.workspaceId, { width: 390, height: 844 });
|
||||
@@ -378,7 +503,13 @@ async function seedClaudeSessions(input: {
|
||||
unrelatedDirectory: string;
|
||||
importSessionId: string;
|
||||
}): Promise<number> {
|
||||
const sessions = [
|
||||
const sessions: {
|
||||
cwd: string;
|
||||
id: string;
|
||||
title: string;
|
||||
prompt: string;
|
||||
answer?: string;
|
||||
}[] = [
|
||||
{
|
||||
cwd: input.projectRoot,
|
||||
id: input.importSessionId,
|
||||
@@ -403,6 +534,7 @@ async function seedClaudeSessions(input: {
|
||||
id: `fixture-root-${String(index + 1).padStart(2, "0")}`,
|
||||
title: `Root session ${String(index + 1).padStart(2, "0")}`,
|
||||
prompt: index === 7 ? "Investigate invoice rendering" : `Review fixture item ${index + 1}`,
|
||||
...(index === 3 ? { answer: "Fixture response 4" } : {}),
|
||||
})),
|
||||
];
|
||||
const newest = Date.now() - 60_000;
|
||||
|
||||
@@ -65,8 +65,7 @@ import {
|
||||
openSettingsHostSection,
|
||||
removeCurrentHostFromSettings,
|
||||
openSidebarHostPicker,
|
||||
sidebarHostSettingsButton,
|
||||
expectStandaloneSidebarHostSettingsButton,
|
||||
sidebarHostRowButton,
|
||||
activateSidebarHostSettingsWithKeyboard,
|
||||
bindCommandCenterToEnter,
|
||||
} from "../support/helpers/settings";
|
||||
@@ -192,17 +191,16 @@ test.describe("Settings sidebar scroll position", () => {
|
||||
});
|
||||
|
||||
test.describe("Settings sidebar navigation", () => {
|
||||
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
|
||||
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
|
||||
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
await openSidebarHostPicker(page);
|
||||
await expectStandaloneSidebarHostSettingsButton(page);
|
||||
await sidebarHostSettingsButton(page).click();
|
||||
await sidebarHostRowButton(page).click();
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
});
|
||||
|
||||
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
|
||||
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
|
||||
await bindCommandCenterToEnter(page);
|
||||
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
@@ -566,7 +564,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 page.getByRole("button", { name: /Open .* settings/ }).click();
|
||||
await sidebarHostRowButton(page).click();
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
|
||||
|
||||
@@ -132,7 +132,10 @@ export async function waitForConnectedHost(
|
||||
): Promise<void> {
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
|
||||
await expect(host).toContainText(input.endpoint, { timeout: 30_000 });
|
||||
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 page.keyboard.press("Escape");
|
||||
await expect(host).not.toBeVisible();
|
||||
}
|
||||
@@ -195,6 +198,12 @@ 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",
|
||||
|
||||
@@ -137,13 +137,22 @@ export class ImportSessionFlow {
|
||||
await this.expectProviderError(label);
|
||||
await expect(this.page.getByRole("progressbar")).toHaveCount(0);
|
||||
}
|
||||
async importSession(id: string) {
|
||||
async startImport(id: string) {
|
||||
await this.revealSession(id);
|
||||
await this.page.getByTestId(rowTestId(id)).click();
|
||||
}
|
||||
async importSession(id: string) {
|
||||
await this.startImport(id);
|
||||
await this.expectClosed();
|
||||
}
|
||||
async expectClosed() {
|
||||
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
async expectSessionUnavailable(id: string) {
|
||||
await expect(this.page.getByTestId(rowTestId(id))).toHaveCount(0);
|
||||
}
|
||||
async expectTranscript(userText: string, assistantText: string) {
|
||||
await expect(this.page.getByTestId("user-message").filter({ visible: true })).toContainText(
|
||||
userText,
|
||||
@@ -169,6 +178,13 @@ export class ImportSessionFlow {
|
||||
await this.page.getByRole("button", { name: "Close", exact: true }).last().click();
|
||||
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0);
|
||||
}
|
||||
async chooseHostForImport(hostLabel: string) {
|
||||
const panel = await openCommandCenter(this.page);
|
||||
await panel.getByTestId("command-center-input").fill("import");
|
||||
await panel.getByText("Import session", { exact: true }).click();
|
||||
await this.page.getByRole("dialog").getByRole("button", { name: hostLabel }).click();
|
||||
await this.expectScope(`Sessions on ${hostLabel}`);
|
||||
}
|
||||
async expectCommandCenterMatch() {
|
||||
const panel = await openCommandCenter(this.page);
|
||||
await panel.getByTestId("command-center-input").fill("import");
|
||||
|
||||
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
|
||||
await page.getByRole("button", { name: "Hosts", exact: true }).click();
|
||||
}
|
||||
|
||||
export function sidebarHostSettingsButton(page: Page) {
|
||||
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
|
||||
export function sidebarHostRowButton(page: Page) {
|
||||
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
|
||||
}
|
||||
|
||||
export async function bindCommandCenterToEnter(page: Page) {
|
||||
@@ -32,20 +32,10 @@ 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 = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
|
||||
const host = sidebarHostRowButton(page);
|
||||
await expect(host).toBeVisible();
|
||||
await expect(host).toBeFocused();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(sidebarHostSettingsButton(page)).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,28 @@
|
||||
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 {
|
||||
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 { HostStatusDot } from "@/components/host-status-dot";
|
||||
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
|
||||
import { Combobox, type ComboboxProps } from "@/components/ui/combobox";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime";
|
||||
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 { orderHostsLocalFirst } from "@/types/host-connection";
|
||||
import {
|
||||
ADD_HOST_OPTION_ID,
|
||||
@@ -22,7 +39,16 @@ 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;
|
||||
@@ -36,122 +62,166 @@ 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;
|
||||
showActiveConnection: boolean;
|
||||
appearance: HostAppearance;
|
||||
selected?: boolean;
|
||||
active: boolean;
|
||||
onPress: () => void;
|
||||
onOpenHostSettings?: (serverId: string) => void;
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
export function HostPickerOption({
|
||||
serverId,
|
||||
label,
|
||||
showActiveConnection,
|
||||
appearance,
|
||||
selected,
|
||||
active,
|
||||
onPress,
|
||||
onOpenHostSettings,
|
||||
testID,
|
||||
}: HostPickerOptionProps): ReactElement {
|
||||
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,
|
||||
]);
|
||||
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";
|
||||
|
||||
return (
|
||||
<ComboboxItem
|
||||
label={label}
|
||||
description={connectionLabel}
|
||||
leadingSlot={leadingSlot}
|
||||
trailingAction={trailingAction}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
testID={testID}
|
||||
/>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = {
|
||||
add: "Add host",
|
||||
all: "All hosts",
|
||||
enableBuiltInDaemon: "Enable built-in daemon",
|
||||
};
|
||||
|
||||
function SystemHostPickerOption({
|
||||
function AllHostsOption({
|
||||
active,
|
||||
selected,
|
||||
onPress,
|
||||
kind,
|
||||
testID,
|
||||
}: {
|
||||
active: boolean;
|
||||
selected?: boolean;
|
||||
onPress: () => void;
|
||||
kind: "add" | "all" | "enableBuiltInDaemon";
|
||||
testID?: string;
|
||||
}): ReactElement {
|
||||
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],
|
||||
);
|
||||
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 (
|
||||
<ComboboxItem
|
||||
label={label}
|
||||
leadingSlot={leadingSlot}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
testID={testID}
|
||||
/>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -168,7 +238,6 @@ export interface HostPickerProps {
|
||||
includeEnableBuiltInDaemon?: boolean;
|
||||
onEnableBuiltInDaemon?: () => void;
|
||||
showActiveConnection?: boolean;
|
||||
onOpenHostSettings?: (serverId: string) => void;
|
||||
searchable?: boolean;
|
||||
title?: string;
|
||||
desktopPlacement?: ComboboxProps["desktopPlacement"];
|
||||
@@ -190,74 +259,85 @@ export function HostPicker({
|
||||
onAddHost,
|
||||
includeEnableBuiltInDaemon,
|
||||
onEnableBuiltInDaemon,
|
||||
showActiveConnection,
|
||||
onOpenHostSettings,
|
||||
searchable,
|
||||
title,
|
||||
desktopPlacement = "bottom-start",
|
||||
desktopMinWidth,
|
||||
desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH,
|
||||
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: "All hosts" });
|
||||
if (includeAddHost) hostOptions.push({ id: ADD_HOST_OPTION_ID, label: "Add host" });
|
||||
if (includeEnableBuiltInDaemon)
|
||||
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) {
|
||||
hostOptions.push({
|
||||
id: ENABLE_BUILT_IN_DAEMON_OPTION_ID,
|
||||
label: "Enable built-in daemon",
|
||||
label: t("settings.enableBuiltInDaemon"),
|
||||
});
|
||||
}
|
||||
return hostOptions;
|
||||
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]);
|
||||
}, [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;
|
||||
}
|
||||
|
||||
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?.();
|
||||
} else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
onEnableBuiltInDaemon?.();
|
||||
} else {
|
||||
onSelect(id);
|
||||
return;
|
||||
}
|
||||
if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
onOpenChange(false);
|
||||
onEnableBuiltInDaemon?.();
|
||||
return;
|
||||
}
|
||||
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 (
|
||||
<SystemHostPickerOption
|
||||
kind="all"
|
||||
<AllHostsOption
|
||||
active={active}
|
||||
selected={selected}
|
||||
onPress={onPress}
|
||||
@@ -265,30 +345,48 @@ export function HostPicker({
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
|
||||
if (option.id === ADD_HOST_OPTION_ID) {
|
||||
return (
|
||||
<SystemHostPickerOption kind="enableBuiltInDaemon" active={active} onPress={onPress} />
|
||||
<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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance();
|
||||
return (
|
||||
<HostPickerOption
|
||||
serverId={option.id}
|
||||
label={option.label}
|
||||
showActiveConnection={showActiveConnection === true}
|
||||
appearance={appearance}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
onOpenHostSettings={onOpenHostSettings ? handleOpenHostSettings : undefined}
|
||||
testID={hostOptionTestID?.(option.id)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
addHostTestID,
|
||||
appearanceByServerId,
|
||||
firstActionOptionId,
|
||||
hostOptionTestID,
|
||||
onOpenHostSettings,
|
||||
showActiveConnection,
|
||||
handleOpenHostSettings,
|
||||
orderedHosts.length,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -301,8 +399,8 @@ export function HostPicker({
|
||||
onSelect={handleSelect}
|
||||
renderOption={renderOption}
|
||||
searchable={isSearchable}
|
||||
searchPlaceholder="Search hosts"
|
||||
title={title ?? "Host"}
|
||||
searchPlaceholder={t("sidebar.host.searchPlaceholder")}
|
||||
title={resolvedTitle}
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
@@ -314,16 +412,86 @@ 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,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -184,7 +184,9 @@ describe("collectProviderErrorRows", () => {
|
||||
[settled(undefined, { isError: true }), settled({ entries: [] })],
|
||||
new Map([["claude", "Claude Code"]]),
|
||||
);
|
||||
expect(rows).toEqual([{ provider: "claude", label: "Claude Code" }]);
|
||||
expect(rows).toEqual([
|
||||
{ provider: "claude", label: "Claude Code", message: null, retrying: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns a row for a provider the daemon reported as failed in a good response", () => {
|
||||
@@ -198,7 +200,9 @@ describe("collectProviderErrorRows", () => {
|
||||
],
|
||||
new Map([["codex", "Codex"]]),
|
||||
);
|
||||
expect(rows).toEqual([{ provider: "codex", label: "Codex" }]);
|
||||
expect(rows).toEqual([
|
||||
{ provider: "codex", label: "Codex", message: "timed out", retrying: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses provider id when the label map has no entry", () => {
|
||||
@@ -207,7 +211,43 @@ describe("collectProviderErrorRows", () => {
|
||||
[settled(undefined, { isError: true })],
|
||||
new Map(),
|
||||
);
|
||||
expect(rows).toEqual([{ provider: "codex", label: "codex" }]);
|
||||
expect(rows).toEqual([{ provider: "codex", label: "codex", message: null, retrying: false }]);
|
||||
});
|
||||
|
||||
it("shows the current request failure instead of an older provider error", () => {
|
||||
const query = {
|
||||
...settled(
|
||||
{ entries: [], providerErrors: [{ provider: "codex", message: "old provider failure" }] },
|
||||
{ isError: true },
|
||||
),
|
||||
error: new Error(" Connection closed. Reconnect the host and retry. "),
|
||||
};
|
||||
expect(collectProviderErrorRows(["codex"], [query], new Map())).toEqual([
|
||||
{
|
||||
provider: "codex",
|
||||
label: "codex",
|
||||
message: "Connection closed. Reconnect the host and retry.",
|
||||
retrying: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the provider failure visible while its retry is in flight", () => {
|
||||
const query = {
|
||||
...settled({
|
||||
entries: [],
|
||||
providerErrors: [{ provider: "codex", message: "Run codex login and retry." }],
|
||||
}),
|
||||
isFetching: true,
|
||||
};
|
||||
expect(collectProviderErrorRows(["codex"], [query], new Map())).toEqual([
|
||||
{
|
||||
provider: "codex",
|
||||
label: "codex",
|
||||
message: "Run codex login and retry.",
|
||||
retrying: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -39,6 +39,8 @@ export interface SessionsQueryResult {
|
||||
}
|
||||
| undefined;
|
||||
isError: boolean;
|
||||
error?: Error | null;
|
||||
isFetching?: boolean;
|
||||
isLoading: boolean;
|
||||
isPending: boolean;
|
||||
isPlaceholderData?: boolean;
|
||||
@@ -120,6 +122,8 @@ export function hasMoreSessions(
|
||||
export interface ProviderErrorRow {
|
||||
provider: string;
|
||||
label: string;
|
||||
message: string | null;
|
||||
retrying: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -140,7 +144,15 @@ export function collectProviderErrorRows(
|
||||
if (!query || provider === undefined) continue;
|
||||
const failed = query.isError || (query.data?.providerErrors?.length ?? 0) > 0;
|
||||
if (!failed) continue;
|
||||
rows.push({ provider, label: providerLabelById.get(provider) ?? provider });
|
||||
const failure = query.data?.providerErrors?.find((error) => error.provider === provider);
|
||||
const failureMessage = query.isError ? query.error?.message : failure?.message;
|
||||
const message = failureMessage?.trim() || null;
|
||||
rows.push({
|
||||
provider,
|
||||
label: providerLabelById.get(provider) ?? provider,
|
||||
message,
|
||||
retrying: query.isFetching === true,
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
@@ -79,15 +79,19 @@ type RecentSessionsResponse = Awaited<
|
||||
|
||||
type SessionsQueryKey = ReadonlyArray<string | number | null>;
|
||||
|
||||
function buildSessionsQueryRoot(serverId: string | null, cwd: string | null) {
|
||||
return ["recent-provider-sessions", serverId, cwd] as const;
|
||||
}
|
||||
|
||||
function buildSessionsQueryKey(input: {
|
||||
serverId: string | null;
|
||||
cwd: string | null;
|
||||
query: string;
|
||||
limit: number;
|
||||
provider?: string;
|
||||
}): SessionsQueryKey {
|
||||
return [
|
||||
"recent-provider-sessions",
|
||||
input.cwd,
|
||||
...buildSessionsQueryRoot(input.serverId, input.cwd),
|
||||
input.query,
|
||||
input.limit,
|
||||
...(input.provider === undefined ? [] : [input.provider]),
|
||||
@@ -101,6 +105,7 @@ interface SessionsQueryConfig {
|
||||
// Query's default retry would keep the header spinner turning and pile up
|
||||
// in-flight daemon requests behind a dead provider (#2512).
|
||||
retry: false;
|
||||
refetchOnMount: true;
|
||||
placeholderData: () => RecentSessionsResponse | undefined;
|
||||
queryFn: () => Promise<RecentSessionsResponse>;
|
||||
}
|
||||
@@ -110,20 +115,23 @@ function buildSessionsQueriesConfig(args: {
|
||||
providersToFetch: AgentProvider[] | null;
|
||||
visible: boolean;
|
||||
client: RecentProviderSessionsClient | null;
|
||||
serverId: string | null;
|
||||
cwd: string | null;
|
||||
query: string;
|
||||
limit: number;
|
||||
hostDisconnectedMessage?: string;
|
||||
}): SessionsQueryConfig[] {
|
||||
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
|
||||
const { queryClient, providersToFetch, visible, client, serverId, cwd, query, limit } = args;
|
||||
const { hostDisconnectedMessage } = args;
|
||||
if (providersToFetch === null) return [];
|
||||
const enabled = visible && Boolean(client);
|
||||
const previousLimit = previousPageLimit(limit);
|
||||
return providersToFetch.map((provider) => ({
|
||||
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
|
||||
queryKey: buildSessionsQueryKey({ serverId, cwd, query, limit, provider }),
|
||||
enabled,
|
||||
retry: false as const,
|
||||
// An import can invalidate an inactive host. Refresh its listing when observed again.
|
||||
refetchOnMount: true as const,
|
||||
// While Load more fetches the next page, keep showing the page it grew from. React Query's
|
||||
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
|
||||
// has no previous data, so the rows would vanish and the list would remount at the top.
|
||||
@@ -131,7 +139,7 @@ function buildSessionsQueriesConfig(args: {
|
||||
previousLimit === null
|
||||
? undefined
|
||||
: queryClient.getQueryData<RecentSessionsResponse>(
|
||||
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
|
||||
buildSessionsQueryKey({ serverId, cwd, query, limit: previousLimit, provider }),
|
||||
),
|
||||
queryFn: async () => {
|
||||
if (!client) {
|
||||
@@ -217,13 +225,21 @@ function ProviderErrorBannerRow({
|
||||
const handleRetry = useCallback(() => onRetry(row.provider), [onRetry, row.provider]);
|
||||
return (
|
||||
<View style={styles.errorRow}>
|
||||
<Text style={styles.errorText}>
|
||||
{t("importSession.status.failedProvider", { provider: row.label })}
|
||||
</Text>
|
||||
<View style={styles.errorContent}>
|
||||
<Text style={styles.errorText}>
|
||||
{t("importSession.status.failedProvider", { provider: row.label })}
|
||||
</Text>
|
||||
{row.message ? (
|
||||
<Text style={styles.errorDetail} selectable>
|
||||
{row.message}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={handleRetry}
|
||||
loading={row.retrying}
|
||||
testID={`import-session-retry-${row.provider}`}
|
||||
>
|
||||
{t("common.actions.retry")}
|
||||
@@ -529,7 +545,10 @@ export function ImportSessionSheet({
|
||||
[snapshotEntries],
|
||||
);
|
||||
|
||||
const sessionsQueryRoot = useMemo(() => ["recent-provider-sessions", scopeCwd], [scopeCwd]);
|
||||
const sessionsQueryRoot = useMemo(
|
||||
() => buildSessionsQueryRoot(serverId, scopeCwd),
|
||||
[serverId, scopeCwd],
|
||||
);
|
||||
|
||||
const queriesConfig = useMemo(
|
||||
() =>
|
||||
@@ -538,12 +557,13 @@ export function ImportSessionSheet({
|
||||
providersToFetch,
|
||||
visible,
|
||||
client,
|
||||
serverId,
|
||||
cwd: scopeCwd,
|
||||
query,
|
||||
limit: pageLimit,
|
||||
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
|
||||
}),
|
||||
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
|
||||
[queryClient, providersToFetch, visible, client, serverId, scopeCwd, query, pageLimit, t],
|
||||
);
|
||||
|
||||
const queries = useQueries({ queries: queriesConfig });
|
||||
@@ -682,19 +702,17 @@ export function ImportSessionSheet({
|
||||
cwd: entry.cwd,
|
||||
...(target.workspaceId ? { workspaceId: target.workspaceId } : {}),
|
||||
});
|
||||
return { agent, target };
|
||||
},
|
||||
onSuccess: ({ agent, target }) => {
|
||||
// A pending import keeps the listing and navigation from the host it was sent to.
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: sessionsQueryRoot,
|
||||
refetchType: "none",
|
||||
});
|
||||
onClose();
|
||||
if (target.crossWorkspace) {
|
||||
onImported?.(agent);
|
||||
} else {
|
||||
onImportedAgent?.(agent.id);
|
||||
}
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: sessionsQueryRoot,
|
||||
refetchType: "none",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -725,10 +743,16 @@ export function ImportSessionSheet({
|
||||
const handleRetryProvider = useCallback(
|
||||
(provider: string) => {
|
||||
void queryClient.refetchQueries({
|
||||
queryKey: buildSessionsQueryKey({ cwd: scopeCwd, query, limit: pageLimit, provider }),
|
||||
queryKey: buildSessionsQueryKey({
|
||||
serverId,
|
||||
cwd: scopeCwd,
|
||||
query,
|
||||
limit: pageLimit,
|
||||
provider,
|
||||
}),
|
||||
});
|
||||
},
|
||||
[pageLimit, query, queryClient, scopeCwd],
|
||||
[pageLimit, query, queryClient, scopeCwd, serverId],
|
||||
);
|
||||
|
||||
const handleShowAll = useCallback(() => setIsShowingAllDirectories(true), []);
|
||||
@@ -1071,6 +1095,12 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: theme.spacing[2],
|
||||
paddingVertical: theme.spacing[1],
|
||||
},
|
||||
errorContent: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
errorText: {
|
||||
flexShrink: 1,
|
||||
@@ -1078,6 +1108,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
color: theme.colors.palette.red[300],
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
errorDetail: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
emptyState: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
|
||||
@@ -388,10 +388,10 @@ function SidebarHostPicker({
|
||||
includeAddHost
|
||||
onAddHost={onAddHost}
|
||||
showActiveConnection
|
||||
onOpenHostSettings={onOpenHostSettings}
|
||||
searchable
|
||||
title={label}
|
||||
desktopPlacement="top-start"
|
||||
desktopMinWidth={240}
|
||||
desktopMinWidth={328}
|
||||
addHostTestID="sidebar-host-add"
|
||||
hostOptionTestID={sidebarHostOptionTestID}
|
||||
>
|
||||
|
||||
@@ -73,6 +73,9 @@ 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";
|
||||
@@ -402,6 +405,7 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme
|
||||
type RenderOptionFn = NonNullable<ComboboxProps["renderOption"]>;
|
||||
|
||||
interface OptionRowProps {
|
||||
index: number;
|
||||
option: ComboboxOption;
|
||||
selected: boolean;
|
||||
active: boolean;
|
||||
@@ -409,20 +413,27 @@ interface OptionRowProps {
|
||||
renderOption: RenderOptionFn | undefined;
|
||||
}
|
||||
|
||||
function OptionRow({ option, selected, active, onSelect, renderOption }: OptionRowProps) {
|
||||
function OptionRow({ index, 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>{renderOption({ option, selected, active, onPress: handlePress })}</View>;
|
||||
return (
|
||||
<View dataSet={optionDataset}>
|
||||
{renderOption({ option, selected, active, onPress: handlePress })}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ComboboxItem
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
kind={option.kind}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={handlePress}
|
||||
/>
|
||||
<View dataSet={optionDataset}>
|
||||
<ComboboxItem
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
kind={option.kind}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={handlePress}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -451,6 +462,7 @@ function OptionsList({
|
||||
{options.map((opt, index) => (
|
||||
<OptionRow
|
||||
key={opt.id}
|
||||
index={index}
|
||||
option={opt}
|
||||
selected={opt.id === value}
|
||||
active={index === activeIndex}
|
||||
@@ -952,8 +964,9 @@ function dispatchDesktopKey(
|
||||
return true;
|
||||
}
|
||||
if (key === "Enter") {
|
||||
// Consume the shortcut but keep the browser's default button activation.
|
||||
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
|
||||
// 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)) {
|
||||
return true;
|
||||
}
|
||||
if (input.orderedVisibleOptions.length === 0) return false;
|
||||
@@ -1127,7 +1140,12 @@ function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children
|
||||
[safeAreaBottom],
|
||||
);
|
||||
const footerView = useMemo(
|
||||
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
|
||||
() =>
|
||||
footer ? (
|
||||
<View style={footerStyle} dataSet={FOOTER_DATASET}>
|
||||
{footer}
|
||||
</View>
|
||||
) : undefined,
|
||||
[footer, footerStyle],
|
||||
);
|
||||
return (
|
||||
@@ -1341,7 +1359,11 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
|
||||
renderOption={props.renderOption}
|
||||
/>
|
||||
)}
|
||||
{props.footer ? <View style={styles.footer}>{props.footer}</View> : null}
|
||||
{props.footer ? (
|
||||
<View style={styles.footer} dataSet={FOOTER_DATASET}>
|
||||
{props.footer}
|
||||
</View>
|
||||
) : null}
|
||||
</FloatingSurface>
|
||||
</View>
|
||||
</OverlayLayerProvider>
|
||||
@@ -1597,6 +1619,30 @@ 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);
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
defaultHostAppearance,
|
||||
normalizeStoredHostAppearance,
|
||||
resolveHostBadgeDisplay,
|
||||
resolveHostIcon,
|
||||
selectHostBadges,
|
||||
} from "@/hosts/appearance";
|
||||
|
||||
@@ -16,7 +17,7 @@ function host(
|
||||
}
|
||||
|
||||
describe("normalizeStoredHostAppearance", () => {
|
||||
it("defaults when the stored registry predates the field or holds junk", () => {
|
||||
it("defaults without writing an icon field so untouched records stay downgrade-safe", () => {
|
||||
const expected = { color: "none", badgeDisplay: null };
|
||||
expect(normalizeStoredHostAppearance(undefined)).toEqual(expected);
|
||||
expect(normalizeStoredHostAppearance(null)).toEqual(expected);
|
||||
@@ -24,13 +25,79 @@ 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("round-trips a value the user actually chose", () => {
|
||||
expect(normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" })).toEqual({
|
||||
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({
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -50,13 +117,13 @@ describe("resolveHostBadgeDisplay", () => {
|
||||
it("prefers an explicit choice over either default", () => {
|
||||
expect(
|
||||
resolveHostBadgeDisplay({
|
||||
appearance: { color: "none", badgeDisplay: "icon" },
|
||||
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
|
||||
isLocalHost: true,
|
||||
}),
|
||||
).toBe("icon");
|
||||
expect(
|
||||
resolveHostBadgeDisplay({
|
||||
appearance: { color: "none", badgeDisplay: "hidden" },
|
||||
appearance: { color: "none", icon: "server", badgeDisplay: "hidden" },
|
||||
isLocalHost: false,
|
||||
}),
|
||||
).toBe("hidden");
|
||||
@@ -72,7 +139,7 @@ describe("resolveHostBadgeDisplay", () => {
|
||||
).toBeNull();
|
||||
expect(
|
||||
resolveHostBadgeDisplay({
|
||||
appearance: { color: "none", badgeDisplay: "icon" },
|
||||
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
|
||||
isLocalHost: false,
|
||||
localHostResolutionPending: true,
|
||||
}),
|
||||
@@ -93,7 +160,7 @@ describe("selectHostBadges", () => {
|
||||
it("omits a host the user hid and keeps its sibling", () => {
|
||||
const badges = selectHostBadges({
|
||||
hosts: [
|
||||
host("alpha", "Alpha", { color: "none", badgeDisplay: "hidden" }),
|
||||
host("alpha", "Alpha", { color: "none", icon: "server", badgeDisplay: "hidden" }),
|
||||
host("beta", "Beta"),
|
||||
],
|
||||
localServerId: null,
|
||||
@@ -104,13 +171,14 @@ 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", badgeDisplay: "icon" })],
|
||||
hosts: [host("alpha", "Alpha", { color: "teal", icon: "mini", badgeDisplay: "icon" })],
|
||||
localServerId: null,
|
||||
enabled: true,
|
||||
});
|
||||
@@ -118,6 +186,7 @@ describe("selectHostBadges", () => {
|
||||
serverId: "alpha",
|
||||
label: "Alpha",
|
||||
color: "teal",
|
||||
icon: "mini",
|
||||
showLabel: false,
|
||||
});
|
||||
});
|
||||
@@ -150,4 +219,21 @@ 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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,25 +6,69 @@ 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. `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.
|
||||
* 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.
|
||||
*/
|
||||
export interface HostAppearance {
|
||||
color: HostColor;
|
||||
icon?: string;
|
||||
badgeDisplay: HostBadgeDisplay | null;
|
||||
}
|
||||
|
||||
export const HostAppearanceSchema: z.ZodType<HostAppearance> = z.strictObject({
|
||||
const StoredHostAppearanceSchema = 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 };
|
||||
}
|
||||
@@ -34,6 +78,17 @@ 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;
|
||||
@@ -52,6 +107,7 @@ export interface HostBadgeModel {
|
||||
serverId: string;
|
||||
label: string;
|
||||
color: HostColor;
|
||||
icon: HostIcon;
|
||||
showLabel: boolean;
|
||||
}
|
||||
|
||||
@@ -66,6 +122,7 @@ 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>();
|
||||
@@ -85,6 +142,10 @@ 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",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
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" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
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) };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Server } from "lucide-react-native";
|
||||
import { HOST_COLORS, type HostBadgeModel, type HostColor } from "@/hosts/appearance";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { type HostBadgeModel, type HostColor } from "@/hosts/appearance";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
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
|
||||
@@ -11,30 +10,9 @@ import type { Theme } from "@/styles/theme";
|
||||
*/
|
||||
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: a server 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: the host's device
|
||||
* 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
|
||||
@@ -47,10 +25,11 @@ export function HostBadge({ badge }: { badge: HostBadgeModel }) {
|
||||
testID={`host-badge-${badge.serverId}`}
|
||||
accessibilityLabel={badge.label}
|
||||
>
|
||||
<ThemedServer
|
||||
<HostIconGlyph
|
||||
icon={badge.icon}
|
||||
color={badge.color}
|
||||
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}>
|
||||
|
||||
@@ -7,14 +7,16 @@ 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 { HostStatusDotSlot } from "@/components/hosts/host-picker";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
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 { useHosts } from "@/runtime/host-runtime";
|
||||
import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { orderHostsLocalFirst, type HostProfile } from "@/types/host-connection";
|
||||
|
||||
type HostFilter = (host: HostProfile) => boolean;
|
||||
@@ -101,36 +103,52 @@ function HostChooserRow({
|
||||
active: boolean;
|
||||
onChooseHost: (serverId: string) => void;
|
||||
}) {
|
||||
const { theme } = useUnistyles();
|
||||
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 handlePress = useCallback(() => onChooseHost(host.serverId), [host.serverId, onChooseHost]);
|
||||
const rowStyle = useCallback(
|
||||
({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
({ pressed }: PressableStateCallbackType) => [
|
||||
styles.row,
|
||||
(active || hovered || pressed) && styles.rowActive,
|
||||
],
|
||||
[active],
|
||||
[active, hovered],
|
||||
);
|
||||
|
||||
return (
|
||||
<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>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -161,6 +179,7 @@ export function HostChooserModal() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!request) return;
|
||||
getHostRuntimeStore().refreshActiveLatencies(request.serverIds);
|
||||
inputRef.current?.replaceText("");
|
||||
setQuery("");
|
||||
setActiveIndex(0);
|
||||
@@ -328,7 +347,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[3],
|
||||
minHeight: 56,
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
@@ -337,19 +356,39 @@ const styles = StyleSheet.create((theme) => ({
|
||||
rowActive: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
},
|
||||
rowTrailing: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
height: 20,
|
||||
flexShrink: 0,
|
||||
},
|
||||
rowIconSlot: {
|
||||
width: 18,
|
||||
width: 16,
|
||||
height: 20,
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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} />;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
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,
|
||||
},
|
||||
}));
|
||||
@@ -1,11 +1,13 @@
|
||||
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 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
|
||||
* 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
|
||||
* 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.
|
||||
*/
|
||||
@@ -17,14 +19,25 @@ export function useHostBadges({
|
||||
const hosts = useHosts();
|
||||
const localServerId = useLocalDaemonServerId();
|
||||
const localDaemon = useLocalDaemonServerIdState();
|
||||
return useMemo(
|
||||
() =>
|
||||
selectHostBadges({
|
||||
hosts,
|
||||
localServerId,
|
||||
localHostResolutionPending: localDaemon.status !== "resolved",
|
||||
enabled,
|
||||
}),
|
||||
[hosts, localDaemon.status, localServerId, enabled],
|
||||
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(() => {
|
||||
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]);
|
||||
}
|
||||
|
||||
@@ -2841,6 +2841,23 @@ 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}}",
|
||||
@@ -2877,6 +2894,14 @@ export const ar: TranslationResources = {
|
||||
local: "محلي",
|
||||
remoteSsh: "SSH عن بُعد",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "محلي",
|
||||
relay: "تتابع",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "مباشر",
|
||||
routed: "عبر",
|
||||
},
|
||||
connections: {
|
||||
title: "اتصالات",
|
||||
removeTitle: "إزالة الاتصال",
|
||||
|
||||
@@ -2936,6 +2936,23 @@ 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}}",
|
||||
@@ -2972,6 +2989,14 @@ 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",
|
||||
|
||||
@@ -2865,6 +2865,23 @@ 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}}",
|
||||
@@ -2901,6 +2918,14 @@ 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",
|
||||
|
||||
@@ -2867,6 +2867,23 @@ 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}}",
|
||||
@@ -2903,6 +2920,14 @@ 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",
|
||||
|
||||
@@ -2833,6 +2833,23 @@ 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}}",
|
||||
@@ -2869,6 +2886,14 @@ export const ja: TranslationResources = {
|
||||
local: "ローカル",
|
||||
remoteSsh: "リモート SSH",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "ローカル",
|
||||
relay: "リレー",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "ダイレクト",
|
||||
routed: "経由",
|
||||
},
|
||||
connections: {
|
||||
title: "接続",
|
||||
removeTitle: "接続を削除",
|
||||
|
||||
@@ -2819,6 +2819,23 @@ 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}}",
|
||||
@@ -2855,6 +2872,14 @@ export const ko: TranslationResources = {
|
||||
local: "로컬",
|
||||
remoteSsh: "원격 SSH",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "로컬",
|
||||
relay: "릴레이",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "직접 연결",
|
||||
routed: "경유",
|
||||
},
|
||||
connections: {
|
||||
title: "연결",
|
||||
removeTitle: "연결 제거",
|
||||
|
||||
@@ -2846,6 +2846,23 @@ 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}}",
|
||||
@@ -2882,6 +2899,14 @@ 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",
|
||||
|
||||
@@ -2854,6 +2854,23 @@ 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}}",
|
||||
@@ -2890,6 +2907,14 @@ export const ru: TranslationResources = {
|
||||
local: "Локальный",
|
||||
remoteSsh: "Удалённый SSH",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "Локальный",
|
||||
relay: "Ретранслятор",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "Прямой",
|
||||
routed: "Через",
|
||||
},
|
||||
connections: {
|
||||
title: "Подключения",
|
||||
removeTitle: "Удалить подключение",
|
||||
|
||||
@@ -2775,6 +2775,23 @@ 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}}",
|
||||
@@ -2811,6 +2828,14 @@ export const zhCN: TranslationResources = {
|
||||
local: "本地",
|
||||
remoteSsh: "远程 SSH",
|
||||
},
|
||||
connectionKinds: {
|
||||
local: "本地",
|
||||
relay: "中继",
|
||||
tailscale: "Tailscale",
|
||||
ssh: "SSH",
|
||||
direct: "直连",
|
||||
routed: "经由",
|
||||
},
|
||||
connections: {
|
||||
title: "连接",
|
||||
removeTitle: "移除连接",
|
||||
|
||||
@@ -1114,6 +1114,106 @@ 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) => {
|
||||
@@ -3366,7 +3466,11 @@ describe("HostRuntimeStore", () => {
|
||||
store.boot();
|
||||
await registryLoaded;
|
||||
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({ color: "none", badgeDisplay: null });
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({
|
||||
color: "none",
|
||||
badgeDisplay: null,
|
||||
});
|
||||
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
@@ -3391,6 +3495,7 @@ 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");
|
||||
@@ -3402,10 +3507,60 @@ 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", badgeDisplay: null },
|
||||
appearance: { color: "amber", icon: "server", badgeDisplay: null },
|
||||
});
|
||||
const storage = createMemoryHostRuntimeStorage();
|
||||
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
|
||||
@@ -3423,11 +3578,16 @@ describe("HostRuntimeStore", () => {
|
||||
await store.setHostBadgeDisplay("srv_appearance", "icon");
|
||||
await hostListChanged;
|
||||
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({ color: "amber", badgeDisplay: "icon" });
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({
|
||||
color: "amber",
|
||||
icon: "server",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
|
||||
const persisted = await storage.getItem("@paseo:daemon-registry");
|
||||
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
|
||||
color: "amber",
|
||||
icon: "server",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
|
||||
@@ -3476,16 +3636,25 @@ 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, display]);
|
||||
await Promise.all([color, icon, display]);
|
||||
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
|
||||
expect(store.getHosts()[0]?.appearance).toEqual({
|
||||
color: "teal",
|
||||
icon: "mini",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
const persistedHosts = JSON.parse((await storage.getItem("@paseo:daemon-registry")) ?? "[]");
|
||||
expect(persistedHosts[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
|
||||
expect(persistedHosts[0]?.appearance).toEqual({
|
||||
color: "teal",
|
||||
icon: "mini",
|
||||
badgeDisplay: "icon",
|
||||
});
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -28,7 +28,12 @@ import {
|
||||
type HostProfile,
|
||||
type UnreadableHostEntries,
|
||||
} from "@/types/host-connection";
|
||||
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
|
||||
import {
|
||||
defaultHostAppearance,
|
||||
type HostBadgeDisplay,
|
||||
type HostColor,
|
||||
type HostIcon,
|
||||
} from "@/hosts/appearance";
|
||||
import {
|
||||
buildDaemonWebSocketUrl,
|
||||
buildRelayWebSocketUrl,
|
||||
@@ -945,6 +950,56 @@ 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;
|
||||
@@ -1001,30 +1056,32 @@ export class HostRuntimeController {
|
||||
return;
|
||||
}
|
||||
|
||||
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
|
||||
const initialProbes = new Map(this.snapshot.probeByConnectionId);
|
||||
for (const connection of connectionsToProbe) {
|
||||
this.connectionLastProbedAt.set(connection.id, performance.now());
|
||||
const existingProbe = probeByConnectionId.get(connection.id);
|
||||
const existingProbe = initialProbes.get(connection.id);
|
||||
const shouldPreserveActiveLatency =
|
||||
isOnline && connection.id === activeConnectionId && existingProbe?.status === "available";
|
||||
if (!shouldPreserveActiveLatency) {
|
||||
probeByConnectionId.set(connection.id, {
|
||||
initialProbes.set(connection.id, {
|
||||
status: "pending",
|
||||
latencyMs: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
|
||||
this.updateSnapshot({ probeByConnectionId: initialProbes });
|
||||
|
||||
let remaining = connectionsToProbe.length;
|
||||
let probeAuthFailure: "password_required" | "incorrect_password" | null = null;
|
||||
let activationLock: Promise<void> | null = null;
|
||||
|
||||
const publishProbeState = (): void => {
|
||||
// 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 => {
|
||||
if (!this.isCurrentProbeRequest(requestVersion)) {
|
||||
return;
|
||||
}
|
||||
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
|
||||
this.setConnectionProbe(connectionId, probe);
|
||||
};
|
||||
|
||||
const maybeActivateFirstAvailable = async (
|
||||
@@ -1053,6 +1110,7 @@ export class HostRuntimeController {
|
||||
return;
|
||||
}
|
||||
|
||||
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
|
||||
const currentActiveConnectionId = this.snapshot.activeConnectionId;
|
||||
if (currentActiveConnectionId) {
|
||||
this.reconcileActiveProbeWithClient(currentActiveConnectionId, probeByConnectionId);
|
||||
@@ -1208,11 +1266,10 @@ export class HostRuntimeController {
|
||||
|
||||
if (activeClient) {
|
||||
if (activeClient.getConnectionState().status !== "connected") {
|
||||
probeByConnectionId.set(connection.id, {
|
||||
publishConnectionProbe(connection.id, {
|
||||
status: "unavailable",
|
||||
latencyMs: null,
|
||||
});
|
||||
publishProbeState();
|
||||
return;
|
||||
}
|
||||
const rttMs = activeClient.getLastLivenessRttMs();
|
||||
@@ -1221,11 +1278,10 @@ export class HostRuntimeController {
|
||||
}
|
||||
if (rttMs !== null) {
|
||||
this.recordActiveRttSample(rttMs, performance.now());
|
||||
probeByConnectionId.set(connection.id, {
|
||||
publishConnectionProbe(connection.id, {
|
||||
status: "available",
|
||||
latencyMs: rttMs,
|
||||
});
|
||||
publishProbeState();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1235,11 +1291,10 @@ export class HostRuntimeController {
|
||||
return;
|
||||
}
|
||||
|
||||
probeByConnectionId.set(connection.id, {
|
||||
publishConnectionProbe(connection.id, {
|
||||
status: "available",
|
||||
latencyMs: rttMs,
|
||||
});
|
||||
publishProbeState();
|
||||
} catch (error) {
|
||||
if (this.isCurrentProbeRequest(requestVersion)) {
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
@@ -1247,11 +1302,10 @@ export class HostRuntimeController {
|
||||
this.authRejectedConnectionIds.add(connection.id);
|
||||
probeAuthFailure = authFailure;
|
||||
}
|
||||
probeByConnectionId.set(connection.id, {
|
||||
publishConnectionProbe(connection.id, {
|
||||
status: "unavailable",
|
||||
latencyMs: null,
|
||||
});
|
||||
publishProbeState();
|
||||
}
|
||||
} finally {
|
||||
if (connectedClient && shouldCloseClient) {
|
||||
@@ -2436,6 +2490,16 @@ 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,
|
||||
@@ -2443,6 +2507,16 @@ 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,
|
||||
@@ -3296,6 +3370,7 @@ 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>;
|
||||
@@ -3311,6 +3386,7 @@ 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={200}
|
||||
desktopMinWidth={320}
|
||||
hostOptionTestID={hostOptionTestID}
|
||||
>
|
||||
<FieldTrigger
|
||||
|
||||
@@ -907,7 +907,7 @@ function HostPicker({
|
||||
showActiveConnection
|
||||
searchable={false}
|
||||
title={t("settings.hostPicker.switchHost")}
|
||||
desktopMinWidth={240}
|
||||
desktopMinWidth={328}
|
||||
addHostTestID="settings-add-host"
|
||||
hostOptionTestID={hostOptionTestID}
|
||||
>
|
||||
|
||||
@@ -4,7 +4,12 @@ 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 } from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
} 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";
|
||||
@@ -13,12 +18,18 @@ 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";
|
||||
@@ -76,10 +87,112 @@ 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) }],
|
||||
@@ -205,9 +318,11 @@ function BadgeDisplayMenuItem({
|
||||
*/
|
||||
function BadgePreview({
|
||||
host,
|
||||
resolvedIcon,
|
||||
badgeDisplay,
|
||||
}: {
|
||||
host: HostProfile;
|
||||
resolvedIcon: HostIcon;
|
||||
badgeDisplay: HostBadgeDisplay;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
@@ -219,9 +334,10 @@ 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],
|
||||
[badgeDisplay, host.serverId, host.label, host.appearance.color, resolvedIcon],
|
||||
);
|
||||
// The real sidebar row, so the preview can't drift from what the setting actually does.
|
||||
return (
|
||||
@@ -244,8 +360,14 @@ function BadgePreview({
|
||||
export function HostAppearanceSection({ host }: { host: HostProfile }) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { setHostColor, setHostBadgeDisplay } = useHostMutations();
|
||||
const { setHostColor, setHostIcon, 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,
|
||||
@@ -263,6 +385,16 @@ 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 {
|
||||
@@ -288,11 +420,18 @@ 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} badgeDisplay={badgeDisplay} />
|
||||
<BadgePreview host={host} resolvedIcon={resolvedIcon} badgeDisplay={badgeDisplay} />
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
|
||||
@@ -293,6 +293,7 @@ export interface DaemonServerInfo {
|
||||
serverId: string;
|
||||
hostname: string | null;
|
||||
version: string | null;
|
||||
machineKind?: string | null;
|
||||
desktopManaged?: boolean;
|
||||
capabilities?: ServerCapabilities;
|
||||
features?: ServerInfoStatusPayload["features"];
|
||||
@@ -303,6 +304,7 @@ 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 }
|
||||
: {}),
|
||||
@@ -786,6 +788,7 @@ 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;
|
||||
@@ -795,16 +798,19 @@ 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)
|
||||
@@ -942,6 +948,7 @@ 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;
|
||||
@@ -951,6 +958,7 @@ export const useSessionStore = create<SessionStore>()(
|
||||
currentServerInfo: session.serverInfo,
|
||||
nextHostname,
|
||||
nextVersion,
|
||||
nextMachineKind,
|
||||
nextDesktopManaged,
|
||||
nextCapabilities,
|
||||
nextFeatures,
|
||||
@@ -970,6 +978,7 @@ export const useSessionStore = create<SessionStore>()(
|
||||
serverId: info.serverId,
|
||||
hostname: nextHostname,
|
||||
version: nextVersion,
|
||||
...(nextMachineKind !== null ? { machineKind: nextMachineKind } : {}),
|
||||
...(nextDesktopManaged !== undefined
|
||||
? { desktopManaged: nextDesktopManaged }
|
||||
: {}),
|
||||
|
||||
@@ -152,7 +152,7 @@ describe("normalizeStoredHostProfile", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("gives a host stored before appearance existed the default appearance", () => {
|
||||
it("gives a host stored before appearance existed the default appearance without an icon key", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_old",
|
||||
connections: [
|
||||
@@ -161,18 +161,35 @@ 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", badgeDisplay: "icon" },
|
||||
appearance: { color: "teal", icon: "laptop", badgeDisplay: "icon" },
|
||||
connections: [
|
||||
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(profile?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
|
||||
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",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes stored Remote SSH connection parameters", () => {
|
||||
@@ -340,12 +357,13 @@ 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", badgeDisplay: "hidden" },
|
||||
appearance: { color: "amber", icon: "workstation", badgeDisplay: "hidden" },
|
||||
connections: [],
|
||||
};
|
||||
|
||||
@@ -355,7 +373,11 @@ describe("upsertHostConnectionInProfiles", () => {
|
||||
connection,
|
||||
});
|
||||
|
||||
expect(profile.appearance).toEqual({ color: "amber", badgeDisplay: "hidden" });
|
||||
expect(profile.appearance).toEqual({
|
||||
color: "amber",
|
||||
icon: "workstation",
|
||||
badgeDisplay: "hidden",
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces a direct connection when its settings change", () => {
|
||||
|
||||
@@ -143,3 +143,11 @@ 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;
|
||||
|
||||
@@ -6560,6 +6560,108 @@ test("fetches scoped recent provider sessions", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
test.each([
|
||||
{
|
||||
scenario: "successful rows after the default RPC deadline",
|
||||
delayMs: 61_000,
|
||||
payload: {
|
||||
requestId: "recent-listing-deadline",
|
||||
entries: [
|
||||
{
|
||||
providerId: "slow-acp",
|
||||
providerLabel: "Slow ACP",
|
||||
providerHandleId: "slow-session",
|
||||
cwd: "/tmp/import-listing",
|
||||
title: "Slow provider session",
|
||||
firstPromptPreview: null,
|
||||
lastPromptPreview: null,
|
||||
lastActivityAt: "2026-04-30T12:34:56.000Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
scenario: "the server's provider timeout after ninety seconds",
|
||||
delayMs: 90_001,
|
||||
payload: {
|
||||
requestId: "recent-listing-deadline",
|
||||
entries: [],
|
||||
providerErrors: [
|
||||
{
|
||||
provider: "slow-acp",
|
||||
message: "Timed out listing importable sessions for provider 'slow-acp' after 90000ms",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
])("recent provider listing receives $scenario", async ({ delayMs, payload }) => {
|
||||
useHeartbeatClock();
|
||||
const transport = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_import_listing_deadline",
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => transport.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
const connected = client.connect();
|
||||
transport.triggerOpen();
|
||||
await connected;
|
||||
|
||||
const outcome = client
|
||||
.fetchRecentProviderSessions({
|
||||
requestId: "recent-listing-deadline",
|
||||
providers: ["slow-acp"],
|
||||
limit: 1,
|
||||
})
|
||||
.then(
|
||||
(response) => ({ status: "success", response }),
|
||||
(error: unknown) => ({ status: "error", error }),
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(delayMs);
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({ type: "fetch_recent_provider_sessions_response", payload }),
|
||||
);
|
||||
|
||||
expect(await outcome).toEqual({ status: "success", response: payload });
|
||||
expect(client.isConnected).toBe(true);
|
||||
});
|
||||
|
||||
test("recent provider listing still expires when the daemon never answers", async () => {
|
||||
useHeartbeatClock();
|
||||
const transport = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_import_listing_no_response",
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => transport.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
const connected = client.connect();
|
||||
transport.triggerOpen();
|
||||
await connected;
|
||||
|
||||
const errors: unknown[] = [];
|
||||
const listing = client
|
||||
.fetchRecentProviderSessions({ providers: ["slow-acp"] })
|
||||
.catch((error: unknown) => {
|
||||
errors.push(error);
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(90_001);
|
||||
expect(errors).toEqual([]);
|
||||
await vi.advanceTimersByTimeAsync(9_999);
|
||||
expect(errors).toEqual([
|
||||
expect.objectContaining({
|
||||
name: "DaemonConnectionError",
|
||||
code: "DAEMON_REQUEST_TIMEOUT",
|
||||
}),
|
||||
]);
|
||||
await listing;
|
||||
expect(client.isConnected).toBe(true);
|
||||
});
|
||||
|
||||
test("imports an agent by provider handle id", async () => {
|
||||
const logger = createMockLogger();
|
||||
const mock = createMockTransport();
|
||||
|
||||
@@ -1172,6 +1172,8 @@ function toTimeoutError(error: unknown, label: string, timeoutMs: number): Error
|
||||
const DEFAULT_RECONNECT_BASE_DELAY_MS = 1500;
|
||||
const DEFAULT_RECONNECT_MAX_DELAY_MS = 30000;
|
||||
const DEFAULT_SESSION_RPC_TIMEOUT_MS = 60_000;
|
||||
// The daemon allows 90s per provider; retain its result through the delivery margin.
|
||||
const RECENT_PROVIDER_SESSIONS_TIMEOUT_MS = 100_000;
|
||||
const PUSH_TOKEN_REVOCATION_TIMEOUT_MS = 2_000;
|
||||
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
|
||||
const DEFAULT_LIVENESS_TIMEOUT_MS = 5000;
|
||||
@@ -2998,6 +3000,7 @@ export class DaemonClient {
|
||||
return this.sendRequest({
|
||||
requestId: resolvedRequestId,
|
||||
message,
|
||||
timeout: RECENT_PROVIDER_SESSIONS_TIMEOUT_MS,
|
||||
options: { skipQueue: true },
|
||||
select: (msg) => {
|
||||
if (msg.type !== "fetch_recent_provider_sessions_response") {
|
||||
|
||||
@@ -3970,6 +3970,9 @@ 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,6 +236,34 @@ 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({
|
||||
|
||||
@@ -317,7 +317,7 @@ interface HydrateTimelineOptions {
|
||||
broadcastTimeline?: boolean;
|
||||
}
|
||||
|
||||
export type ImportablePersistedAgentQueryOptions = ListImportableSessionsOptions & {
|
||||
export type ImportablePersistedAgentQueryOptions = Omit<ListImportableSessionsOptions, "signal"> & {
|
||||
/**
|
||||
* When set, only providers in this set are scanned, in addition to the
|
||||
* built-in importable allowlist + enabled + non-derived rules.
|
||||
@@ -1296,9 +1296,11 @@ export class AgentManager {
|
||||
);
|
||||
const providerResults = await Promise.all(
|
||||
providerEntries.map(async ([provider, client]) => {
|
||||
const cancellation = new AbortController();
|
||||
try {
|
||||
const sessions = await withTimeout(
|
||||
client.listImportableSessions!({
|
||||
signal: cancellation.signal,
|
||||
limit: options?.limit,
|
||||
query: options?.query,
|
||||
scanLimit: options?.scanLimit,
|
||||
@@ -1314,6 +1316,7 @@ export class AgentManager {
|
||||
error: null,
|
||||
};
|
||||
} catch (error) {
|
||||
cancellation.abort(error);
|
||||
this.logger.warn(
|
||||
{ err: error, provider },
|
||||
"Failed to list importable sessions for provider",
|
||||
|
||||
@@ -586,6 +586,8 @@ export interface AgentSlashCommand {
|
||||
}
|
||||
|
||||
export interface ListImportableSessionsOptions {
|
||||
/** Aborts provider work when the caller stops waiting for a listing. */
|
||||
signal?: AbortSignal;
|
||||
providerOptions?: ProviderOptions;
|
||||
limit?: number;
|
||||
/** Optional case-insensitive descriptor search text. */
|
||||
|
||||
@@ -1,7 +1,29 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
import type { AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
|
||||
import { registerAgentAutoArchive } from "./create-agent-lifecycle-dispatch.js";
|
||||
import type { ForgeService } from "../../services/forge-service.js";
|
||||
import { createWorktree } from "../../utils/worktree.js";
|
||||
import { WorkspaceAutomationBlockedError } from "../workspace-automation-gate.js";
|
||||
import type { WorkspaceGitService } from "../workspace-git-service.js";
|
||||
import type { PersistedWorkspaceRecord } from "../workspace-registry.js";
|
||||
import type { AgentManager, AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
|
||||
import type { AgentStorage } from "./agent-storage.js";
|
||||
import {
|
||||
CreateAgentLifecycleDispatch,
|
||||
registerAgentAutoArchive,
|
||||
} from "./create-agent-lifecycle-dispatch.js";
|
||||
|
||||
const cleanupPaths: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const target of cleanupPaths.splice(0)) {
|
||||
rmSync(target, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
class AgentLifecycleEvents {
|
||||
private readonly listeners = new Set<AgentSubscriber>();
|
||||
@@ -25,6 +47,109 @@ class AgentLifecycleEvents {
|
||||
}
|
||||
}
|
||||
|
||||
async function createUntrustedWorktreeFixture(slug: string, markerName: string) {
|
||||
const tempDir = mkdtempSync(path.join(tmpdir(), "lifecycle-dispatch-"));
|
||||
cleanupPaths.push(tempDir);
|
||||
const repoDir = path.join(tempDir, "repo");
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
mkdirSync(repoDir, { recursive: true });
|
||||
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
|
||||
writeFileSync(
|
||||
path.join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: [
|
||||
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "init"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const worktree = await createWorktree({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: slug,
|
||||
source: { kind: "branch-off", baseBranch: "main", branchName: slug },
|
||||
paseoHome,
|
||||
});
|
||||
const workspace: PersistedWorkspaceRecord = {
|
||||
workspaceId: `ws-${slug}`,
|
||||
projectId: "proj-1",
|
||||
cwd: worktree.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: worktree.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: repoDir,
|
||||
createdAt: "2026-11-24T00:00:00.000Z",
|
||||
updatedAt: "2026-11-24T00:00:00.000Z",
|
||||
};
|
||||
const blockedSource = {
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number: 99,
|
||||
headRepository: "contributor/paseo",
|
||||
};
|
||||
const assertWorkspaceAutomationAllowed = vi.fn(async (id: string) => {
|
||||
if (id === workspace.workspaceId) {
|
||||
throw new WorkspaceAutomationBlockedError(blockedSource);
|
||||
}
|
||||
});
|
||||
const activeWorkspaces = [workspace];
|
||||
const archived = new Set<string>();
|
||||
const events = new AgentLifecycleEvents();
|
||||
const agentManager = {
|
||||
subscribe: (cb: AgentSubscriber) => events.subscribe(cb),
|
||||
listAgents: () => [],
|
||||
getAgent: () => null,
|
||||
archiveAgent: vi.fn(async () => ({ archivedAt: new Date().toISOString() })),
|
||||
archiveSnapshot: vi.fn(async () => ({})),
|
||||
} as unknown as AgentManager;
|
||||
const dispatch = new CreateAgentLifecycleDispatch({
|
||||
paseoHome,
|
||||
getWorkspace: async (id) => (id === workspace.workspaceId ? workspace : null),
|
||||
assertWorkspaceAutomationAllowed,
|
||||
isCheckoutUntrusted: async () => false,
|
||||
agentManager,
|
||||
agentStorage: { listByWorkspace: async () => [] } as unknown as AgentStorage,
|
||||
github: { invalidate: () => {} } as unknown as ForgeService,
|
||||
workspaceGitService: {
|
||||
getSnapshot: vi.fn(async () => null),
|
||||
invalidateWorktrees: () => {},
|
||||
} as unknown as WorkspaceGitService,
|
||||
createPaseoWorktreeWorkflow: vi.fn(),
|
||||
archiveAgentForClose: vi.fn(async () => undefined),
|
||||
findWorkspaceIdForCwd: async () => workspace.workspaceId,
|
||||
listActiveWorkspaces: async () => activeWorkspaces.filter((w) => !archived.has(w.workspaceId)),
|
||||
archiveWorkspaceRecord: async (id) => {
|
||||
archived.add(id);
|
||||
},
|
||||
emit: vi.fn(),
|
||||
emitAgentRemove: vi.fn(async () => undefined),
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => undefined),
|
||||
logger: pino({ level: "silent" }),
|
||||
});
|
||||
|
||||
return {
|
||||
dispatch,
|
||||
events,
|
||||
marker: path.join(repoDir, markerName),
|
||||
createdWorktree: { worktree, workspace },
|
||||
archived,
|
||||
assertWorkspaceAutomationAllowed,
|
||||
};
|
||||
}
|
||||
|
||||
test("auto-archive self-releases once and later cancellation waits harmlessly", async () => {
|
||||
const agentId = "4a7e2521-286d-4ad5-af35-e091c55302e3";
|
||||
const agents = new AgentLifecycleEvents();
|
||||
@@ -45,3 +170,41 @@ test("auto-archive self-releases once and later cancellation waits harmlessly",
|
||||
expect(archiveCount).toBe(1);
|
||||
expect(agents.listenerCount()).toBe(0);
|
||||
});
|
||||
|
||||
test("failed create cleanup skips teardown commands for an unapproved cross-repository checkout", async () => {
|
||||
const { dispatch, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
|
||||
await createUntrustedWorktreeFixture("failed-create-untrusted", "failed-create-teardown.log");
|
||||
|
||||
await dispatch.cleanupCreatedWorktreeAfterFailedAgentCreate({
|
||||
createdWorktree,
|
||||
createdAgentId: null,
|
||||
});
|
||||
|
||||
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
|
||||
createdWorktree.workspace.workspaceId,
|
||||
);
|
||||
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
|
||||
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("first-turn auto-archive skips teardown commands for an unapproved cross-repository checkout", async () => {
|
||||
const { dispatch, events, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
|
||||
await createUntrustedWorktreeFixture("auto-archive-untrusted", "auto-archive-teardown.log");
|
||||
const agentId = "agent-auto-archive-untrusted";
|
||||
|
||||
const registration = dispatch.registerAutoArchiveIfRequested({
|
||||
autoArchive: true,
|
||||
agentId,
|
||||
createdWorktree,
|
||||
});
|
||||
events.completeTurn(agentId);
|
||||
await registration.cancel();
|
||||
|
||||
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
|
||||
createdWorktree.workspace.workspaceId,
|
||||
);
|
||||
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
|
||||
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
@@ -29,7 +29,8 @@ interface CreateAgentLifecycleDispatchDependencies {
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
|
||||
getWorkspace?: ArchiveDependencies["getWorkspace"];
|
||||
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
|
||||
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
agentManager: AgentManager;
|
||||
agentStorage: AgentStorage;
|
||||
github: ForgeService;
|
||||
@@ -201,6 +202,7 @@ export class CreateAgentLifecycleDispatch {
|
||||
agentStorage: this.dependencies.agentStorage,
|
||||
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
|
||||
getWorkspace: this.dependencies.getWorkspace,
|
||||
assertWorkspaceAutomationAllowed: this.dependencies.assertWorkspaceAutomationAllowed,
|
||||
isCheckoutUntrusted: this.dependencies.isCheckoutUntrusted,
|
||||
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
|
||||
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
|
||||
|
||||
@@ -2527,6 +2527,8 @@ describe("create_agent MCP tool", () => {
|
||||
emitWorkspaceUpdatesForWorkspaceIds,
|
||||
markWorkspaceArchiving,
|
||||
clearWorkspaceArchiving,
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
github: createGitHubServiceStub(),
|
||||
logger,
|
||||
});
|
||||
@@ -2643,6 +2645,8 @@ describe("create_agent MCP tool", () => {
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
github: createGitHubServiceStub(),
|
||||
logger,
|
||||
});
|
||||
@@ -2675,6 +2679,117 @@ describe("create_agent MCP tool", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("skips teardown commands when archiving a worktree with blocked repository automation", async () => {
|
||||
const { agentManager, agentStorage } = createTestDeps();
|
||||
const tempDir = realpathSync.native(
|
||||
await mkdtemp(join(tmpdir(), "paseo-mcp-archive-worktree-blocked-")),
|
||||
);
|
||||
const repoDir = join(tempDir, "repo");
|
||||
const paseoHome = join(tempDir, ".paseo");
|
||||
const markerName = "mcp-blocked-teardown.log";
|
||||
const markerPath = join(repoDir, markerName);
|
||||
|
||||
try {
|
||||
execFileSync("git", ["init", repoDir], { stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@example.com"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "commit.gpgsign", "false"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
await writeFile(
|
||||
join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: [
|
||||
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
execFileSync("git", ["add", "paseo.json"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["commit", "-m", "init"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["branch", "-M", "main"], { cwd: repoDir, stdio: "pipe" });
|
||||
|
||||
const workspaceGitService = {
|
||||
getSnapshot: vi.fn(async () => null),
|
||||
listWorktrees: vi.fn(async () => []),
|
||||
resolveRepoRoot: vi.fn(async () => repoDir),
|
||||
invalidateWorktrees: vi.fn(),
|
||||
};
|
||||
const archivedWorkspaceIds: string[] = [];
|
||||
const activeWorkspaces: Array<{
|
||||
workspaceId: string;
|
||||
cwd: string;
|
||||
kind: "worktree" | "local_checkout" | "directory";
|
||||
}> = [];
|
||||
const listActiveWorkspaces = vi.fn(async () => activeWorkspaces);
|
||||
const archiveWorkspaceRecord = createArchiveWorkspaceRecordMutator(
|
||||
activeWorkspaces,
|
||||
archivedWorkspaceIds,
|
||||
);
|
||||
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
paseoHome,
|
||||
createPaseoWorktree: createPaseoWorktreeForMcpTest({ paseoHome, broadcasts: [] }),
|
||||
workspaceGitService: workspaceGitService as unknown as Pick<
|
||||
WorkspaceGitService,
|
||||
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
|
||||
>,
|
||||
findWorkspaceIdForCwd: vi.fn(async () => "ws-mcp-blocked"),
|
||||
listActiveWorkspaces,
|
||||
archiveWorkspaceRecord,
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
assertWorkspaceAutomationAllowed: async () => {
|
||||
throw new WorkspaceAutomationBlockedError({
|
||||
kind: "change_request",
|
||||
forge: "github",
|
||||
number: 77,
|
||||
headRepository: "contributor/repo",
|
||||
});
|
||||
},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
github: createGitHubServiceStub(),
|
||||
logger,
|
||||
});
|
||||
const createTool = registeredTool(server, "create_workspace");
|
||||
const archiveTool = registeredTool(server, "archive_workspace");
|
||||
const created = await createTool.handler({
|
||||
isolation: "worktree",
|
||||
path: repoDir,
|
||||
worktreeSlug: "archive-blocked-worktree",
|
||||
baseBranch: "main",
|
||||
});
|
||||
const worktreePath = z.string().parse(created.structuredContent.cwd);
|
||||
activeWorkspaces.push({
|
||||
workspaceId: "ws-mcp-blocked",
|
||||
cwd: worktreePath,
|
||||
kind: "worktree",
|
||||
});
|
||||
|
||||
const archived = await archiveTool.handler({
|
||||
workspaceId: "ws-mcp-blocked",
|
||||
});
|
||||
|
||||
expect(archived.structuredContent).toMatchObject({
|
||||
workspaceId: "ws-mcp-blocked",
|
||||
removedDirectory: true,
|
||||
});
|
||||
await expect(access(worktreePath)).rejects.toThrow();
|
||||
await expect(access(markerPath)).rejects.toThrow();
|
||||
} finally {
|
||||
await removeTempDir(tempDir);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not expose worktree path or slug operations", async () => {
|
||||
const { agentManager, agentStorage } = createTestDeps();
|
||||
const tempDir = realpathSync.native(
|
||||
|
||||
@@ -4,6 +4,7 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { PassThrough, Readable, Writable } from "node:stream";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import {
|
||||
@@ -37,6 +38,7 @@ import {
|
||||
summarizeACPRequestError,
|
||||
} from "./acp-agent.js";
|
||||
import { createIdleRuntimeCleanup } from "../idle-runtime-cleanup/index.js";
|
||||
import { AgentManager } from "../agent-manager.js";
|
||||
import type { ProcessTerminator, TreeKillTarget } from "../../../utils/tree-kill.js";
|
||||
import {
|
||||
COPILOT_AGENT_FEATURE_OPTION,
|
||||
@@ -2899,6 +2901,450 @@ describe("ACPAgentClient listImportableSessions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("ACPAgentClient import listing deadlines", () => {
|
||||
type ListingPhase = "spawn" | "initialize" | "session/list";
|
||||
const phases: ListingPhase[] = ["initialize", "session/list"];
|
||||
|
||||
function createBlockedListing(
|
||||
phase: ListingPhase,
|
||||
terminator = new FakeTerminator(),
|
||||
responseError?: RequestError,
|
||||
) {
|
||||
const child = createProbeChildStub();
|
||||
const clientToAgent = new PassThrough();
|
||||
const agentToClient = new PassThrough();
|
||||
child.stdin = clientToAgent;
|
||||
child.stdout = agentToClient;
|
||||
child.stderr = new PassThrough();
|
||||
let release!: () => void;
|
||||
const blocked = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
let markStarted!: () => void;
|
||||
const started = new Promise<void>((resolve) => {
|
||||
markStarted = resolve;
|
||||
});
|
||||
const operations: string[] = [];
|
||||
const agent: Agent = {
|
||||
async initialize() {
|
||||
operations.push("initialize");
|
||||
if (phase === "initialize") {
|
||||
markStarted();
|
||||
await blocked;
|
||||
if (responseError) throw responseError;
|
||||
}
|
||||
return {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
agentCapabilities: { sessionCapabilities: { list: {} } },
|
||||
};
|
||||
},
|
||||
async listSessions() {
|
||||
operations.push("session/list");
|
||||
if (phase === "session/list") {
|
||||
markStarted();
|
||||
await blocked;
|
||||
if (responseError) throw responseError;
|
||||
}
|
||||
return { sessions: [] };
|
||||
},
|
||||
async newSession() {
|
||||
throw new Error("Import listing must not create a session");
|
||||
},
|
||||
async prompt() {
|
||||
throw new Error("Import listing must not submit a prompt");
|
||||
},
|
||||
async authenticate() {},
|
||||
async cancel() {},
|
||||
};
|
||||
const agentConnection = new AgentSideConnection(
|
||||
() => agent,
|
||||
ndJsonStream(Writable.toWeb(agentToClient), Readable.toWeb(clientToAgent)),
|
||||
);
|
||||
const connection = new ClientSideConnection(
|
||||
() => ({
|
||||
async requestPermission() {
|
||||
return { outcome: { outcome: "cancelled" } };
|
||||
},
|
||||
async sessionUpdate() {},
|
||||
}),
|
||||
ndJsonStream(Writable.toWeb(clientToAgent), Readable.toWeb(agentToClient)),
|
||||
);
|
||||
|
||||
const processError = new Promise<never>((_resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("close", () => reject(new Error("Import probe exited during cleanup")));
|
||||
});
|
||||
|
||||
class ListingClient extends ACPAgentClient {
|
||||
protected override async spawnTransport() {
|
||||
if (phase === "spawn") {
|
||||
operations.push("spawn");
|
||||
markStarted();
|
||||
await blocked;
|
||||
}
|
||||
return {
|
||||
child,
|
||||
connection,
|
||||
stderrChunks: [],
|
||||
spawnReady: Promise.resolve(),
|
||||
processError,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const client = new ListingClient({
|
||||
provider: "test-acp",
|
||||
logger: createTestLogger(),
|
||||
defaultCommand: ["test-acp"],
|
||||
defaultModes: [],
|
||||
terminateProcess: async (target, options) => {
|
||||
const result = await terminator.terminate(target, options);
|
||||
child.emit("close", 0, null);
|
||||
return result;
|
||||
},
|
||||
});
|
||||
return { client, child, agentConnection, terminator, started, release, operations };
|
||||
}
|
||||
|
||||
function listSessionsThroughManager(client: ACPAgentClient) {
|
||||
return new AgentManager({
|
||||
clients: { [client.provider]: client },
|
||||
logger: createTestLogger(),
|
||||
}).listImportableSessions({ limit: 1 });
|
||||
}
|
||||
|
||||
test.runIf(process.platform !== "win32")(
|
||||
"reclaims the stalled listing provider after its launcher exits",
|
||||
async () => {
|
||||
const fixtureDir = await mkdtemp(path.join(tmpdir(), "paseo-acp-listing-"));
|
||||
const fixturePath = path.join(fixtureDir, "launcher.cjs");
|
||||
const readyPath = path.join(fixtureDir, "listing-ready");
|
||||
const pidsPath = path.join(fixtureDir, "pids.json");
|
||||
await writeFile(
|
||||
fixturePath,
|
||||
`
|
||||
const { spawn } = require("node:child_process");
|
||||
const { writeFileSync } = require("node:fs");
|
||||
const { createInterface } = require("node:readline");
|
||||
if (process.argv[4] === "provider") {
|
||||
process.on("SIGTERM", () => {});
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method } = JSON.parse(line);
|
||||
if (method === "initialize") {
|
||||
console.log(JSON.stringify({ jsonrpc: "2.0", id, result: {
|
||||
protocolVersion: ${PROTOCOL_VERSION},
|
||||
agentCapabilities: { sessionCapabilities: { list: {} } },
|
||||
}}));
|
||||
}
|
||||
if (method === "session/list") {
|
||||
writeFileSync(process.argv[2], "ready");
|
||||
setInterval(() => {}, 1000);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
const child = spawn(process.execPath, [...process.argv.slice(1), "provider"], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
writeFileSync(process.argv[3], JSON.stringify({
|
||||
launcher: process.pid, provider: child.pid,
|
||||
}));
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
const client = new ACPAgentClient({
|
||||
provider: "test-acp",
|
||||
logger: createTestLogger(),
|
||||
defaultCommand: [process.execPath, fixturePath, readyPath, pidsPath],
|
||||
defaultModes: [],
|
||||
});
|
||||
const isRunning = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const readPids = async (): Promise<{ launcher: number; provider: number }> =>
|
||||
JSON.parse(await readFile(pidsPath, "utf8"));
|
||||
vi.useFakeTimers({ now: 0, toFake: ["setTimeout", "clearTimeout", "performance", "Date"] });
|
||||
let responseReceived = false;
|
||||
const listing = listSessionsThroughManager(client).then((response) => {
|
||||
responseReceived = true;
|
||||
return response;
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => readFile(readyPath, "utf8"), { timeout: 3000 });
|
||||
const { launcher, provider } = await readPids();
|
||||
expect(isRunning(launcher)).toBe(true);
|
||||
expect(isRunning(provider)).toBe(true);
|
||||
|
||||
// waitFor advances the fake clock while starting the real processes.
|
||||
await vi.advanceTimersByTimeAsync(89_999 - Date.now());
|
||||
expect(responseReceived).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(listing).resolves.toEqual({
|
||||
sessions: [],
|
||||
providerErrors: [
|
||||
{
|
||||
provider: "test-acp",
|
||||
message:
|
||||
"Timed out listing importable sessions for provider 'test-acp' after 90000ms",
|
||||
},
|
||||
],
|
||||
});
|
||||
await vi.waitFor(() => expect(isRunning(launcher)).toBe(false));
|
||||
await vi.waitFor(
|
||||
() => expect(isRunning(provider), "provider outlived launcher cleanup").toBe(false),
|
||||
{ timeout: 3500 },
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
const pids = await readPids().catch(() => ({}));
|
||||
for (const pid of Object.values(pids)) {
|
||||
if (isRunning(pid)) process.kill(pid, "SIGKILL");
|
||||
}
|
||||
await rm(fixtureDir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
|
||||
test("accepts a listing that finishes within the daemon's provider deadline", async () => {
|
||||
vi.useFakeTimers();
|
||||
const probe = createBlockedListing("session/list");
|
||||
const listing = listSessionsThroughManager(probe.client);
|
||||
|
||||
try {
|
||||
await probe.started;
|
||||
await vi.advanceTimersByTimeAsync(88_000);
|
||||
probe.release();
|
||||
|
||||
await expect(listing).resolves.toEqual({ sessions: [], providerErrors: [] });
|
||||
expect(probe.terminator.terminated).toEqual([probe.child]);
|
||||
} finally {
|
||||
probe.release();
|
||||
await listing;
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test.each<{ phase: ListingPhase; errorMessage?: string }>([
|
||||
{ phase: "session/list" },
|
||||
{ phase: "session/list", errorMessage: "Provider rejected listing" },
|
||||
{ phase: "initialize", errorMessage: "Sign in to the provider and retry" },
|
||||
])(
|
||||
"returns a timely $phase outcome while its probe is still shutting down ($errorMessage)",
|
||||
async ({ phase, errorMessage }) => {
|
||||
vi.useFakeTimers();
|
||||
const terminator = new FakeTerminator("deferred");
|
||||
const responseError = errorMessage ? new RequestError(-32001, errorMessage) : undefined;
|
||||
const probe = createBlockedListing(phase, terminator, responseError);
|
||||
const providerErrors = errorMessage
|
||||
? [{ provider: "test-acp", message: expect.stringContaining(errorMessage) }]
|
||||
: [];
|
||||
const listing = listSessionsThroughManager(probe.client);
|
||||
|
||||
try {
|
||||
await probe.started;
|
||||
await vi.advanceTimersByTimeAsync(88_000);
|
||||
probe.release();
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
|
||||
expect(terminator.terminated.map((child) => child.pid)).toEqual([probe.child.pid]);
|
||||
expect(probe.child.stdout.destroyed).toBe(false);
|
||||
await expect(listing).resolves.toEqual({ sessions: [], providerErrors });
|
||||
terminator.releaseAll();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(probe.child.stdout.destroyed).toBe(true);
|
||||
} finally {
|
||||
probe.release();
|
||||
terminator.releaseAll();
|
||||
await listing;
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test.each(phases)("cleans up when import listing stalls in %s", async (phase) => {
|
||||
vi.useFakeTimers();
|
||||
const probe = createBlockedListing(phase);
|
||||
const listing = listSessionsThroughManager(probe.client);
|
||||
|
||||
try {
|
||||
await probe.started;
|
||||
await vi.advanceTimersByTimeAsync(89_999);
|
||||
expect(probe.terminator.terminated).toEqual([]);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(listing).resolves.toEqual({
|
||||
sessions: [],
|
||||
providerErrors: [
|
||||
{
|
||||
provider: "test-acp",
|
||||
message: "Timed out listing importable sessions for provider 'test-acp' after 90000ms",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(probe.terminator.terminated).toEqual([probe.child]);
|
||||
expect(probe.child.stdin.destroyed).toBe(true);
|
||||
expect(probe.child.stdout.destroyed).toBe(true);
|
||||
expect(probe.child.stderr.destroyed).toBe(true);
|
||||
} finally {
|
||||
probe.release();
|
||||
await listing;
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test.each(phases)("cleans up when import listing is aborted in %s", async (phase) => {
|
||||
vi.useFakeTimers();
|
||||
const probe = createBlockedListing(phase);
|
||||
const abort = new AbortController();
|
||||
const reason = new Error("Import listing cancelled");
|
||||
const options = { limit: 1, signal: abort.signal };
|
||||
const errors: unknown[] = [];
|
||||
const listing = probe.client.listImportableSessions(options).catch((error: unknown) => {
|
||||
errors.push(error);
|
||||
return [];
|
||||
});
|
||||
|
||||
try {
|
||||
await probe.started;
|
||||
abort.abort(reason);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(errors).toEqual([reason]);
|
||||
expect(probe.terminator.terminated).toEqual([probe.child]);
|
||||
expect(probe.child.stdin.destroyed).toBe(true);
|
||||
expect(probe.child.stdout.destroyed).toBe(true);
|
||||
expect(probe.child.stderr.destroyed).toBe(true);
|
||||
|
||||
probe.release();
|
||||
await listing;
|
||||
expect(probe.operations).toEqual(
|
||||
phase === "initialize" ? ["initialize"] : ["initialize", "session/list"],
|
||||
);
|
||||
expect(probe.terminator.terminated).toEqual([probe.child]);
|
||||
} finally {
|
||||
probe.release();
|
||||
await listing;
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test("closes an import probe that finishes spawning after cancellation", async () => {
|
||||
const probe = createBlockedListing("spawn");
|
||||
const abort = new AbortController();
|
||||
const reason = new Error("Import listing cancelled before spawn completed");
|
||||
const options = { limit: 1, signal: abort.signal };
|
||||
const errors: unknown[] = [];
|
||||
const unhandledRejections: unknown[] = [];
|
||||
function recordUnhandledRejection(error: unknown): void {
|
||||
unhandledRejections.push(error);
|
||||
}
|
||||
process.on("unhandledRejection", recordUnhandledRejection);
|
||||
const listing = probe.client.listImportableSessions(options).catch((error: unknown) => {
|
||||
errors.push(error);
|
||||
return [];
|
||||
});
|
||||
|
||||
try {
|
||||
await probe.started;
|
||||
abort.abort(reason);
|
||||
await listing;
|
||||
expect(errors).toEqual([reason]);
|
||||
expect(probe.terminator.terminated).toEqual([]);
|
||||
|
||||
probe.release();
|
||||
// Node reports unhandled rejections after the cleanup microtasks settle.
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(probe.terminator.terminated).toEqual([probe.child]);
|
||||
expect(probe.child.stdin.destroyed).toBe(true);
|
||||
expect(probe.child.stdout.destroyed).toBe(true);
|
||||
expect(probe.child.stderr.destroyed).toBe(true);
|
||||
expect(probe.operations).toEqual(["spawn"]);
|
||||
expect(errors).toEqual([reason]);
|
||||
expect(unhandledRejections).toEqual([]);
|
||||
} finally {
|
||||
probe.release();
|
||||
await listing;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
process.removeListener("unhandledRejection", recordUnhandledRejection);
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves process failures during import probe initialization", async () => {
|
||||
vi.useFakeTimers();
|
||||
const probe = createBlockedListing("initialize");
|
||||
const failure = new Error("Import probe failed during initialize");
|
||||
const errors: unknown[] = [];
|
||||
const listing = probe.client.listImportableSessions({ limit: 1 }).catch((error: unknown) => {
|
||||
errors.push(error);
|
||||
return [];
|
||||
});
|
||||
|
||||
try {
|
||||
await probe.started;
|
||||
probe.child.emit("error", failure);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(errors).toEqual([
|
||||
expect.objectContaining({ message: "Import probe failed during initialize" }),
|
||||
]);
|
||||
expect(probe.operations).toEqual(["initialize"]);
|
||||
expect(probe.terminator.terminated).toEqual([probe.child]);
|
||||
expect(probe.child.stdin.destroyed).toBe(true);
|
||||
expect(probe.child.stdout.destroyed).toBe(true);
|
||||
expect(probe.child.stderr.destroyed).toBe(true);
|
||||
} finally {
|
||||
probe.release();
|
||||
await listing;
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test("waits for owned import probe cleanup before rejecting cancellation", async () => {
|
||||
vi.useFakeTimers();
|
||||
const terminator = new FakeTerminator("deferred");
|
||||
const probe = createBlockedListing("session/list", terminator);
|
||||
const abort = new AbortController();
|
||||
const reason = new Error("Import listing cancelled during session/list");
|
||||
const options = { limit: 1, signal: abort.signal };
|
||||
const errors: unknown[] = [];
|
||||
const listing = probe.client.listImportableSessions(options).catch((error: unknown) => {
|
||||
errors.push(error);
|
||||
return [];
|
||||
});
|
||||
|
||||
try {
|
||||
await probe.started;
|
||||
abort.abort(reason);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(terminator.terminated).toEqual([probe.child]);
|
||||
expect(errors).toEqual([]);
|
||||
|
||||
terminator.releaseAll();
|
||||
await listing;
|
||||
expect(errors).toEqual([reason]);
|
||||
expect(probe.child.stdin.destroyed).toBe(true);
|
||||
expect(probe.child.stdout.destroyed).toBe(true);
|
||||
expect(probe.child.stderr.destroyed).toBe(true);
|
||||
} finally {
|
||||
probe.release();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
terminator.releaseAll();
|
||||
await listing;
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("ACP providers advertise session listing", () => {
|
||||
// The daemon's agent-manager only queries providers whose
|
||||
// capabilities.supportsSessionListing is true. Without it, ACP providers
|
||||
|
||||
@@ -560,12 +560,14 @@ export interface SpawnedACPProcess {
|
||||
stderrChunks?: string[];
|
||||
}
|
||||
|
||||
type UninitializedACPProcess = Omit<SpawnedACPProcess, "initialize"> & {
|
||||
type ACPProbeProcess = SpawnedACPProcess & { ownsProcessGroup?: boolean };
|
||||
type UninitializedACPProcess = Omit<ACPProbeProcess, "initialize"> & {
|
||||
initialize?: InitializeResponse;
|
||||
};
|
||||
|
||||
interface ACPProcessTransport {
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
ownsProcessGroup?: boolean;
|
||||
connection: ClientSideConnection;
|
||||
stderrChunks: string[];
|
||||
spawnReady: Promise<void>;
|
||||
@@ -1357,57 +1359,84 @@ export class ACPAgentClient implements AgentClient {
|
||||
options?: ListImportableSessionsOptions,
|
||||
): Promise<ImportableProviderSession[]> {
|
||||
const history = new ACPImportHistoryCollector();
|
||||
const signal = options?.signal ?? new AbortController().signal;
|
||||
signal.throwIfAborted();
|
||||
const probe = await this.spawnProcess(PROBE_ENV, {
|
||||
signal,
|
||||
deferCleanupOnError: true,
|
||||
ownsProcessGroup: true,
|
||||
client: this.buildProbeClient((params) => history.accept(params)),
|
||||
});
|
||||
try {
|
||||
if (!probe.initialize.agentCapabilities?.sessionCapabilities?.list) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const sessions: ImportableProviderSession[] = [];
|
||||
const resultLimit = options?.limit ?? Number.POSITIVE_INFINITY;
|
||||
const scanLimit = Math.min(options?.scanLimit ?? 500, 500);
|
||||
const canLoadHistory = probe.initialize.agentCapabilities.loadSession === true;
|
||||
const historyDeadline = this.now() + ACP_IMPORT_HISTORY_BUDGET_MS;
|
||||
let scanned = 0;
|
||||
let cursor: string | null | undefined;
|
||||
for (;;) {
|
||||
const page: ListSessionsResponse = await this.runACPRequest(() =>
|
||||
probe.connection.listSessions(acpSessionListRequest(cursor, options?.cwd)),
|
||||
);
|
||||
for (const session of page.sessions) {
|
||||
if (scanned >= scanLimit || sessions.length >= resultLimit) break;
|
||||
scanned += 1;
|
||||
const descriptor = await this.describeImportableSession(
|
||||
probe,
|
||||
history,
|
||||
session,
|
||||
canLoadHistory,
|
||||
historyDeadline,
|
||||
);
|
||||
if (descriptor) sessions.push(descriptor);
|
||||
}
|
||||
cursor = page.nextCursor ?? null;
|
||||
if (!cursor) break;
|
||||
if (scanned >= scanLimit || sessions.length >= resultLimit) break;
|
||||
}
|
||||
|
||||
return sessions;
|
||||
return await this.listImportableSessionsFromProbe(probe, history, options, signal);
|
||||
} finally {
|
||||
await this.closeProbe(probe);
|
||||
if (signal.aborted) {
|
||||
await this.closeProbe(probe);
|
||||
} else {
|
||||
this.finishListingProbeCleanup(this.closeProbe(probe));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async listImportableSessionsFromProbe(
|
||||
probe: SpawnedACPProcess,
|
||||
history: ACPImportHistoryCollector,
|
||||
options: ListImportableSessionsOptions | undefined,
|
||||
signal: AbortSignal,
|
||||
): Promise<ImportableProviderSession[]> {
|
||||
signal.throwIfAborted();
|
||||
if (!probe.initialize.agentCapabilities?.sessionCapabilities?.list) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const sessions: ImportableProviderSession[] = [];
|
||||
const resultLimit = options?.limit ?? Number.POSITIVE_INFINITY;
|
||||
const scanLimit = Math.min(options?.scanLimit ?? 500, 500);
|
||||
const canLoadHistory = probe.initialize.agentCapabilities.loadSession === true;
|
||||
const historyDeadline = this.now() + ACP_IMPORT_HISTORY_BUDGET_MS;
|
||||
let scanned = 0;
|
||||
let cursor: string | null | undefined;
|
||||
for (;;) {
|
||||
signal.throwIfAborted();
|
||||
const page: ListSessionsResponse = await raceProviderRefreshAbort(
|
||||
signal,
|
||||
this.runACPRequest(() =>
|
||||
probe.connection.listSessions(acpSessionListRequest(cursor, options?.cwd)),
|
||||
),
|
||||
);
|
||||
for (const session of page.sessions) {
|
||||
signal.throwIfAborted();
|
||||
if (scanned >= scanLimit || sessions.length >= resultLimit) break;
|
||||
scanned += 1;
|
||||
const descriptor = await this.describeImportableSession(
|
||||
probe,
|
||||
history,
|
||||
session,
|
||||
canLoadHistory,
|
||||
historyDeadline,
|
||||
signal,
|
||||
);
|
||||
if (descriptor) sessions.push(descriptor);
|
||||
}
|
||||
cursor = page.nextCursor ?? null;
|
||||
if (!cursor) break;
|
||||
if (scanned >= scanLimit || sessions.length >= resultLimit) break;
|
||||
}
|
||||
|
||||
signal.throwIfAborted();
|
||||
return sessions;
|
||||
}
|
||||
|
||||
private async describeImportableSession(
|
||||
probe: SpawnedACPProcess,
|
||||
history: ACPImportHistoryCollector,
|
||||
session: ListSessionsResponse["sessions"][number],
|
||||
canLoadHistory: boolean,
|
||||
historyDeadline: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<ImportableProviderSession | null> {
|
||||
const loadedPreviews = canLoadHistory
|
||||
? await this.loadImportPromptPreviews(probe, history, session, historyDeadline)
|
||||
? await this.loadImportPromptPreviews(probe, history, session, historyDeadline, signal)
|
||||
: null;
|
||||
if (loadedPreviews?.hasConversation === false) return null;
|
||||
return {
|
||||
@@ -1425,7 +1454,9 @@ export class ACPAgentClient implements AgentClient {
|
||||
history: ACPImportHistoryCollector,
|
||||
session: ListSessionsResponse["sessions"][number],
|
||||
historyDeadline: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<ACPImportPromptPreviews | null> {
|
||||
signal.throwIfAborted();
|
||||
const updatedAt = session.updatedAt ?? null;
|
||||
const cached = this.importPromptCache.get(session.sessionId);
|
||||
if (updatedAt !== null && cached?.updatedAt === updatedAt) {
|
||||
@@ -1443,12 +1474,15 @@ export class ACPAgentClient implements AgentClient {
|
||||
history.begin(session.sessionId);
|
||||
try {
|
||||
await withTimeout(
|
||||
this.runACPRequest(() =>
|
||||
probe.connection.loadSession({
|
||||
sessionId: session.sessionId,
|
||||
cwd: session.cwd,
|
||||
mcpServers: [],
|
||||
}),
|
||||
raceProviderRefreshAbort(
|
||||
signal,
|
||||
this.runACPRequest(() =>
|
||||
probe.connection.loadSession({
|
||||
sessionId: session.sessionId,
|
||||
cwd: session.cwd,
|
||||
mcpServers: [],
|
||||
}),
|
||||
),
|
||||
),
|
||||
loadTimeoutMs,
|
||||
`ACP import history load timed out after ${loadTimeoutMs}ms`,
|
||||
@@ -1460,13 +1494,16 @@ export class ACPAgentClient implements AgentClient {
|
||||
return previews;
|
||||
} catch (error) {
|
||||
history.discard(session.sessionId);
|
||||
signal.throwIfAborted();
|
||||
this.logger.debug(
|
||||
{ err: error, sessionId: session.sessionId },
|
||||
"ACP import history load failed; keeping the session visible",
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
await this.closeLoadedSession(probe, session.sessionId, historyDeadline);
|
||||
if (!signal.aborted) {
|
||||
await this.closeLoadedSession(probe, session.sessionId, historyDeadline, signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1474,6 +1511,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
probe: SpawnedACPProcess,
|
||||
sessionId: string,
|
||||
historyDeadline: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
if (!probe.initialize.agentCapabilities?.sessionCapabilities?.close) return;
|
||||
const remainingMs = historyDeadline - this.now();
|
||||
@@ -1481,11 +1519,12 @@ export class ACPAgentClient implements AgentClient {
|
||||
const closeTimeoutMs = Math.min(ACP_PROBE_CLOSE_TIMEOUT_MS, remainingMs);
|
||||
try {
|
||||
await withTimeout(
|
||||
probe.connection.unstable_closeSession({ sessionId }),
|
||||
raceProviderRefreshAbort(signal, probe.connection.unstable_closeSession({ sessionId })),
|
||||
closeTimeoutMs,
|
||||
`ACP loaded session/close timed out after ${closeTimeoutMs}ms`,
|
||||
);
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
this.logger.debug({ err: error, sessionId }, "ACP loaded session close failed");
|
||||
}
|
||||
}
|
||||
@@ -1515,41 +1554,90 @@ export class ACPAgentClient implements AgentClient {
|
||||
providerOptions?: Record<string, unknown>;
|
||||
onSpawned?: (probe: UninitializedACPProcess) => void;
|
||||
client?: ACPClient;
|
||||
signal?: AbortSignal;
|
||||
deferCleanupOnError?: boolean;
|
||||
ownsProcessGroup?: boolean;
|
||||
},
|
||||
): Promise<SpawnedACPProcess> {
|
||||
): Promise<ACPProbeProcess> {
|
||||
const configuredOptions = ACPProviderOptionsSchema.parse(options?.providerOptions ?? {});
|
||||
const transport = await this.spawnTransport(launchEnv, options?.client);
|
||||
const probe: UninitializedACPProcess = {
|
||||
child: transport.child,
|
||||
connection: transport.connection,
|
||||
stderrChunks: transport.stderrChunks,
|
||||
const signal = options?.signal;
|
||||
signal?.throwIfAborted();
|
||||
let transport: ACPProcessTransport | undefined;
|
||||
let closePromise: Promise<void> | undefined;
|
||||
const closeTransport = (): Promise<void> => {
|
||||
if (!transport) return Promise.resolve();
|
||||
closePromise ??= terminateChildProcess(transport, 2_000, this.terminateProcess);
|
||||
return closePromise;
|
||||
};
|
||||
options?.onSpawned?.(probe);
|
||||
try {
|
||||
const initialize = await this.initializeTransport(
|
||||
transport,
|
||||
options?.initializeTimeoutMs,
|
||||
configuredOptions.clientCapabilities,
|
||||
const spawned = await raceProviderRefreshAbort(
|
||||
signal,
|
||||
this.spawnTransport(launchEnv, options?.client, options?.ownsProcessGroup).then(
|
||||
async (spawnedTransport) => {
|
||||
transport = spawnedTransport;
|
||||
// Cancellation can close the process before initialize observes its failure.
|
||||
void spawnedTransport.processError.catch(() => undefined);
|
||||
if (signal?.aborted) {
|
||||
await closeTransport();
|
||||
signal.throwIfAborted();
|
||||
}
|
||||
return spawnedTransport;
|
||||
},
|
||||
),
|
||||
);
|
||||
const initializedProbe: SpawnedACPProcess = {
|
||||
const probe: UninitializedACPProcess = {
|
||||
child: spawned.child,
|
||||
ownsProcessGroup: spawned.ownsProcessGroup,
|
||||
connection: spawned.connection,
|
||||
stderrChunks: spawned.stderrChunks,
|
||||
};
|
||||
options?.onSpawned?.(probe);
|
||||
signal?.throwIfAborted();
|
||||
const initialize = await raceProviderRefreshAbort(
|
||||
signal,
|
||||
this.initializeTransport(
|
||||
spawned,
|
||||
options?.initializeTimeoutMs,
|
||||
configuredOptions.clientCapabilities,
|
||||
),
|
||||
);
|
||||
const initializedProbe: ACPProbeProcess = {
|
||||
...probe,
|
||||
initialize,
|
||||
};
|
||||
probe.initialize = initialize;
|
||||
return initializedProbe;
|
||||
} catch (error) {
|
||||
await terminateChildProcess(transport.child, 2_000, this.terminateProcess);
|
||||
const cleanup = closeTransport();
|
||||
if (options?.deferCleanupOnError && !signal?.aborted) {
|
||||
this.finishListingProbeCleanup(cleanup);
|
||||
} else {
|
||||
await cleanup;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private finishListingProbeCleanup(cleanup: Promise<void>): void {
|
||||
// Deliver the provider's result while its probe finishes shutting down.
|
||||
void cleanup.catch((error) => {
|
||||
this.logger.warn(
|
||||
{ err: error, provider: this.provider },
|
||||
"Failed to close ACP listing probe",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
protected async spawnTransport(
|
||||
launchEnv?: Record<string, string>,
|
||||
client: ACPClient = this.buildProbeClient(),
|
||||
ownsProcessGroup = false,
|
||||
): Promise<ACPProcessTransport> {
|
||||
const { command, args } = await this.resolveLaunchCommand();
|
||||
const detached = ownsProcessGroup && process.platform !== "win32";
|
||||
const child = spawnProcess(command, args, {
|
||||
cwd: process.cwd(),
|
||||
detached,
|
||||
...createProviderEnvSpec({
|
||||
runtimeSettings: this.runtimeSettings,
|
||||
overlays: [launchEnv],
|
||||
@@ -1579,6 +1667,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
|
||||
return {
|
||||
child,
|
||||
ownsProcessGroup: detached,
|
||||
connection,
|
||||
stderrChunks,
|
||||
spawnReady: spawnReadyPromise,
|
||||
@@ -1662,7 +1751,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
} catch (error) {
|
||||
this.logger.debug({ err: error, sessionId }, "ACP probe closeSession failed during cleanup");
|
||||
} finally {
|
||||
await terminateChildProcess(probe.child, 2_000, this.terminateProcess);
|
||||
await terminateChildProcess(probe, 2_000, this.terminateProcess);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4470,12 +4559,16 @@ function coerceSessionConfigMetadata(
|
||||
}
|
||||
|
||||
async function terminateChildProcess(
|
||||
child: ChildProcessWithoutNullStreams,
|
||||
{ child, ownsProcessGroup }: Pick<ACPProbeProcess, "child" | "ownsProcessGroup">,
|
||||
timeoutMs: number,
|
||||
terminate: ProcessTerminator,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await terminate(child, { gracefulTimeoutMs: timeoutMs, forceTimeoutMs: timeoutMs });
|
||||
await terminate(child, {
|
||||
gracefulTimeoutMs: timeoutMs,
|
||||
forceTimeoutMs: timeoutMs,
|
||||
ownsProcessGroup,
|
||||
});
|
||||
} finally {
|
||||
child.stdin.destroy();
|
||||
child.stdout.destroy();
|
||||
|
||||
@@ -1827,7 +1827,7 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
}
|
||||
|
||||
async listImportableSessions(
|
||||
options?: ListImportableSessionsOptions & { signal?: AbortSignal },
|
||||
options?: ListImportableSessionsOptions,
|
||||
): Promise<ImportableProviderSession[]> {
|
||||
// Leave time to deliver the provider error before the client RPC expires at 60 seconds.
|
||||
const deadline = AbortSignal.timeout(45_000);
|
||||
|
||||
@@ -145,6 +145,7 @@ export interface PaseoToolHostDependencies {
|
||||
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
|
||||
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
|
||||
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
|
||||
assertWorkspaceAutomationAllowed?: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
|
||||
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
|
||||
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
|
||||
@@ -3427,11 +3428,18 @@ function archiveWorktreeDependencies(
|
||||
if (!options.clearWorkspaceArchiving) {
|
||||
throw new Error("Workspace archiving clearer is required to archive worktrees");
|
||||
}
|
||||
if (!options.assertWorkspaceAutomationAllowed) {
|
||||
throw new Error("Workspace automation gate is required to archive worktrees");
|
||||
}
|
||||
if (!options.isCheckoutUntrusted) {
|
||||
throw new Error("Checkout trust lookup is required to archive worktrees");
|
||||
}
|
||||
return {
|
||||
paseoHome: options.paseoHome,
|
||||
paseoWorktreesBaseRoot: options.worktreesRoot,
|
||||
worktreeManagers: options.worktreeManagers,
|
||||
workspaceArchiveOperations: options.workspaceArchiveOperations,
|
||||
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
|
||||
isCheckoutUntrusted: options.isCheckoutUntrusted,
|
||||
github: options.github,
|
||||
workspaceGitService: options.workspaceGitService,
|
||||
|
||||
@@ -111,6 +111,8 @@ function createHarness(overrides?: {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
|
||||
assertWorkspaceAutomationAllowed: vi.fn(async () => undefined),
|
||||
isCheckoutUntrusted: vi.fn(async () => false),
|
||||
};
|
||||
const archiveByScope = vi.fn(
|
||||
overrides?.archiveByScope ??
|
||||
@@ -328,6 +330,8 @@ function createRealOutcomeHarness(input: {
|
||||
},
|
||||
markWorkspaceArchiving: () => {},
|
||||
clearWorkspaceArchiving: () => {},
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
|
||||
};
|
||||
|
||||
@@ -628,4 +632,68 @@ describe("archiveIfSafe", () => {
|
||||
expect(archivedWorkspaceIds.has(workspace.workspaceId)).toBe(false);
|
||||
expect(existsSync(worktree.worktreePath)).toBe(true);
|
||||
});
|
||||
|
||||
test("real outcome: skips teardown commands for an unapproved cross-repository checkout", async () => {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const markerName = "auto-archive-merge-teardown.log";
|
||||
const marker = path.join(repoDir, markerName);
|
||||
const fs = await import("node:fs");
|
||||
fs.writeFileSync(
|
||||
path.join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: [
|
||||
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "teardown"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "merged-untrusted");
|
||||
const workspaceId = "ws-merged-untrusted";
|
||||
const archivedWorkspaceIds = new Set<string>();
|
||||
const harness = createRealOutcomeHarness({
|
||||
paseoHome,
|
||||
repoDir,
|
||||
worktreePath: worktree.worktreePath,
|
||||
activeWorkspaces: [
|
||||
{
|
||||
workspaceId,
|
||||
cwd: worktree.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: worktree.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: repoDir,
|
||||
},
|
||||
],
|
||||
archivedWorkspaceIds,
|
||||
});
|
||||
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
|
||||
const assertWorkspaceAutomationAllowed = vi.fn(async () => {
|
||||
throw new WorkspaceAutomationBlockedError({
|
||||
kind: "change_request",
|
||||
forge: "github",
|
||||
number: 123,
|
||||
headRepository: "contributor/repo",
|
||||
});
|
||||
});
|
||||
harness.options.assertWorkspaceAutomationAllowed = assertWorkspaceAutomationAllowed;
|
||||
|
||||
await archiveIfSafe({
|
||||
workspaceId,
|
||||
snapshot: { ...createSnapshot(), cwd: worktree.worktreePath },
|
||||
options: harness.options,
|
||||
log: harness.log,
|
||||
});
|
||||
|
||||
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(workspaceId);
|
||||
expect(archivedWorkspaceIds.has(workspaceId)).toBe(true);
|
||||
expect(existsSync(worktree.worktreePath)).toBe(false);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,7 +25,8 @@ export interface AutoArchiveArchiveOptions {
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
|
||||
getWorkspace?: ArchiveDependencies["getWorkspace"];
|
||||
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
|
||||
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
daemonConfigStore: DaemonConfigStore;
|
||||
workspaceGitService: WorkspaceGitServiceImpl;
|
||||
github: ForgeService;
|
||||
@@ -113,6 +114,7 @@ export async function archiveIfSafe(input: {
|
||||
agentStorage: options.agentStorage,
|
||||
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
|
||||
getWorkspace: options.getWorkspace,
|
||||
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
|
||||
isCheckoutUntrusted: options.isCheckoutUntrusted,
|
||||
listActiveWorkspaces: options.listActiveWorkspaces,
|
||||
archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) =>
|
||||
|
||||
@@ -16,6 +16,7 @@ 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";
|
||||
@@ -636,6 +637,9 @@ 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");
|
||||
@@ -874,11 +878,13 @@ 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),
|
||||
});
|
||||
});
|
||||
@@ -1246,6 +1252,8 @@ export async function createPaseoDaemon(
|
||||
logger,
|
||||
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
|
||||
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
getAutoArchivedChangeRequestUrl: async (workspaceId) =>
|
||||
@@ -1358,6 +1366,8 @@ export async function createPaseoDaemon(
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
agentManager,
|
||||
agentStorage,
|
||||
@@ -1611,6 +1621,8 @@ export async function createPaseoDaemon(
|
||||
workspaceGitService,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
@@ -1803,7 +1815,20 @@ export async function createPaseoDaemon(
|
||||
const start = async () => {
|
||||
let mainStarted = false;
|
||||
try {
|
||||
localCredential = await writeLocalCredential(config.paseoHome);
|
||||
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;
|
||||
if (serviceProxyListenTarget) {
|
||||
const boundServiceProxyTarget = await serviceProxy.startStandalone({
|
||||
listenTarget: serviceProxyListenTarget,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
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;
|
||||
}
|
||||
@@ -365,7 +365,7 @@ export default function contribute(server) {
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 60_000);
|
||||
}, 90_000);
|
||||
|
||||
test("worktree manager supports decline fallback, rollback delegation, and disabled-plugin fallback on archive and restore", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-manager-fallback-"));
|
||||
@@ -606,9 +606,7 @@ export default function contribute(server) {
|
||||
const pending = client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "concurrent" },
|
||||
});
|
||||
// Cleanup closes the client if the marker never arrives.
|
||||
void pending.catch(() => undefined);
|
||||
await expect
|
||||
const managerStarted = expect
|
||||
.poll(
|
||||
() =>
|
||||
stat(path.join(root, "manager-started")).then(
|
||||
@@ -618,6 +616,12 @@ export default function contribute(server) {
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
await Promise.race([
|
||||
managerStarted,
|
||||
pending.then(({ error }) => {
|
||||
throw new Error(`Worktree creation finished before the manager was released: ${error}`);
|
||||
}),
|
||||
]);
|
||||
const concurrent = path.join(root, "concurrent-manual");
|
||||
git(repository, ["worktree", "add", "-b", "concurrent", concurrent, "main"]);
|
||||
await writeFile(path.join(concurrent, "local.txt"), "uncommitted work");
|
||||
|
||||
@@ -171,6 +171,8 @@ function createScheduleService(options: TestScheduleServiceOptions): ScheduleSer
|
||||
markWorkspaceArchiving: () => {},
|
||||
clearWorkspaceArchiving: () => {},
|
||||
killTerminalsForWorkspace: async () => {},
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: options.logger,
|
||||
},
|
||||
{
|
||||
@@ -276,6 +278,8 @@ async function createRegistryBackedScheduleWorkspaceDeps(rootDir: string): Promi
|
||||
markWorkspaceArchiving: () => {},
|
||||
clearWorkspaceArchiving: () => {},
|
||||
killTerminalsForWorkspace: async () => {},
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: logger,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1301,6 +1301,8 @@ export class Session {
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
workspaceArchiveOperations: this.workspaceArchiveOperations,
|
||||
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
|
||||
assertWorkspaceAutomationAllowed: (workspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) =>
|
||||
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
|
||||
agentManager: this.agentManager,
|
||||
@@ -5850,6 +5852,8 @@ export class Session {
|
||||
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
|
||||
killTerminalsForWorkspace: (workspaceId) =>
|
||||
this.terminalController.killTerminalsForWorkspace(workspaceId),
|
||||
assertWorkspaceAutomationAllowed: (workspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) =>
|
||||
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
|
||||
sessionLogger: this.sessionLogger,
|
||||
@@ -6557,16 +6561,19 @@ export class Session {
|
||||
};
|
||||
}
|
||||
|
||||
private async withWorkspaceCheckout<T>(workspaceId: string, run: () => Promise<T>): Promise<T> {
|
||||
private async withWorkspaceCheckout<T>(
|
||||
workspaceId: string,
|
||||
run: (checkoutPath: string | null) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const workspace = await this.workspaceRegistry.get(workspaceId);
|
||||
if (!workspace) {
|
||||
return run();
|
||||
return run(null);
|
||||
}
|
||||
const checkoutPath = await resolveWorkspaceBackingPath(workspace, {
|
||||
paseoHome: this.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.worktreesRoot,
|
||||
});
|
||||
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
|
||||
return this.workspaceArchiveOperations.withCheckout(checkoutPath, () => run(checkoutPath));
|
||||
}
|
||||
|
||||
private async withCheckoutForDirectory<T>(cwd: string, run: () => Promise<T>): Promise<T> {
|
||||
@@ -8209,7 +8216,15 @@ export class Session {
|
||||
{
|
||||
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
|
||||
clearAutomationBlock: (workspaceId) =>
|
||||
clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId),
|
||||
this.withWorkspaceCheckout(workspaceId, async (checkoutPath) => {
|
||||
const current = await this.workspaceRegistry.get(workspaceId);
|
||||
if (!current || current.archivedAt) {
|
||||
throw new Error(`Workspace not found: ${workspaceId}`);
|
||||
}
|
||||
return clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId, {
|
||||
checkoutPath,
|
||||
});
|
||||
}),
|
||||
startWorkspaceSetup: (workspaceId, operation) =>
|
||||
this.workspaceSetupRuntime.start(workspaceId, operation),
|
||||
paseoHome: this.paseoHome,
|
||||
|
||||
+148
-1
@@ -1,8 +1,9 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync } from "node:fs";
|
||||
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { getCheckoutStatus } from "../../../utils/checkout-git.js";
|
||||
import {
|
||||
@@ -1168,3 +1169,149 @@ test("a failed workspace unarchive write keeps agents archived and permits retry
|
||||
expect((await registry.get(workspace.workspaceId))?.archivedAt).toBeNull();
|
||||
expect(agentArchived).toBe(false);
|
||||
});
|
||||
|
||||
describe("checkout approval state on open and unarchive", () => {
|
||||
const sampleUntrustedSource = (number: number) => ({
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number,
|
||||
headRepository: "contributor/repo",
|
||||
});
|
||||
|
||||
function createCheckoutDirs(name: string) {
|
||||
const sourceCwd = path.join(tmpDir, `repo-${name}`);
|
||||
const worktreePath = path.join(tmpDir, `worktree-${name}`);
|
||||
mkdirSync(sourceCwd, { recursive: true });
|
||||
mkdirSync(worktreePath, { recursive: true });
|
||||
gitRoots.add(sourceCwd);
|
||||
gitRoots.add(worktreePath);
|
||||
return { sourceCwd, worktreePath };
|
||||
}
|
||||
|
||||
function addWorktreeRecord(
|
||||
dirs: { sourceCwd: string; worktreePath: string },
|
||||
branch: string,
|
||||
untrustedSource?: ReturnType<typeof sampleUntrustedSource>,
|
||||
) {
|
||||
return provisioning.createWorkspaceForWorktree({
|
||||
sourceCwd: dirs.sourceCwd,
|
||||
repoRoot: dirs.sourceCwd,
|
||||
cwd: dirs.worktreePath,
|
||||
worktreeRoot: dirs.worktreePath,
|
||||
branch,
|
||||
baseBranch: "main",
|
||||
title: null,
|
||||
...(untrustedSource ? { untrustedSource } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
test("unarchiving an approved workspace onto an active unapproved checkout inherits untrustedSource", async () => {
|
||||
const dirs = createCheckoutDirs("unarchive-inherit");
|
||||
const original = await addWorktreeRecord(dirs, "feature/approved");
|
||||
await workspaceRegistry.archive(original.workspaceId, ARCHIVED_AT);
|
||||
const archivedOriginal = (await workspaceRegistry.get(original.workspaceId))!;
|
||||
|
||||
const untrustedSource = sampleUntrustedSource(55);
|
||||
await addWorktreeRecord(dirs, "contributor/pr-55", untrustedSource);
|
||||
|
||||
const restored = await provisioning.ensureWorkspaceRecordUnarchived(archivedOriginal);
|
||||
|
||||
expect(restored.archivedAt).toBeNull();
|
||||
expect(restored.untrustedSource).toEqual(untrustedSource);
|
||||
expect((await workspaceRegistry.get(original.workspaceId))?.untrustedSource).toEqual(
|
||||
untrustedSource,
|
||||
);
|
||||
});
|
||||
|
||||
test("unarchiving an approved workspace ignores archived unapproved records on the same path", async () => {
|
||||
const dirs = createCheckoutDirs("unarchive-historical");
|
||||
const oldUntrusted = await addWorktreeRecord(
|
||||
dirs,
|
||||
"contributor/pr-56",
|
||||
sampleUntrustedSource(56),
|
||||
);
|
||||
await workspaceRegistry.archive(oldUntrusted.workspaceId, "2026-04-01T00:00:00.000Z");
|
||||
|
||||
const approved = await addWorktreeRecord(dirs, "feature/fresh");
|
||||
await workspaceRegistry.archive(approved.workspaceId, "2026-04-02T00:00:00.000Z");
|
||||
|
||||
const restored = await provisioning.ensureWorkspaceRecordUnarchived(
|
||||
(await workspaceRegistry.get(approved.workspaceId))!,
|
||||
);
|
||||
|
||||
expect(restored.archivedAt).toBeNull();
|
||||
expect(restored.untrustedSource).toBeUndefined();
|
||||
});
|
||||
|
||||
test("unarchiving an approved workspace onto a retained unapproved checkout inherits untrustedSource from checkout metadata", async () => {
|
||||
const sourceCwd = path.join(tmpDir, "repo-retained-metadata");
|
||||
mkdirSync(sourceCwd, { recursive: true });
|
||||
execFileSync("git", ["init", "-b", "main"], { cwd: sourceCwd, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
|
||||
cwd: sourceCwd,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: sourceCwd, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "init"], {
|
||||
cwd: sourceCwd,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const worktreePath = path.join(tmpDir, "worktree-retained-metadata");
|
||||
execFileSync("git", ["worktree", "add", "-b", "retained-pr", worktreePath, "main"], {
|
||||
cwd: sourceCwd,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const untrustedSource = sampleUntrustedSource(57);
|
||||
await writePaseoWorktreeMetadata(worktreePath, {
|
||||
baseRefName: "main",
|
||||
untrustedSource,
|
||||
});
|
||||
gitRoots.add(sourceCwd);
|
||||
gitRoots.add(worktreePath);
|
||||
|
||||
const approved = await addWorktreeRecord({ sourceCwd, worktreePath }, "feature/approved");
|
||||
await workspaceRegistry.archive(approved.workspaceId, ARCHIVED_AT);
|
||||
|
||||
const restored = await provisioning.ensureWorkspaceRecordUnarchived(
|
||||
(await workspaceRegistry.get(approved.workspaceId))!,
|
||||
);
|
||||
|
||||
expect(restored.archivedAt).toBeNull();
|
||||
expect(restored.untrustedSource).toEqual(untrustedSource);
|
||||
});
|
||||
|
||||
test("creating a directory workspace ignores archived unapproved records on the same path", async () => {
|
||||
const dirs = createCheckoutDirs("dir-reused-path");
|
||||
const oldUntrusted = await addWorktreeRecord(
|
||||
dirs,
|
||||
"contributor/pr-58",
|
||||
sampleUntrustedSource(58),
|
||||
);
|
||||
await workspaceRegistry.archive(oldUntrusted.workspaceId, ARCHIVED_AT);
|
||||
|
||||
const opened = await provisioning.createWorkspaceForDirectory(dirs.worktreePath);
|
||||
|
||||
expect(opened.untrustedSource).toBeUndefined();
|
||||
});
|
||||
|
||||
test("unarchiving an old unapproved workspace onto a live approved checkout drops its stale untrustedSource", async () => {
|
||||
const dirs = createCheckoutDirs("unarchive-stale-block");
|
||||
const oldUntrusted = await addWorktreeRecord(
|
||||
dirs,
|
||||
"contributor/pr-59",
|
||||
sampleUntrustedSource(59),
|
||||
);
|
||||
await workspaceRegistry.archive(oldUntrusted.workspaceId, ARCHIVED_AT);
|
||||
const archivedOldUntrusted = (await workspaceRegistry.get(oldUntrusted.workspaceId))!;
|
||||
|
||||
await addWorktreeRecord(dirs, "feature/fresh-approved");
|
||||
|
||||
const unarchived = await provisioning.ensureWorkspaceRecordUnarchived(archivedOldUntrusted);
|
||||
|
||||
expect(unarchived.archivedAt).toBeNull();
|
||||
expect(unarchived.untrustedSource).toBeUndefined();
|
||||
expect(
|
||||
(await workspaceRegistry.get(oldUntrusted.workspaceId))?.untrustedSource,
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
+48
-7
@@ -275,12 +275,10 @@ export function createWorkspaceProvisioningService(deps: {
|
||||
? await readPaseoWorktreeMetadata(checkout.worktreeRoot ?? normalizedCwd)
|
||||
: null;
|
||||
const checkoutRoot = checkout.worktreeRoot ?? normalizedCwd;
|
||||
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
|
||||
const inheritedUntrustedSource = (await workspaceRegistry.listAll()).find(
|
||||
(candidate) =>
|
||||
Boolean(candidate.untrustedSource) &&
|
||||
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
|
||||
)?.untrustedSource;
|
||||
const { untrustedSource: inheritedUntrustedSource } = await resolveCheckoutUntrustedSource(
|
||||
checkoutRoot,
|
||||
baseMetadata?.untrustedSource,
|
||||
);
|
||||
const timestamp = new Date().toISOString();
|
||||
const workspace = createPersistedWorkspaceRecord({
|
||||
workspaceId: context?.workspaceId ?? generateWorkspaceId(),
|
||||
@@ -429,6 +427,49 @@ export function createWorkspaceProvisioningService(deps: {
|
||||
).workspaceId;
|
||||
}
|
||||
|
||||
async function resolveCheckoutUntrustedSource(
|
||||
checkoutRoot: string,
|
||||
knownMetadataUntrustedSource?: UntrustedWorkspaceSource,
|
||||
): Promise<{ hasEvidence: boolean; untrustedSource: UntrustedWorkspaceSource | undefined }> {
|
||||
const metadataUntrustedSource =
|
||||
knownMetadataUntrustedSource ??
|
||||
(await readPaseoWorktreeMetadata(checkoutRoot).catch(() => null))?.untrustedSource;
|
||||
if (metadataUntrustedSource) {
|
||||
return { hasEvidence: true, untrustedSource: metadataUntrustedSource };
|
||||
}
|
||||
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
|
||||
const active = (await workspaceRegistry.listActive()).filter((candidate) =>
|
||||
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
|
||||
);
|
||||
if (active.length === 0) {
|
||||
return { hasEvidence: false, untrustedSource: undefined };
|
||||
}
|
||||
return {
|
||||
hasEvidence: true,
|
||||
untrustedSource: active.find((candidate) => Boolean(candidate.untrustedSource))
|
||||
?.untrustedSource,
|
||||
};
|
||||
}
|
||||
|
||||
async function syncUnarchivedCheckoutUntrustedSource(
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
): Promise<PersistedWorkspaceRecord> {
|
||||
const resolved = await resolveCheckoutUntrustedSource(workspace.worktreeRoot ?? workspace.cwd);
|
||||
if (!resolved.hasEvidence) {
|
||||
return workspace;
|
||||
}
|
||||
if (resolved.untrustedSource) {
|
||||
return workspace.untrustedSource
|
||||
? workspace
|
||||
: { ...workspace, untrustedSource: resolved.untrustedSource };
|
||||
}
|
||||
if (!workspace.untrustedSource) {
|
||||
return workspace;
|
||||
}
|
||||
const { untrustedSource: _stale, ...approved } = workspace;
|
||||
return approved;
|
||||
}
|
||||
|
||||
async function resolveRestoredAutoArchiveChangeRequestUrl(
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
): Promise<string | null> {
|
||||
@@ -466,7 +507,7 @@ export function createWorkspaceProvisioningService(deps: {
|
||||
updatedAt: timestamp,
|
||||
});
|
||||
next = {
|
||||
...(placementUpdate?.workspace ?? workspace),
|
||||
...(await syncUnarchivedCheckoutUntrustedSource(placementUpdate?.workspace ?? workspace)),
|
||||
archivedAt: null,
|
||||
autoArchivedChangeRequestUrl,
|
||||
updatedAt: timestamp,
|
||||
|
||||
+133
@@ -23,12 +23,14 @@ import {
|
||||
} from "../../../utils/worktree-metadata.js";
|
||||
import { createWorktree, deletePaseoWorktree } from "../../../utils/worktree.js";
|
||||
import {
|
||||
FileBackedProjectRegistry,
|
||||
FileBackedWorkspaceRegistry,
|
||||
createPersistedProjectRecord,
|
||||
createPersistedWorkspaceRecord,
|
||||
type PersistedProjectRecord,
|
||||
type PersistedWorkspaceRecord,
|
||||
} from "../../workspace-registry.js";
|
||||
import { createWorkspaceProvisioningService } from "../workspace-provisioning/workspace-provisioning-service.js";
|
||||
import { createWorkspaceRecoveryService } from "./workspace-recovery-service.js";
|
||||
|
||||
const NOW = "2026-07-11T10:12:30.752Z";
|
||||
@@ -719,3 +721,134 @@ test("restores a user-created worktree at its recorded path outside Paseo's root
|
||||
).toBe("external-feature");
|
||||
expect(unarchived).toEqual([workspace.workspaceId]);
|
||||
});
|
||||
|
||||
describe("recovery approval ownership for shared archived history", () => {
|
||||
async function setupSlugReuseHistory(options: { keepLatestCheckoutOnDisk: boolean }) {
|
||||
const { tempDir, repoDir } = createGitRepository();
|
||||
const paseoHome = join(tempDir, "paseo-home");
|
||||
const workspaceRegistry = new FileBackedWorkspaceRegistry(
|
||||
join(paseoHome, "workspaces.json"),
|
||||
pino({ level: "silent" }),
|
||||
);
|
||||
const projectRegistry = new FileBackedProjectRegistry(
|
||||
join(paseoHome, "projects.json"),
|
||||
pino({ level: "silent" }),
|
||||
);
|
||||
const provisioning = createWorkspaceProvisioningService({
|
||||
unarchiveWorkspaceAgents: async () => {},
|
||||
workspaceRegistry,
|
||||
projectRegistry,
|
||||
workspaceGitService: {
|
||||
getCheckout: async (cwd) => getCheckoutStatus(cwd),
|
||||
getSnapshot: async () => ({
|
||||
checkout: null,
|
||||
forge: { pullRequest: null, checkedAt: null, error: null },
|
||||
}),
|
||||
},
|
||||
isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(),
|
||||
logger: pino({ level: "silent" }),
|
||||
});
|
||||
|
||||
const firstWorktree = await createWorktree({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "shared-slug",
|
||||
source: { kind: "branch-off", branchName: "feature/older-approved", baseBranch: "main" },
|
||||
paseoHome,
|
||||
});
|
||||
const olderApproved = await provisioning.createWorkspaceForWorktree({
|
||||
sourceCwd: repoDir,
|
||||
repoRoot: repoDir,
|
||||
cwd: firstWorktree.worktreePath,
|
||||
worktreeRoot: firstWorktree.worktreePath,
|
||||
branch: firstWorktree.branchName,
|
||||
baseBranch: firstWorktree.baseRef,
|
||||
title: null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
});
|
||||
await workspaceRegistry.archive(olderApproved.workspaceId, "2026-04-01T00:00:00.000Z");
|
||||
await deletePaseoWorktree({
|
||||
cwd: repoDir,
|
||||
worktreePath: firstWorktree.worktreePath,
|
||||
paseoHome,
|
||||
});
|
||||
|
||||
const untrustedSource = {
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number: 72,
|
||||
headRepository: "contributor/repo",
|
||||
};
|
||||
const secondWorktree = await createWorktree({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "shared-slug",
|
||||
source: { kind: "branch-off", branchName: "contributor/pr-72", baseBranch: "main" },
|
||||
paseoHome,
|
||||
});
|
||||
await writePaseoWorktreeMetadata(secondWorktree.worktreePath, {
|
||||
baseRefName: "main",
|
||||
untrustedSource,
|
||||
});
|
||||
const laterUntrusted = await provisioning.createWorkspaceForWorktree({
|
||||
sourceCwd: repoDir,
|
||||
repoRoot: repoDir,
|
||||
cwd: secondWorktree.worktreePath,
|
||||
worktreeRoot: secondWorktree.worktreePath,
|
||||
branch: secondWorktree.branchName,
|
||||
baseBranch: secondWorktree.baseRef,
|
||||
title: null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
untrustedSource,
|
||||
});
|
||||
await workspaceRegistry.archive(laterUntrusted.workspaceId, "2026-04-02T00:00:00.000Z");
|
||||
if (!options.keepLatestCheckoutOnDisk) {
|
||||
await deletePaseoWorktree({
|
||||
cwd: repoDir,
|
||||
worktreePath: secondWorktree.worktreePath,
|
||||
paseoHome,
|
||||
});
|
||||
}
|
||||
|
||||
const recovery = createWorkspaceRecoveryService({
|
||||
paseoHome,
|
||||
getWorkspace: (id) => workspaceRegistry.get(id),
|
||||
getProject: (id) => projectRegistry.get(id),
|
||||
isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(),
|
||||
unarchiveWorkspace: async (workspace) => {
|
||||
await provisioning.ensureWorkspaceRecordUnarchived(workspace);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
olderApproved,
|
||||
untrustedSource,
|
||||
worktreePath: firstWorktree.worktreePath,
|
||||
workspaceRegistry,
|
||||
recovery,
|
||||
};
|
||||
}
|
||||
|
||||
test("restoring a deleted approved workspace after slug reuse keeps the recreated worktree approved", async () => {
|
||||
const { olderApproved, worktreePath, workspaceRegistry, recovery } =
|
||||
await setupSlugReuseHistory({ keepLatestCheckoutOnDisk: false });
|
||||
|
||||
const result = await recovery.restore(olderApproved.workspaceId);
|
||||
|
||||
expect(result).toEqual({ workspaceId: olderApproved.workspaceId, action: "restore" });
|
||||
const restored = await workspaceRegistry.get(olderApproved.workspaceId);
|
||||
expect(restored?.archivedAt).toBeNull();
|
||||
expect(restored?.untrustedSource).toBeUndefined();
|
||||
expect((await readPaseoWorktreeMetadata(worktreePath))?.untrustedSource).toBeUndefined();
|
||||
});
|
||||
|
||||
test("unarchiving onto a retained unapproved checkout inherits untrustedSource from worktree metadata", async () => {
|
||||
const { olderApproved, untrustedSource, workspaceRegistry, recovery } =
|
||||
await setupSlugReuseHistory({ keepLatestCheckoutOnDisk: true });
|
||||
|
||||
const result = await recovery.restore(olderApproved.workspaceId);
|
||||
|
||||
expect(result).toEqual({ workspaceId: olderApproved.workspaceId, action: "unarchive" });
|
||||
const restored = await workspaceRegistry.get(olderApproved.workspaceId);
|
||||
expect(restored?.archivedAt).toBeNull();
|
||||
expect(restored?.untrustedSource).toEqual(untrustedSource);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js";
|
||||
import { runWithRepositoryRoot } from "../../../utils/git-repository-discovery.js";
|
||||
import { createRealpathAwarePathMatcher } from "../../../utils/path.js";
|
||||
import { runGitCommand } from "../../../utils/run-git-command.js";
|
||||
import { setPaseoWorktreeUntrustedSource } from "../../../utils/worktree-metadata.js";
|
||||
import {
|
||||
createWorktree,
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
@@ -280,6 +281,9 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
error,
|
||||
);
|
||||
}
|
||||
if (workspace.untrustedSource) {
|
||||
await setPaseoWorktreeUntrustedSource(recreatedWorktreePath, workspace.untrustedSource);
|
||||
}
|
||||
return { worktreePath: recreatedWorktreePath, pluginId: restoredByPluginId };
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ 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";
|
||||
@@ -2060,12 +2061,14 @@ 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.
|
||||
|
||||
@@ -7,12 +7,17 @@ import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import type { ForgeService } from "../services/forge-service.js";
|
||||
import { createRealpathAwarePathMatcher } from "../utils/path.js";
|
||||
import { getPaseoWorktreeMetadataPath } from "../utils/worktree-metadata.js";
|
||||
import {
|
||||
getPaseoWorktreeMetadataPath,
|
||||
readPaseoWorktreeMetadata,
|
||||
setPaseoWorktreeUntrustedSource,
|
||||
} from "../utils/worktree-metadata.js";
|
||||
import { archiveCommand } from "./worktree/commands.js";
|
||||
import { createWorktree, listPaseoWorktrees, type WorktreeConfig } from "../utils/worktree.js";
|
||||
import type { ManagedAgent } from "./agent/agent-manager.js";
|
||||
import type { AgentStorage, StoredAgentRecord } from "./agent/agent-storage.js";
|
||||
import type { WorkspaceGitService } from "./workspace-git-service.js";
|
||||
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
|
||||
import {
|
||||
archiveByScope,
|
||||
unarchiveWorkspaceAgents,
|
||||
@@ -22,7 +27,16 @@ import {
|
||||
resolveWorkspaceIdAtPath,
|
||||
WorkspaceArchiveCanceledError,
|
||||
} from "./workspace-archive-service.js";
|
||||
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
|
||||
import {
|
||||
assertWorkspaceAutomationAllowedForWorkspace,
|
||||
clearWorkspaceAutomationBlock,
|
||||
isCheckoutUntrusted,
|
||||
WorkspaceAutomationBlockedError,
|
||||
} from "./workspace-automation-gate.js";
|
||||
import {
|
||||
createPersistedWorkspaceRecord,
|
||||
FileBackedWorkspaceRegistry,
|
||||
} from "./workspace-registry.js";
|
||||
|
||||
const cleanupPaths: string[] = [];
|
||||
|
||||
@@ -175,6 +189,8 @@ function createArchiveDeps(input: ArchiveDepsInput): ArchiveTestDependencies {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
activeWorkspaces: active,
|
||||
archivedAgentIds,
|
||||
@@ -480,6 +496,394 @@ describe("archiveByScope", () => {
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
describe("teardown approval gating", () => {
|
||||
const sampleBlockedSource = (number = 42) => ({
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number,
|
||||
headRepository: "contributor/paseo",
|
||||
});
|
||||
|
||||
async function createTeardownWorktree(slug: string, options?: { nestedRelative?: string }) {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const markerName = `${slug}-teardown.log`;
|
||||
const marker = path.join(repoDir, markerName);
|
||||
const configDir = options?.nestedRelative
|
||||
? path.join(repoDir, options.nestedRelative)
|
||||
: repoDir;
|
||||
mkdirSync(configDir, { recursive: true });
|
||||
writeFileSync(
|
||||
path.join(configDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: [
|
||||
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", `teardown ${slug}`], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, slug);
|
||||
return { repoDir, paseoHome, worktreePath: worktree.worktreePath, marker };
|
||||
}
|
||||
|
||||
function makeWorktreeWorkspace(
|
||||
workspaceId: string,
|
||||
fixture: { repoDir: string; worktreePath: string },
|
||||
overrides: Partial<ActiveWorkspaceRef> = {},
|
||||
): ActiveWorkspaceRef {
|
||||
return {
|
||||
workspaceId,
|
||||
cwd: fixture.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: fixture.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: fixture.repoDir,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test("workspace scope skips teardown when the workspace record carries untrustedSource", async () => {
|
||||
const fixture = await createTeardownWorktree("untrusted-record");
|
||||
const workspaceId = "ws-untrusted-record";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [
|
||||
makeWorktreeWorkspace(workspaceId, fixture, { untrustedSource: sampleBlockedSource() }),
|
||||
],
|
||||
});
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-untrusted-record",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("workspace scope runs teardown for a fresh worktree reusing the path of an archived unapproved checkout", async () => {
|
||||
const fixture = await createTeardownWorktree("reused-slug");
|
||||
const workspaceId = "ws-fresh-reused-slug";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [makeWorktreeWorkspace(workspaceId, fixture)],
|
||||
});
|
||||
// Simulates an earlier archived unapproved workspace that previously used the same path.
|
||||
deps.isCheckoutUntrusted = async () => true;
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-fresh-reused-slug",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
|
||||
});
|
||||
|
||||
test("retrying archive on an already-archived unapproved workspace does not mark a fresh worktree at the same path", async () => {
|
||||
const fixture = await createTeardownWorktree("reused-after-retry");
|
||||
const oldArchivedId = "ws-old-archived-unapproved";
|
||||
const freshWorkspaceId = "ws-fresh-approved";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [makeWorktreeWorkspace(freshWorkspaceId, fixture)],
|
||||
});
|
||||
deps.getWorkspace = async (workspaceId) =>
|
||||
workspaceId === oldArchivedId
|
||||
? {
|
||||
...makeWorktreeWorkspace(oldArchivedId, fixture, {
|
||||
untrustedSource: sampleBlockedSource(),
|
||||
}),
|
||||
projectId: "proj-1",
|
||||
archivedAt: "2026-11-24T00:00:00.000Z",
|
||||
createdAt: "2026-11-24T00:00:00.000Z",
|
||||
updatedAt: "2026-11-24T00:00:00.000Z",
|
||||
}
|
||||
: null;
|
||||
deps.isCheckoutUntrusted = async () => true;
|
||||
|
||||
const retry = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: oldArchivedId },
|
||||
requestId: "req-retry-archived",
|
||||
});
|
||||
expect(retry.archivedWorkspaceIds).toEqual([]);
|
||||
expect(retry.removedDirectory).toBe(false);
|
||||
expect(
|
||||
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
|
||||
).toBeUndefined();
|
||||
|
||||
const fresh = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: freshWorkspaceId },
|
||||
requestId: "req-archive-fresh",
|
||||
});
|
||||
expect(fresh.archivedWorkspaceIds).toEqual([freshWorkspaceId]);
|
||||
expect(fresh.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
|
||||
});
|
||||
|
||||
test("workspace scope skips teardown when retained checkout metadata carries untrustedSource", async () => {
|
||||
const fixture = await createTeardownWorktree("retained-metadata");
|
||||
await setPaseoWorktreeUntrustedSource(fixture.worktreePath, sampleBlockedSource(88));
|
||||
const workspaceId = "ws-reopened-on-retained";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [makeWorktreeWorkspace(workspaceId, fixture)],
|
||||
});
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-retained-metadata",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("workspace scope backfills checkout metadata when archiving a pre-upgrade unapproved worktree whose directory stays on disk", async () => {
|
||||
const fixture = await createTeardownWorktree("pre-upgrade-retained");
|
||||
expect(
|
||||
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
|
||||
).toBeUndefined();
|
||||
const untrustedSource = sampleBlockedSource(91);
|
||||
const blockedWorkspaceId = "ws-pre-upgrade-blocked";
|
||||
const keptSiblingId = "ws-pre-upgrade-sibling";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [
|
||||
makeWorktreeWorkspace(blockedWorkspaceId, fixture, { untrustedSource }),
|
||||
makeWorktreeWorkspace(keptSiblingId, fixture),
|
||||
],
|
||||
});
|
||||
|
||||
const first = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: blockedWorkspaceId },
|
||||
requestId: "req-pre-upgrade-first",
|
||||
});
|
||||
expect(first.removedDirectory).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
expect((await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource).toEqual(
|
||||
untrustedSource,
|
||||
);
|
||||
|
||||
const second = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: keptSiblingId },
|
||||
requestId: "req-pre-upgrade-second",
|
||||
});
|
||||
expect(second.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test.each(["approval-first", "archive-first"] as const)(
|
||||
"serializing archive and setup approval through withCheckout preserves completed approval (%s)",
|
||||
async (order) => {
|
||||
const fixture = await createTeardownWorktree(`serialized-${order}`);
|
||||
const untrustedSource = sampleBlockedSource(92);
|
||||
const registry = new FileBackedWorkspaceRegistry(
|
||||
path.join(fixture.paseoHome, "workspaces.json"),
|
||||
createLogger(),
|
||||
);
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
const now = "2026-11-24T00:00:00.000Z";
|
||||
const ws1 = createPersistedWorkspaceRecord({
|
||||
workspaceId: "ws-archive-target",
|
||||
projectId: "proj-1",
|
||||
displayName: "ws-archive-target",
|
||||
cwd: fixture.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: fixture.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: fixture.repoDir,
|
||||
untrustedSource,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
const ws2 = createPersistedWorkspaceRecord({
|
||||
workspaceId: "ws-approve-sibling",
|
||||
projectId: "proj-1",
|
||||
displayName: "ws-approve-sibling",
|
||||
cwd: fixture.worktreePath,
|
||||
kind: "worktree",
|
||||
worktreeRoot: fixture.worktreePath,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: fixture.repoDir,
|
||||
untrustedSource,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
await registry.upsert(ws1);
|
||||
await registry.upsert(ws2);
|
||||
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [],
|
||||
});
|
||||
deps.workspaceArchiveOperations = operations;
|
||||
deps.getWorkspace = (id) => registry.get(id);
|
||||
deps.listActiveWorkspaces = () => registry.listActive();
|
||||
deps.archiveWorkspaceRecord = async (id, archivedAt) => {
|
||||
await registry.archive(id, archivedAt);
|
||||
};
|
||||
deps.assertWorkspaceAutomationAllowed = (id) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(registry, id);
|
||||
deps.isCheckoutUntrusted = (checkoutPath) => isCheckoutUntrusted(registry, checkoutPath);
|
||||
|
||||
async function clearInsideCheckoutLock() {
|
||||
return clearWorkspaceAutomationBlock(registry, ws2.workspaceId, {
|
||||
checkoutPath: fixture.worktreePath,
|
||||
});
|
||||
}
|
||||
|
||||
if (order === "approval-first") {
|
||||
const [cleared, archived] = await Promise.all([
|
||||
operations.withCheckout(fixture.worktreePath, clearInsideCheckoutLock),
|
||||
archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: ws1.workspaceId },
|
||||
requestId: `req-${order}-ws1`,
|
||||
}),
|
||||
]);
|
||||
expect(cleared).toBe(true);
|
||||
expect(archived.removedDirectory).toBe(false);
|
||||
} else {
|
||||
// Pause archive mid-flight (after resolving targets, before backfill) while Run setup
|
||||
// queues on the same checkout lock, ensuring approval runs after backfill and wins.
|
||||
let enteredStop!: () => void;
|
||||
let releaseStop!: () => void;
|
||||
const stopEntered = new Promise<void>((resolve) => {
|
||||
enteredStop = resolve;
|
||||
});
|
||||
const stopGate = new Promise<void>((resolve) => {
|
||||
releaseStop = resolve;
|
||||
});
|
||||
deps.stopWorkspaceSetup = async () => {
|
||||
enteredStop();
|
||||
await stopGate;
|
||||
};
|
||||
const archivePromise = archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: ws1.workspaceId },
|
||||
requestId: `req-${order}-ws1`,
|
||||
});
|
||||
await stopEntered;
|
||||
const approvalPromise = operations.withCheckout(
|
||||
fixture.worktreePath,
|
||||
clearInsideCheckoutLock,
|
||||
);
|
||||
releaseStop();
|
||||
const [archived, cleared] = await Promise.all([archivePromise, approvalPromise]);
|
||||
expect(archived.removedDirectory).toBe(false);
|
||||
expect(cleared).toBe(true);
|
||||
deps.stopWorkspaceSetup = undefined;
|
||||
}
|
||||
|
||||
expect(
|
||||
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
|
||||
).toBeUndefined();
|
||||
expect((await registry.get(ws2.workspaceId))?.untrustedSource).toBeUndefined();
|
||||
|
||||
const finalArchive = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: ws2.workspaceId },
|
||||
requestId: `req-${order}-ws2`,
|
||||
});
|
||||
expect(finalArchive.removedDirectory).toBe(true);
|
||||
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
|
||||
},
|
||||
);
|
||||
|
||||
test("workspace scope skips teardown when an active sibling on the same checkout is blocked", async () => {
|
||||
const nestedRelative = path.join("packages", "app");
|
||||
const fixture = await createTeardownWorktree("shared-blocked-sibling", { nestedRelative });
|
||||
const blockedRootId = "ws-shared-blocked-root";
|
||||
const nestedWorkspaceId = "ws-shared-nested";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [
|
||||
makeWorktreeWorkspace(blockedRootId, fixture),
|
||||
makeWorktreeWorkspace(nestedWorkspaceId, fixture, {
|
||||
cwd: path.join(fixture.worktreePath, nestedRelative),
|
||||
}),
|
||||
],
|
||||
});
|
||||
deps.assertWorkspaceAutomationAllowed = async (workspaceId) => {
|
||||
if (workspaceId === blockedRootId) {
|
||||
throw new WorkspaceAutomationBlockedError(sampleBlockedSource());
|
||||
}
|
||||
};
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId: nestedWorkspaceId },
|
||||
requestId: "req-shared-blocked-sibling",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual([nestedWorkspaceId]);
|
||||
expect(result.removedDirectory).toBe(false);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(true);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("worktree scope skips teardown when archiving an unrecorded worktree directory", async () => {
|
||||
const fixture = await createTeardownWorktree("unrecorded-worktree");
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [],
|
||||
});
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "worktree", targetPath: fixture.worktreePath },
|
||||
requestId: "req-unrecorded-worktree",
|
||||
});
|
||||
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("worktree scope skips teardown for nested siblings when any workspace on the checkout is blocked", async () => {
|
||||
const nestedRelative = path.join("packages", "app");
|
||||
const fixture = await createTeardownWorktree("blocked-sibling", { nestedRelative });
|
||||
const rootWorkspaceId = "ws-blocked-root";
|
||||
const nestedWorkspaceId = "ws-nested-sibling";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome: fixture.paseoHome,
|
||||
activeWorkspaces: [
|
||||
makeWorktreeWorkspace(rootWorkspaceId, fixture),
|
||||
makeWorktreeWorkspace(nestedWorkspaceId, fixture, {
|
||||
cwd: path.join(fixture.worktreePath, nestedRelative),
|
||||
}),
|
||||
],
|
||||
});
|
||||
deps.assertWorkspaceAutomationAllowed = async (workspaceId) => {
|
||||
if (workspaceId === rootWorkspaceId) {
|
||||
throw new WorkspaceAutomationBlockedError(sampleBlockedSource());
|
||||
}
|
||||
};
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "worktree", targetPath: fixture.worktreePath },
|
||||
requestId: "req-blocked-sibling",
|
||||
});
|
||||
|
||||
expect(result.archivedWorkspaceIds).toEqual(
|
||||
expect.arrayContaining([rootWorkspaceId, nestedWorkspaceId]),
|
||||
);
|
||||
expect(result.removedDirectory).toBe(true);
|
||||
expect(existsSync(fixture.worktreePath)).toBe(false);
|
||||
expect(existsSync(fixture.marker)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test("workspace scope keeps a worktree for an active workspace in a subdirectory", async () => {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
|
||||
@@ -21,7 +21,14 @@ import type {
|
||||
} from "./workspace-registry.js";
|
||||
import { createRealpathAwarePathMatcher, isRealpathInsideRoot } from "../utils/path.js";
|
||||
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
|
||||
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
|
||||
import {
|
||||
readPaseoWorktreeMetadata,
|
||||
setPaseoWorktreeUntrustedSource,
|
||||
} from "../utils/worktree-metadata.js";
|
||||
import {
|
||||
WorkspaceAutomationBlockedError,
|
||||
type UntrustedWorkspaceSource,
|
||||
} from "./workspace-automation-gate.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
|
||||
import type { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
|
||||
|
||||
@@ -59,8 +66,8 @@ export interface ArchiveDependencies {
|
||||
clearWorkspaceArchiving: (workspaceIds: Iterable<string>) => void;
|
||||
killTerminalsForWorkspace: (workspaceId: string) => Promise<void>;
|
||||
stopWorkspaceSetup?: (workspaceId: string) => Promise<void>;
|
||||
assertWorkspaceAutomationAllowed?: (workspaceId: string) => Promise<void>;
|
||||
isCheckoutUntrusted?: (checkoutPath: string) => Promise<boolean>;
|
||||
assertWorkspaceAutomationAllowed: (workspaceId: string) => Promise<void>;
|
||||
isCheckoutUntrusted: (checkoutPath: string) => Promise<boolean>;
|
||||
sessionLogger?: Logger;
|
||||
}
|
||||
|
||||
@@ -128,12 +135,17 @@ interface BackingDirectory {
|
||||
mainRepoRoot: string | null;
|
||||
paseoWorktreesRoot: string | null;
|
||||
worktreeManagerPluginId: string | null;
|
||||
untrusted: boolean;
|
||||
untrustedSource: UntrustedWorkspaceSource | null;
|
||||
}
|
||||
|
||||
interface ArchiveTarget {
|
||||
backing: BackingDirectory | null;
|
||||
teardownTargets: Array<{ workspaceId: string | null; cwd: string }>;
|
||||
teardownTargets: Array<{ workspaceId: string; cwd: string }>;
|
||||
// Active workspaces sharing the resolved backing checkout when archive starts
|
||||
// (including the records being archived and any active siblings). Keeps
|
||||
// teardown approval scoped to the live checkout rather than historical
|
||||
// archived records that previously occupied the same path.
|
||||
checkoutWorkspaceIds: string[];
|
||||
setupWorkspaceIds: string[];
|
||||
workspaceIds: string[];
|
||||
}
|
||||
@@ -275,6 +287,33 @@ async function resolveArchiveCheckoutPath(
|
||||
return (await resolveBackingDirectory(scope.targetPath, dependencies)).path;
|
||||
}
|
||||
|
||||
async function listActiveWorkspacesOnBacking(
|
||||
activeWorkspaces: ActiveWorkspaceRef[],
|
||||
backingPath: string,
|
||||
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
|
||||
): Promise<ActiveWorkspaceRef[]> {
|
||||
const matchesBackingDirectory = createRealpathAwarePathMatcher(backingPath);
|
||||
return (
|
||||
await Promise.all(
|
||||
activeWorkspaces.map(async (workspace) => {
|
||||
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
|
||||
return matchesBackingDirectory(backingDirectory.path) ? workspace : null;
|
||||
}),
|
||||
)
|
||||
).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null);
|
||||
}
|
||||
|
||||
function firstUntrustedSource(
|
||||
primary: UntrustedWorkspaceSource | null,
|
||||
workspaces: ActiveWorkspaceRef[],
|
||||
): UntrustedWorkspaceSource | null {
|
||||
return (
|
||||
primary ??
|
||||
workspaces.find((workspace) => Boolean(workspace.untrustedSource))?.untrustedSource ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveArchiveTarget(
|
||||
dependencies: ArchiveDependencies,
|
||||
scope: ArchiveScope,
|
||||
@@ -291,12 +330,37 @@ async function resolveArchiveTarget(
|
||||
{ workspaceId },
|
||||
"Workspace not found for archive-by-scope; skipping",
|
||||
);
|
||||
return { backing: null, teardownTargets: [], setupWorkspaceIds: [], workspaceIds: [] };
|
||||
return {
|
||||
backing: null,
|
||||
teardownTargets: [],
|
||||
checkoutWorkspaceIds: [],
|
||||
setupWorkspaceIds: [],
|
||||
workspaceIds: [],
|
||||
};
|
||||
}
|
||||
const isArchived = "archivedAt" in record && Boolean(record.archivedAt);
|
||||
const backing = await resolveWorkspaceBackingDirectory(record, dependencies);
|
||||
const activeOnCheckout = await listActiveWorkspacesOnBacking(
|
||||
activeWorkspaces,
|
||||
backing.path,
|
||||
dependencies,
|
||||
);
|
||||
const checkoutWorkspaceIds = Array.from(
|
||||
new Set([
|
||||
...(isArchived ? [] : [workspaceId]),
|
||||
...activeOnCheckout.map((workspace) => workspace.workspaceId),
|
||||
]),
|
||||
);
|
||||
return {
|
||||
backing: await resolveWorkspaceBackingDirectory(record, dependencies),
|
||||
backing: {
|
||||
...backing,
|
||||
untrustedSource: firstUntrustedSource(
|
||||
isArchived ? null : backing.untrustedSource,
|
||||
activeOnCheckout,
|
||||
),
|
||||
},
|
||||
teardownTargets: isArchived ? [] : [{ workspaceId, cwd: record.cwd }],
|
||||
checkoutWorkspaceIds,
|
||||
setupWorkspaceIds: [workspaceId],
|
||||
workspaceIds: isArchived ? [] : [workspaceId],
|
||||
};
|
||||
@@ -304,14 +368,11 @@ async function resolveArchiveTarget(
|
||||
|
||||
const backing = await resolveBackingDirectory(scope.targetPath, dependencies);
|
||||
const matchesBackingDirectory = createRealpathAwarePathMatcher(backing.path);
|
||||
const targetWorkspaces = (
|
||||
await Promise.all(
|
||||
activeWorkspaces.map(async (workspace) => {
|
||||
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
|
||||
return matchesBackingDirectory(backingDirectory.path) ? workspace : null;
|
||||
}),
|
||||
)
|
||||
).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null);
|
||||
const targetWorkspaces = await listActiveWorkspacesOnBacking(
|
||||
activeWorkspaces,
|
||||
backing.path,
|
||||
dependencies,
|
||||
);
|
||||
const recordedId = await dependencies.findWorkspaceIdForCwd(backing.path);
|
||||
const recorded = recordedId ? await dependencies.getWorkspace?.(recordedId) : null;
|
||||
const record =
|
||||
@@ -320,15 +381,19 @@ async function resolveArchiveTarget(
|
||||
? recorded
|
||||
: null) ??
|
||||
targetWorkspaces[0];
|
||||
const resolvedBacking = record
|
||||
? await resolveWorkspaceBackingDirectory(record, dependencies)
|
||||
: backing;
|
||||
return {
|
||||
backing: record ? await resolveWorkspaceBackingDirectory(record, dependencies) : backing,
|
||||
teardownTargets:
|
||||
targetWorkspaces.length > 0
|
||||
? targetWorkspaces.map((workspace) => ({
|
||||
workspaceId: workspace.workspaceId,
|
||||
cwd: workspace.cwd,
|
||||
}))
|
||||
: [{ workspaceId: null, cwd: scope.targetPath }],
|
||||
backing: {
|
||||
...resolvedBacking,
|
||||
untrustedSource: firstUntrustedSource(null, targetWorkspaces),
|
||||
},
|
||||
teardownTargets: targetWorkspaces.map((workspace) => ({
|
||||
workspaceId: workspace.workspaceId,
|
||||
cwd: workspace.cwd,
|
||||
})),
|
||||
checkoutWorkspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
|
||||
setupWorkspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
|
||||
workspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
|
||||
};
|
||||
@@ -360,7 +425,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
|
||||
): Promise<BackingDirectory> {
|
||||
const worktreeManagerPluginId = workspace.worktreeManagerPluginId ?? null;
|
||||
const untrusted = Boolean(workspace.untrustedSource);
|
||||
const untrustedSource = workspace.untrustedSource ?? null;
|
||||
if (workspace.isPaseoOwnedWorktree === false) {
|
||||
return {
|
||||
path: resolve(workspace.worktreeRoot ?? workspace.cwd),
|
||||
@@ -370,7 +435,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? null,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
untrustedSource,
|
||||
};
|
||||
}
|
||||
if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) {
|
||||
@@ -382,7 +447,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
mainRepoRoot: workspace.mainRepoRoot,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
untrustedSource,
|
||||
};
|
||||
}
|
||||
if (workspace.kind !== "worktree") {
|
||||
@@ -394,7 +459,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? null,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
untrustedSource,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -408,7 +473,7 @@ async function resolveWorkspaceBackingDirectory(
|
||||
...backing,
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot,
|
||||
worktreeManagerPluginId: worktreeManagerPluginId ?? backing.worktreeManagerPluginId,
|
||||
untrusted: untrusted || backing.untrusted,
|
||||
untrustedSource: untrustedSource ?? backing.untrustedSource,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -429,7 +494,7 @@ async function resolveBackingDirectory(
|
||||
mainRepoRoot: ownership.repoRoot ?? null,
|
||||
paseoWorktreesRoot: ownership.worktreeRoot ?? null,
|
||||
worktreeManagerPluginId: null,
|
||||
untrusted: false,
|
||||
untrustedSource: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -509,22 +574,20 @@ async function maybeRemoveDirectory(
|
||||
}
|
||||
|
||||
const archivedWorkspaceIdSet = new Set(archivedWorkspaceIds);
|
||||
const teardownTargets = target.teardownTargets.filter(
|
||||
(teardownTarget) =>
|
||||
teardownTarget.workspaceId === null || archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
|
||||
const teardownTargets = target.teardownTargets.filter((teardownTarget) =>
|
||||
archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
|
||||
);
|
||||
|
||||
const teardownPlan = await resolveCheckoutTeardownPlan(
|
||||
dependencies,
|
||||
backing,
|
||||
teardownTargets,
|
||||
target.checkoutWorkspaceIds,
|
||||
);
|
||||
let untrustedBacking =
|
||||
backing.untrusted || Boolean(await dependencies.isCheckoutUntrusted?.(backing.path));
|
||||
teardownPlan.untrustedBacking || Boolean(await dependencies.isCheckoutUntrusted(backing.path));
|
||||
try {
|
||||
const allowedTeardownTargets = await filterAllowedTeardownTargets(
|
||||
dependencies,
|
||||
teardownTargets,
|
||||
);
|
||||
if (allowedTeardownTargets.length < teardownTargets.length) {
|
||||
untrustedBacking = true;
|
||||
}
|
||||
for (const teardownTarget of uniqueTeardownTargets(allowedTeardownTargets)) {
|
||||
for (const teardownTarget of uniqueTeardownTargets(teardownPlan.allowedTargets)) {
|
||||
request.checkpoint();
|
||||
await runWorktreeTeardownCommands({
|
||||
worktreePath: backing.path,
|
||||
@@ -584,25 +647,66 @@ async function maybeRemoveDirectory(
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveCheckoutTeardownPlan(
|
||||
dependencies: ArchiveDependencies,
|
||||
backing: BackingDirectory,
|
||||
teardownTargets: Array<{ workspaceId: string; cwd: string }>,
|
||||
checkoutWorkspaceIds: string[],
|
||||
): Promise<{
|
||||
allowedTargets: Array<{ workspaceId: string; cwd: string }>;
|
||||
untrustedBacking: boolean;
|
||||
}> {
|
||||
const metadataUntrustedSource =
|
||||
(await readPaseoWorktreeMetadata(backing.path).catch(() => null))?.untrustedSource ?? null;
|
||||
const checkoutUntrusted = Boolean(backing.untrustedSource || metadataUntrustedSource);
|
||||
const teardownGate = checkoutUntrusted
|
||||
? { allowed: [] as Array<{ workspaceId: string; cwd: string }>, blockedSource: null }
|
||||
: await filterAllowedTeardownTargets(dependencies, teardownTargets, checkoutWorkspaceIds);
|
||||
const untrustedSourceToPersist =
|
||||
teardownTargets.length === 0 || metadataUntrustedSource
|
||||
? null
|
||||
: (backing.untrustedSource ?? teardownGate.blockedSource);
|
||||
if (untrustedSourceToPersist) {
|
||||
// Runs inside workspaceArchiveOperations.withCheckout alongside Run setup approval,
|
||||
// so retained pre-upgrade checkouts keep their block without racing approval clears.
|
||||
await setPaseoWorktreeUntrustedSource(backing.path, untrustedSourceToPersist).catch(
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
return {
|
||||
allowedTargets: teardownGate.allowed,
|
||||
untrustedBacking: checkoutUntrusted || teardownGate.allowed.length < teardownTargets.length,
|
||||
};
|
||||
}
|
||||
|
||||
async function filterAllowedTeardownTargets(
|
||||
dependencies: ArchiveDependencies,
|
||||
targets: Array<{ workspaceId: string | null; cwd: string }>,
|
||||
): Promise<Array<{ workspaceId: string | null; cwd: string }>> {
|
||||
const allowed: Array<{ workspaceId: string | null; cwd: string }> = [];
|
||||
const blockedCwds: string[] = [];
|
||||
for (const target of targets) {
|
||||
targets: Array<{ workspaceId: string; cwd: string }>,
|
||||
checkoutWorkspaceIds: string[],
|
||||
): Promise<{
|
||||
allowed: Array<{ workspaceId: string; cwd: string }>;
|
||||
blockedSource: UntrustedWorkspaceSource | null;
|
||||
}> {
|
||||
if (targets.length === 0) {
|
||||
return { allowed: [], blockedSource: null };
|
||||
}
|
||||
if (typeof dependencies.assertWorkspaceAutomationAllowed !== "function") {
|
||||
return { allowed: [], blockedSource: null };
|
||||
}
|
||||
const workspaceIdsToCheck = Array.from(
|
||||
new Set([...targets.map((target) => target.workspaceId), ...checkoutWorkspaceIds]),
|
||||
);
|
||||
for (const workspaceId of workspaceIdsToCheck) {
|
||||
try {
|
||||
if (target.workspaceId)
|
||||
await dependencies.assertWorkspaceAutomationAllowed?.(target.workspaceId);
|
||||
allowed.push(target);
|
||||
await dependencies.assertWorkspaceAutomationAllowed(workspaceId);
|
||||
} catch (error) {
|
||||
if (!(error instanceof WorkspaceAutomationBlockedError)) throw error;
|
||||
blockedCwds.push(target.cwd);
|
||||
// Every workspace in checkoutWorkspaceIds shares the same backing checkout;
|
||||
// if any active workspace on it is blocked, skip teardown for the checkout.
|
||||
return { allowed: [], blockedSource: error.source };
|
||||
}
|
||||
}
|
||||
return allowed.filter(
|
||||
(target) => !blockedCwds.some((cwd) => createRealpathAwarePathMatcher(cwd)(target.cwd)),
|
||||
);
|
||||
return { allowed: targets, blockedSource: null };
|
||||
}
|
||||
|
||||
function uniqueTeardownTargets<T extends { cwd: string }>(targets: T[]): T[] {
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
getPaseoWorktreeMetadataPath,
|
||||
readPaseoWorktreeMetadata,
|
||||
writePaseoWorktreeMetadata,
|
||||
} from "../utils/worktree-metadata.js";
|
||||
import {
|
||||
WorkspaceAutomationBlockedError,
|
||||
assertWorkspaceAutomationAllowed,
|
||||
clearWorkspaceAutomationBlock,
|
||||
formatWorkspaceAutomationBlockedMessage,
|
||||
} from "./workspace-automation-gate.js";
|
||||
import type { PersistedWorkspaceRecord } from "./workspace-registry.js";
|
||||
|
||||
const cleanupPaths: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const target of cleanupPaths.splice(0)) {
|
||||
rmSync(target, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("workspace automation gate", () => {
|
||||
it("refuses executable repository automation for a cross-repository change request", () => {
|
||||
@@ -43,4 +62,96 @@ describe("workspace automation gate", () => {
|
||||
}),
|
||||
).toBe(`Scripts are blocked for ${noun} #42 from contributor/paseo. Run setup to allow them.`);
|
||||
});
|
||||
|
||||
async function createUntrustedWorktreeFixture(number: number) {
|
||||
const tempDir = mkdtempSync(path.join(tmpdir(), `automation-gate-${number}-`));
|
||||
cleanupPaths.push(tempDir);
|
||||
const repoDir = path.join(tempDir, "repo");
|
||||
const worktreeDir = path.join(tempDir, "wt");
|
||||
mkdirSync(repoDir, { recursive: true });
|
||||
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "init"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
execFileSync("git", ["worktree", "add", "-b", `pr-${number}`, worktreeDir, "main"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const source = {
|
||||
kind: "change_request" as const,
|
||||
forge: "github",
|
||||
number,
|
||||
headRepository: "contributor/paseo",
|
||||
};
|
||||
await writePaseoWorktreeMetadata(worktreeDir, { baseRefName: "main", untrustedSource: source });
|
||||
const records = new Map<string, PersistedWorkspaceRecord>([
|
||||
[
|
||||
"ws-1",
|
||||
{
|
||||
workspaceId: "ws-1",
|
||||
projectId: "proj-1",
|
||||
cwd: worktreeDir,
|
||||
kind: "worktree",
|
||||
worktreeRoot: worktreeDir,
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot: repoDir,
|
||||
untrustedSource: source,
|
||||
createdAt: "2026-11-24T00:00:00.000Z",
|
||||
updatedAt: "2026-11-24T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
]);
|
||||
const registry = {
|
||||
listAll: async () => Array.from(records.values()),
|
||||
update: async (
|
||||
id: string,
|
||||
updater: (record: PersistedWorkspaceRecord) => PersistedWorkspaceRecord,
|
||||
) => {
|
||||
const current = records.get(id);
|
||||
if (!current) return null;
|
||||
const next = updater(current);
|
||||
records.set(id, next);
|
||||
return next;
|
||||
},
|
||||
};
|
||||
return { worktreeDir, source, records, registry };
|
||||
}
|
||||
|
||||
it("clears untrustedSource from both workspace records and worktree metadata", async () => {
|
||||
const { worktreeDir, records, registry } = await createUntrustedWorktreeFixture(42);
|
||||
|
||||
const cleared = await clearWorkspaceAutomationBlock(registry, "ws-1");
|
||||
|
||||
expect(cleared).toBe(true);
|
||||
expect(records.get("ws-1")?.untrustedSource).toBeUndefined();
|
||||
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toBeUndefined();
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"fails without clearing workspace records when worktree metadata cannot be written",
|
||||
async () => {
|
||||
const { worktreeDir, source, records, registry } = await createUntrustedWorktreeFixture(43);
|
||||
const metadataDir = path.dirname(await getPaseoWorktreeMetadataPath(worktreeDir));
|
||||
|
||||
chmodSync(metadataDir, 0o555);
|
||||
try {
|
||||
await expect(clearWorkspaceAutomationBlock(registry, "ws-1")).rejects.toThrow();
|
||||
expect(records.get("ws-1")?.untrustedSource).toEqual(source);
|
||||
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toEqual(source);
|
||||
} finally {
|
||||
chmodSync(metadataDir, 0o755);
|
||||
}
|
||||
|
||||
const retried = await clearWorkspaceAutomationBlock(registry, "ws-1");
|
||||
expect(retried).toBe(true);
|
||||
expect(records.get("ws-1")?.untrustedSource).toBeUndefined();
|
||||
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toBeUndefined();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createRealpathAwarePathMatcher } from "../utils/path.js";
|
||||
import { setPaseoWorktreeUntrustedSource } from "../utils/worktree-metadata.js";
|
||||
import type { WorkspaceRegistry } from "./workspace-registry.js";
|
||||
|
||||
export interface UntrustedWorkspaceSource {
|
||||
@@ -51,23 +52,26 @@ export async function isCheckoutUntrusted(
|
||||
export async function clearWorkspaceAutomationBlock(
|
||||
registry: Pick<WorkspaceRegistry, "update" | "listAll">,
|
||||
workspaceId: string,
|
||||
options?: { checkoutPath?: string | null },
|
||||
): Promise<boolean> {
|
||||
let cleared = false;
|
||||
const allWorkspaces = await registry.listAll();
|
||||
const target = allWorkspaces.find((record) => record.workspaceId === workspaceId);
|
||||
if (!target) throw new Error(`Workspace not found: ${workspaceId}`);
|
||||
const checkoutPath = options?.checkoutPath ?? target.worktreeRoot ?? target.cwd;
|
||||
// Clear checkout metadata before mutating workspace records so a failed metadata
|
||||
// write surfaces an error and leaves workspace records intact to retry approval.
|
||||
let cleared = await setPaseoWorktreeUntrustedSource(checkoutPath, null);
|
||||
const timestamp = new Date().toISOString();
|
||||
const workspace = await registry.update(workspaceId, (record) => {
|
||||
if (!record.untrustedSource) return record;
|
||||
cleared = true;
|
||||
const { untrustedSource: _removed, ...trusted } = record;
|
||||
return { ...trusted, updatedAt: timestamp };
|
||||
});
|
||||
if (!workspace) throw new Error(`Workspace not found: ${workspaceId}`);
|
||||
const checkoutPath = workspace.worktreeRoot ?? workspace.cwd;
|
||||
const matchesCheckout = createRealpathAwarePathMatcher(checkoutPath);
|
||||
const siblings = await registry.listAll();
|
||||
for (const sibling of siblings) {
|
||||
if (sibling.workspaceId === workspaceId || !sibling.untrustedSource) continue;
|
||||
if (!matchesCheckout(sibling.worktreeRoot ?? sibling.cwd)) continue;
|
||||
await registry.update(sibling.workspaceId, (record) => {
|
||||
for (const candidate of allWorkspaces) {
|
||||
if (!candidate.untrustedSource) continue;
|
||||
if (
|
||||
candidate.workspaceId !== workspaceId &&
|
||||
!matchesCheckout(candidate.worktreeRoot ?? candidate.cwd)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
await registry.update(candidate.workspaceId, (record) => {
|
||||
if (!record.untrustedSource) return record;
|
||||
cleared = true;
|
||||
const { untrustedSource: _removed, ...trusted } = record;
|
||||
|
||||
@@ -29,6 +29,7 @@ import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/p
|
||||
import type { WorkspaceGitService } from "./workspace-git-service.js";
|
||||
import { runWithRepositoryRoot } from "../utils/git-repository-discovery.js";
|
||||
import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js";
|
||||
import { setPaseoWorktreeUntrustedSource } from "../utils/worktree-metadata.js";
|
||||
|
||||
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
|
||||
|
||||
@@ -185,18 +186,9 @@ async function createWorktreeAtRepositoryRoot(
|
||||
input,
|
||||
deps,
|
||||
});
|
||||
if (managedWorktree) {
|
||||
return {
|
||||
worktree: managedWorktree,
|
||||
intent,
|
||||
untrustedSource,
|
||||
repoRoot,
|
||||
created: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
worktree: await createWorktree({
|
||||
const createdWorktree =
|
||||
managedWorktree ??
|
||||
(await createWorktree({
|
||||
cwd: repoRoot,
|
||||
worktreeSlug: normalizedSlug,
|
||||
worktreePath: transformed.path,
|
||||
@@ -204,7 +196,12 @@ async function createWorktreeAtRepositoryRoot(
|
||||
preparedBranchOff,
|
||||
paseoHome: input.paseoHome,
|
||||
worktreesRoot: input.worktreesRoot,
|
||||
}),
|
||||
}));
|
||||
if (untrustedSource) {
|
||||
await setPaseoWorktreeUntrustedSource(createdWorktree.worktreePath, untrustedSource);
|
||||
}
|
||||
return {
|
||||
worktree: createdWorktree,
|
||||
intent,
|
||||
untrustedSource,
|
||||
repoRoot,
|
||||
|
||||
@@ -1756,6 +1756,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
},
|
||||
{
|
||||
@@ -1832,6 +1834,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
},
|
||||
{
|
||||
@@ -1909,6 +1913,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
},
|
||||
{
|
||||
@@ -1982,6 +1988,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
|
||||
markWorkspaceArchiving: vi.fn(),
|
||||
clearWorkspaceArchiving: vi.fn(),
|
||||
killTerminalsForWorkspace: vi.fn(async () => {}),
|
||||
assertWorkspaceAutomationAllowed: async () => {},
|
||||
isCheckoutUntrusted: async () => false,
|
||||
sessionLogger: createLogger(),
|
||||
};
|
||||
|
||||
|
||||
@@ -2594,14 +2594,20 @@ it.each([false, true])(
|
||||
...nodeTerminalCommand(`
|
||||
process.stdin.setRawMode(true);
|
||||
let row = 0;
|
||||
function print(count) {
|
||||
for(let i=0;i<count;i++,row++) process.stdout.write("\\x1b[31mrow-" + String(row).padStart(5,"0") + " 界é🙂 " + "log ".repeat(20) + "\\x1b[0m\\r\\n");
|
||||
function nextRow() {
|
||||
return "\\x1b[31mrow-" + String(row++).padStart(5,"0") + " 界é🙂 " + "log ".repeat(20) + "\\x1b[0m\\r\\n";
|
||||
}
|
||||
// Fill the initial history in batches to avoid a TTY write for every row.
|
||||
for (let start = 0; start < 12050; start += 256) {
|
||||
const count = Math.min(256, 12050 - start);
|
||||
process.stdout.write(Array.from({ length: count }, nextRow).join(""));
|
||||
}
|
||||
print(12050);
|
||||
process.stdout.write("READY\\r\\n");
|
||||
process.stdin.on("data", data => {
|
||||
if(data.toString().includes("BURST")) { print(4000); process.stdout.write("BURST-DONE\\r\\n"); }
|
||||
else process.stdout.write("ECHO:" + data.toString() + "\\r\\n");
|
||||
if(data.toString().includes("BURST")) {
|
||||
for (let i = 0; i < 4000; i++) process.stdout.write(nextRow());
|
||||
process.stdout.write("BURST-DONE\\r\\n");
|
||||
} else process.stdout.write("ECHO:" + data.toString() + "\\r\\n");
|
||||
});
|
||||
setInterval(()=>{},1000);
|
||||
`),
|
||||
|
||||
@@ -14,6 +14,8 @@ export interface TerminateWithTreeKillOptions {
|
||||
gracefulTimeoutMs: number;
|
||||
forceTimeoutMs?: number;
|
||||
onForceSignal?: () => void;
|
||||
/** Only set for a process spawned as the leader of its own POSIX process group. */
|
||||
ownsProcessGroup?: boolean;
|
||||
}
|
||||
|
||||
export type TerminateWithTreeKillResult =
|
||||
@@ -33,24 +35,67 @@ export async function terminateWithTreeKill(
|
||||
child: TreeKillTarget,
|
||||
options: TerminateWithTreeKillOptions,
|
||||
): Promise<TerminateWithTreeKillResult> {
|
||||
if (isProcessExited(child)) {
|
||||
const processGroupId =
|
||||
options.ownsProcessGroup && child.pid !== undefined && child.pid > 1 ? child.pid : undefined;
|
||||
const launcherExited = isProcessExited(child);
|
||||
if (launcherExited && (processGroupId === undefined || !signalGroup(processGroupId, 0))) {
|
||||
return "already-exited";
|
||||
}
|
||||
|
||||
const exitPromise = waitForProcessExit(child);
|
||||
await signalProcessTree(child, options.gracefulSignal ?? "SIGTERM");
|
||||
if (await waitForExitOrTimeout(exitPromise, options.gracefulTimeoutMs)) {
|
||||
const waitForExit = createExitWaiter(child, processGroupId);
|
||||
|
||||
const gracefulSignal = options.gracefulSignal ?? "SIGTERM";
|
||||
if (launcherExited && processGroupId !== undefined) {
|
||||
signalGroup(processGroupId, gracefulSignal);
|
||||
} else {
|
||||
await signalProcessTree(child, gracefulSignal);
|
||||
}
|
||||
if (await waitForExit(options.gracefulTimeoutMs)) {
|
||||
return "terminated";
|
||||
}
|
||||
|
||||
options.onForceSignal?.();
|
||||
await signalProcessTree(child, options.forceSignal ?? "SIGKILL");
|
||||
const forceSignal = options.forceSignal ?? "SIGKILL";
|
||||
await signalProcessTree(child, forceSignal);
|
||||
if (processGroupId !== undefined) {
|
||||
// The tree walk loses sight of children once their launcher exits.
|
||||
signalGroup(processGroupId, forceSignal);
|
||||
}
|
||||
if (options.forceTimeoutMs === undefined) {
|
||||
return "killed";
|
||||
}
|
||||
return (await waitForExitOrTimeout(exitPromise, options.forceTimeoutMs))
|
||||
? "killed"
|
||||
: "kill-timeout";
|
||||
return (await waitForExit(options.forceTimeoutMs)) ? "killed" : "kill-timeout";
|
||||
}
|
||||
|
||||
function createExitWaiter(
|
||||
child: TreeKillTarget,
|
||||
processGroupId: number | undefined,
|
||||
): (timeoutMs: number) => Promise<boolean> {
|
||||
if (processGroupId !== undefined) {
|
||||
return (timeoutMs) => waitForProcessGroupExit(processGroupId, timeoutMs);
|
||||
}
|
||||
const exitPromise = waitForProcessExit(child);
|
||||
return (timeoutMs) => waitForExitOrTimeout(exitPromise, timeoutMs);
|
||||
}
|
||||
|
||||
function signalGroup(groupId: number, signal: NodeJS.Signals | 0): boolean {
|
||||
try {
|
||||
process.kill(-groupId, signal);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ESRCH") return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForProcessGroupExit(groupId: number, timeoutMs: number): Promise<boolean> {
|
||||
const deadline = performance.now() + timeoutMs;
|
||||
while (signalGroup(groupId, 0)) {
|
||||
const remainingMs = deadline - performance.now();
|
||||
if (remainingMs <= 0) return false;
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, Math.min(50, remainingMs)));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function signalProcessTree(child: TreeKillTarget, signal: NodeJS.Signals): Promise<void> {
|
||||
|
||||
@@ -14,6 +14,13 @@ const ChangeRequestLookupTargetSchema = z.object({
|
||||
localBranchName: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
const UntrustedWorktreeSourceSchema = z.object({
|
||||
kind: z.literal("change_request"),
|
||||
forge: z.string().min(1),
|
||||
number: z.number().int().positive(),
|
||||
headRepository: z.string().min(1),
|
||||
});
|
||||
|
||||
// baseRefName is the display name; baseRef is the checkout's current exact base
|
||||
// ("refs/remotes/upstream/main"). baseRef is optional because worktrees written before it
|
||||
// existed only have the name — there are no migrations, so readers fall back.
|
||||
@@ -23,6 +30,7 @@ const PaseoWorktreeMetadataV1Schema = z.object({
|
||||
baseRef: z.string().min(1).optional(),
|
||||
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
|
||||
worktreeManagerPluginId: z.string().min(1).optional(),
|
||||
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
|
||||
});
|
||||
|
||||
const PaseoWorktreeMetadataV2Schema = z.object({
|
||||
@@ -31,6 +39,7 @@ const PaseoWorktreeMetadataV2Schema = z.object({
|
||||
baseRef: z.string().min(1).optional(),
|
||||
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
|
||||
worktreeManagerPluginId: z.string().min(1).optional(),
|
||||
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
|
||||
firstAgentBranchAutoName: z
|
||||
.discriminatedUnion("status", [
|
||||
z.object({
|
||||
@@ -58,6 +67,7 @@ const PaseoWorktreeMetadataSchema = z.union([
|
||||
|
||||
export type PaseoWorktreeMetadata = z.infer<typeof PaseoWorktreeMetadataSchema>;
|
||||
export type PaseoWorktreeChangeRequestHint = z.infer<typeof ChangeRequestLookupTargetSchema>;
|
||||
export type PaseoWorktreeUntrustedSource = z.infer<typeof UntrustedWorktreeSourceSchema>;
|
||||
|
||||
export function createPaseoWorktreeChangeRequestHint(
|
||||
input: PaseoWorktreeChangeRequestHint,
|
||||
@@ -230,6 +240,7 @@ export async function writePaseoWorktreeMetadata(
|
||||
baseRef?: string;
|
||||
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
|
||||
worktreeManagerPluginId?: string;
|
||||
untrustedSource?: PaseoWorktreeUntrustedSource;
|
||||
},
|
||||
): Promise<void> {
|
||||
return mutateMetadata(worktreeRoot, async (root) => {
|
||||
@@ -250,11 +261,41 @@ export async function writePaseoWorktreeMetadata(
|
||||
...(options.worktreeManagerPluginId
|
||||
? { worktreeManagerPluginId: options.worktreeManagerPluginId }
|
||||
: {}),
|
||||
...(options.untrustedSource ? { untrustedSource: options.untrustedSource } : {}),
|
||||
};
|
||||
await writePaseoWorktreeMetadataFile(root, metadata);
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPaseoWorktreeUntrustedSource(
|
||||
worktreeRoot: string,
|
||||
untrustedSource: PaseoWorktreeUntrustedSource | null,
|
||||
): Promise<boolean> {
|
||||
return mutateMetadata(worktreeRoot, async (root) => {
|
||||
let current: PaseoWorktreeMetadata | null;
|
||||
try {
|
||||
current = await readMetadataFile(root);
|
||||
} catch (error) {
|
||||
const cause = (error as { cause?: NodeJS.ErrnoException }).cause;
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT" || cause?.code === "ENOENT") {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (!current) {
|
||||
return false;
|
||||
}
|
||||
const hadUntrustedSource = Boolean(current.untrustedSource);
|
||||
if (!untrustedSource && !hadUntrustedSource) {
|
||||
return false;
|
||||
}
|
||||
const { untrustedSource: _previous, ...rest } = current;
|
||||
const next: PaseoWorktreeMetadata = untrustedSource ? { ...rest, untrustedSource } : rest;
|
||||
await writePaseoWorktreeMetadataFile(root, next);
|
||||
return untrustedSource ? true : hadUntrustedSource;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPaseoWorktreeBaseRef(input: {
|
||||
worktreeRoot: string;
|
||||
baseRef: string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Computer, Globe, Laptop, Monitor, PcCase, Plus, Server, Terminal, X } from "lucide-react";
|
||||
import { Computer, Globe, Laptop, Monitor, PcCase, Plus, Server, Terminal } from "lucide-react";
|
||||
import type * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TailscaleMark } from "./icons";
|
||||
@@ -53,7 +53,6 @@ interface ConnectedHost {
|
||||
endpoint?: string;
|
||||
/** Round trip time, formatted as the app's `formatLatency` prints it. */
|
||||
latency: string;
|
||||
agents: number;
|
||||
}
|
||||
|
||||
const CONNECTED_HOSTS: ConnectedHost[] = [
|
||||
@@ -63,7 +62,6 @@ const CONNECTED_HOSTS: ConnectedHost[] = [
|
||||
tone: "text-mock-fg-muted",
|
||||
link: "local",
|
||||
latency: "1ms",
|
||||
agents: 4,
|
||||
},
|
||||
{
|
||||
name: "devbox",
|
||||
@@ -72,7 +70,6 @@ const CONNECTED_HOSTS: ConnectedHost[] = [
|
||||
link: "relay",
|
||||
endpoint: "relay.paseo.sh",
|
||||
latency: "38ms",
|
||||
agents: 6,
|
||||
},
|
||||
{
|
||||
name: "mac-mini",
|
||||
@@ -81,7 +78,6 @@ const CONNECTED_HOSTS: ConnectedHost[] = [
|
||||
link: "tailscale",
|
||||
endpoint: "mac-mini:6767",
|
||||
latency: "12ms",
|
||||
agents: 3,
|
||||
},
|
||||
{
|
||||
name: "workstation",
|
||||
@@ -90,39 +86,41 @@ const CONNECTED_HOSTS: ConnectedHost[] = [
|
||||
link: "ssh",
|
||||
endpoint: "mo@workstation",
|
||||
latency: "24ms",
|
||||
agents: 2,
|
||||
},
|
||||
];
|
||||
|
||||
function HostRow({ host }: { host: ConnectedHost }) {
|
||||
function HostRow({ host, highlighted }: { host: ConnectedHost; highlighted?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const Device = host.device;
|
||||
const LinkIcon = LINK_ICON[host.link];
|
||||
return (
|
||||
<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" />
|
||||
<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" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[13.5px] leading-[18px] text-mock-fg">
|
||||
{host.name}
|
||||
<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>
|
||||
<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 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>
|
||||
</span>
|
||||
<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 className="flex h-[18px] shrink-0 items-center text-right text-[12px] leading-[16px] text-mock-fg-muted tabular-nums">
|
||||
{host.latency}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
@@ -130,25 +128,23 @@ function HostRow({ host }: { host: ConnectedHost }) {
|
||||
|
||||
/**
|
||||
* Every machine this window is connected to: what kind of machine it is, how the app reaches it,
|
||||
* the round trip time, and how many agents it runs.
|
||||
* and its round trip time.
|
||||
*/
|
||||
export function HostsModal() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<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 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>
|
||||
{CONNECTED_HOSTS.map((host) => (
|
||||
<HostRow key={host.name} host={host} />
|
||||
{CONNECTED_HOSTS.map((host, index) => (
|
||||
<HostRow key={host.name} host={host} highlighted={index === 1} />
|
||||
))}
|
||||
<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" />
|
||||
<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" />
|
||||
</span>
|
||||
{t("landing.mockup.app.addHost")}
|
||||
</div>
|
||||
|
||||
@@ -498,7 +498,6 @@
|
||||
"addProject": "Add project",
|
||||
"addHost": "Add host",
|
||||
"hosts": "Hosts",
|
||||
"agentCount": "{{count}} agents",
|
||||
"hostLinks": {
|
||||
"local": "Local",
|
||||
"relay": "Relay",
|
||||
|
||||
@@ -498,7 +498,6 @@
|
||||
"addProject": "添加 project",
|
||||
"addHost": "添加主机",
|
||||
"hosts": "主机",
|
||||
"agentCount": "{{count}} 个 Agent",
|
||||
"hostLinks": {
|
||||
"local": "本地",
|
||||
"relay": "中继",
|
||||
|
||||
Reference in New Issue
Block a user