mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
065eac9f47 | ||
|
|
3936137993 | ||
|
|
d97d0ba1c0 | ||
|
|
f84cfbc362 | ||
|
|
c990940288 | ||
|
|
72b9e7da38 |
@@ -342,6 +342,8 @@ jobs:
|
||||
run: |
|
||||
npm run test:unit --workspace=@getpaseo/server -- \
|
||||
src/server/file-observer \
|
||||
src/server/workspace-reconciliation-observation.test.ts \
|
||||
src/utils/checkout-git-identity.test.ts \
|
||||
src/server/workspace-git-service.observation.test.ts \
|
||||
src/server/workspace-git-service.observation.integration.test.ts \
|
||||
--bail=1
|
||||
|
||||
@@ -10,7 +10,6 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Agent** — See **Agent session**. UI still says "Agent" / "New Agent" in places, but moving toward **Agent session** as the canonical term. Code: `AgentSnapshotPayload` (`packages/protocol/src/messages.ts:608`). Forbidden: "Task", "Job", "Run".
|
||||
- **Daemon** — Local Paseo server process; identified by `serverId`. UI: "Daemon" (system contexts only). Code: `serverId` in `ServerInfoStatusPayloadSchema` (`packages/protocol/src/messages.ts:1936`), `DaemonClient` (`packages/client/src/daemon-client.ts`).
|
||||
- **Host** — Client-side connection profile pointing at a daemon; bundles one or more `HostConnection`s. UI: "Host" / "Add host" / "Switch host". Code: `HostProfile` (`packages/app/src/types/host-connection.ts:37`). Forbidden: "Connection" (means `HostConnection`, not host).
|
||||
- **Device** — A computer or phone running a Paseo client. Open **Devices** in a host’s settings to connect another device.
|
||||
- **Host badge** — The item on a sidebar workspace row's meta row naming which host that workspace lives on. Three things gate it, and they compose as a lattice rather than competing: the sidebar must span more than one host (automatic), **Show → Host** in the sidebar's display preferences must be on (global, all hosts at once), and then that host's own display mode decides _how_ it draws — **Name** / **Icon only** / **Hidden**. Name, color, and display mode are per-host, per-device, and live client-side on `HostProfile.appearance`; nothing about it reaches the daemon. Never add a fourth way to hide it. UI: the "Appearance" group on a host's settings page, and the "Show" submenu in the sidebar's display preferences. Code: `selectHostBadges` (`packages/app/src/hosts/appearance.ts`) takes the first two as its `enabled` input; `WorkspaceMetaRow` (`packages/app/src/components/sidebar/workspace-meta-row/index.tsx`) draws it. Don't confuse with **Status pill**, which reports state rather than identity.
|
||||
- **Project host entry** — One row in a project for a single (project, daemon) pair, aggregating that daemon's workspaces in the project. Internal. Code: `ProjectHostEntry` (`packages/app/src/utils/projects.ts:11`). Don't introduce "Checkout" as a synonym.
|
||||
- **Placement** — One workspace's stable foreign-key relationship to its project plus its git checkout snapshot. Internal. An explicit creation `projectId` is authoritative when active.
|
||||
|
||||
Generated
-1
@@ -40625,7 +40625,6 @@
|
||||
"p-limit": "^7.3.0",
|
||||
"p-memoize": "^8.0.0",
|
||||
"p-throttle": "^8.1.0",
|
||||
"parse5": "^7.3.0",
|
||||
"pino": "^10.2.0",
|
||||
"pino-pretty": "^13.1.3",
|
||||
"qrcode": "^1.5.4",
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
closeRelayPairing,
|
||||
emptyHome,
|
||||
loadingScreen,
|
||||
expectTailscaleSwitchDisabled,
|
||||
openTailscaleDocsFromSetup,
|
||||
paseoToolsSwitch,
|
||||
pickTheme,
|
||||
projectSuggestion,
|
||||
@@ -403,10 +403,12 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
|
||||
await continueSetup(page);
|
||||
});
|
||||
|
||||
await test.step("Phone shows a disabled Tailscale switch and pairs over relay", async () => {
|
||||
await test.step("Phone offers Tailscale docs and pairs over relay in its own modal", async () => {
|
||||
await expectSetupStep(page, "Take your agents with you");
|
||||
await page.screenshot({ path: testInfo.outputPath("5-phone.png") });
|
||||
await expectTailscaleSwitchDisabled(page);
|
||||
expect(await openTailscaleDocsFromSetup(page)).toBe(
|
||||
"https://paseo.sh/docs/connectivity#tailscale",
|
||||
);
|
||||
const pairing = await openRelayPairingFromSetup(page);
|
||||
await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible();
|
||||
await enableRelayAndExpectOffer(page);
|
||||
|
||||
@@ -1,24 +1,7 @@
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
addDirectHostFromSettings,
|
||||
openSettingsHostSection,
|
||||
selectSettingsHost,
|
||||
} from "../support/helpers/settings";
|
||||
import { test } from "../support/fixtures";
|
||||
import { startTailscaleTestDaemon } from "../support/helpers/tailscale-daemon";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import {
|
||||
expectPairingOffer,
|
||||
cancelTailscaleTurnOff,
|
||||
confirmTailscaleTurnOff,
|
||||
connectThroughTailscale,
|
||||
disableTailscale,
|
||||
enableTailscale,
|
||||
expectTailscaleAddress,
|
||||
expectTailscaleRowLoadsOn,
|
||||
openSetupMobileStep,
|
||||
slowConnectionToHost,
|
||||
expectTailscaleUpdateRequired,
|
||||
expectCompletePairingQr,
|
||||
expectRelayConsent,
|
||||
openPairDeviceModal,
|
||||
@@ -54,59 +37,3 @@ test("keeps the pairing QR code inside its compact tile", async ({ page }, testI
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("asks for a host update when Tailscale controls are unavailable", async ({ page }) => {
|
||||
const daemon = await startIsolatedHostDaemon("pair-device-browser-old-host", {
|
||||
publishedVersion: "0.13.0-beta.2",
|
||||
});
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: daemon.port });
|
||||
await selectSettingsHost(page, daemon.serverId);
|
||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||
await expectTailscaleUpdateRequired(page);
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("turns Tailscale on and off from Devices, asking first over Tailscale", async ({
|
||||
page,
|
||||
baseURL,
|
||||
}, testInfo) => {
|
||||
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
|
||||
// The journey opens Devices or the setup six times, two of them over a slowed connection.
|
||||
test.setTimeout(120_000);
|
||||
if (!baseURL) throw new Error("Expected the app base URL");
|
||||
const daemon = await startTailscaleTestDaemon(baseURL);
|
||||
try {
|
||||
await preparePairingHost(page, daemon);
|
||||
await enableTailscale(page);
|
||||
await expectTailscaleAddress(page, daemon.tailscaleAddress);
|
||||
await page.screenshot({ path: testInfo.outputPath("devices.png") });
|
||||
|
||||
await test.step("While its status loads, the row never shows Tailscale off", async () => {
|
||||
const address = daemon.tailscaleAddress;
|
||||
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
|
||||
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
|
||||
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 300);
|
||||
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
|
||||
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
|
||||
restoreSpeed();
|
||||
});
|
||||
|
||||
await disableTailscale(page, daemon.tailscaleAddress);
|
||||
|
||||
await test.step("Over Tailscale, turning it off asks first and Cancel changes nothing", async () => {
|
||||
await enableTailscale(page);
|
||||
await connectThroughTailscale(page, daemon);
|
||||
await cancelTailscaleTurnOff(page, daemon.tailscaleAddress);
|
||||
});
|
||||
await test.step("Confirming turns it off and cuts this connection", async () => {
|
||||
await confirmTailscaleTurnOff(page, daemon.tailscaleAddress);
|
||||
});
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Start on Settings > Host > Devices with relay enabled in the Android app.
|
||||
// Start on Settings > Host > Pair device with relay enabled in the Android app.
|
||||
// node packages/app/e2e/mobile/pair-device/android.mjs <agent-device-session>
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
@@ -13,7 +13,11 @@ function ad(...args) {
|
||||
});
|
||||
}
|
||||
|
||||
ad("press", 'label="Relay"', "--settle");
|
||||
ad(
|
||||
"press",
|
||||
'label="Pair a device, Scan a QR code or copy a link to connect your phone to this host"',
|
||||
"--settle",
|
||||
);
|
||||
ad("wait", "text", "Pairing QR code", "10000");
|
||||
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
|
||||
const sheet = data.nodes.find((node) => node.label === "Bottom Sheet");
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { promisify } from "node:util";
|
||||
import { once } from "node:events";
|
||||
import {
|
||||
spawn,
|
||||
execFile,
|
||||
@@ -12,7 +11,6 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import net from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { WebSocket } from "ws";
|
||||
import { withDisabledE2ESpeechEnv } from "./speech-env";
|
||||
import { killProcessTree, spawnTsx } from "./spawn-node";
|
||||
|
||||
@@ -66,14 +64,12 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
|
||||
* Resolves once this daemon answers on its port. An open TCP port is not
|
||||
* enough: the port is released before the daemon binds it, and whatever takes
|
||||
* it in between also accepts connections while the daemon exits with
|
||||
* EADDRINUSE. Only the daemon's own status reports its server id. Published
|
||||
* daemons can serve status before they accept WebSocket upgrades.
|
||||
* EADDRINUSE. Only the daemon's own status reports its server id.
|
||||
*/
|
||||
async function waitForServer(
|
||||
port: number,
|
||||
child: ChildProcess,
|
||||
identity: { serverId: string; paseoHome: string },
|
||||
published: boolean,
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + 90_000;
|
||||
let lastError: unknown = null;
|
||||
@@ -86,10 +82,7 @@ async function waitForServer(
|
||||
}
|
||||
try {
|
||||
const serverId = await readServerId(port, identity.paseoHome);
|
||||
if (serverId === identity.serverId) {
|
||||
if (published) await checkWebSocketUpgrade(port);
|
||||
return;
|
||||
}
|
||||
if (serverId === identity.serverId) return;
|
||||
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
@@ -104,12 +97,6 @@ async function waitForServer(
|
||||
);
|
||||
}
|
||||
|
||||
async function checkWebSocketUpgrade(port: number): Promise<void> {
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${port}/ws`, { handshakeTimeout: 1_000 });
|
||||
await once(socket, "open");
|
||||
socket.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the server id from the daemon's status route. The route needs a bearer
|
||||
* on a password-protected daemon; the daemon accepts the local credential it
|
||||
@@ -259,7 +246,7 @@ export async function startIsolatedHostDaemon(
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServer(port, spawned, { serverId, paseoHome }, Boolean(publishedPackageRoot));
|
||||
await waitForServer(port, spawned, { serverId, paseoHome });
|
||||
return spawned;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
|
||||
@@ -161,7 +161,7 @@ export async function finishSetup(page: Page): Promise<void> {
|
||||
/** Opens the Phone step's Relay row: the pair device modal, over setup. */
|
||||
export async function openRelayPairingFromSetup(page: Page): Promise<Locator> {
|
||||
await setupModal(page).getByRole("button", { name: "Relay", exact: true }).click();
|
||||
const pairing = page.getByTestId("devices-relay-pairing");
|
||||
const pairing = page.getByTestId("onboarding-pair-device-card");
|
||||
await expect(pairing).toBeVisible();
|
||||
return pairing;
|
||||
}
|
||||
@@ -171,9 +171,20 @@ export async function closeRelayPairing(pairing: Locator): Promise<void> {
|
||||
await expect(pairing).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectTailscaleSwitchDisabled(page: Page): Promise<void> {
|
||||
const setup = setupModal(page);
|
||||
await expect(setup.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
/** Clicks the Phone step's Tailscale row and returns the docs page it opened. */
|
||||
export async function openTailscaleDocsFromSetup(page: Page): Promise<string> {
|
||||
await page
|
||||
.context()
|
||||
.route("https://paseo.sh/**", (route) =>
|
||||
route.fulfill({ contentType: "text/html", body: "<title>Paseo docs</title>" }),
|
||||
);
|
||||
const popup = page.waitForEvent("popup");
|
||||
await setupModal(page).getByRole("link", { name: "Tailscale, Docs", exact: true }).click();
|
||||
const docs = await popup;
|
||||
await docs.waitForLoadState("domcontentloaded");
|
||||
const url = docs.url();
|
||||
await docs.close();
|
||||
return url;
|
||||
}
|
||||
|
||||
export interface SetupHost {
|
||||
|
||||
@@ -9,8 +9,6 @@ import {
|
||||
selectSettingsHost,
|
||||
} from "./settings";
|
||||
import { expectAppRoute } from "./route-assertions";
|
||||
import { wsRoutePatternForPort } from "./daemon-port";
|
||||
import { goToSetupStep, showSetupAgainFromSettings } from "./onboarding";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
interface PairingHostInput {
|
||||
@@ -62,33 +60,9 @@ export async function prepareLocalPairingHost(
|
||||
await preparePairingHost(page, daemon, additionalHosts);
|
||||
}
|
||||
|
||||
type PairingHost =
|
||||
| Pick<IsolatedHostDaemon, "serverId" | "port">
|
||||
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
|
||||
|
||||
export async function preparePairingHost(
|
||||
page: Page,
|
||||
daemon: PairingHost,
|
||||
additionalHosts: PairingHostInput[] = [],
|
||||
): Promise<void> {
|
||||
await openAppOnPairingHost(page, daemon, additionalHosts);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, daemon.serverId);
|
||||
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
|
||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
}
|
||||
|
||||
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
|
||||
export async function openSetupMobileStep(page: Page, daemon: PairingHost): Promise<void> {
|
||||
await openAppOnPairingHost(page, daemon);
|
||||
await showSetupAgainFromSettings(page);
|
||||
await goToSetupStep(page, "Mobile");
|
||||
}
|
||||
|
||||
async function openAppOnPairingHost(
|
||||
page: Page,
|
||||
daemon: PairingHost,
|
||||
daemon: IsolatedHostDaemon | OutdatedDaemon,
|
||||
additionalHosts: PairingHostInput[] = [],
|
||||
): Promise<void> {
|
||||
await seedSavedSettingsHosts(page, [
|
||||
@@ -100,271 +74,20 @@ async function openAppOnPairingHost(
|
||||
...additionalHosts,
|
||||
]);
|
||||
await gotoAppShell(page);
|
||||
}
|
||||
|
||||
export async function enableTailscale(page: Page): Promise<void> {
|
||||
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
|
||||
await expect(toggle).toBeEnabled();
|
||||
await expect(toggle).not.toBeChecked();
|
||||
await toggle.click();
|
||||
await expect(toggle).toBeChecked();
|
||||
}
|
||||
|
||||
export async function expectTailscaleAddress(page: Page, address: string): Promise<void> {
|
||||
const row = tailscaleAddressRow(page, address);
|
||||
await expect(row).toBeVisible();
|
||||
await expect(
|
||||
row.getByText("On a phone with Tailscale, add a host at this address"),
|
||||
).toBeVisible();
|
||||
await expect(row.getByRole("button", { name: "Copy", exact: true })).toBeVisible();
|
||||
const response = await fetch(`http://${address}/api/health`);
|
||||
expect(response.ok).toBe(true);
|
||||
}
|
||||
|
||||
/** The switch shows off as soon as it is tapped; the host stops listening when its answer lands. */
|
||||
async function expectHostUnreachableAt(address: string): Promise<void> {
|
||||
await expect
|
||||
.poll(() =>
|
||||
fetch(`http://${address}/api/health`).then(
|
||||
() => "reachable",
|
||||
() => "unreachable",
|
||||
),
|
||||
)
|
||||
.toBe("unreachable");
|
||||
}
|
||||
|
||||
function tailscaleAddressRow(page: Page, address: string) {
|
||||
return page.getByTestId("devices-tailscale-address").filter({ hasText: address });
|
||||
}
|
||||
|
||||
export async function disableTailscale(page: Page, address: string): Promise<void> {
|
||||
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
|
||||
await expect(toggle).toBeEnabled();
|
||||
await toggle.click();
|
||||
await expect(toggle).not.toBeChecked();
|
||||
await expect(tailscaleAddressRow(page, address)).toHaveCount(0);
|
||||
await expectHostUnreachableAt(address);
|
||||
}
|
||||
|
||||
/** Reopens the host over its Tailscale address, as a phone on the tailnet would reach it. */
|
||||
export async function connectThroughTailscale(
|
||||
page: Page,
|
||||
daemon: { serverId: string; tailscaleAddress: string },
|
||||
): Promise<void> {
|
||||
await preparePairingHost(page, { serverId: daemon.serverId, endpoint: daemon.tailscaleAddress });
|
||||
await expectTailscaleAddress(page, daemon.tailscaleAddress);
|
||||
}
|
||||
|
||||
const TURN_OFF_QUESTION =
|
||||
"Turn off Tailscale?\n\nThis device is connected through Tailscale and will lose its connection to the host.";
|
||||
|
||||
/**
|
||||
* Taps the switch off over the Tailscale connection and cancels the question. Every state the row
|
||||
* commits from the tap to after Cancel must still show Tailscale on with its address: nothing
|
||||
* changes until the user confirms.
|
||||
*/
|
||||
export async function cancelTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
||||
const row = await recordTailscaleRow(page);
|
||||
const question = answerNextDialog(page, "dismiss");
|
||||
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
expect(await question).toBe(TURN_OFF_QUESTION);
|
||||
await page.waitForTimeout(500);
|
||||
expect(new Set((await row()).map((state) => `${state.value} ${state.address}`))).toEqual(
|
||||
new Set(["on true"]),
|
||||
);
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
|
||||
await expect(tailscaleAddressRow(page, address)).toBeVisible();
|
||||
expect((await fetch(`http://${address}/api/health`)).ok).toBe(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms turning Tailscale off over the Tailscale connection, which cuts this app off the host.
|
||||
* Without the host the row shows no value at all, on or off.
|
||||
*/
|
||||
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
||||
const question = answerNextDialog(page, "accept");
|
||||
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
expect(await question).toBe(TURN_OFF_QUESTION);
|
||||
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||
await expectHostUnreachableAt(address);
|
||||
}
|
||||
|
||||
function answerNextDialog(page: Page, answer: "accept" | "dismiss"): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
page.once("dialog", async (dialog) => {
|
||||
resolve(dialog.message());
|
||||
await (answer === "accept" ? dialog.accept() : dialog.dismiss());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
interface TailscaleRowState {
|
||||
/** `none` while the row shows no value yet. */
|
||||
value: "on" | "off" | "none";
|
||||
address: boolean;
|
||||
hint: string;
|
||||
labelTop: number;
|
||||
hintTop: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records every state the Tailscale row commits, painted or not: from now on in this page, and
|
||||
* from the first paint of every page load after it. Recording again starts a new record.
|
||||
*/
|
||||
async function recordTailscaleRow(page: Page): Promise<() => Promise<TailscaleRowState[]>> {
|
||||
const record = () => {
|
||||
const host = window as unknown as {
|
||||
tailscaleRow?: { states: unknown[]; last: string; sample(): void };
|
||||
};
|
||||
if (host.tailscaleRow) {
|
||||
host.tailscaleRow.states = [];
|
||||
host.tailscaleRow.last = "";
|
||||
host.tailscaleRow.sample();
|
||||
return;
|
||||
}
|
||||
const isVisibleText = (element: Element, text?: string) =>
|
||||
element.childElementCount === 0 &&
|
||||
(text === undefined
|
||||
? (element.textContent ?? "").trim() !== ""
|
||||
: element.textContent === text) &&
|
||||
element.getBoundingClientRect().height > 0;
|
||||
const readValue = (toggle: Element | null) => {
|
||||
if (!toggle) return "none";
|
||||
return toggle.getAttribute("aria-checked") === "true" ? "on" : "off";
|
||||
};
|
||||
const read = () => {
|
||||
const label = [...document.querySelectorAll("div, span")].find((element) =>
|
||||
isVisibleText(element, "Tailscale"),
|
||||
);
|
||||
if (!label) return null;
|
||||
let row: Element = label;
|
||||
while (row.parentElement && !(row as HTMLElement).innerText.includes("\n")) {
|
||||
row = row.parentElement;
|
||||
}
|
||||
const hint = [...row.querySelectorAll("div, span")].find(
|
||||
(element) => element !== label && isVisibleText(element),
|
||||
);
|
||||
const toggle = document.querySelector('[role="switch"][aria-label="Tailscale"]');
|
||||
return {
|
||||
value: readValue(toggle),
|
||||
address: document.querySelector('[data-testid="devices-tailscale-address"]') !== null,
|
||||
hint: hint?.textContent ?? "",
|
||||
labelTop: Math.round(label.getBoundingClientRect().top),
|
||||
hintTop: Math.round(hint?.getBoundingClientRect().top ?? -1),
|
||||
};
|
||||
};
|
||||
const recorder = {
|
||||
states: [] as unknown[],
|
||||
last: "",
|
||||
sample() {
|
||||
const state = read();
|
||||
const key = JSON.stringify(state);
|
||||
if (state && key !== recorder.last) recorder.states.push(state);
|
||||
recorder.last = key;
|
||||
},
|
||||
};
|
||||
host.tailscaleRow = recorder;
|
||||
new MutationObserver(() => recorder.sample()).observe(document, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
characterData: true,
|
||||
attributes: true,
|
||||
});
|
||||
};
|
||||
await page.addInitScript(record);
|
||||
await page.evaluate(record);
|
||||
return () =>
|
||||
page.evaluate(
|
||||
() =>
|
||||
(window as unknown as { tailscaleRow: { states: TailscaleRowState[] } }).tailscaleRow
|
||||
.states,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `open`, which first shows the Tailscale row of a host with Tailscale on, and checks the row
|
||||
* from its first state to its last: it starts with no value, never shows Tailscale off, and its
|
||||
* label and hint keep their text and place until it settles on, with the address below.
|
||||
*/
|
||||
export async function expectTailscaleRowLoadsOn(
|
||||
page: Page,
|
||||
address: string,
|
||||
open: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
const row = await recordTailscaleRow(page);
|
||||
await open();
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
|
||||
await expect(tailscaleAddressRow(page, address)).toBeVisible();
|
||||
const states = await row();
|
||||
expect(states[0]?.value).toBe("none");
|
||||
expect(states.filter((state) => state.value === "off")).toEqual([]);
|
||||
expect(
|
||||
new Set(states.map(({ hint, labelTop, hintTop }) => `${hint} ${labelTop} ${hintTop}`)).size,
|
||||
).toBe(1);
|
||||
expect(states.at(-1)).toMatchObject({ value: "on", address: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds every message between the app and the host on `port` for `ms` in each direction, as on a
|
||||
* slow network. The returned function brings the connection back to full speed.
|
||||
*/
|
||||
export async function slowConnectionToHost(
|
||||
page: Page,
|
||||
port: number,
|
||||
ms: number,
|
||||
): Promise<() => void> {
|
||||
let delay = ms;
|
||||
await page.routeWebSocket(wsRoutePatternForPort(String(port)), (app) => {
|
||||
const host = app.connectToServer();
|
||||
app.onMessage(
|
||||
deliverInOrderAfter(
|
||||
() => delay,
|
||||
(message) => host.send(message),
|
||||
),
|
||||
);
|
||||
host.onMessage(
|
||||
deliverInOrderAfter(
|
||||
() => delay,
|
||||
(message) => app.send(message),
|
||||
),
|
||||
);
|
||||
});
|
||||
return () => {
|
||||
delay = 0;
|
||||
};
|
||||
}
|
||||
|
||||
function deliverInOrderAfter(
|
||||
delay: () => number,
|
||||
deliver: (message: string | Buffer) => void,
|
||||
): (message: string | Buffer) => void {
|
||||
const queue: { at: number; message: string | Buffer }[] = [];
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const flush = () => {
|
||||
timer = null;
|
||||
while (queue[0] && queue[0].at <= Date.now()) deliver(queue.shift()!.message);
|
||||
if (queue[0]) timer = setTimeout(flush, queue[0].at - Date.now());
|
||||
};
|
||||
return (message) => {
|
||||
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
|
||||
if (!timer) flush();
|
||||
};
|
||||
}
|
||||
|
||||
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
await expect(page.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, daemon.serverId);
|
||||
await expect(page.getByTestId("host-page-pair-device-row")).toHaveCount(0);
|
||||
await openSettingsHostSection(page, daemon.serverId, "pair-device");
|
||||
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openPairDeviceModal(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Relay", exact: true }).click();
|
||||
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
|
||||
await page.getByRole("button", { name: /Pair a device/ }).click();
|
||||
await expect(page.getByTestId("host-page-pair-device-card")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectRelayConsent(page: Page): Promise<void> {
|
||||
const modal = page.getByTestId("devices-relay-pairing");
|
||||
const modal = page.getByTestId("host-page-pair-device-card");
|
||||
await expect(modal.getByText("Enable relay?", { exact: true })).toBeVisible();
|
||||
await expect(modal.getByText(/end-to-end encrypted/)).toBeVisible();
|
||||
await expect(modal.getByRole("link", { name: "Read how Paseo relay works" })).toBeVisible();
|
||||
@@ -376,7 +99,7 @@ export async function expectRelayConsent(page: Page): Promise<void> {
|
||||
|
||||
export async function declineRelay(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Not now", exact: true }).click();
|
||||
await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0);
|
||||
await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function enableRelayAndExpectOffer(page: Page): Promise<void> {
|
||||
@@ -401,10 +124,10 @@ export async function expectPairingOffer(page: Page): Promise<void> {
|
||||
|
||||
export async function closePairDeviceModal(page: Page): Promise<void> {
|
||||
await page
|
||||
.getByTestId("devices-relay-pairing")
|
||||
.getByTestId("host-page-pair-device-card")
|
||||
.getByRole("button", { name: "Close", exact: true })
|
||||
.click();
|
||||
await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0);
|
||||
await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function reloadAndOpenPairDevice(page: Page): Promise<void> {
|
||||
@@ -422,7 +145,7 @@ export async function enableRelayAndExpectFailure(
|
||||
expectedError = "Relay is controlled by a daemon launch override",
|
||||
): Promise<void> {
|
||||
await page.getByRole("button", { name: "Enable relay", exact: true }).click();
|
||||
const modal = page.getByTestId("devices-relay-pairing");
|
||||
const modal = page.getByTestId("host-page-pair-device-card");
|
||||
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
||||
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
||||
await expect(modal.getByRole("textbox", { name: "Pairing link" })).toHaveCount(0);
|
||||
@@ -432,7 +155,7 @@ export async function retryRelayAndExpectFailure(
|
||||
page: Page,
|
||||
expectedError = "Relay is controlled by a daemon launch override",
|
||||
): Promise<void> {
|
||||
const modal = page.getByTestId("devices-relay-pairing");
|
||||
const modal = page.getByTestId("host-page-pair-device-card");
|
||||
await modal.getByRole("button", { name: "Retry", exact: true }).click();
|
||||
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
||||
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
||||
@@ -450,7 +173,7 @@ export async function openPairDeviceFromHome(page: Page): Promise<void> {
|
||||
}
|
||||
|
||||
export async function expectRelayUpdateRequired(page: Page): Promise<void> {
|
||||
const modal = page.getByTestId("devices-relay-pairing");
|
||||
const modal = page.getByTestId("host-page-pair-device-card");
|
||||
await expect(
|
||||
modal.getByText("Update the host to enable relay from Paseo Desktop."),
|
||||
).toBeVisible();
|
||||
@@ -472,15 +195,15 @@ export function observePairingOfferRequests(page: Page, daemon: OutdatedDaemon):
|
||||
}
|
||||
|
||||
export async function expectPairingDisconnected(page: Page): Promise<void> {
|
||||
const modal = page.getByTestId("devices-relay-pairing");
|
||||
const modal = page.getByTestId("host-page-pair-device-card");
|
||||
await expect(modal.getByRole("alert")).toContainText("Host is not connected");
|
||||
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
|
||||
await selectSettingsHost(page, serverId);
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices"));
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "pair-device"));
|
||||
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openRelaySecurityDocs(page: Page): Promise<void> {
|
||||
|
||||
@@ -66,7 +66,7 @@ export type SettingsSection = keyof typeof SECTION_LABELS;
|
||||
type HostSection =
|
||||
| "projects"
|
||||
| "connections"
|
||||
| "devices"
|
||||
| "pair-device"
|
||||
| "agents"
|
||||
| "metadata"
|
||||
| "voice"
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import { once } from "node:events";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
import { killProcessTree, spawnTsx } from "./spawn-node";
|
||||
|
||||
const readySchema = z.object({ port: z.number(), serverId: z.string() });
|
||||
|
||||
export async function startTailscaleTestDaemon(origin: string) {
|
||||
const entrypoint = path.resolve(
|
||||
__dirname,
|
||||
"../../../../server/src/server/test-utils/tailscale-daemon.ts",
|
||||
);
|
||||
const child = spawnTsx(entrypoint, [origin], {
|
||||
stdio: ["ignore", "inherit", "inherit", "ipc"],
|
||||
});
|
||||
const signal = AbortSignal.timeout(30_000);
|
||||
try {
|
||||
const ready = await Promise.race([
|
||||
once(child, "message", { signal }).then(([message]) => readySchema.parse(message)),
|
||||
once(child, "exit", { signal }).then(([code]) => {
|
||||
throw new Error(`Tailscale test daemon exited before startup with code ${code}`);
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
...ready,
|
||||
tailscaleAddress: `127.0.0.2:${ready.port}`,
|
||||
close: () => killProcessTree(child),
|
||||
};
|
||||
} catch (error) {
|
||||
await killProcessTree(child);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Redirect, useLocalSearchParams } from "expo-router";
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
import { useMemo } from "react";
|
||||
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
||||
import SettingsScreen from "@/screens/settings-screen";
|
||||
import { buildSettingsHostSectionRoute, normalizeHostSectionSlug } from "@/utils/host-routes";
|
||||
import { normalizeHostSectionSlug } from "@/utils/host-routes";
|
||||
|
||||
export default function SettingsHostSectionRoute() {
|
||||
const params = useLocalSearchParams<{ serverId?: string; hostSection?: string }>();
|
||||
@@ -11,10 +11,6 @@ export default function SettingsHostSectionRoute() {
|
||||
const section = normalizeHostSectionSlug(rawSection) ?? "connections";
|
||||
const view = useMemo(() => ({ kind: "host" as const, serverId, section }), [serverId, section]);
|
||||
|
||||
if (rawSection === "pair-device" && serverId) {
|
||||
return <Redirect href={buildSettingsHostSectionRoute(serverId, "devices")} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<HostRouteBootstrapBoundary>
|
||||
<SettingsScreen view={view} />
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import { Children, isValidElement, useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { SettingsRowChildren } from "./row-children";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { NestedSettingsRows } from "./row-density";
|
||||
import { SettingsRowHeader } from "./row-header";
|
||||
|
||||
interface SettingsCollapsibleRowProps {
|
||||
@@ -46,7 +48,27 @@ export function SettingsCollapsibleRow({
|
||||
webAccessibilityProps={webExpandedProps}
|
||||
testID={testID ? `${testID}-toggle` : undefined}
|
||||
/>
|
||||
{expanded ? <SettingsRowChildren>{children}</SettingsRowChildren> : null}
|
||||
{expanded ? (
|
||||
<View style={styles.children}>
|
||||
<NestedSettingsRows>
|
||||
{Children.toArray(children).map((child, index) => (
|
||||
<View
|
||||
key={isValidElement(child) ? child.key : index}
|
||||
style={settingsStyles.rowBorder}
|
||||
>
|
||||
{child}
|
||||
</View>
|
||||
))}
|
||||
</NestedSettingsRows>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The revealed rows keep the card's rails; the tint is what groups them under their header.
|
||||
children: {
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -25,10 +25,7 @@ import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { ControlSizeProvider } from "@/components/ui/control-size";
|
||||
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
|
||||
import { useSettingsRowLayout } from "./row-density";
|
||||
import { SettingsRowTitle } from "./row-label";
|
||||
export { SettingsRowChildren } from "./row-children";
|
||||
export { SettingsGroup } from "./headings/settings-group";
|
||||
export { SettingsSection } from "./headings/settings-section";
|
||||
export { SettingsCollapsibleRow } from "./collapsible-row";
|
||||
@@ -39,16 +36,11 @@ export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
|
||||
export { SettingsInfoTip } from "./headings/settings-info-tip";
|
||||
export { MenuSettingsRows } from "./row-density";
|
||||
|
||||
/**
|
||||
* What app screens can add to a plugin-facing row: an accessory beside the label, such as an info
|
||||
* tip, an icon before the label, and a link to a page outside the app under the hint.
|
||||
*/
|
||||
/** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */
|
||||
interface AppRowExtras {
|
||||
labelAccessory?: ReactNode;
|
||||
/** An icon before the label, such as the thing the row is about. */
|
||||
leading?: ReactNode;
|
||||
/** A page outside the app that helps with this row, drawn under the hint as "Label ↗". */
|
||||
link?: Pick<ExternalLinkProps, "href" | "label" | "accessibilityLabel">;
|
||||
}
|
||||
|
||||
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
|
||||
@@ -75,7 +67,6 @@ export function SettingsRow({
|
||||
leading,
|
||||
labelAccessory,
|
||||
hint,
|
||||
link,
|
||||
error,
|
||||
children,
|
||||
testID,
|
||||
@@ -83,17 +74,20 @@ export function SettingsRow({
|
||||
const compact = useIsCompactFormFactor();
|
||||
const layout = useSettingsRowLayout();
|
||||
const rowStyle = useMemo(() => [layout.row, compact && styles.compactRow], [compact, layout]);
|
||||
const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]);
|
||||
return (
|
||||
<View style={rowStyle} testID={testID}>
|
||||
{leading ? <View style={styles.leading}>{leading}</View> : null}
|
||||
<View style={styles.label}>
|
||||
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
||||
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
|
||||
{link ? (
|
||||
<View style={styles.link}>
|
||||
<ExternalLink {...link} />
|
||||
{labelAccessory ? (
|
||||
<View style={styles.labelRow}>
|
||||
<Text style={accessoryTitleStyle}>{label}</Text>
|
||||
{labelAccessory}
|
||||
</View>
|
||||
) : null}
|
||||
) : (
|
||||
<Text style={layout.title}>{label}</Text>
|
||||
)}
|
||||
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
|
||||
{error ? (
|
||||
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
|
||||
{error}
|
||||
@@ -109,15 +103,7 @@ export function SettingsRow({
|
||||
);
|
||||
}
|
||||
|
||||
/** A switch row. App screens may pass `null` while the value is not known yet; see `Switch`. */
|
||||
export function SettingsSwitch({
|
||||
value,
|
||||
onValueChange,
|
||||
disabled,
|
||||
...row
|
||||
}: Omit<SettingsSwitchProps, "onValueChange" | "value"> &
|
||||
Partial<Pick<SettingsSwitchProps, "onValueChange">> &
|
||||
AppRowExtras & { value: boolean | null }) {
|
||||
export function SettingsSwitch({ value, onValueChange, disabled, ...row }: SettingsSwitchProps) {
|
||||
return (
|
||||
<SettingsRow {...row}>
|
||||
<Switch
|
||||
@@ -218,12 +204,7 @@ export function SettingsInput({
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsAction({
|
||||
actionLabel,
|
||||
onPress,
|
||||
disabled,
|
||||
...row
|
||||
}: SettingsActionProps & AppRowExtras) {
|
||||
export function SettingsAction({ actionLabel, onPress, disabled, ...row }: SettingsActionProps) {
|
||||
return (
|
||||
<SettingsRow {...row}>
|
||||
<Button variant="outline" onPress={onPress} disabled={disabled}>
|
||||
@@ -240,7 +221,13 @@ const styles = StyleSheet.create((theme) => ({
|
||||
// The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds.
|
||||
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
|
||||
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
|
||||
link: { alignItems: "flex-start", marginTop: theme.spacing[1] },
|
||||
labelRow: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
accessoryLabel: { flexShrink: 1, minWidth: 0 },
|
||||
control: { flexShrink: 1, maxWidth: "100%" },
|
||||
input: { minWidth: 180 },
|
||||
}));
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { Children, isValidElement, type ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { NestedSettingsRows } from "./row-density";
|
||||
|
||||
/**
|
||||
* Rows that belong to the row above them, such as the rows an expanded row reveals or the details
|
||||
* a switch turns on. They sit in the same card on a tinted band, laid out as nested rows.
|
||||
*/
|
||||
export function SettingsRowChildren({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<View style={styles.band}>
|
||||
<NestedSettingsRows>
|
||||
{Children.toArray(children).map((child, index) => (
|
||||
<View key={isValidElement(child) ? child.key : index} style={settingsStyles.rowBorder}>
|
||||
{child}
|
||||
</View>
|
||||
))}
|
||||
</NestedSettingsRows>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The rows keep the card's rails; the tint is what groups them under the row above.
|
||||
band: {
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
}));
|
||||
@@ -11,7 +11,6 @@ import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
|
||||
import { SettingsRowTitle } from "./row-label";
|
||||
|
||||
const ThemedChevron = withUnistyles(ChevronRight);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
@@ -119,8 +118,9 @@ export function SettingsRowHeader({
|
||||
</View>
|
||||
) : null}
|
||||
<View style={[contentStyle, styles.passThrough]}>
|
||||
<View {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
||||
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<Text style={layout.title}>{label}</Text>
|
||||
{labelAccessory}
|
||||
</View>
|
||||
{hintStatus ? (
|
||||
<RowHintLine hint={hint} status={hintStatus} hintStyle={layout.hint} />
|
||||
@@ -293,6 +293,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
labelRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
|
||||
summary: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { useSettingsRowLayout } from "./row-density";
|
||||
|
||||
/**
|
||||
* A row's label line: the label, and beside it an accessory such as a badge or an info tip. Rows
|
||||
* with inline controls and rows that lead somewhere both draw it, so their labels and hints keep
|
||||
* the same distances whether or not a row carries an accessory.
|
||||
*/
|
||||
export function SettingsRowTitle({ label, accessory }: { label: string; accessory?: ReactNode }) {
|
||||
const layout = useSettingsRowLayout();
|
||||
const titleStyle = useMemo(() => [layout.title, styles.title], [layout]);
|
||||
if (!accessory) return <Text style={layout.title}>{label}</Text>;
|
||||
return (
|
||||
<View style={styles.line}>
|
||||
<Text style={titleStyle}>{label}</Text>
|
||||
<View style={styles.accessory}>{accessory}</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
line: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
title: { flexShrink: 1, minWidth: 0 },
|
||||
// An accessory is taller than the label's line. It hangs into the row's padding instead, so the
|
||||
// label and hint keep the distances of a row without one.
|
||||
accessory: { marginVertical: -theme.spacing[1] },
|
||||
}));
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
View,
|
||||
type GestureResponderEvent,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
@@ -20,11 +19,7 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
interface SwitchProps {
|
||||
/**
|
||||
* `null` while the value is not known yet, such as while it loads from a host. The switch's space
|
||||
* stays reserved and empty, so the switch takes it when the value arrives and nothing moves.
|
||||
*/
|
||||
value: boolean | null;
|
||||
value: boolean;
|
||||
onValueChange?: (value: boolean) => void;
|
||||
disabled?: boolean;
|
||||
accessibilityLabel?: string;
|
||||
@@ -114,7 +109,7 @@ export function Switch({
|
||||
const handlePress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
event.stopPropagation();
|
||||
if (disabled || value === null) return;
|
||||
if (disabled) return;
|
||||
onValueChange?.(!value);
|
||||
},
|
||||
[disabled, onValueChange, value],
|
||||
@@ -124,10 +119,7 @@ export function Switch({
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const geometry = useMemo(() => switchGeometryForLayout(size, isCompact), [size, isCompact]);
|
||||
|
||||
const accessibilityState = useMemo(
|
||||
() => ({ checked: value === true, disabled }),
|
||||
[value, disabled],
|
||||
);
|
||||
const accessibilityState = useMemo(() => ({ checked: value, disabled }), [value, disabled]);
|
||||
const pressableStyle = useMemo(
|
||||
() => [
|
||||
styles.switchControl,
|
||||
@@ -142,12 +134,6 @@ export function Switch({
|
||||
],
|
||||
[disabled, geometry.hitHeight, geometry.trackHeight, style],
|
||||
);
|
||||
const unknownStyle = useMemo(
|
||||
() => [{ width: geometry.trackWidth, minHeight: geometry.trackHeight }, style],
|
||||
[geometry.trackWidth, geometry.trackHeight, style],
|
||||
);
|
||||
|
||||
if (value === null) return <View style={unknownStyle} testID={testID} />;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { PairDeviceSection } from "@/devices/pair-device-section";
|
||||
import { PairDeviceSection } from "@/desktop/components/pair-device-section";
|
||||
|
||||
export interface PairDeviceModalProps {
|
||||
serverId: string;
|
||||
+1
-1
@@ -23,7 +23,7 @@ import {
|
||||
|
||||
const RELAY_DOCS_URL = "https://paseo.sh/docs/security";
|
||||
export const CONNECTIVITY_DOCS_URL = "https://paseo.sh/docs/connectivity";
|
||||
const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
|
||||
export const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const ThemedShieldCheck = withUnistyles(ShieldCheck);
|
||||
@@ -1,2 +0,0 @@
|
||||
export { PairDeviceModal } from "./pair-device-modal";
|
||||
export { WaysToConnect } from "./ways-to-connect";
|
||||
@@ -1,36 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { describeTailscale } from "./tailscale-hint";
|
||||
|
||||
// Statuses as the host reports them; see `createDaemonListeners` in the server's listeners.ts.
|
||||
const off: TailscaleStatus = { ip: "100.101.102.103", address: null, state: "off" };
|
||||
|
||||
describe("the Tailscale row's hint", () => {
|
||||
it("says why Tailscale stays off when the host listens on a socket", () => {
|
||||
const socketHint = "Off, because this host listens on a local socket";
|
||||
expect(describeTailscale({ ...off, lockedBy: "main", mainIsSocket: true }, i18n.t)).toBe(
|
||||
socketHint,
|
||||
);
|
||||
expect(describeTailscale({ ...off, lockedBy: "launch", mainIsSocket: true }, i18n.t)).toBe(
|
||||
socketHint,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the hint of every other state", () => {
|
||||
const hint = (status: TailscaleStatus) => describeTailscale(status, i18n.t);
|
||||
expect(hint(off)).toBe("Direct over your tailnet, enter an address");
|
||||
expect(hint({ ip: null, address: null, state: "unavailable", lockedBy: "launch" })).toBe(
|
||||
"Tailscale is not running on this host",
|
||||
);
|
||||
expect(hint({ ...off, state: "waiting", address: "100.101.102.103:6767" })).toBe(
|
||||
"Waiting for Tailscale to start on this host",
|
||||
);
|
||||
expect(hint({ ...off, state: "on", address: "100.101.102.103:6767", lockedBy: "main" })).toBe(
|
||||
"Always on, because this host already accepts Tailscale connections",
|
||||
);
|
||||
expect(hint({ ...off, lockedBy: "launch" })).toBe(
|
||||
"Controlled by the command that starts this host",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
/** The line under the Tailscale label for each state the host reports, most specific first. */
|
||||
export function describeTailscale(status: TailscaleStatus, t: TFunction): string {
|
||||
if (status.state === "unavailable") return t("devices.tailscale.unavailable");
|
||||
if (status.state === "waiting") return t("devices.tailscale.waiting");
|
||||
// A socket is why Tailscale cannot be on, even when the launch command also fixes the address.
|
||||
if (status.mainIsSocket) return t("devices.tailscale.socket");
|
||||
if (status.lockedBy === "launch") return t("devices.tailscale.launch");
|
||||
if (status.lockedBy === "main") return t("devices.tailscale.alwaysOn");
|
||||
return t("devices.tailscale.hint");
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SettingsAction, SettingsRowChildren, SettingsSwitch } from "@/components/settings";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { copyToClipboard } from "@/utils/copy-to-clipboard";
|
||||
import { describeTailscale } from "./tailscale-hint";
|
||||
|
||||
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
||||
const TAILSCALE_DOWNLOAD_URL = "https://tailscale.com/download";
|
||||
// A product name, the same in every language.
|
||||
const LABEL = "Tailscale";
|
||||
|
||||
type HostClient = NonNullable<ReturnType<typeof useHostRuntimeClient>>;
|
||||
|
||||
/**
|
||||
* Turns Tailscale on or off for a host and shows the address a phone on the tailnet adds. Renders
|
||||
* as a row inside a `SettingsCard`; when Tailscale is on, the address is a nested row under it.
|
||||
*/
|
||||
export function TailscaleRow({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const connection = useHostRuntimeSnapshot(serverId)?.connectionStatus;
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo);
|
||||
const updateLink = useMemo(
|
||||
() => ({ href: UPDATES_DOCS_URL, label: t("devices.tailscale.updateDocs") }),
|
||||
[t],
|
||||
);
|
||||
// COMPAT(tailscale): added in v0.16.0, remove after 2027-05-25 once daemon floor >= v0.16.0.
|
||||
if (serverInfo && serverInfo.features?.tailscale !== true) {
|
||||
return (
|
||||
<SettingsSwitch
|
||||
label={LABEL}
|
||||
hint={t("devices.tailscale.update")}
|
||||
link={updateLink}
|
||||
value={false}
|
||||
disabled
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (client && connection === "online" && serverInfo) {
|
||||
return <TailscaleControl serverId={serverId} client={client} />;
|
||||
}
|
||||
// Without the host the row shows no value: the switch's space stays empty. A host the app has
|
||||
// reached before keeps its server info, so while the app retries it still reads as disconnected.
|
||||
const lost = connection === "offline" || connection === "error" || Boolean(serverInfo);
|
||||
return (
|
||||
<SettingsSwitch
|
||||
label={LABEL}
|
||||
hint={t(lost ? "workspace.terminal.hostDisconnected" : "devices.tailscale.hint")}
|
||||
value={null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TailscaleControl({ serverId, client }: { serverId: string; client: HostClient }) {
|
||||
const { t } = useTranslation();
|
||||
const tailscale = useTailscale(serverId, client);
|
||||
const { status } = tailscale;
|
||||
const installLink = useMemo(
|
||||
() => ({ href: TAILSCALE_DOWNLOAD_URL, label: t("devices.tailscale.install") }),
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsSwitch
|
||||
label={LABEL}
|
||||
hint={status ? describeTailscale(status, t) : t("devices.tailscale.hint")}
|
||||
link={status?.state === "unavailable" ? installLink : undefined}
|
||||
error={tailscale.error}
|
||||
value={tailscale.value}
|
||||
disabled={!status || status.state === "unavailable" || Boolean(status.lockedBy)}
|
||||
onValueChange={tailscale.setEnabled}
|
||||
/>
|
||||
{tailscale.address ? <TailscaleAddress address={tailscale.address} /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function TailscaleAddress({ address }: { address: string }) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const copy = useCallback(() => {
|
||||
void copyToClipboard(address)
|
||||
.then(() => toast.copied())
|
||||
.catch(() => toast.error(t("common.errors.error")));
|
||||
}, [address, t, toast]);
|
||||
return (
|
||||
<SettingsRowChildren>
|
||||
<SettingsAction
|
||||
label={address}
|
||||
hint={t("devices.tailscale.address")}
|
||||
actionLabel={t("common.actions.copy")}
|
||||
onPress={copy}
|
||||
testID="devices-tailscale-address"
|
||||
/>
|
||||
</SettingsRowChildren>
|
||||
);
|
||||
}
|
||||
|
||||
interface TailscaleChange {
|
||||
enabled: boolean;
|
||||
confirmed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The host's Tailscale state and the one way to change it. While a change is in flight the switch
|
||||
* already shows where it is going, so a tap answers at once; the host's answer then settles it.
|
||||
* Turning Tailscale off over the connection it would cut asks first, and nothing changes on screen
|
||||
* until the user confirms.
|
||||
*/
|
||||
function useTailscale(serverId: string, client: HostClient) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const queryKey = useMemo(() => ["tailscale-status", serverId], [serverId]);
|
||||
|
||||
const query = useFetchQuery({
|
||||
queryKey,
|
||||
queryFn: async () => {
|
||||
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
|
||||
if (!tailscale) throw new Error("Host did not report Tailscale status");
|
||||
return tailscale;
|
||||
},
|
||||
// Tailscale can come up after the host does; polling moves "waiting" to "on" on its own.
|
||||
refetchInterval: 2_000,
|
||||
staleTimeMs: 0,
|
||||
dataShape: "value",
|
||||
});
|
||||
|
||||
const change = useMutation({
|
||||
mutationFn: async ({ enabled, confirmed }: TailscaleChange) => {
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
return client.setTailscaleEnabled(enabled, confirmed);
|
||||
},
|
||||
onSuccess: (result) => queryClient.setQueryData(queryKey, result.tailscale),
|
||||
});
|
||||
|
||||
const status = query.data;
|
||||
const pending = change.isPending ? change.variables.enabled : undefined;
|
||||
const on = status?.state === "on" || status?.state === "waiting";
|
||||
// Not known until the host first answers.
|
||||
const value = pending ?? (status ? on : null);
|
||||
|
||||
const { mutate } = change;
|
||||
const confirmTurnOff = useCallback(
|
||||
() =>
|
||||
confirmDialog({
|
||||
title: t("devices.tailscale.confirmTitle"),
|
||||
message: t("devices.tailscale.confirmMessage"),
|
||||
confirmLabel: t("devices.tailscale.confirmAction"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
destructive: true,
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
const turnOffConfirmed = useCallback(async () => {
|
||||
if (await confirmTurnOff()) mutate({ enabled: false, confirmed: true });
|
||||
}, [confirmTurnOff, mutate]);
|
||||
const disconnects = status?.disconnectsCurrentConnection === true;
|
||||
const setEnabled = useCallback(
|
||||
(enabled: boolean) => {
|
||||
if (!enabled && disconnects) {
|
||||
void turnOffConfirmed();
|
||||
return;
|
||||
}
|
||||
mutate(
|
||||
{ enabled, confirmed: false },
|
||||
{
|
||||
// The status was stale: the host would cut this connection after all. Its answer has
|
||||
// already put the row back to on, so the question is asked over what is true.
|
||||
onSuccess: (result) => {
|
||||
if (result.confirmationRequired) void turnOffConfirmed();
|
||||
},
|
||||
},
|
||||
);
|
||||
},
|
||||
[disconnects, mutate, turnOffConfirmed],
|
||||
);
|
||||
|
||||
let error: string | undefined;
|
||||
if (change.isError) {
|
||||
error = t(
|
||||
change.variables.enabled ? "devices.tailscale.turnOnError" : "devices.tailscale.turnOffError",
|
||||
);
|
||||
} else if (query.isError && !status) {
|
||||
error = t("devices.tailscale.statusError");
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
value,
|
||||
error,
|
||||
// A tap is ignored until the host answers the one before it.
|
||||
setEnabled: change.isPending ? undefined : setEnabled,
|
||||
address: status?.state === "on" && value ? status.address : null,
|
||||
};
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
|
||||
import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { PairDeviceModal } from "./pair-device-modal";
|
||||
import { CONNECTIVITY_DOCS_URL } from "./pair-device-section";
|
||||
import { TailscaleRow } from "./tailscale-row";
|
||||
|
||||
/**
|
||||
* The ways another device can connect to a host: Relay, which pairs through a QR code in a sheet,
|
||||
* and Tailscale, a switch and an address. Settings and the setup's phone step show this same block.
|
||||
*/
|
||||
export function WaysToConnect({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [pairing, setPairing] = useState(false);
|
||||
const openPairing = useCallback(() => setPairing(true), []);
|
||||
const closePairing = useCallback(() => setPairing(false), []);
|
||||
const recommended = useMemo(
|
||||
() => <StatusBadge size="xs" variant="success" label={t("devices.recommended")} />,
|
||||
[t],
|
||||
);
|
||||
const docsLink = useMemo(
|
||||
() => ({
|
||||
href: CONNECTIVITY_DOCS_URL,
|
||||
label: t("devices.docs"),
|
||||
accessibilityLabel: t("devices.docsAccessibility"),
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsSection title={t("devices.waysToConnect")} link={docsLink}>
|
||||
<SettingsCard>
|
||||
<SettingsDetailRow
|
||||
label={t("devices.relay.title")}
|
||||
labelAccessory={recommended}
|
||||
hint={t("devices.relay.hint")}
|
||||
onPress={openPairing}
|
||||
testID="devices-relay"
|
||||
/>
|
||||
<TailscaleRow serverId={serverId} />
|
||||
</SettingsCard>
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={pairing}
|
||||
onClose={closePairing}
|
||||
testID="devices-relay-pairing"
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
@@ -1791,6 +1791,12 @@ export const ar: TranslationResources = {
|
||||
"يتيح لك تطبيق الجوال الأصلي كامل الميزات التحكم في أي كمبيوتر يعمل عليه Paseo من هاتفك",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "اختر طريقة الاتصال",
|
||||
connectDocs: "الوثائق",
|
||||
openConnectDocs: "افتح وثائق الاتصال",
|
||||
recommended: "موصى به",
|
||||
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
|
||||
tailscale: { title: "Tailscale", hint: "يتطلب بعض الإعداد" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1869,32 +1875,6 @@ export const ar: TranslationResources = {
|
||||
hostDisconnected: "Host غير متصل",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "الأجهزة",
|
||||
waysToConnect: "طرق الاتصال",
|
||||
docs: "الوثائق",
|
||||
docsAccessibility: "افتح وثائق الاتصال",
|
||||
recommended: "موصى به",
|
||||
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
|
||||
tailscale: {
|
||||
hint: "اتصال مباشر عبر شبكة tailnet الخاصة بك، أدخل عنوانًا",
|
||||
unavailable: "Tailscale لا يعمل على هذا المضيف",
|
||||
install: "احصل على Tailscale",
|
||||
waiting: "في انتظار بدء Tailscale على هذا المضيف",
|
||||
alwaysOn: "مفعّل دائمًا، لأن هذا المضيف يقبل اتصالات Tailscale بالفعل",
|
||||
socket: "متوقف، لأن هذا المضيف يستمع على مقبس محلي",
|
||||
launch: "يتحكم فيه الأمر الذي يشغّل هذا المضيف",
|
||||
update: "حدّث هذا المضيف لاستخدام Tailscale",
|
||||
updateDocs: "طريقة التحديث",
|
||||
address: "على هاتف متصل بـ Tailscale، أضف مضيفًا بهذا العنوان",
|
||||
statusError: "تعذّر التحقق من Tailscale",
|
||||
turnOnError: "تعذّر تشغيل Tailscale",
|
||||
turnOffError: "تعذّر إيقاف Tailscale",
|
||||
confirmTitle: "إيقاف Tailscale؟",
|
||||
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
|
||||
confirmAction: "إيقاف",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "كلمة المرور لـ {{host}}",
|
||||
@@ -2949,7 +2929,9 @@ export const ar: TranslationResources = {
|
||||
timeout: "نفذ الوقت",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "إقران الأجهزة",
|
||||
rowTitle: "إقران جهاز",
|
||||
rowHint: "امسح رمز QR ضوئيًا أو انسخ رابطًا لتوصيل هاتفك بهذا المضيف",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1820,6 +1820,12 @@ export const en = {
|
||||
"The fully featured native mobile app allows you to control any Paseo computer from your phone",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Choose how to connect",
|
||||
connectDocs: "Docs",
|
||||
openConnectDocs: "Open connectivity documentation",
|
||||
recommended: "Recommended",
|
||||
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
|
||||
tailscale: { title: "Tailscale", hint: "Requires some setup" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1898,33 +1904,6 @@ export const en = {
|
||||
hostDisconnected: "Host is not connected",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Devices",
|
||||
waysToConnect: "Ways to connect",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Open connectivity documentation",
|
||||
recommended: "Recommended",
|
||||
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
|
||||
tailscale: {
|
||||
hint: "Direct over your tailnet, enter an address",
|
||||
unavailable: "Tailscale is not running on this host",
|
||||
install: "Get Tailscale",
|
||||
waiting: "Waiting for Tailscale to start on this host",
|
||||
alwaysOn: "Always on, because this host already accepts Tailscale connections",
|
||||
socket: "Off, because this host listens on a local socket",
|
||||
launch: "Controlled by the command that starts this host",
|
||||
update: "Update this host to use Tailscale",
|
||||
updateDocs: "How to update",
|
||||
address: "On a phone with Tailscale, add a host at this address",
|
||||
statusError: "Could not check Tailscale",
|
||||
turnOnError: "Could not turn on Tailscale",
|
||||
turnOffError: "Could not turn off Tailscale",
|
||||
confirmTitle: "Turn off Tailscale?",
|
||||
confirmMessage:
|
||||
"This device is connected through Tailscale and will lose its connection to the host.",
|
||||
confirmAction: "Turn off",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Password for {{host}}",
|
||||
@@ -3045,7 +3024,9 @@ export const en = {
|
||||
timeout: "Timeout",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Pair devices",
|
||||
rowTitle: "Pair a device",
|
||||
rowHint: "Scan a QR code or copy a link to connect your phone to this host",
|
||||
},
|
||||
skills: {
|
||||
sectionTitle: "Orchestration skills",
|
||||
|
||||
@@ -1839,6 +1839,12 @@ export const es: TranslationResources = {
|
||||
"La app móvil nativa completa te permite controlar cualquier ordenador con Paseo desde tu teléfono",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Elige cómo conectarte",
|
||||
connectDocs: "Docs",
|
||||
openConnectDocs: "Abrir la documentación de conectividad",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
|
||||
tailscale: { title: "Tailscale", hint: "Requiere algo de configuración" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1917,33 +1923,6 @@ export const es: TranslationResources = {
|
||||
hostDisconnected: "Hostno está conectado",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Dispositivos",
|
||||
waysToConnect: "Formas de conectarse",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Abrir la documentación de conectividad",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
|
||||
tailscale: {
|
||||
hint: "Conexión directa por tu tailnet, introduce una dirección",
|
||||
unavailable: "Tailscale no se está ejecutando en este host",
|
||||
install: "Obtener Tailscale",
|
||||
waiting: "Esperando a que Tailscale se inicie en este host",
|
||||
alwaysOn: "Siempre activado, porque este host ya acepta conexiones de Tailscale",
|
||||
socket: "Desactivado, porque este host escucha en un socket local",
|
||||
launch: "Lo controla el comando que inicia este host",
|
||||
update: "Actualiza este host para usar Tailscale",
|
||||
updateDocs: "Cómo actualizar",
|
||||
address: "En un teléfono con Tailscale, añade un host con esta dirección",
|
||||
statusError: "No se pudo comprobar Tailscale",
|
||||
turnOnError: "No se pudo activar Tailscale",
|
||||
turnOffError: "No se pudo desactivar Tailscale",
|
||||
confirmTitle: "¿Desactivar Tailscale?",
|
||||
confirmMessage:
|
||||
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
|
||||
confirmAction: "Desactivar",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Contraseña de {{host}}",
|
||||
@@ -2974,7 +2953,9 @@ export const es: TranslationResources = {
|
||||
timeout: "Se acabó el tiempo",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Emparejar dispositivos",
|
||||
rowTitle: "Emparejar un dispositivo",
|
||||
rowHint: "Escanee un códigoQRo copie un enlace para conectar su teléfono a este host",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1837,6 +1837,12 @@ export const fr: TranslationResources = {
|
||||
"L'application mobile native complète vous permet de contrôler n'importe quel ordinateur Paseo depuis votre téléphone",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Choisissez comment vous connecter",
|
||||
connectDocs: "Docs",
|
||||
openConnectDocs: "Ouvrir la documentation sur la connectivité",
|
||||
recommended: "Recommandé",
|
||||
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
|
||||
tailscale: { title: "Tailscale", hint: "Demande un peu de configuration" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1915,32 +1921,6 @@ export const fr: TranslationResources = {
|
||||
hostDisconnected: "L’hôte n’est pas connecté",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Appareils",
|
||||
waysToConnect: "Moyens de connexion",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Ouvrir la documentation sur la connectivité",
|
||||
recommended: "Recommandé",
|
||||
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
|
||||
tailscale: {
|
||||
hint: "Connexion directe via votre tailnet, saisissez une adresse",
|
||||
unavailable: "Tailscale ne fonctionne pas sur cet hôte",
|
||||
install: "Obtenir Tailscale",
|
||||
waiting: "En attente du démarrage de Tailscale sur cet hôte",
|
||||
alwaysOn: "Toujours activé, car cet hôte accepte déjà les connexions Tailscale",
|
||||
socket: "Désactivé, car cet hôte écoute sur un socket local",
|
||||
launch: "Contrôlé par la commande qui démarre cet hôte",
|
||||
update: "Mettez cet hôte à jour pour utiliser Tailscale",
|
||||
updateDocs: "Comment mettre à jour",
|
||||
address: "Sur un téléphone avec Tailscale, ajoutez un hôte à cette adresse",
|
||||
statusError: "Impossible de vérifier Tailscale",
|
||||
turnOnError: "Impossible d’activer Tailscale",
|
||||
turnOffError: "Impossible de désactiver Tailscale",
|
||||
confirmTitle: "Désactiver Tailscale ?",
|
||||
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
|
||||
confirmAction: "Désactiver",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Mot de passe pour {{host}}",
|
||||
@@ -2975,7 +2955,9 @@ export const fr: TranslationResources = {
|
||||
timeout: "Délai dépassé",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Associer des appareils",
|
||||
rowTitle: "Associer un appareil",
|
||||
rowHint: "Scannez un QR code ou copiez un lien pour connecter votre téléphone à cet hôte",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1811,6 +1811,12 @@ export const ja: TranslationResources = {
|
||||
"フル機能のネイティブモバイルアプリで、スマートフォンからどの Paseo コンピューターでも操作できます",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "接続方法を選択",
|
||||
connectDocs: "ドキュメント",
|
||||
openConnectDocs: "接続のドキュメントを開く",
|
||||
recommended: "おすすめ",
|
||||
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
|
||||
tailscale: { title: "Tailscale", hint: "少し設定が必要です" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1889,32 +1895,6 @@ export const ja: TranslationResources = {
|
||||
hostDisconnected: "ホストが接続されていません",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "デバイス",
|
||||
waysToConnect: "接続方法",
|
||||
docs: "ドキュメント",
|
||||
docsAccessibility: "接続のドキュメントを開く",
|
||||
recommended: "おすすめ",
|
||||
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
|
||||
tailscale: {
|
||||
hint: "tailnet 経由で直接接続、アドレスを入力",
|
||||
unavailable: "このホストで Tailscale が動作していません",
|
||||
install: "Tailscale を入手",
|
||||
waiting: "このホストで Tailscale が起動するのを待っています",
|
||||
alwaysOn: "常にオン。このホストはすでに Tailscale からの接続を受け付けています",
|
||||
socket: "オフ。このホストはローカルソケットで待ち受けています",
|
||||
launch: "このホストを起動するコマンドで制御されています",
|
||||
update: "Tailscale を使うにはこのホストを更新してください",
|
||||
updateDocs: "更新方法",
|
||||
address: "Tailscale を使うスマートフォンで、このアドレスのホストを追加してください",
|
||||
statusError: "Tailscale を確認できませんでした",
|
||||
turnOnError: "Tailscale をオンにできませんでした",
|
||||
turnOffError: "Tailscale をオフにできませんでした",
|
||||
confirmTitle: "Tailscale をオフにしますか?",
|
||||
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
|
||||
confirmAction: "オフにする",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} のパスワード",
|
||||
@@ -2941,7 +2921,9 @@ export const ja: TranslationResources = {
|
||||
timeout: "タイムアウト",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "デバイスをペアリング",
|
||||
rowTitle: "デバイスをペアリング",
|
||||
rowHint: "QRコードをスキャンするかリンクをコピーしてスマートフォンをこのホストに接続",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1802,6 +1802,12 @@ export const ko: TranslationResources = {
|
||||
"모든 기능을 갖춘 네이티브 모바일 앱으로 휴대폰에서 어떤 Paseo 컴퓨터든 제어할 수 있습니다",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "연결 방법 선택",
|
||||
connectDocs: "문서",
|
||||
openConnectDocs: "연결 문서 열기",
|
||||
recommended: "권장",
|
||||
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
||||
tailscale: { title: "Tailscale", hint: "약간의 설정이 필요합니다" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1880,32 +1886,6 @@ export const ko: TranslationResources = {
|
||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "기기",
|
||||
waysToConnect: "연결 방법",
|
||||
docs: "문서",
|
||||
docsAccessibility: "연결 문서 열기",
|
||||
recommended: "권장",
|
||||
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
||||
tailscale: {
|
||||
hint: "tailnet으로 직접 연결, 주소 입력",
|
||||
unavailable: "이 호스트에서 Tailscale이 실행 중이 아닙니다",
|
||||
install: "Tailscale 받기",
|
||||
waiting: "이 호스트에서 Tailscale이 시작되기를 기다리는 중",
|
||||
alwaysOn: "항상 켜짐. 이 호스트가 이미 Tailscale 연결을 받고 있습니다",
|
||||
socket: "꺼짐. 이 호스트가 로컬 소켓에서 수신 대기 중입니다",
|
||||
launch: "이 호스트를 시작하는 명령이 제어합니다",
|
||||
update: "Tailscale을 사용하려면 이 호스트를 업데이트하세요",
|
||||
updateDocs: "업데이트 방법",
|
||||
address: "Tailscale을 사용하는 휴대전화에서 이 주소로 호스트를 추가하세요",
|
||||
statusError: "Tailscale을 확인하지 못했습니다",
|
||||
turnOnError: "Tailscale을 켜지 못했습니다",
|
||||
turnOffError: "Tailscale을 끄지 못했습니다",
|
||||
confirmTitle: "Tailscale을 끌까요?",
|
||||
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
|
||||
confirmAction: "끄기",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}}의 비밀번호",
|
||||
@@ -2927,7 +2907,9 @@ export const ko: TranslationResources = {
|
||||
timeout: "시간 초과",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "기기 페어링",
|
||||
rowTitle: "기기 페어링",
|
||||
rowHint: "QR 코드를 스캔하거나 링크를 복사하여 휴대폰을 이 호스트에 연결하세요",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1824,6 +1824,12 @@ export const ptBR: TranslationResources = {
|
||||
"O app móvel nativo completo permite controlar qualquer computador com Paseo pelo seu celular",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Escolha como se conectar",
|
||||
connectDocs: "Docs",
|
||||
openConnectDocs: "Abrir documentação de conectividade",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
|
||||
tailscale: { title: "Tailscale", hint: "Requer alguma configuração" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1902,33 +1908,6 @@ export const ptBR: TranslationResources = {
|
||||
hostDisconnected: "Host não está conectado",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Dispositivos",
|
||||
waysToConnect: "Formas de conexão",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Abrir documentação de conectividade",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
|
||||
tailscale: {
|
||||
hint: "Conexão direta pela sua tailnet, digite um endereço",
|
||||
unavailable: "O Tailscale não está em execução neste host",
|
||||
install: "Baixar o Tailscale",
|
||||
waiting: "Aguardando o Tailscale iniciar neste host",
|
||||
alwaysOn: "Sempre ativado, porque este host já aceita conexões do Tailscale",
|
||||
socket: "Desativado, porque este host escuta em um socket local",
|
||||
launch: "Controlado pelo comando que inicia este host",
|
||||
update: "Atualize este host para usar o Tailscale",
|
||||
updateDocs: "Como atualizar",
|
||||
address: "Em um celular com Tailscale, adicione um host com este endereço",
|
||||
statusError: "Não foi possível verificar o Tailscale",
|
||||
turnOnError: "Não foi possível ativar o Tailscale",
|
||||
turnOffError: "Não foi possível desativar o Tailscale",
|
||||
confirmTitle: "Desativar o Tailscale?",
|
||||
confirmMessage:
|
||||
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
|
||||
confirmAction: "Desativar",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Senha de {{host}}",
|
||||
@@ -2955,7 +2934,9 @@ export const ptBR: TranslationResources = {
|
||||
timeout: "Timeout",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Parear dispositivos",
|
||||
rowTitle: "Parear um dispositivo",
|
||||
rowHint: "Escaneie um QR code ou copie um link para conectar seu celular a este host",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1824,6 +1824,12 @@ export const ru: TranslationResources = {
|
||||
"Полнофункциональное нативное мобильное приложение позволяет управлять любым компьютером с Paseo с телефона",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Выберите способ подключения",
|
||||
connectDocs: "Документация",
|
||||
openConnectDocs: "Открыть документацию по подключению",
|
||||
recommended: "Рекомендуется",
|
||||
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
|
||||
tailscale: { title: "Tailscale", hint: "Требует небольшой настройки" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1902,32 +1908,6 @@ export const ru: TranslationResources = {
|
||||
hostDisconnected: "Хост не подключён",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Устройства",
|
||||
waysToConnect: "Способы подключения",
|
||||
docs: "Документация",
|
||||
docsAccessibility: "Открыть документацию по подключению",
|
||||
recommended: "Рекомендуется",
|
||||
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
|
||||
tailscale: {
|
||||
hint: "Прямое подключение через ваш tailnet, по адресу",
|
||||
unavailable: "Tailscale не запущен на этом хосте",
|
||||
install: "Скачать Tailscale",
|
||||
waiting: "Ожидаем запуска Tailscale на этом хосте",
|
||||
alwaysOn: "Всегда включено, так как хост уже принимает подключения Tailscale",
|
||||
socket: "Выключено, так как хост слушает локальный сокет",
|
||||
launch: "Управляется командой, которая запускает этот хост",
|
||||
update: "Обновите этот хост, чтобы использовать Tailscale",
|
||||
updateDocs: "Как обновить",
|
||||
address: "На телефоне с Tailscale добавьте хост с этим адресом",
|
||||
statusError: "Не удалось проверить Tailscale",
|
||||
turnOnError: "Не удалось включить Tailscale",
|
||||
turnOffError: "Не удалось выключить Tailscale",
|
||||
confirmTitle: "Выключить Tailscale?",
|
||||
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
|
||||
confirmAction: "Выключить",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Пароль для {{host}}",
|
||||
@@ -2962,7 +2942,10 @@ export const ru: TranslationResources = {
|
||||
timeout: "Время ожидания истекло",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Подключение устройств",
|
||||
rowTitle: "Подключить устройство",
|
||||
rowHint:
|
||||
"Отсканируйте QR-код или скопируйте ссылку, чтобы подключить телефон к этому хосту.",
|
||||
},
|
||||
skills: {
|
||||
sectionTitle: "Навыки оркестрации",
|
||||
|
||||
@@ -1773,6 +1773,12 @@ export const zhCN: TranslationResources = {
|
||||
description: "功能完整的原生移动应用让你可以在手机上控制任意一台 Paseo 电脑",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "选择连接方式",
|
||||
connectDocs: "文档",
|
||||
openConnectDocs: "打开连接文档",
|
||||
recommended: "推荐",
|
||||
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
|
||||
tailscale: { title: "Tailscale", hint: "需要一些设置" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1851,32 +1857,6 @@ export const zhCN: TranslationResources = {
|
||||
hostDisconnected: "Host 未连接",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "设备",
|
||||
waysToConnect: "连接方式",
|
||||
docs: "文档",
|
||||
docsAccessibility: "打开连接文档",
|
||||
recommended: "推荐",
|
||||
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
|
||||
tailscale: {
|
||||
hint: "通过你的 tailnet 直连,输入地址即可",
|
||||
unavailable: "此主机未运行 Tailscale",
|
||||
install: "获取 Tailscale",
|
||||
waiting: "正在等待此主机上的 Tailscale 启动",
|
||||
alwaysOn: "始终开启,因为此主机已接受 Tailscale 连接",
|
||||
socket: "已关闭,因为此主机监听的是本地套接字",
|
||||
launch: "由启动此主机的命令控制",
|
||||
update: "更新此主机以使用 Tailscale",
|
||||
updateDocs: "如何更新",
|
||||
address: "在已连接 Tailscale 的手机上,用此地址添加主机",
|
||||
statusError: "无法检查 Tailscale",
|
||||
turnOnError: "无法开启 Tailscale",
|
||||
turnOffError: "无法关闭 Tailscale",
|
||||
confirmTitle: "关闭 Tailscale?",
|
||||
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
|
||||
confirmAction: "关闭",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} 的密码",
|
||||
@@ -2883,7 +2863,9 @@ export const zhCN: TranslationResources = {
|
||||
timeout: "超时",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "配对设备",
|
||||
rowTitle: "配对设备",
|
||||
rowHint: "扫描二维码或复制链接,将手机连接到这个 Host",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { useCallback } from "react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { AppleIcon } from "@/components/icons/apple-icon";
|
||||
import { GooglePlayIcon } from "@/components/icons/google-play-icon";
|
||||
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { WaysToConnect } from "@/devices";
|
||||
import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||
import {
|
||||
CONNECTIVITY_DOCS_URL,
|
||||
TAILSCALE_DOCS_URL,
|
||||
} from "@/desktop/components/pair-device-section";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
|
||||
@@ -20,11 +26,33 @@ function openUrl(url: string) {
|
||||
void openExternalUrl(url).catch(console.error);
|
||||
}
|
||||
|
||||
/** Get the app, then connect it the same ways the host's Devices settings offer. */
|
||||
/** Get the app, then connect it: the relay pairs in a modal, Tailscale is a docs page away. */
|
||||
export function PhoneStep({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [isPairing, setIsPairing] = useState(false);
|
||||
const openAppStore = useCallback(() => openUrl(APP_STORE_URL), []);
|
||||
const openPlayStore = useCallback(() => openUrl(PLAY_STORE_URL), []);
|
||||
const openTailscaleDocs = useCallback(() => openUrl(TAILSCALE_DOCS_URL), []);
|
||||
const openPairing = useCallback(() => setIsPairing(true), []);
|
||||
const closePairing = useCallback(() => setIsPairing(false), []);
|
||||
const recommendedBadge = useMemo(
|
||||
() => (
|
||||
<StatusBadge
|
||||
size="xs"
|
||||
variant="success"
|
||||
label={t("onboarding.setup.steps.phone.recommended")}
|
||||
/>
|
||||
),
|
||||
[t],
|
||||
);
|
||||
const docsLink = useMemo(
|
||||
() => ({
|
||||
href: CONNECTIVITY_DOCS_URL,
|
||||
label: t("onboarding.setup.steps.phone.connectDocs"),
|
||||
accessibilityLabel: t("onboarding.setup.steps.phone.openConnectDocs"),
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
@@ -36,7 +64,31 @@ export function PhoneStep({ serverId }: { serverId: string }) {
|
||||
{t("onboarding.setup.steps.phone.googlePlay")}
|
||||
</Button>
|
||||
</View>
|
||||
<WaysToConnect serverId={serverId} />
|
||||
<SettingsSection title={t("onboarding.setup.steps.phone.connectTitle")} link={docsLink}>
|
||||
<SettingsCard>
|
||||
<SettingsDetailRow
|
||||
label={t("onboarding.setup.steps.phone.relay.title")}
|
||||
labelAccessory={recommendedBadge}
|
||||
hint={t("onboarding.setup.steps.phone.relay.hint")}
|
||||
onPress={openPairing}
|
||||
testID="onboarding-phone-relay"
|
||||
/>
|
||||
<SettingsDetailRow
|
||||
label={t("onboarding.setup.steps.phone.tailscale.title")}
|
||||
hint={t("onboarding.setup.steps.phone.tailscale.hint")}
|
||||
summary={t("onboarding.setup.steps.phone.connectDocs")}
|
||||
onPress={openTailscaleDocs}
|
||||
external
|
||||
testID="onboarding-phone-tailscale"
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={isPairing}
|
||||
onClose={closePairing}
|
||||
testID="onboarding-pair-device-card"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
HEADER_TOP_PADDING_MOBILE,
|
||||
} from "@/constants/layout";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { PairDeviceModal } from "@/devices";
|
||||
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ import {
|
||||
} from "@/i18n/locales";
|
||||
import {
|
||||
HostConnectionsPage,
|
||||
HostDevicesPage,
|
||||
HostPairDevicePage,
|
||||
HostAgentsPage,
|
||||
HostAgentProfilesPage,
|
||||
HostSettingsPage,
|
||||
@@ -250,7 +250,7 @@ const HOST_SECTION_ITEMS: HostSectionItem[] = [
|
||||
{ id: "host", labelKey: "settings.hostSections.host", icon: Server },
|
||||
{ id: "projects", labelKey: "settings.hostSections.projects", icon: FolderGit2 },
|
||||
{ id: "connections", labelKey: "settings.hostSections.connections", icon: Network },
|
||||
{ id: "devices", labelKey: "devices.title", icon: Smartphone },
|
||||
{ id: "pair-device", labelKey: "openProject.tiles.pairDevice.title", icon: Smartphone },
|
||||
{ id: "agents", labelKey: "settings.hostSections.agents", icon: Bot },
|
||||
{ id: "agent-profiles", labelKey: "settings.hostSections.agentProfiles", icon: Layers },
|
||||
{ id: "metadata", labelKey: "settings.hostSections.metadata", icon: Sparkles },
|
||||
@@ -271,8 +271,8 @@ function renderHostSettingsContent(
|
||||
return <ProjectsScreen serverId={view.serverId} />;
|
||||
case "connections":
|
||||
return <HostConnectionsPage serverId={view.serverId} />;
|
||||
case "devices":
|
||||
return <HostDevicesPage serverId={view.serverId} />;
|
||||
case "pair-device":
|
||||
return <HostPairDevicePage serverId={view.serverId} />;
|
||||
case "agents":
|
||||
return <HostAgentsPage serverId={view.serverId} />;
|
||||
case "agent-profiles":
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
ArrowUpToLine,
|
||||
ChevronRight,
|
||||
Globe,
|
||||
Monitor,
|
||||
Pencil,
|
||||
@@ -13,7 +14,7 @@ import {
|
||||
import type { TFunction } from "i18next";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Alert, Text, View } from "react-native";
|
||||
import { Alert, Pressable, Text, View } from "react-native";
|
||||
import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles";
|
||||
import type { TerminalProfile } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
@@ -37,7 +38,7 @@ import { startDesktopDaemon, stopDesktopDaemon } from "@/desktop/daemon/desktop-
|
||||
import { LocalDaemonSection } from "@/desktop/components/desktop-updates-section";
|
||||
import { useDaemonStatus } from "@/desktop/hooks/use-daemon-status";
|
||||
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
|
||||
import { WaysToConnect } from "@/devices";
|
||||
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
|
||||
import {
|
||||
@@ -264,14 +265,19 @@ export function HostConnectionsPage({ serverId }: { serverId: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function HostDevicesPage({ serverId }: { serverId: string }) {
|
||||
export function HostPairDevicePage({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const host = useHostProfile(serverId);
|
||||
|
||||
if (!host) {
|
||||
return <HostNotFound />;
|
||||
}
|
||||
|
||||
return <WaysToConnect serverId={serverId} />;
|
||||
return (
|
||||
<SettingsSection title={t("settings.host.pairDevices.title")}>
|
||||
<PairDeviceRow serverId={serverId} />
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
export function HostAgentsPage({ serverId }: { serverId: string }) {
|
||||
@@ -1124,6 +1130,39 @@ function AppendSystemPromptCard({ serverId }: { serverId: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PairDeviceRow({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const { theme } = useUnistyles();
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
const handleOpen = useCallback(() => setIsModalOpen(true), []);
|
||||
const handleClose = useCallback(() => setIsModalOpen(false), []);
|
||||
|
||||
return (
|
||||
<View style={settingsStyles.card}>
|
||||
<Pressable
|
||||
style={settingsStyles.row}
|
||||
onPress={handleOpen}
|
||||
accessibilityRole="button"
|
||||
testID="host-page-pair-device-row"
|
||||
>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{t("settings.host.pairDevices.rowTitle")}</Text>
|
||||
<Text style={settingsStyles.rowHint}>{t("settings.host.pairDevices.rowHint")}</Text>
|
||||
</View>
|
||||
<ChevronRight size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
|
||||
</Pressable>
|
||||
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={isModalOpen}
|
||||
onClose={handleClose}
|
||||
testID="host-page-pair-device-card"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function RemoveHostSection({
|
||||
host,
|
||||
isLocalDaemon,
|
||||
|
||||
@@ -246,8 +246,7 @@ describe("global routes", () => {
|
||||
describe("host settings section slugs", () => {
|
||||
it("keeps current host settings sections", () => {
|
||||
expect(normalizeHostSectionSlug("connections")).toBe("connections");
|
||||
expect(normalizeHostSectionSlug("devices")).toBe("devices");
|
||||
expect(normalizeHostSectionSlug("pair-device")).toBe("devices");
|
||||
expect(normalizeHostSectionSlug("pair-device")).toBe("pair-device");
|
||||
expect(normalizeHostSectionSlug("agents")).toBe("agents");
|
||||
expect(normalizeHostSectionSlug("metadata")).toBe("metadata");
|
||||
expect(normalizeHostSectionSlug("workspaces")).toBe("workspaces");
|
||||
|
||||
@@ -515,7 +515,7 @@ export function isSettingsSectionSlug(value: string): value is SettingsSectionSl
|
||||
export const HOST_SECTION_SLUGS = [
|
||||
"projects",
|
||||
"connections",
|
||||
"devices",
|
||||
"pair-device",
|
||||
"agents",
|
||||
"agent-profiles",
|
||||
"metadata",
|
||||
@@ -531,7 +531,6 @@ export const HOST_SECTION_SLUGS = [
|
||||
export type HostSectionSlug = (typeof HOST_SECTION_SLUGS)[number];
|
||||
|
||||
const LEGACY_HOST_SECTION_SLUGS: Record<string, HostSectionSlug> = {
|
||||
"pair-device": "devices",
|
||||
orchestration: "agents",
|
||||
daemon: "host",
|
||||
};
|
||||
|
||||
@@ -6,11 +6,7 @@ import {
|
||||
isSameDaemonInstance,
|
||||
DaemonInstanceError,
|
||||
} from "@getpaseo/server/daemon-control";
|
||||
import {
|
||||
readPersistedConfig,
|
||||
resolveConfigFromPersisted,
|
||||
getMainListenAddress,
|
||||
} from "@getpaseo/server/configuration";
|
||||
import { readPersistedConfig, resolveConfigFromPersisted } from "@getpaseo/server/configuration";
|
||||
import { connectToDaemon, buildDaemonConnectionCommandError } from "../../utils/client.js";
|
||||
import { withOutput, toCommandError, type CommandOptions } from "../../output/index.js";
|
||||
import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js";
|
||||
@@ -107,8 +103,6 @@ async function probeDaemonStatus(
|
||||
daemonNode: status.nodePath,
|
||||
providers: status.providers,
|
||||
relay: status.relay,
|
||||
tailscale: status.tailscale,
|
||||
extraListeners: status.extraListeners,
|
||||
...(status.terminalsUnavailable ? { terminals: status.terminalsUnavailable } : {}),
|
||||
};
|
||||
}
|
||||
@@ -133,7 +127,7 @@ function localStatus(home: string, instance: Awaited<ReturnType<typeof readDaemo
|
||||
listen: instance?.listen ?? null,
|
||||
serverId: instance?.serverId ?? undefined,
|
||||
hostname: instance?.hostname ?? null,
|
||||
configuredListen: getMainListenAddress(config.listen),
|
||||
configuredListen: config.listen,
|
||||
localDaemon,
|
||||
desktopManaged: instance?.desktopManaged === true,
|
||||
logPath: daemonLogPath(home),
|
||||
|
||||
@@ -123,7 +123,6 @@ import type {
|
||||
ProviderInstallationCheckUpdatesResponseMessage,
|
||||
UsageReportEntry,
|
||||
DaemonGetStatusResponse,
|
||||
DaemonTailscaleSetResponse,
|
||||
DaemonGetPairingOfferResponse,
|
||||
DaemonConfigReloadResponse,
|
||||
DiagnosticsResponse,
|
||||
@@ -843,7 +842,6 @@ export interface ShutdownServerOptions {
|
||||
keepTerminals?: boolean;
|
||||
}
|
||||
export interface DaemonStatusOptions {
|
||||
includeProviders?: boolean;
|
||||
requestId?: string;
|
||||
timeout?: number;
|
||||
}
|
||||
@@ -6126,17 +6124,6 @@ export class DaemonClient {
|
||||
});
|
||||
}
|
||||
|
||||
async setTailscaleEnabled(
|
||||
enabled: boolean,
|
||||
confirmed = false,
|
||||
): Promise<DaemonTailscaleSetResponse["payload"]> {
|
||||
return this.sendCorrelatedSessionRequest({
|
||||
message: { type: "daemon.tailscale.set.request", enabled, confirmed },
|
||||
responseType: "daemon.tailscale.set.response",
|
||||
});
|
||||
}
|
||||
|
||||
/** The Tailscale disconnect flag describes the connection used for this request. */
|
||||
async getDaemonStatus(options?: DaemonStatusOptions): Promise<DaemonStatusPayload> {
|
||||
if (!this.lastServerInfoMessage) throw new DaemonConnectionError("Transport not connected");
|
||||
if (this.lastServerInfoMessage?.features?.daemonStatusRpc !== true) {
|
||||
@@ -6146,7 +6133,6 @@ export class DaemonClient {
|
||||
requestId: options?.requestId,
|
||||
message: {
|
||||
type: "daemon.get_status.request",
|
||||
includeProviders: options?.includeProviders,
|
||||
},
|
||||
responseType: "daemon.get_status.response",
|
||||
timeout: options?.timeout,
|
||||
|
||||
@@ -23,7 +23,7 @@ const SETTINGS_DESTINATIONS = [
|
||||
"Overview",
|
||||
"Projects",
|
||||
"Connections",
|
||||
"Devices",
|
||||
"Pair device",
|
||||
"Agents",
|
||||
"Metadata",
|
||||
"Workspaces",
|
||||
|
||||
@@ -1552,17 +1552,9 @@ export const WaitForFinishRequestSchema = z.object({
|
||||
timeoutMs: z.number().int().positive().optional(),
|
||||
});
|
||||
|
||||
export const DaemonTailscaleSetRequestSchema = z.object({
|
||||
type: z.literal("daemon.tailscale.set.request"),
|
||||
requestId: z.string(),
|
||||
enabled: z.boolean(),
|
||||
confirmed: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const DaemonGetStatusRequestSchema = z.object({
|
||||
type: z.literal("daemon.get_status.request"),
|
||||
requestId: z.string(),
|
||||
includeProviders: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const DaemonGetPairingOfferRequestSchema = z.object({
|
||||
@@ -3630,7 +3622,6 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
SendAgentMessageRequestSchema,
|
||||
WaitForFinishRequestSchema,
|
||||
DaemonGetStatusRequestSchema,
|
||||
DaemonTailscaleSetRequestSchema,
|
||||
DaemonGetPairingOfferRequestSchema,
|
||||
DaemonConfigReloadRequestSchema,
|
||||
HubManagementDaemonConnectRequestSchema,
|
||||
@@ -4055,7 +4046,6 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
forgeSearch: z.boolean().optional(),
|
||||
// COMPAT(daemonStatusRpc): added in v0.1.76, remove gate after 2026-11-18.
|
||||
daemonStatusRpc: z.boolean().optional(),
|
||||
tailscale: z.boolean().optional(),
|
||||
// COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14.
|
||||
daemonConfigReload: z.boolean().optional(),
|
||||
// COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18.
|
||||
@@ -5587,32 +5577,6 @@ export const GetDaemonConfigResponseMessageSchema = z.object({
|
||||
.passthrough(),
|
||||
});
|
||||
|
||||
const TailscaleStatusSchema = z.object({
|
||||
ip: z.string().nullable(),
|
||||
address: z.string().nullable(),
|
||||
state: z.enum(["unavailable", "off", "waiting", "on"]),
|
||||
lockedBy: z.enum(["main", "launch"]).optional(),
|
||||
// COMPAT(tailscale): keep lockedBy "main" for older clients when the main listener is a socket.
|
||||
mainIsSocket: z.literal(true).optional(),
|
||||
// Whether turning off Tailscale would disconnect the source of this request.
|
||||
disconnectsCurrentConnection: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const ExtraListenerStatusSchema = z.object({
|
||||
address: z.string(),
|
||||
state: z.enum(["waiting", "listening"]),
|
||||
});
|
||||
|
||||
export const DaemonTailscaleSetResponseSchema = z.object({
|
||||
type: z.literal("daemon.tailscale.set.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
confirmationRequired: z.boolean(),
|
||||
tailscale: TailscaleStatusSchema,
|
||||
extraListeners: z.array(ExtraListenerStatusSchema),
|
||||
}),
|
||||
});
|
||||
|
||||
export const DaemonGetStatusResponseSchema = z.object({
|
||||
type: z.literal("daemon.get_status.response"),
|
||||
payload: z
|
||||
@@ -5624,8 +5588,6 @@ export const DaemonGetStatusResponseSchema = z.object({
|
||||
nodePath: z.string(),
|
||||
startedAt: z.string().nullable().optional(),
|
||||
listen: z.string().nullable(),
|
||||
tailscale: TailscaleStatusSchema.optional(),
|
||||
extraListeners: z.array(ExtraListenerStatusSchema).optional(),
|
||||
relay: z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
@@ -7840,7 +7802,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
SendAgentMessageResponseMessageSchema,
|
||||
SetVoiceModeResponseMessageSchema,
|
||||
DaemonGetStatusResponseSchema,
|
||||
DaemonTailscaleSetResponseSchema,
|
||||
DaemonGetPairingOfferResponseSchema,
|
||||
DaemonConfigReloadResponseSchema,
|
||||
HubManagementDaemonConnectResponseSchema,
|
||||
@@ -8603,6 +8564,3 @@ export function parseServerInfoStatusPayload(payload: unknown): ServerInfoStatus
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
export type TailscaleStatus = z.infer<typeof TailscaleStatusSchema>;
|
||||
export type DaemonTailscaleSetResponse = z.infer<typeof DaemonTailscaleSetResponseSchema>;
|
||||
|
||||
@@ -139,7 +139,6 @@
|
||||
"p-limit": "^7.3.0",
|
||||
"p-memoize": "^8.0.0",
|
||||
"p-throttle": "^8.1.0",
|
||||
"parse5": "^7.3.0",
|
||||
"pino": "^10.2.0",
|
||||
"pino-pretty": "^13.1.3",
|
||||
"qrcode": "^1.5.4",
|
||||
|
||||
@@ -1604,10 +1604,6 @@ export class OmpAgentSession implements AgentSession {
|
||||
private handleExtensionUiRequest(
|
||||
event: Extract<OmpRuntimeEvent, { type: "extension_ui_request" }>,
|
||||
): void {
|
||||
if (event.method === "cancel") {
|
||||
if (event.targetId) this.closeExtensionUiRequest(event.targetId);
|
||||
return;
|
||||
}
|
||||
const message = optionalString(event.message);
|
||||
if (event.method === "notify" && message) {
|
||||
this.emit({
|
||||
@@ -1654,19 +1650,6 @@ export class OmpAgentSession implements AgentSession {
|
||||
});
|
||||
}
|
||||
|
||||
/** OMP aborted or timed out a dialog: close its card without a reply OMP would reject. */
|
||||
private closeExtensionUiRequest(requestId: string): void {
|
||||
if (!this.pendingExtensionUiRequests.delete(requestId)) return;
|
||||
this.questionUi.forget(requestId);
|
||||
this.emit({
|
||||
type: "permission_resolved",
|
||||
provider: this.provider,
|
||||
requestId,
|
||||
resolution: { behavior: "deny", message: "OMP closed the question." },
|
||||
turnId: this.currentTurnIdForEvent(),
|
||||
});
|
||||
}
|
||||
|
||||
private mapExtensionUiSideEffect(
|
||||
event: Extract<OmpRuntimeEvent, { type: "extension_ui_request" }>,
|
||||
): AgentTimelineItem | null {
|
||||
|
||||
@@ -309,405 +309,3 @@ describe("OMP ask RPC UI", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
function form(omp: OmpHarness, id: string, html: string | undefined): void {
|
||||
omp.emit({
|
||||
type: "extension_ui_request",
|
||||
id,
|
||||
method: "form",
|
||||
...(html === undefined ? {} : { html }),
|
||||
});
|
||||
}
|
||||
|
||||
function questions(omp: OmpHarness): unknown {
|
||||
return omp.pendingPermissions()[0]?.input?.questions;
|
||||
}
|
||||
|
||||
describe("OMP 19.1 HTML form ask", () => {
|
||||
// Captured from `omp --mode rpc-ui --no-session` 19.1.0 and 19.2.1 (issue #10471).
|
||||
const YES_NO =
|
||||
'<form><label><input type="radio" name="ok" value="yes" checked> Yes</label><label><input type="radio" name="ok" value="no"> No</label></form>';
|
||||
const COLOR =
|
||||
'<form><fieldset><legend>Which color do you prefer?</legend><label><input type="radio" name="color" value="Red" checked> Red</label><label><input type="radio" name="color" value="Blue"> Blue</label></fieldset></form>';
|
||||
|
||||
test("shows a radio form as a question card and returns the chosen value", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(omp, "form-1", YES_NO);
|
||||
|
||||
expect(omp.pendingPermissions()).toMatchObject([
|
||||
{ id: "form-1", kind: "question", metadata: { extensionUiMethod: "form" } },
|
||||
]);
|
||||
expect(questions(omp)).toEqual([
|
||||
{
|
||||
question: "ok",
|
||||
header: "ok",
|
||||
options: [{ label: "Yes", description: "Default" }, { label: "No" }],
|
||||
multiSelect: false,
|
||||
allowOther: true,
|
||||
allowEmpty: true,
|
||||
},
|
||||
]);
|
||||
await omp.respondToPermission("form-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { ok: "No" } },
|
||||
});
|
||||
expect(omp.pendingPermissions()).toEqual([]);
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "form-1", response: { data: { ok: "no" } } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("submits the preselected default when the question is left unanswered", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(omp, "form-1", COLOR);
|
||||
|
||||
expect(questions(omp)).toMatchObject([
|
||||
{ question: "Which color do you prefer?", header: "color" },
|
||||
]);
|
||||
await omp.respondToPermission("form-1", { behavior: "allow", updatedInput: { answers: {} } });
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "form-1", response: { data: { color: "Red" } } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("passes a typed Other answer as the radio value", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(omp, "form-1", COLOR);
|
||||
await omp.respondToPermission("form-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { color: "Green" } },
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "form-1", response: { data: { color: "Green" } } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("maps a multi-control form to one question per named control", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(
|
||||
omp,
|
||||
"form-1",
|
||||
`<form>
|
||||
<h2>Setup</h2>
|
||||
<p>Pick a store and the tools to install.</p>
|
||||
<label><input type="radio" name="store" value="sqlite" checked>SQLite</label>
|
||||
<label><input type="radio" name="store" value="pg">Postgres</label>
|
||||
<label><input type="radio" name="store" value="other">Other (describe)</label>
|
||||
<p>Which tools?</p>
|
||||
<label><input type="checkbox" name="tools" value="x,y">X, Y</label>
|
||||
<label><input type="checkbox" name="tools" value="z" checked>Z</label>
|
||||
<label><input type="checkbox" name="tools" value="w" disabled>W</label>
|
||||
<label>Days <input type="number" name="days" min="1"></label>
|
||||
<label for="note">Note</label><textarea id="note" name="note" placeholder="Anything else?">keep logs</textarea>
|
||||
<label>Region <select name="region"><option value="eu">Europe</option><option value="us" selected>US</option><option value="ap" disabled>Asia</option></select></label>
|
||||
<label><input type="checkbox" name="agree" value="yes"> I accept the terms</label>
|
||||
<input type="hidden" name="token" value="abc">
|
||||
<input type="text" placeholder="unnamed">
|
||||
<input type="file" name="upload">
|
||||
<button type="submit">Send</button>
|
||||
</form>`,
|
||||
);
|
||||
|
||||
expect(questions(omp)).toEqual([
|
||||
{
|
||||
question: "Setup\n\nPick a store and the tools to install.",
|
||||
header: "store",
|
||||
options: [
|
||||
{ label: "SQLite", description: "Default" },
|
||||
{ label: "Postgres" },
|
||||
{ label: "Other (describe)" },
|
||||
],
|
||||
multiSelect: false,
|
||||
allowOther: false,
|
||||
allowEmpty: true,
|
||||
},
|
||||
{
|
||||
question: "Which tools?",
|
||||
header: "tools",
|
||||
options: [{ label: "X,Y" }, { label: "Z", description: "Default" }],
|
||||
multiSelect: true,
|
||||
allowOther: true,
|
||||
allowEmpty: true,
|
||||
},
|
||||
{
|
||||
question: "Days",
|
||||
header: "days",
|
||||
options: [],
|
||||
multiSelect: false,
|
||||
allowOther: false,
|
||||
allowEmpty: true,
|
||||
},
|
||||
{
|
||||
question: "Note",
|
||||
header: "note",
|
||||
options: [{ label: "keep logs", description: "Default" }],
|
||||
multiSelect: false,
|
||||
allowOther: true,
|
||||
allowEmpty: true,
|
||||
placeholder: "Anything else?",
|
||||
},
|
||||
{
|
||||
question: "Region",
|
||||
header: "region",
|
||||
options: [{ label: "Europe" }, { label: "US", description: "Default" }],
|
||||
multiSelect: false,
|
||||
allowOther: false,
|
||||
allowEmpty: true,
|
||||
},
|
||||
{
|
||||
question: "I accept the terms",
|
||||
header: "agree",
|
||||
options: [{ label: "Yes" }, { label: "No" }],
|
||||
multiSelect: false,
|
||||
allowOther: false,
|
||||
allowEmpty: false,
|
||||
},
|
||||
]);
|
||||
|
||||
await omp.respondToPermission("form-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: {
|
||||
answers: {
|
||||
store: "Postgres",
|
||||
tools: "X,Y, Z, hammer",
|
||||
days: "7",
|
||||
note: "",
|
||||
region: "Europe",
|
||||
agree: "No",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{
|
||||
id: "form-1",
|
||||
response: {
|
||||
data: {
|
||||
store: "pg",
|
||||
tools: ["x,y", "z", "hammer"],
|
||||
days: "7",
|
||||
note: "keep logs",
|
||||
region: "eu",
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("returns cancelled when the user dismisses the form", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(omp, "form-1", YES_NO);
|
||||
await omp.respondToPermission("form-1", { behavior: "deny" });
|
||||
expect(omp.extensionUiResponses()).toEqual([{ id: "form-1", response: { cancelled: true } }]);
|
||||
});
|
||||
|
||||
test("closes the card without a reply when OMP cancels the form", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(omp, "form-1", YES_NO);
|
||||
omp.emit({
|
||||
type: "extension_ui_request",
|
||||
id: "cancel-1",
|
||||
method: "cancel",
|
||||
targetId: "form-1",
|
||||
});
|
||||
|
||||
expect(omp.pendingPermissions()).toEqual([]);
|
||||
expect(omp.eventTypes()).toContain("permission_resolved");
|
||||
await expect(omp.respondToPermission("form-1", { behavior: "deny" })).rejects.toThrow();
|
||||
expect(omp.extensionUiResponses()).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps Dismiss a cancel when a text field is prefilled", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(omp, "form-1", '<form><label>Branch <input name="branch" value="main"></label></form>');
|
||||
|
||||
// The card submits on Dismiss only when every question is optional free text;
|
||||
// the prefilled value is an option, so Dismiss stays a cancel.
|
||||
expect(questions(omp)).toEqual([
|
||||
{
|
||||
question: "Branch",
|
||||
header: "branch",
|
||||
options: [{ label: "main", description: "Default" }],
|
||||
multiSelect: false,
|
||||
allowOther: true,
|
||||
allowEmpty: true,
|
||||
},
|
||||
]);
|
||||
await omp.respondToPermission("form-1", { behavior: "allow", updatedInput: { answers: {} } });
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "form-1", response: { data: { branch: "main" } } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("lets optional text fields stay blank and names Dismiss Skip when that submits", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(
|
||||
omp,
|
||||
"form-1",
|
||||
'<form><label>Why? <input name="why"></label><label>Notes <textarea name="notes"></textarea></label></form>',
|
||||
);
|
||||
|
||||
expect(questions(omp)).toMatchObject([
|
||||
{ header: "why", options: [], allowEmpty: true, dismissLabel: "Skip" },
|
||||
{ header: "notes", options: [], allowEmpty: true, dismissLabel: "Skip" },
|
||||
]);
|
||||
await omp.respondToPermission("form-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { why: "", notes: "" } },
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "form-1", response: { data: { why: "", notes: "" } } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("requires an answer for a required text field", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(
|
||||
omp,
|
||||
"form-1",
|
||||
'<form><label>Name <input name="name" required></label><label>Why? <input name="why"></label></form>',
|
||||
);
|
||||
|
||||
expect(questions(omp)).toMatchObject([
|
||||
{ header: "name", allowEmpty: false },
|
||||
{ header: "why", allowEmpty: true },
|
||||
]);
|
||||
expect(questions(omp)).toEqual(
|
||||
expect.not.arrayContaining([expect.objectContaining({ dismissLabel: expect.anything() })]),
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps multi-select answers distinct when a label joins other labels", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
const html =
|
||||
'<form><label><input type="checkbox" name="r" value="us">US</label><label><input type="checkbox" name="r" value="ca">Canada</label><label><input type="checkbox" name="r" value="both">US, Canada</label></form>';
|
||||
form(omp, "form-1", html);
|
||||
form(omp, "form-2", html);
|
||||
|
||||
expect(questions(omp)).toMatchObject([
|
||||
{ options: [{ label: "US" }, { label: "Canada" }, { label: "US,Canada" }] },
|
||||
]);
|
||||
// The card joins checked labels with ", ".
|
||||
await omp.respondToPermission("form-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { r: "US, Canada" } },
|
||||
});
|
||||
await omp.respondToPermission("form-2", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { r: "US,Canada" } },
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "form-1", response: { data: { r: ["us", "ca"] } } },
|
||||
{ id: "form-2", response: { data: { r: ["both"] } } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("offers None so an optional multi-select without a text input can submit no choices", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
const html =
|
||||
'<form><label>Tools <select name="tools" multiple><option value="d">Docker</option><option value="k">Kubernetes</option></select></label><label>Must <select name="must" multiple required><option value="a">A</option><option value="b">B</option></select></label></form>';
|
||||
form(omp, "form-1", html);
|
||||
form(omp, "form-2", html);
|
||||
|
||||
expect(questions(omp)).toMatchObject([
|
||||
{
|
||||
header: "tools",
|
||||
options: [{ label: "Docker" }, { label: "Kubernetes" }, { label: "None" }],
|
||||
allowOther: false,
|
||||
},
|
||||
{ header: "must", options: [{ label: "A" }, { label: "B" }] },
|
||||
]);
|
||||
await omp.respondToPermission("form-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { tools: "None", must: "A" } },
|
||||
});
|
||||
await omp.respondToPermission("form-2", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { tools: "Docker, None", must: "B" } },
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "form-1", response: { data: { tools: [], must: ["a"] } } },
|
||||
{ id: "form-2", response: { data: { tools: ["d"], must: ["b"] } } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("reads an option's text value the way OMP does when it wraps across lines", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(
|
||||
omp,
|
||||
"form-1",
|
||||
'<form><label>Region <select name="region"><option>Europe</option><option>North\n America</option></select></label></form>',
|
||||
);
|
||||
|
||||
expect(questions(omp)).toMatchObject([
|
||||
{ options: [{ label: "Europe", description: "Default" }, { label: "North America" }] },
|
||||
]);
|
||||
await omp.respondToPermission("form-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { region: "North America" } },
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toEqual([
|
||||
{ id: "form-1", response: { data: { region: "North America" } } },
|
||||
]);
|
||||
});
|
||||
|
||||
test("shows a form without controls as readable text with a Continue answer", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(
|
||||
omp,
|
||||
"form-1",
|
||||
"<form><p>Deploy <b>finished</b>.</p><ul><li>web</li><li>api</li></ul></form>",
|
||||
);
|
||||
|
||||
expect(questions(omp)).toEqual([
|
||||
{
|
||||
question: "Deploy finished.\n\n- web\n- api",
|
||||
header: "Response",
|
||||
options: [{ label: "Continue" }],
|
||||
multiSelect: false,
|
||||
allowOther: false,
|
||||
allowEmpty: false,
|
||||
},
|
||||
]);
|
||||
await omp.respondToPermission("form-1", {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { Response: "Continue" } },
|
||||
});
|
||||
expect(omp.extensionUiResponses()).toEqual([{ id: "form-1", response: { data: {} } }]);
|
||||
});
|
||||
|
||||
test("keeps malformed HTML readable instead of dropping the form", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(
|
||||
omp,
|
||||
"form-1",
|
||||
"<form><p>Pick one<label><input type=radio name=pick value=a>A<label><input type=radio name=pick value=b>B",
|
||||
);
|
||||
|
||||
expect(questions(omp)).toMatchObject([
|
||||
{ question: "Pick one", header: "pick", options: [{ label: "A" }, { label: "B" }] },
|
||||
]);
|
||||
});
|
||||
|
||||
test("cancels a form request without HTML instead of leaving OMP waiting", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
form(omp, "form-1", undefined);
|
||||
|
||||
expect(omp.pendingPermissions()).toEqual([]);
|
||||
expect(omp.extensionUiResponses()).toEqual([{ id: "form-1", response: { cancelled: true } }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
OmpBranchMessagesResultSchema,
|
||||
OmpBranchResultSchema,
|
||||
OmpCommandsResultSchema,
|
||||
type OmpExtensionUiResponse,
|
||||
OmpHostToolsResultSchema,
|
||||
OmpMessagesResultSchema,
|
||||
OmpModelSchema,
|
||||
@@ -290,7 +289,10 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
|
||||
});
|
||||
}
|
||||
|
||||
respondToExtensionUiRequest(id: string, response: OmpExtensionUiResponse): void {
|
||||
respondToExtensionUiRequest(
|
||||
id: string,
|
||||
response: { value?: string; confirmed?: boolean; cancelled?: boolean },
|
||||
): void {
|
||||
this.process.send({ type: "extension_ui_response", id, ...response });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,225 +0,0 @@
|
||||
import type {
|
||||
AgentPermissionRequest,
|
||||
AgentPermissionResponse,
|
||||
AgentProvider,
|
||||
} from "../../agent-sdk-types.js";
|
||||
import { splitMultiSelectAnswer } from "../question-card-answer.js";
|
||||
import {
|
||||
type OmpFormChoiceField,
|
||||
type OmpFormField,
|
||||
type OmpFormOption,
|
||||
parseOmpHtmlForm,
|
||||
} from "./html-form.js";
|
||||
import type { OmpExtensionUiResponse, OmpFormData, OmpFormValue } from "./rpc-types.js";
|
||||
|
||||
const DEFAULT = "Default";
|
||||
const YES = "Yes";
|
||||
const NO = "No";
|
||||
const CONTINUE = "Continue";
|
||||
const RESPONSE_HEADER = "Response";
|
||||
const SKIP = "Skip";
|
||||
const NONE = "None";
|
||||
const NO_SELECTION = "No selection";
|
||||
|
||||
interface CardOption {
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface CardQuestion {
|
||||
question: string;
|
||||
header: string;
|
||||
options: CardOption[];
|
||||
multiSelect: boolean;
|
||||
allowOther: boolean;
|
||||
allowEmpty: boolean;
|
||||
placeholder?: string;
|
||||
dismissLabel?: string;
|
||||
}
|
||||
|
||||
/** One form field as a card question, and how the card's answer becomes the field's value. */
|
||||
interface FieldQuestion {
|
||||
name: string;
|
||||
question: CardQuestion;
|
||||
value(answer: string | undefined): OmpFormValue | undefined;
|
||||
}
|
||||
|
||||
function cardOption(label: string, isDefault: boolean): CardOption {
|
||||
return isDefault ? { label, description: DEFAULT } : { label };
|
||||
}
|
||||
|
||||
/**
|
||||
* Labels the card answers with must be unique within a question. The card joins
|
||||
* multi-select labels with ", ", so those labels must not contain ", " or one
|
||||
* selection could read as another ("US", "Canada" versus "US, Canada").
|
||||
*/
|
||||
function labelOptions(
|
||||
options: OmpFormOption[],
|
||||
multi: boolean,
|
||||
): Array<OmpFormOption & { cardLabel: string }> {
|
||||
const used = new Set<string>();
|
||||
return options.map((option, index) => {
|
||||
const label = option.label || option.value;
|
||||
let cardLabel = multi ? label.replaceAll(", ", ",") : label;
|
||||
if (used.has(cardLabel)) cardLabel = `${cardLabel} (${option.value})`;
|
||||
if (used.has(cardLabel)) cardLabel = `${cardLabel} ${index + 1}`;
|
||||
used.add(cardLabel);
|
||||
return { ...option, cardLabel };
|
||||
});
|
||||
}
|
||||
|
||||
function noneLabel(taken: Map<string, string>): string {
|
||||
return taken.has(NONE) ? NO_SELECTION : NONE;
|
||||
}
|
||||
|
||||
/** A lone checkbox is a yes/no question: checked gives its value, unchecked omits it. */
|
||||
function checkboxQuestion(field: OmpFormChoiceField, option: OmpFormOption): FieldQuestion {
|
||||
return {
|
||||
name: field.name,
|
||||
question: {
|
||||
question: [field.prompt, option.label].filter(Boolean).join("\n\n") || field.name,
|
||||
header: field.name,
|
||||
options: [cardOption(YES, option.checked), cardOption(NO, false)],
|
||||
multiSelect: false,
|
||||
allowOther: false,
|
||||
allowEmpty: option.checked,
|
||||
},
|
||||
value(answer) {
|
||||
const checked = answer === undefined ? option.checked : answer === YES;
|
||||
return checked && !option.disabled ? option.value : undefined;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function choiceQuestion(field: OmpFormChoiceField): FieldQuestion {
|
||||
const enabled = field.options.filter((option) => !option.disabled);
|
||||
if (field.control === "checkbox" && field.options.length === 1 && enabled[0]) {
|
||||
return checkboxQuestion(field, enabled[0]);
|
||||
}
|
||||
// OMP reports an array for checkbox groups and multi-selects of two or more options.
|
||||
const array = field.multi && field.options.length > 1;
|
||||
const options = labelOptions(enabled, array);
|
||||
const defaults = options.filter((option) => option.checked).map((option) => option.value);
|
||||
const valueOf = new Map(options.map((option) => [option.cardLabel, option.value]));
|
||||
// The card submits zero choices only beside a text input, so an optional
|
||||
// multi-select without Other gets an explicit None choice.
|
||||
const needsNone = array && !field.other && !field.required;
|
||||
const none = needsNone ? noneLabel(valueOf) : undefined;
|
||||
const labels = [...valueOf.keys(), ...(none ? [none] : [])];
|
||||
return {
|
||||
name: field.name,
|
||||
question: {
|
||||
question: field.prompt || field.name,
|
||||
header: field.name,
|
||||
options: [
|
||||
...options.map((option) => cardOption(option.cardLabel, option.checked)),
|
||||
...(none ? [{ label: none }] : []),
|
||||
],
|
||||
multiSelect: array,
|
||||
allowOther: field.other,
|
||||
// The card honors this only beside a text input, that is when the field offers Other.
|
||||
allowEmpty: array || defaults.length > 0 || !field.required,
|
||||
},
|
||||
value(answer) {
|
||||
const typed = answer?.trim();
|
||||
if (!typed) return array ? defaults : defaults[0];
|
||||
if (!array) return valueOf.get(typed) ?? (field.other ? typed : defaults[0]);
|
||||
const { selected, custom } = splitMultiSelectAnswer(typed, labels);
|
||||
const values = selected.flatMap((label) => valueOf.get(label) ?? []);
|
||||
return field.other && custom && !values.includes(custom) ? [...values, custom] : values;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fieldQuestion(field: OmpFormField): FieldQuestion {
|
||||
if (field.kind === "choice") return choiceQuestion(field);
|
||||
// A prefilled value is a one-tap option beside the text input.
|
||||
const prefilled = field.value !== "";
|
||||
return {
|
||||
name: field.name,
|
||||
question: {
|
||||
question: field.prompt || field.name,
|
||||
header: field.name,
|
||||
options: prefilled ? [cardOption(field.value, true)] : [],
|
||||
multiSelect: false,
|
||||
allowOther: prefilled,
|
||||
allowEmpty: prefilled || !field.required,
|
||||
...(field.placeholder ? { placeholder: field.placeholder } : {}),
|
||||
},
|
||||
value(answer) {
|
||||
return answer || field.value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A form without answerable fields still needs a reply: Continue submits empty data. */
|
||||
function continueQuestion(text: string): FieldQuestion {
|
||||
return {
|
||||
name: "",
|
||||
question: {
|
||||
question: text || "Continue?",
|
||||
header: RESPONSE_HEADER,
|
||||
options: [{ label: CONTINUE }],
|
||||
multiSelect: false,
|
||||
allowOther: false,
|
||||
allowEmpty: false,
|
||||
},
|
||||
value: () => undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function readAnswers(response: AgentPermissionResponse): Record<string, unknown> {
|
||||
const answers = response.behavior === "allow" ? response.updatedInput?.answers : undefined;
|
||||
return typeof answers === "object" && answers !== null && !Array.isArray(answers)
|
||||
? (answers as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
/** An OMP `form` request shown as one Paseo question per named form control. */
|
||||
export class OmpFormQuestion {
|
||||
private constructor(
|
||||
readonly request: AgentPermissionRequest,
|
||||
private readonly fields: FieldQuestion[],
|
||||
) {}
|
||||
|
||||
static fromHtml(input: { id: string; html: string; provider: AgentProvider }): OmpFormQuestion {
|
||||
const form = parseOmpHtmlForm(input.html);
|
||||
const fields = form.fields.map(fieldQuestion);
|
||||
const last = fields.at(-1);
|
||||
if (!last) fields.push(continueQuestion(form.notes));
|
||||
else if (form.notes) last.question.question = `${last.question.question}\n\n${form.notes}`;
|
||||
const questions = fields.map((field) => field.question);
|
||||
// The card submits instead of cancelling when every question is optional free text;
|
||||
// name that button for what it does.
|
||||
if (questions.every((question) => question.options.length === 0 && question.allowEmpty)) {
|
||||
for (const question of questions) question.dismissLabel = SKIP;
|
||||
}
|
||||
return new OmpFormQuestion(
|
||||
{
|
||||
id: input.id,
|
||||
provider: input.provider,
|
||||
name: "OMP ask",
|
||||
kind: "question",
|
||||
title: questions[0]?.question.split("\n")[0] ?? "OMP ask",
|
||||
input: { questions },
|
||||
metadata: { extensionUiMethod: "form" },
|
||||
},
|
||||
fields,
|
||||
);
|
||||
}
|
||||
|
||||
/** The reply OMP validates against its own parse of the same HTML. */
|
||||
response(response: AgentPermissionResponse): OmpExtensionUiResponse {
|
||||
if (response.behavior === "deny") return { cancelled: true };
|
||||
const answers = readAnswers(response);
|
||||
const entries = this.fields.flatMap((field): Array<[string, OmpFormValue]> => {
|
||||
const header = field.question.header;
|
||||
const answer = Object.hasOwn(answers, header) ? answers[header] : undefined;
|
||||
const value = field.value(typeof answer === "string" ? answer : undefined);
|
||||
return value === undefined ? [] : [[field.name, value]];
|
||||
});
|
||||
// fromEntries defines own keys, so a control named `__proto__` stays a field.
|
||||
const data: OmpFormData = Object.fromEntries(entries);
|
||||
return { data };
|
||||
}
|
||||
}
|
||||
@@ -1,457 +0,0 @@
|
||||
import { type DefaultTreeAdapterMap, parse } from "parse5";
|
||||
|
||||
/**
|
||||
* Reads the HTML `<form>` OMP 19.1+ sends with `extension_ui_request` `method: "form"`.
|
||||
*
|
||||
* It follows OMP's own form parser (`tools/html-form/parse.ts` in `@oh-my-pi/pi-coding-agent`)
|
||||
* where the answer depends on it: which controls are fields, option values, defaults,
|
||||
* array-versus-single choices and the "Other" free-text answer. OMP validates the reply
|
||||
* against its parse and rejects unknown names or option values. Layout is reduced to
|
||||
* plain prompt text, because Paseo shows each field as a question-card question.
|
||||
*/
|
||||
|
||||
type Node = DefaultTreeAdapterMap["node"];
|
||||
type Element = DefaultTreeAdapterMap["element"];
|
||||
|
||||
export interface OmpFormOption {
|
||||
value: string;
|
||||
label: string;
|
||||
checked: boolean;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
export interface OmpFormChoiceField {
|
||||
kind: "choice";
|
||||
name: string;
|
||||
control: "radio" | "checkbox" | "select";
|
||||
/** Checkbox group or `<select multiple>`. */
|
||||
multi: boolean;
|
||||
/** OMP accepts one typed answer beside the options. */
|
||||
other: boolean;
|
||||
/** Text shown before the field plus its own label. */
|
||||
prompt: string;
|
||||
options: OmpFormOption[];
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
export interface OmpFormTextField {
|
||||
kind: "text";
|
||||
name: string;
|
||||
prompt: string;
|
||||
value: string;
|
||||
placeholder: string;
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
export type OmpFormField = OmpFormChoiceField | OmpFormTextField;
|
||||
|
||||
export interface OmpHtmlForm {
|
||||
/** One field per control name, in document order. */
|
||||
fields: OmpFormField[];
|
||||
/** Text after the last field. */
|
||||
notes: string;
|
||||
}
|
||||
|
||||
const SKIPPED = new Set([
|
||||
"button",
|
||||
"head",
|
||||
"iframe",
|
||||
"link",
|
||||
"meta",
|
||||
"noscript",
|
||||
"script",
|
||||
"style",
|
||||
"svg",
|
||||
"template",
|
||||
"title",
|
||||
]);
|
||||
const BLOCK = new Set([
|
||||
"address",
|
||||
"article",
|
||||
"aside",
|
||||
"blockquote",
|
||||
"dd",
|
||||
"details",
|
||||
"div",
|
||||
"dl",
|
||||
"dt",
|
||||
"fieldset",
|
||||
"figcaption",
|
||||
"figure",
|
||||
"footer",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"header",
|
||||
"hr",
|
||||
"legend",
|
||||
"li",
|
||||
"main",
|
||||
"nav",
|
||||
"p",
|
||||
"section",
|
||||
"summary",
|
||||
]);
|
||||
const CONTROLS = new Set(["input", "select", "textarea"]);
|
||||
const IGNORED_INPUTS = new Set(["button", "file", "hidden", "image", "reset", "submit"]);
|
||||
|
||||
function isElement(node: Node): node is Element {
|
||||
return "tagName" in node;
|
||||
}
|
||||
|
||||
function isText(node: Node): node is DefaultTreeAdapterMap["textNode"] {
|
||||
return node.nodeName === "#text";
|
||||
}
|
||||
|
||||
function attr(element: Element, name: string): string | undefined {
|
||||
return element.attrs.find((item) => item.name === name)?.value;
|
||||
}
|
||||
|
||||
function hasAttr(element: Element, name: string): boolean {
|
||||
return element.attrs.some((item) => item.name === name);
|
||||
}
|
||||
|
||||
function children(node: Node): Node[] {
|
||||
return "childNodes" in node ? node.childNodes : [];
|
||||
}
|
||||
|
||||
function findElement(node: Node, match: (element: Element) => boolean): Element | undefined {
|
||||
for (const child of children(node)) {
|
||||
if (!isElement(child)) continue;
|
||||
if (match(child)) return child;
|
||||
const found = findElement(child, match);
|
||||
if (found) return found;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function collectElements(
|
||||
node: Node,
|
||||
match: (element: Element) => boolean,
|
||||
found: Element[] = [],
|
||||
): Element[] {
|
||||
for (const child of children(node)) {
|
||||
if (!isElement(child)) continue;
|
||||
if (match(child)) found.push(child);
|
||||
collectElements(child, match, found);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Source whitespace, newlines included, renders as one space; only `<br>` breaks a line. */
|
||||
function collapse(text: string): string {
|
||||
return text.replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
function normalize(text: string): string {
|
||||
return text
|
||||
.replace(/[^\S\n]+/g, " ")
|
||||
.replace(/ ?\n ?/g, "\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Visible text of `node`, skipping controls and, inside a label, nested labels. */
|
||||
function textOf(node: Node, options: { skipLabels?: boolean } = {}): string {
|
||||
const parts: string[] = [];
|
||||
const visit = (current: Node): void => {
|
||||
if (isText(current)) {
|
||||
parts.push(collapse(current.value));
|
||||
return;
|
||||
}
|
||||
if (!isElement(current)) return;
|
||||
const tag = current.tagName;
|
||||
if (SKIPPED.has(tag) || CONTROLS.has(tag)) return;
|
||||
if (options.skipLabels && tag === "label") return;
|
||||
if (tag === "br") {
|
||||
parts.push("\n");
|
||||
return;
|
||||
}
|
||||
if (tag === "img") {
|
||||
parts.push(attr(current, "alt") ?? "");
|
||||
return;
|
||||
}
|
||||
if (BLOCK.has(tag)) parts.push(" ");
|
||||
for (const child of children(current)) visit(child);
|
||||
};
|
||||
for (const child of children(node)) visit(child);
|
||||
return normalize(parts.join(""));
|
||||
}
|
||||
|
||||
function firstNamed(fields: OmpFormField[]): OmpFormField[] {
|
||||
const seen = new Set<string>();
|
||||
return fields.filter((field) => {
|
||||
if (seen.has(field.name)) return false;
|
||||
seen.add(field.name);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
class FormReader {
|
||||
private readonly fields: OmpFormField[] = [];
|
||||
private readonly groups = new Map<string, OmpFormChoiceField>();
|
||||
private readonly labelFor = new Map<string, Element>();
|
||||
private context: string[] = [];
|
||||
private inline: string[] = [];
|
||||
|
||||
constructor(private readonly root: Node) {
|
||||
const ids = new Set(
|
||||
collectElements(root, (element) => CONTROLS.has(element.tagName)).flatMap((control) => {
|
||||
const id = attr(control, "id");
|
||||
return id ? [id] : [];
|
||||
}),
|
||||
);
|
||||
for (const label of collectElements(root, (element) => element.tagName === "label")) {
|
||||
const target = attr(label, "for");
|
||||
if (target && ids.has(target) && !this.labelFor.has(target)) {
|
||||
this.labelFor.set(target, label);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
read(): OmpHtmlForm {
|
||||
this.walk(this.root, undefined);
|
||||
this.flush();
|
||||
for (const field of this.fields) {
|
||||
if (field.kind !== "choice" || field.control === "select" || field.options.length < 2) {
|
||||
continue;
|
||||
}
|
||||
field.other = !field.options.some((option) => /^\s*other\b/i.test(option.label));
|
||||
}
|
||||
return {
|
||||
fields: firstNamed(this.fields.filter((field) => field.name)),
|
||||
notes: this.takeContext(),
|
||||
};
|
||||
}
|
||||
|
||||
private walk(node: Node, label: string | undefined): void {
|
||||
for (const child of children(node)) this.visit(child, label);
|
||||
}
|
||||
|
||||
private visit(node: Node, label: string | undefined): void {
|
||||
if (isText(node)) {
|
||||
if (label === undefined) this.inline.push(collapse(node.value));
|
||||
return;
|
||||
}
|
||||
if (!isElement(node)) return;
|
||||
const tag = node.tagName;
|
||||
if (SKIPPED.has(tag)) return;
|
||||
if (CONTROLS.has(tag)) {
|
||||
this.control(node, label);
|
||||
return;
|
||||
}
|
||||
if (label !== undefined) {
|
||||
if (tag === "label") this.label(node);
|
||||
else this.walk(node, label);
|
||||
return;
|
||||
}
|
||||
switch (tag) {
|
||||
case "br":
|
||||
this.inline.push("\n");
|
||||
return;
|
||||
case "img":
|
||||
this.inline.push(attr(node, "alt") ?? "");
|
||||
return;
|
||||
case "label":
|
||||
this.label(node);
|
||||
return;
|
||||
case "ul":
|
||||
case "ol":
|
||||
this.list(node, tag === "ol");
|
||||
return;
|
||||
case "pre":
|
||||
this.flush();
|
||||
this.context.push(`\`\`\`\n${rawText(node).replace(/^\n/, "").trimEnd()}\n\`\`\``);
|
||||
return;
|
||||
case "table":
|
||||
this.table(node);
|
||||
return;
|
||||
}
|
||||
if (BLOCK.has(tag)) {
|
||||
this.flush();
|
||||
this.walk(node, undefined);
|
||||
this.flush();
|
||||
return;
|
||||
}
|
||||
this.walk(node, undefined);
|
||||
}
|
||||
|
||||
private label(label: Element): void {
|
||||
const target = attr(label, "for");
|
||||
if (target && this.labelFor.get(target) === label) return;
|
||||
if (!findElement(label, (element) => CONTROLS.has(element.tagName))) {
|
||||
this.walk(label, undefined);
|
||||
return;
|
||||
}
|
||||
this.flush();
|
||||
this.walk(label, textOf(label, { skipLabels: true }));
|
||||
}
|
||||
|
||||
private list(list: Element, ordered: boolean): void {
|
||||
this.flush();
|
||||
if (findElement(list, (element) => CONTROLS.has(element.tagName))) {
|
||||
this.walk(list, undefined);
|
||||
this.flush();
|
||||
return;
|
||||
}
|
||||
const items = children(list)
|
||||
.filter((child): child is Element => isElement(child) && child.tagName === "li")
|
||||
.map((item) => textOf(item))
|
||||
.filter(Boolean);
|
||||
const lines = items.map((item, index) => `${ordered ? `${index + 1}.` : "-"} ${item}`);
|
||||
if (lines.length > 0) this.context.push(lines.join("\n"));
|
||||
}
|
||||
|
||||
private table(table: Element): void {
|
||||
this.flush();
|
||||
if (findElement(table, (element) => CONTROLS.has(element.tagName))) {
|
||||
// A table of controls is layout: each cell reads as its own block.
|
||||
for (const cell of collectElements(table, (element) => /^t[dh]$/.test(element.tagName))) {
|
||||
this.walk(cell, undefined);
|
||||
this.flush();
|
||||
}
|
||||
return;
|
||||
}
|
||||
const rows = collectElements(table, (element) => element.tagName === "tr")
|
||||
.map((row) =>
|
||||
children(row)
|
||||
.filter((cell): cell is Element => isElement(cell) && /^t[dh]$/.test(cell.tagName))
|
||||
.map((cell) => textOf(cell))
|
||||
.join(" | "),
|
||||
)
|
||||
.filter(Boolean);
|
||||
if (rows.length > 0) this.context.push(rows.join("\n"));
|
||||
}
|
||||
|
||||
private control(control: Element, wrapping: string | undefined): void {
|
||||
this.flush();
|
||||
const label = wrapping || this.detachedLabel(control);
|
||||
const name = attr(control, "name") ?? "";
|
||||
const required = hasAttr(control, "required");
|
||||
const tag = control.tagName;
|
||||
if (tag === "select") {
|
||||
const multi = hasAttr(control, "multiple");
|
||||
const options = collectElements(control, (element) => element.tagName === "option").map(
|
||||
(option) => {
|
||||
// Same text OMP derives an option's value from when `value` is absent.
|
||||
const text = rawText(option).replace(/\s+/g, " ").trim();
|
||||
return {
|
||||
value: attr(option, "value") ?? text,
|
||||
label: text,
|
||||
checked: hasAttr(option, "selected"),
|
||||
disabled: hasAttr(option, "disabled"),
|
||||
};
|
||||
},
|
||||
);
|
||||
// A single select always has a selection: the first enabled option unless one is marked.
|
||||
if (!multi && !options.some((option) => option.checked)) {
|
||||
const first = options.find((option) => !option.disabled);
|
||||
if (first) first.checked = true;
|
||||
}
|
||||
this.addField({
|
||||
kind: "choice",
|
||||
name,
|
||||
control: "select",
|
||||
multi,
|
||||
other: false,
|
||||
prompt: this.prompt(label),
|
||||
options,
|
||||
required,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (tag === "textarea") {
|
||||
this.addField({
|
||||
kind: "text",
|
||||
name,
|
||||
prompt: this.prompt(label),
|
||||
value: rawText(control).replace(/^\r?\n/, ""),
|
||||
placeholder: attr(control, "placeholder") ?? "",
|
||||
required,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const type = (attr(control, "type") ?? "text").toLowerCase();
|
||||
if (IGNORED_INPUTS.has(type)) return;
|
||||
const value = attr(control, "value");
|
||||
if (type === "radio" || type === "checkbox") {
|
||||
const option = {
|
||||
value: value ?? "on",
|
||||
label: label || value || name,
|
||||
checked: hasAttr(control, "checked"),
|
||||
disabled: hasAttr(control, "disabled"),
|
||||
};
|
||||
const key = `${type}\0${name}`;
|
||||
const group = this.groups.get(key);
|
||||
if (group) {
|
||||
group.options.push(option);
|
||||
group.required ||= required;
|
||||
return;
|
||||
}
|
||||
const field: OmpFormChoiceField = {
|
||||
kind: "choice",
|
||||
name,
|
||||
control: type,
|
||||
multi: type === "checkbox",
|
||||
other: false,
|
||||
prompt: this.prompt(""),
|
||||
options: [option],
|
||||
required,
|
||||
};
|
||||
this.groups.set(key, field);
|
||||
this.addField(field);
|
||||
return;
|
||||
}
|
||||
this.addField({
|
||||
kind: "text",
|
||||
name,
|
||||
prompt: this.prompt(label),
|
||||
value: value ?? "",
|
||||
placeholder: attr(control, "placeholder") ?? "",
|
||||
required,
|
||||
});
|
||||
}
|
||||
|
||||
/** Label of a control outside any wrapping `<label>`: `<label for>`, then `aria-label`, `title`. */
|
||||
private detachedLabel(control: Element): string {
|
||||
const id = attr(control, "id");
|
||||
const label = id ? this.labelFor.get(id) : undefined;
|
||||
if (label) return textOf(label, { skipLabels: true });
|
||||
return normalize(attr(control, "aria-label") ?? attr(control, "title") ?? "");
|
||||
}
|
||||
|
||||
private prompt(label: string): string {
|
||||
return [this.takeContext(), label].filter(Boolean).join("\n\n");
|
||||
}
|
||||
|
||||
private takeContext(): string {
|
||||
const text = this.context.join("\n\n");
|
||||
this.context = [];
|
||||
return text;
|
||||
}
|
||||
|
||||
private flush(): void {
|
||||
const text = normalize(this.inline.join(""));
|
||||
this.inline = [];
|
||||
if (text) this.context.push(text);
|
||||
}
|
||||
|
||||
private addField(field: OmpFormField): void {
|
||||
this.fields.push(field);
|
||||
}
|
||||
}
|
||||
|
||||
function rawText(node: Node): string {
|
||||
return children(node)
|
||||
.map((child) => (isText(child) ? child.value : rawText(child)))
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Parse agent-written form HTML; content outside the first `<form>` is ignored when one exists. */
|
||||
export function parseOmpHtmlForm(html: string): OmpHtmlForm {
|
||||
const document = parse(html);
|
||||
const root = findElement(document, (element) => element.tagName === "form") ?? document;
|
||||
return new FormReader(root).read();
|
||||
}
|
||||
@@ -4,11 +4,15 @@ import type {
|
||||
AgentProvider,
|
||||
} from "../../agent-sdk-types.js";
|
||||
import { splitMultiSelectAnswer } from "../question-card-answer.js";
|
||||
import { OmpFormQuestion } from "./form-question.js";
|
||||
import type { OmpAgentMessage, OmpExtensionUiResponse, OmpRuntimeEvent } from "./rpc-types.js";
|
||||
import type { OmpAgentMessage, OmpRuntimeEvent } from "./rpc-types.js";
|
||||
|
||||
type UiRequest = Extract<OmpRuntimeEvent, { type: "extension_ui_request" }>;
|
||||
type SendResponse = (id: string, response: OmpExtensionUiResponse) => void;
|
||||
interface UiResponse {
|
||||
value?: string;
|
||||
confirmed?: boolean;
|
||||
cancelled?: boolean;
|
||||
}
|
||||
type SendResponse = (id: string, response: UiResponse) => void;
|
||||
|
||||
const OTHER = "Other (type your own)";
|
||||
const ANSWER_HEADER = "Response";
|
||||
@@ -119,7 +123,7 @@ function mapGenericQuestion(
|
||||
function genericResponse(
|
||||
request: AgentPermissionRequest,
|
||||
response: AgentPermissionResponse,
|
||||
): OmpExtensionUiResponse {
|
||||
): UiResponse {
|
||||
if (response.behavior === "deny") return { cancelled: true };
|
||||
const answers = record(response.updatedInput?.answers);
|
||||
const answer = Object.values(answers ?? {}).find(
|
||||
@@ -180,7 +184,6 @@ function selectedAnswer(
|
||||
export class OmpQuestionUi {
|
||||
private questions: AskQuestion[] = [];
|
||||
private pending: PendingAnswer | null = null;
|
||||
private readonly forms = new Map<string, OmpFormQuestion>();
|
||||
|
||||
observeMessage(message: OmpAgentMessage): void {
|
||||
if (message.role !== "assistant") return;
|
||||
@@ -208,31 +211,10 @@ export class OmpQuestionUi {
|
||||
provider: AgentProvider,
|
||||
send: SendResponse,
|
||||
): AgentPermissionRequest | null {
|
||||
if (event.method === "form") return this.mapForm(event, provider, send);
|
||||
if (this.consume(event, send)) return null;
|
||||
return this.mapAsk(event, provider) ?? mapGenericQuestion(event, provider);
|
||||
}
|
||||
|
||||
/** OMP 19.1+ asks with one HTML form; an empty one is cancelled so the tool does not wait. */
|
||||
private mapForm(
|
||||
event: UiRequest,
|
||||
provider: AgentProvider,
|
||||
send: SendResponse,
|
||||
): AgentPermissionRequest | null {
|
||||
if (!event.html?.trim()) {
|
||||
send(event.id, { cancelled: true });
|
||||
return null;
|
||||
}
|
||||
const form = OmpFormQuestion.fromHtml({ id: event.id, html: event.html, provider });
|
||||
this.forms.set(event.id, form);
|
||||
return form.request;
|
||||
}
|
||||
|
||||
/** OMP settled the request itself; drop it without replying. */
|
||||
forget(requestId: string): void {
|
||||
this.forms.delete(requestId);
|
||||
}
|
||||
|
||||
private mapAsk(event: UiRequest, provider: AgentProvider): AgentPermissionRequest | null {
|
||||
if (event.method !== "select" || typeof event.title !== "string") return null;
|
||||
const title = event.title;
|
||||
@@ -281,12 +263,6 @@ export class OmpQuestionUi {
|
||||
response: AgentPermissionResponse,
|
||||
send: SendResponse,
|
||||
): void {
|
||||
const form = this.forms.get(request.id);
|
||||
if (form) {
|
||||
this.forms.delete(request.id);
|
||||
send(request.id, form.response(response));
|
||||
return;
|
||||
}
|
||||
if (request.metadata?.ompAsk !== true) {
|
||||
send(request.id, genericResponse(request, response));
|
||||
return;
|
||||
|
||||
@@ -482,24 +482,8 @@ const OmpExtensionUiRequestSchema = z
|
||||
url: z.string().optional(),
|
||||
launchUrl: z.string().optional(),
|
||||
instructions: z.string().optional(),
|
||||
/** OMP 19.1+ `form`: the whole HTML form of one `ask` call. */
|
||||
html: z.string().optional(),
|
||||
/** `cancel`: the request OMP settled itself (abort or timeout). */
|
||||
targetId: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
/** Submitted value of one form control: text, or the checked values of a group. */
|
||||
export type OmpFormValue = string | string[];
|
||||
export type OmpFormData = Record<string, OmpFormValue>;
|
||||
|
||||
export interface OmpExtensionUiResponse {
|
||||
value?: string;
|
||||
confirmed?: boolean;
|
||||
cancelled?: boolean;
|
||||
data?: OmpFormData;
|
||||
}
|
||||
|
||||
const OmpSubagentLifecycleEventSchema = z
|
||||
.object({ type: z.literal("subagent_lifecycle"), payload: OmpSubagentLifecyclePayloadSchema })
|
||||
.passthrough();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type {
|
||||
OmpAgentMessage,
|
||||
OmpExtensionUiResponse,
|
||||
OmpModel,
|
||||
OmpPromptAck,
|
||||
OmpRpcHostToolDefinition,
|
||||
@@ -82,7 +81,10 @@ export interface OmpRuntimeSession {
|
||||
images?: Array<{ type: "image"; data: string; mimeType: string }>,
|
||||
): Promise<void>;
|
||||
handoff(customInstructions?: string): Promise<void>;
|
||||
respondToExtensionUiRequest(id: string, response: OmpExtensionUiResponse): void;
|
||||
respondToExtensionUiRequest(
|
||||
id: string,
|
||||
response: { value?: string; confirmed?: boolean; cancelled?: boolean },
|
||||
): void;
|
||||
cancelExtensionUiRequest(id: string): void;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import type {
|
||||
OmpStartSessionInput,
|
||||
} from "../runtime.js";
|
||||
import type {
|
||||
OmpExtensionUiResponse,
|
||||
OmpRpcHostToolDefinition,
|
||||
OmpRpcHostToolResult,
|
||||
OmpRpcHostToolUpdate,
|
||||
@@ -160,7 +159,7 @@ export class FakeOmpSession implements OmpRuntimeSession {
|
||||
readonly canceledExtensionUiRequests: string[] = [];
|
||||
readonly extensionUiResponses: Array<{
|
||||
id: string;
|
||||
response: OmpExtensionUiResponse;
|
||||
response: { value?: string; confirmed?: boolean; cancelled?: boolean };
|
||||
}> = [];
|
||||
setModelResult: OmpModel | null = null;
|
||||
models: OmpModel[] = [];
|
||||
@@ -469,7 +468,10 @@ export class FakeOmpSession implements OmpRuntimeSession {
|
||||
this.handoffRequests.push(customInstructions ? { customInstructions } : {});
|
||||
}
|
||||
|
||||
respondToExtensionUiRequest(id: string, response: OmpExtensionUiResponse): void {
|
||||
respondToExtensionUiRequest(
|
||||
id: string,
|
||||
response: { value?: string; confirmed?: boolean; cancelled?: boolean },
|
||||
): void {
|
||||
this.extensionUiResponses.push({ id, response });
|
||||
}
|
||||
|
||||
|
||||
@@ -82,7 +82,6 @@ const INBOUND_PERMISSION = {
|
||||
"daemon.config.reload.request": "daemon.manage",
|
||||
"daemon.get_pairing_offer.request": "access.manage",
|
||||
"daemon.get_status.request": "daemon.read",
|
||||
"daemon.tailscale.set.request": "daemon.manage",
|
||||
"daemon.update.request": "daemon.manage",
|
||||
delete_agent_request: "workspace.write",
|
||||
"diagnostics.request": "daemon.read",
|
||||
@@ -337,7 +336,6 @@ const OUTBOUND_PERMISSION = {
|
||||
"daemon.config.reload.response": "daemon.manage",
|
||||
"daemon.get_pairing_offer.response": "access.manage",
|
||||
"daemon.get_status.response": "daemon.read",
|
||||
"daemon.tailscale.set.response": "daemon.manage",
|
||||
"daemon.update.progress": "daemon.manage",
|
||||
"daemon.update.response": "daemon.manage",
|
||||
"diagnostics.response": "daemon.read",
|
||||
|
||||
@@ -68,302 +68,6 @@ describe("paseo daemon bootstrap", () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test("switches Tailscale live and requires confirmation from the extra listener", async () => {
|
||||
let tailscaleAddress: string | null = null;
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
relayEnabled: false,
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: tailscaleAddress ? [tailscaleAddress] : [],
|
||||
otherAddresses: new Set(),
|
||||
}),
|
||||
});
|
||||
const local = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const address = `127.0.0.2:${daemon.port}`;
|
||||
const remote = new DaemonClient({ url: `ws://${address}/ws` });
|
||||
|
||||
try {
|
||||
const configPath = path.join(daemon.paseoHome, "config.json");
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: 1, daemon: { listen: daemon.config.listen } }),
|
||||
);
|
||||
await local.connect();
|
||||
expect(local.getLastServerInfoMessage()?.features?.tailscale).toBe(true);
|
||||
const initial = await local.getDaemonStatus();
|
||||
expect(initial.tailscale?.state).toBe("unavailable");
|
||||
|
||||
tailscaleAddress = "127.0.0.2";
|
||||
expect((await local.getDaemonStatus()).tailscale?.state).toBe("off");
|
||||
expect(await local.setTailscaleEnabled(true)).toMatchObject({
|
||||
tailscale: { address, state: "on" },
|
||||
extraListeners: [{ address, state: "listening" }],
|
||||
});
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).daemon.listen).toBe(
|
||||
`${daemon.config.listen},${address}`,
|
||||
);
|
||||
|
||||
await remote.connect();
|
||||
expect(remote.getLastServerInfoMessage()?.serverId).toBe(initial.serverId);
|
||||
const [mainStatus, tailscaleStatus] = await Promise.all([
|
||||
local.getDaemonStatus({ includeProviders: false }),
|
||||
remote.getDaemonStatus({ includeProviders: false }),
|
||||
]);
|
||||
expect([mainStatus.tailscale, tailscaleStatus.tailscale]).toMatchObject([
|
||||
{ address, state: "on", disconnectsCurrentConnection: false },
|
||||
{ address, state: "on", disconnectsCurrentConnection: true },
|
||||
]);
|
||||
expect(await remote.setTailscaleEnabled(false)).toMatchObject({
|
||||
confirmationRequired: true,
|
||||
tailscale: tailscaleStatus.tailscale,
|
||||
});
|
||||
expect(await local.setTailscaleEnabled(true)).toMatchObject({
|
||||
confirmationRequired: false,
|
||||
tailscale: mainStatus.tailscale,
|
||||
});
|
||||
expect(await remote.setTailscaleEnabled(false, true)).toMatchObject({
|
||||
confirmationRequired: false,
|
||||
tailscale: { state: "off", disconnectsCurrentConnection: false },
|
||||
});
|
||||
await expect.poll(() => remote.isConnected).toBe(false);
|
||||
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).daemon.listen).toBe(
|
||||
daemon.config.listen,
|
||||
);
|
||||
expect(await local.getDaemonStatus()).toMatchObject({
|
||||
pid: initial.pid,
|
||||
listen: initial.listen,
|
||||
tailscale: { state: "off" },
|
||||
extraListeners: [],
|
||||
});
|
||||
} finally {
|
||||
await Promise.all([remote.close(), local.close()]);
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ condition: "the interface goes away", nextAddress: null, nextState: "unavailable" },
|
||||
{ condition: "the interface gets a new IP", nextAddress: "100.127.255.253", nextState: "off" },
|
||||
])(
|
||||
"turns off a saved Tailscale listener after $condition",
|
||||
async ({ nextAddress, nextState }) => {
|
||||
let tailscaleAddress: string | null = "100.127.255.254";
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
relayEnabled: false,
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: tailscaleAddress ? [tailscaleAddress] : [],
|
||||
otherAddresses: new Set(),
|
||||
}),
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const configPath = path.join(daemon.paseoHome, "config.json");
|
||||
const originalAddress = `100.127.255.254:${daemon.port}`;
|
||||
const unrelatedAddress = `127.0.0.3:${daemon.port}`;
|
||||
const originalListen = `${daemon.config.listen},${unrelatedAddress}`;
|
||||
const readListen = async () => JSON.parse(await readFile(configPath, "utf8")).daemon.listen;
|
||||
|
||||
try {
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: 1, daemon: { listen: originalListen } }),
|
||||
);
|
||||
await client.connect();
|
||||
await client.reloadDaemonConfig();
|
||||
await client.setTailscaleEnabled(true);
|
||||
expect(await readListen()).toBe(`${originalListen},${originalAddress}`);
|
||||
|
||||
tailscaleAddress = nextAddress;
|
||||
expect((await client.getDaemonStatus()).tailscale).toMatchObject({
|
||||
address: originalAddress,
|
||||
state: "waiting",
|
||||
});
|
||||
expect(await client.setTailscaleEnabled(false)).toMatchObject({
|
||||
tailscale: { address: null, state: nextState },
|
||||
extraListeners: [{ address: unrelatedAddress }],
|
||||
});
|
||||
expect(await readListen()).toBe(originalListen);
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("keeps Tailscale on its original port across a main port change", async () => {
|
||||
const tailscaleIp = "127.0.0.2";
|
||||
const carrierNatIp = "100.127.255.254";
|
||||
const dependencies = {
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: [tailscaleIp],
|
||||
otherAddresses: new Set([carrierNatIp]),
|
||||
}),
|
||||
};
|
||||
const original = await createTestPaseoDaemon({ ...dependencies, cleanup: false });
|
||||
const oldAddress = `${tailscaleIp}:${original.port}`;
|
||||
const first = new DaemonClient({ url: `ws://127.0.0.1:${original.port}/ws` });
|
||||
const configPath = path.join(original.paseoHome, "config.json");
|
||||
const persist = (listen: string) =>
|
||||
writeFile(configPath, JSON.stringify({ version: 1, daemon: { listen } }));
|
||||
const readListen = async () => JSON.parse(await readFile(configPath, "utf8")).daemon.listen;
|
||||
let restarted: Awaited<ReturnType<typeof createPaseoDaemon>> | undefined;
|
||||
let local: DaemonClient | undefined;
|
||||
let remote: DaemonClient | undefined;
|
||||
try {
|
||||
await first.connect();
|
||||
await first.setTailscaleEnabled(true);
|
||||
const [, savedExtra] = (await readListen()).split(",");
|
||||
expect(savedExtra).toBe(oldAddress);
|
||||
|
||||
const newPort = await findFreePort();
|
||||
const newMain = `127.0.0.1:${newPort}`;
|
||||
await persist(`${newMain},${savedExtra}`);
|
||||
await first.close();
|
||||
await original.close();
|
||||
restarted = await createPaseoDaemon(
|
||||
{ ...original.config, listen: loadConfig(original.paseoHome, { env: {} }).listen },
|
||||
pino({ level: "silent" }),
|
||||
{
|
||||
...dependencies,
|
||||
builtinPlugins: new BuiltinPluginLoader(undefined, []),
|
||||
lazyTerminalWorker: true,
|
||||
},
|
||||
);
|
||||
await restarted.start();
|
||||
|
||||
local = new DaemonClient({ url: `ws://${newMain}/ws` });
|
||||
remote = new DaemonClient({ url: `ws://${oldAddress}/ws` });
|
||||
await Promise.all([local.connect(), remote.connect()]);
|
||||
expect((await local.getDaemonStatus()).tailscale).toMatchObject({
|
||||
state: "on",
|
||||
address: oldAddress,
|
||||
});
|
||||
expect(await local.setTailscaleEnabled(true)).toMatchObject({
|
||||
extraListeners: [{ address: oldAddress, state: "listening" }],
|
||||
});
|
||||
expect(await readListen()).toBe(`${newMain},${oldAddress}`);
|
||||
|
||||
const anotherTailscale = `${tailscaleIp}:${newPort}`;
|
||||
const carrierNat = `${carrierNatIp}:${original.port}`;
|
||||
await persist(`${newMain},${oldAddress},${carrierNat},${anotherTailscale}`);
|
||||
await local.reloadDaemonConfig();
|
||||
expect((await fetch(`http://${anotherTailscale}/api/health`)).ok).toBe(true);
|
||||
expect((await local.getDaemonStatus()).tailscale?.address).toBe(oldAddress);
|
||||
expect(await remote.setTailscaleEnabled(false)).toMatchObject({
|
||||
confirmationRequired: true,
|
||||
tailscale: { state: "on", address: oldAddress },
|
||||
});
|
||||
expect(await remote.setTailscaleEnabled(false, true)).toMatchObject({
|
||||
confirmationRequired: false,
|
||||
tailscale: { state: "off" },
|
||||
extraListeners: [{ address: carrierNat }],
|
||||
});
|
||||
await expect.poll(() => remote.isConnected).toBe(false);
|
||||
await expect(fetch(`http://${anotherTailscale}/api/health`)).rejects.toThrow();
|
||||
expect(await readListen()).toBe(`${newMain},${carrierNat}`);
|
||||
} finally {
|
||||
await Promise.all([first.close(), local?.close(), remote?.close()]);
|
||||
if (restarted) await restarted.stop();
|
||||
else await original.close();
|
||||
await Promise.all([
|
||||
rm(path.dirname(original.paseoHome), { recursive: true, force: true }),
|
||||
rm(original.staticDir, { recursive: true, force: true }),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
test("reload changes only the extra TCP listeners without replacing the main endpoint", async () => {
|
||||
const daemon = await createTestPaseoDaemon({ relayEnabled: false, hostnames: [] });
|
||||
const local = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const address = `127.0.0.2:${daemon.port}`;
|
||||
const configPath = path.join(daemon.paseoHome, "config.json");
|
||||
try {
|
||||
await local.connect();
|
||||
const persist = (listen: string) =>
|
||||
writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: 1, daemon: { listen, relay: { enabled: false } } }),
|
||||
);
|
||||
await persist(`${daemon.config.listen},${address}`);
|
||||
expect(await local.reloadDaemonConfig()).toMatchObject({
|
||||
appliedPaths: expect.arrayContaining(["daemon.listen"]),
|
||||
restartRequiredPaths: [],
|
||||
});
|
||||
expect((await fetch(`http://${address}/api/health`)).ok).toBe(true);
|
||||
const rejectedHost = await new Promise<number | undefined>((resolve, reject) => {
|
||||
const request = http.get(
|
||||
`http://${address}/api/health`,
|
||||
{ headers: { host: "unlisted.example.test" } },
|
||||
(response) => {
|
||||
response.resume();
|
||||
resolve(response.statusCode);
|
||||
},
|
||||
);
|
||||
request.on("error", reject);
|
||||
});
|
||||
expect(rejectedHost).toBe(403);
|
||||
|
||||
await persist("127.0.0.3:0");
|
||||
expect(await local.reloadDaemonConfig()).toMatchObject({
|
||||
appliedPaths: expect.arrayContaining(["daemon.listen"]),
|
||||
restartRequiredPaths: ["daemon.listen"],
|
||||
});
|
||||
expect((await local.getDaemonStatus()).listen).toBe(`127.0.0.1:${daemon.port}`);
|
||||
await expect(fetch(`http://${address}/api/health`)).rejects.toThrow();
|
||||
} finally {
|
||||
await local.close();
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("switching Tailscale preserves unrelated live listeners and pending listen edits", async () => {
|
||||
const carrierNatIp = "100.127.255.254";
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
relayEnabled: false,
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: ["127.0.0.2"],
|
||||
otherAddresses: new Set([carrierNatIp]),
|
||||
}),
|
||||
});
|
||||
const tailscale = `127.0.0.2:${daemon.port}`;
|
||||
const live = `127.0.0.3:${daemon.port}`;
|
||||
const pending = `127.0.0.4:${daemon.port}`;
|
||||
const carrierNat = `${carrierNatIp}:${daemon.port}`;
|
||||
const local = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const other = new DaemonClient({ url: `ws://${live}/ws` });
|
||||
const configPath = path.join(daemon.paseoHome, "config.json");
|
||||
const persist = (listen: string) =>
|
||||
writeFile(configPath, JSON.stringify({ version: 1, daemon: { listen } }));
|
||||
try {
|
||||
await local.connect();
|
||||
await persist(`${daemon.config.listen},${live},${carrierNat}`);
|
||||
await local.reloadDaemonConfig();
|
||||
await other.connect();
|
||||
|
||||
// Leave another addition and removal pending in config.json across both toggles.
|
||||
await persist(`${daemon.config.listen},${carrierNat},${pending}`);
|
||||
expect(await local.setTailscaleEnabled(true)).toMatchObject({
|
||||
extraListeners: [{ address: live }, { address: carrierNat }, { address: tailscale }],
|
||||
});
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).daemon.listen).toBe(
|
||||
`${daemon.config.listen},${carrierNat},${pending},${tailscale}`,
|
||||
);
|
||||
|
||||
expect(await other.setTailscaleEnabled(false)).toMatchObject({
|
||||
confirmationRequired: false,
|
||||
extraListeners: [{ address: live }, { address: carrierNat }],
|
||||
});
|
||||
expect((await other.getDaemonStatus({ includeProviders: false })).tailscale?.state).toBe(
|
||||
"off",
|
||||
);
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).daemon.listen).toBe(
|
||||
`${daemon.config.listen},${carrierNat},${pending}`,
|
||||
);
|
||||
} finally {
|
||||
await Promise.all([other.close(), local.close()]);
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("starts and serves health endpoint", async () => {
|
||||
const daemonHandle = await createTestPaseoDaemon({
|
||||
openai: { stt: { apiKey: "test-openai-api-key" }, tts: { apiKey: "test-openai-api-key" } },
|
||||
@@ -1226,47 +930,6 @@ export default function contribute(plugin: unknown) {
|
||||
});
|
||||
});
|
||||
|
||||
test.skipIf(isPlatform("win32"))(
|
||||
"keeps network listeners closed when a socket daemon reloads a staged TCP main address",
|
||||
async () => {
|
||||
const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-socket-listen-"));
|
||||
const socketPath = path.join(paseoHome, "daemon.sock");
|
||||
const configPath = path.join(paseoHome, "config.json");
|
||||
const persist = (listen: string) =>
|
||||
writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: 1, daemon: { listen, relay: { enabled: false } } }),
|
||||
);
|
||||
await persist(socketPath);
|
||||
const config = loadConfig(paseoHome, { env: {} });
|
||||
config.agentClients = createTestAgentClients();
|
||||
const daemon = await createPaseoDaemon(config, pino({ level: "silent" }), {
|
||||
builtinPlugins: new BuiltinPluginLoader(undefined, []),
|
||||
lazyTerminalWorker: true,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws+unix://${socketPath}:/ws` });
|
||||
try {
|
||||
await daemon.start();
|
||||
await client.connect();
|
||||
const extra = `127.0.0.1:${await findFreePort()}`;
|
||||
await persist(`127.0.0.1:6767,${extra}`);
|
||||
expect(await client.reloadDaemonConfig()).toMatchObject({
|
||||
appliedPaths: [],
|
||||
restartRequiredPaths: ["daemon.listen"],
|
||||
});
|
||||
expect(await client.getDaemonStatus({ includeProviders: false })).toMatchObject({
|
||||
listen: socketPath,
|
||||
extraListeners: [],
|
||||
});
|
||||
await expect(fetch(`http://${extra}/api/health`)).rejects.toThrow();
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.stop();
|
||||
await rm(paseoHome, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// POSIX-only: Unix socket listen paths are invalid Windows listen targets.
|
||||
test.skipIf(isPlatform("win32"))(
|
||||
"generates a relay pairing offer for unix socket listeners",
|
||||
@@ -1274,7 +937,7 @@ export default function contribute(plugin: unknown) {
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-socket-relay-"));
|
||||
const paseoHome = path.join(paseoHomeRoot, ".paseo");
|
||||
const staticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-static-"));
|
||||
const socketPath = path.join(paseoHomeRoot, "run", "paseo.sock,127.0.0.1:12345");
|
||||
const socketPath = path.join(paseoHomeRoot, "run", "paseo.sock");
|
||||
await mkdir(path.dirname(socketPath), { recursive: true });
|
||||
await mkdir(paseoHome, { recursive: true });
|
||||
const logger = pino({ level: "silent" });
|
||||
@@ -1304,7 +967,6 @@ export default function contribute(plugin: unknown) {
|
||||
|
||||
try {
|
||||
await daemon.start();
|
||||
expect(daemon.getListenTarget()).toEqual({ type: "socket", path: socketPath });
|
||||
const pairing = await generateLocalPairingOffer({
|
||||
paseoHome,
|
||||
relayEnabled: true,
|
||||
|
||||
@@ -25,16 +25,10 @@ import type { Logger } from "pino";
|
||||
import { z } from "zod";
|
||||
import { createBranchChangeRouteHandler } from "./script-route-branch-handler.js";
|
||||
|
||||
import {
|
||||
createDaemonListeners,
|
||||
parseListenString,
|
||||
formatListenTarget,
|
||||
formatHostForHttpUrl,
|
||||
splitListen,
|
||||
type ListenTarget,
|
||||
type TailscaleNetwork,
|
||||
} from "./listeners.js";
|
||||
export { parseListenString, formatListenTarget, type ListenTarget } from "./listeners.js";
|
||||
export type ListenTarget =
|
||||
| { type: "tcp"; host: string; port: number }
|
||||
| { type: "socket"; path: string }
|
||||
| { type: "pipe"; path: string };
|
||||
|
||||
function resolveBoundListenTarget(
|
||||
listenTarget: ListenTarget,
|
||||
@@ -56,6 +50,60 @@ function resolveBoundListenTarget(
|
||||
};
|
||||
}
|
||||
|
||||
// Matches a Windows drive-letter path like C:\ or D:\
|
||||
const WINDOWS_DRIVE_RE = /^[A-Za-z]:\\/;
|
||||
|
||||
export function parseListenString(listen: string): ListenTarget {
|
||||
// 1. Windows named pipes: \\.\pipe\... or pipe://...
|
||||
if (listen.startsWith("\\\\.\\pipe\\") || listen.startsWith("pipe://")) {
|
||||
return {
|
||||
type: "pipe",
|
||||
path: listen.startsWith("pipe://") ? listen.slice("pipe://".length) : listen,
|
||||
};
|
||||
}
|
||||
// 2. Explicit unix:// prefix
|
||||
if (listen.startsWith("unix://")) {
|
||||
return { type: "socket", path: listen.slice(7) };
|
||||
}
|
||||
// 3. Reject Windows absolute drive paths — they are not Unix sockets
|
||||
if (WINDOWS_DRIVE_RE.test(listen)) {
|
||||
throw new Error(`Invalid listen string (Windows path is not a valid listen target): ${listen}`);
|
||||
}
|
||||
// 4. POSIX absolute path (/ or ~) — Unix socket
|
||||
if (listen.startsWith("/") || listen.startsWith("~")) {
|
||||
return { type: "socket", path: listen };
|
||||
}
|
||||
// 5. Pure numeric — TCP port on 127.0.0.1
|
||||
const trimmed = listen.trim();
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const port = parseInt(trimmed, 10);
|
||||
return { type: "tcp", host: "127.0.0.1", port };
|
||||
}
|
||||
// 6. host:port — TCP
|
||||
if (listen.includes(":")) {
|
||||
const lastColonIdx = listen.lastIndexOf(":");
|
||||
const host = listen.slice(0, lastColonIdx);
|
||||
const portStr = listen.slice(lastColonIdx + 1);
|
||||
const parsedPort = parseInt(portStr, 10);
|
||||
if (!Number.isFinite(parsedPort)) {
|
||||
throw new Error(`Invalid port in listen string: ${listen}`);
|
||||
}
|
||||
const cleanHost = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
||||
return { type: "tcp", host: cleanHost || "127.0.0.1", port: parsedPort };
|
||||
}
|
||||
throw new Error(`Invalid listen string: ${listen}`);
|
||||
}
|
||||
|
||||
export function formatListenTarget(listenTarget: ListenTarget | null): string | null {
|
||||
if (!listenTarget) {
|
||||
return null;
|
||||
}
|
||||
if (listenTarget.type === "tcp") {
|
||||
return `${formatHostForHttpUrl(listenTarget.host)}:${listenTarget.port}`;
|
||||
}
|
||||
return listenTarget.path;
|
||||
}
|
||||
|
||||
export async function fanOutReconciledWorkspaceUpdates(input: {
|
||||
sessions: Iterable<{
|
||||
syncWorkspaceGitObserversForExternalWorkspaceIds(workspaceIds: Iterable<string>): Promise<void>;
|
||||
@@ -125,7 +173,6 @@ import { DaemonConfigStore, type MutableDaemonConfig } from "./daemon-config-sto
|
||||
import { createOrchestrationSkills } from "./orchestration-skills/index.js";
|
||||
import {
|
||||
resolveReloadableConfig,
|
||||
resolveListenAddress,
|
||||
type ResolvedDaemonSettings,
|
||||
type CliConfigOverrides,
|
||||
} from "./config.js";
|
||||
@@ -223,6 +270,10 @@ const MCP_DEBUG_SECRET = "[redacted]";
|
||||
const DOWNLOAD_OPEN_FLAGS =
|
||||
process.platform === "win32" ? constants.O_RDONLY : constants.O_RDONLY | constants.O_NOFOLLOW;
|
||||
|
||||
function formatHostForHttpUrl(host: string): string {
|
||||
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
}
|
||||
|
||||
function resolveAgentMcpClientHost(host: string): string {
|
||||
if (host === "0.0.0.0") {
|
||||
return "127.0.0.1";
|
||||
@@ -471,7 +522,6 @@ export interface PaseoDaemon {
|
||||
export interface PaseoDaemonDependencies {
|
||||
builtinPlugins?: BuiltinPluginLoader;
|
||||
lazyTerminalWorker?: boolean;
|
||||
getTailscaleNetwork?: () => TailscaleNetwork;
|
||||
hubRelationshipRemote?: HubRelationshipRemote;
|
||||
hubRelationshipClock?: HubRelationshipClock;
|
||||
hubRelationshipRetryPolicy?: HubRelationshipRetryPolicy;
|
||||
@@ -538,10 +588,6 @@ function resolveReloadEnv(config: PaseoDaemonConfig): NodeJS.ProcessEnv {
|
||||
return config.configReload?.env ?? process.env;
|
||||
}
|
||||
|
||||
function isListenOverridden(config: PaseoDaemonConfig): boolean {
|
||||
return config.configReload?.overrideControlledPaths.includes("daemon.listen") === true;
|
||||
}
|
||||
|
||||
function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): MutableDaemonConfig {
|
||||
const providers = config.providerOverrides ?? {};
|
||||
|
||||
@@ -631,9 +677,6 @@ export async function createPaseoDaemon(
|
||||
});
|
||||
return {
|
||||
mutable: createInitialMutableDaemonConfig(reloaded),
|
||||
listen: config.configReload
|
||||
? resolveListenAddress(resolveReloadEnv(config), config.configReload.cli, persisted)
|
||||
: persisted.daemon?.listen,
|
||||
overrideControlledPaths: reloaded.overrideControlledPaths,
|
||||
};
|
||||
},
|
||||
@@ -688,7 +731,7 @@ export async function createPaseoDaemon(
|
||||
// pattern.
|
||||
const agentMcpAuthToken = randomUUID();
|
||||
|
||||
const listenTarget = parseListenString(splitListen(config.listen)[0]);
|
||||
const listenTarget = parseListenString(config.listen);
|
||||
|
||||
const app = express();
|
||||
app.set("trust proxy", resolveExpressTrustProxySetting(config));
|
||||
@@ -759,17 +802,17 @@ export async function createPaseoDaemon(
|
||||
app.use(serviceProxy.middleware());
|
||||
|
||||
// Host allowlist / DNS rebinding protection (vite-like semantics).
|
||||
// Validate the accepted connection so extra TCP listeners also enforce the allowlist.
|
||||
app.use((req, res, next) => {
|
||||
if (req.socket.localPort !== undefined) {
|
||||
// For non-TCP (unix sockets), skip host validation.
|
||||
if (listenTarget.type === "tcp") {
|
||||
app.use((req, res, next) => {
|
||||
const hostHeader = typeof req.headers.host === "string" ? req.headers.host : undefined;
|
||||
if (!isHostnameAllowed(hostHeader, configuredHostnames)) {
|
||||
res.status(403).json({ error: "Invalid Host header" });
|
||||
return;
|
||||
}
|
||||
}
|
||||
next();
|
||||
});
|
||||
next();
|
||||
});
|
||||
}
|
||||
|
||||
// CORS - allow same-origin + configured origins
|
||||
const fixedAllowedOrigins = [
|
||||
@@ -910,14 +953,6 @@ export async function createPaseoDaemon(
|
||||
});
|
||||
|
||||
const httpServer = createHTTPServer(app);
|
||||
const listeners = createDaemonListeners({
|
||||
http: httpServer,
|
||||
listen: config.listen,
|
||||
overridden: isListenOverridden(config),
|
||||
getMain: () => boundListenTarget,
|
||||
getTailscaleNetwork: dependencies.getTailscaleNetwork,
|
||||
});
|
||||
daemonConfigStore.attachListeners(listeners);
|
||||
|
||||
// Script proxy WebSocket upgrade handler — must be registered before the
|
||||
// VoiceAssistantWebSocketServer attaches its own "upgrade" listener so that
|
||||
@@ -1925,9 +1960,6 @@ export async function createPaseoDaemon(
|
||||
providerSnapshotManager,
|
||||
{
|
||||
listen: formatListenTarget(boundListenTarget ?? listenTarget),
|
||||
getListenStatus: listeners.status,
|
||||
setTailscaleEnabled: (enabled, localEndpoint, confirmed) =>
|
||||
daemonConfigStore.setTailscaleEnabled(enabled, localEndpoint, confirmed),
|
||||
worktreesRoot: config.worktreesRoot,
|
||||
get appBaseUrl() {
|
||||
return appBaseUrl;
|
||||
@@ -1960,7 +1992,6 @@ export async function createPaseoDaemon(
|
||||
restartRecovery.resumePending();
|
||||
await finishSubscriptions.start();
|
||||
await changeRequestWatches.start();
|
||||
await listeners.apply(config.listen);
|
||||
wsServer.beginAcceptingConnections();
|
||||
const relaySecurityLogger = logger.child({ module: "relay-security" });
|
||||
relayRuntime = createRelayRuntime({
|
||||
@@ -2024,7 +2055,6 @@ export async function createPaseoDaemon(
|
||||
await pluginRuntime.stopAllPlugins().catch(() => undefined);
|
||||
await serviceProxy.stopStandalone().catch(() => undefined);
|
||||
await agentProviderRuntime.shutdown().catch(() => undefined);
|
||||
await listeners.stop();
|
||||
if (mainStarted) {
|
||||
httpServer.closeAllConnections();
|
||||
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
|
||||
@@ -2100,7 +2130,6 @@ export async function createPaseoDaemon(
|
||||
await speechService.stop();
|
||||
await scheduleService.stop().catch(() => undefined);
|
||||
await relayRuntime?.stop().catch(() => undefined);
|
||||
await listeners.stop();
|
||||
if (wsServer) {
|
||||
await wsServer.close();
|
||||
}
|
||||
|
||||
@@ -34,7 +34,6 @@ export {
|
||||
editPersistedConfig,
|
||||
type PersistedConfig,
|
||||
} from "./persisted-config.js";
|
||||
export { getMainListenAddress } from "./listeners.js";
|
||||
|
||||
const DEFAULT_PORT = 6767;
|
||||
const DEFAULT_RELAY_ENDPOINT = "relay.paseo.sh:443";
|
||||
@@ -475,11 +474,11 @@ function resolveTrustedProxiesConfig(
|
||||
}
|
||||
|
||||
// PASEO_LISTEN can be:
|
||||
// - host:port (TCP), with optional comma-separated extra TCP listeners
|
||||
// - host:port (TCP)
|
||||
// - /path/to/socket (Unix socket)
|
||||
// - unix:///path/to/socket (Unix socket)
|
||||
// Default is TCP at 127.0.0.1:6767
|
||||
export function resolveListenAddress(
|
||||
function resolveListenAddress(
|
||||
env: NodeJS.ProcessEnv,
|
||||
cli: CliConfigOverrides | undefined,
|
||||
persisted: ReturnType<typeof loadPersistedConfig>,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { createDaemonListeners } from "./listeners.js";
|
||||
import {
|
||||
loadPersistedConfig,
|
||||
savePersistedConfigAsync,
|
||||
@@ -70,7 +69,6 @@ export interface DaemonConfigReloadResult {
|
||||
export interface DaemonConfigReloadSource {
|
||||
resolve(persisted: PersistedConfig): {
|
||||
mutable: MutableDaemonConfig;
|
||||
listen?: string;
|
||||
overrideControlledPaths: readonly string[];
|
||||
};
|
||||
}
|
||||
@@ -425,7 +423,6 @@ export class DaemonConfigStore {
|
||||
private readonly reloadSource: DaemonConfigReloadSource | undefined;
|
||||
private readonly startupPersisted: PersistedConfig;
|
||||
private readonly speechOwner: SpeechSettingsOwner | undefined;
|
||||
private listeners?: ReturnType<typeof createDaemonListeners>;
|
||||
private lastKnownPersisted: PersistedConfig;
|
||||
|
||||
constructor(
|
||||
@@ -570,41 +567,6 @@ export class DaemonConfigStore {
|
||||
);
|
||||
}
|
||||
|
||||
public attachListeners(listeners: ReturnType<typeof createDaemonListeners>) {
|
||||
this.listeners = listeners;
|
||||
}
|
||||
|
||||
public setTailscaleEnabled(
|
||||
enabled: boolean,
|
||||
localEndpoint: string | undefined,
|
||||
confirmed: boolean,
|
||||
) {
|
||||
return this.enqueue(async () => {
|
||||
const listeners = this.listeners;
|
||||
if (!listeners) throw new Error("Tailscale is unavailable");
|
||||
const persisted = await loadPersistedConfigAsync(this.paseoHome, this.logger);
|
||||
const change = listeners.prepareTailscaleChange(
|
||||
persisted.daemon?.listen,
|
||||
enabled,
|
||||
localEndpoint,
|
||||
confirmed,
|
||||
);
|
||||
if (change.confirmationRequired) {
|
||||
return { confirmationRequired: true, ...listeners.status(localEndpoint) };
|
||||
}
|
||||
await savePersistedConfigAsync(
|
||||
this.paseoHome,
|
||||
{
|
||||
...persisted,
|
||||
daemon: { ...persisted.daemon, listen: change.listen },
|
||||
},
|
||||
this.logger,
|
||||
);
|
||||
await change.apply();
|
||||
return { confirmationRequired: false, ...listeners.status(localEndpoint) };
|
||||
});
|
||||
}
|
||||
|
||||
public reload(): Promise<DaemonConfigReloadResult> {
|
||||
return this.enqueue(() => this.reloadPersisted());
|
||||
}
|
||||
@@ -647,11 +609,8 @@ export class DaemonConfigStore {
|
||||
)
|
||||
);
|
||||
});
|
||||
const listenChange = await this.listeners?.apply(resolved.listen ?? persisted.daemon?.listen);
|
||||
if (listenChange?.applied) appliedPaths.push("daemon.listen");
|
||||
const restartRequiredPaths = compactOwnedPaths(
|
||||
diffPaths(this.startupPersisted, persisted).filter((path) => {
|
||||
if (path === "daemon.listen" && listenChange) return false;
|
||||
if (path === "$schema" || path === "version") return false;
|
||||
if (RELOADABLE_PATHS.some((owner) => pathBelongsTo(path, owner))) return false;
|
||||
if (this.speechOwner && SPEECH_PERSISTED_PATHS.some((owner) => pathBelongsTo(path, owner)))
|
||||
@@ -661,11 +620,6 @@ export class DaemonConfigStore {
|
||||
[],
|
||||
);
|
||||
|
||||
if (listenChange?.restartRequired) {
|
||||
restartRequiredPaths.push("daemon.listen");
|
||||
restartRequiredPaths.sort();
|
||||
}
|
||||
|
||||
const removedProviders = Object.keys(this.current.providers).filter(
|
||||
(provider) => !(provider in desired.providers),
|
||||
);
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createServer, type IncomingMessage, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import pino from "pino";
|
||||
import semver from "semver";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { afterEach, beforeAll, describe, expect, test } from "vitest";
|
||||
@@ -56,10 +53,7 @@ async function preflight(): Promise<void> {
|
||||
|
||||
// OMP exits at startup when no model is usable at all, so the home offers one offline
|
||||
// model, and an agent on any other provider's model has no credentials.
|
||||
function createOfflineOmpHome(
|
||||
options: { baseUrl?: string; askTimeoutSeconds?: number } = {},
|
||||
): string {
|
||||
const baseUrl = options.baseUrl ?? "http://127.0.0.1:9/v1";
|
||||
function createOfflineOmpHome(): string {
|
||||
const home = mkdtempSync(path.join(tmpdir(), "paseo-real-omp-offline-"));
|
||||
roots.add(home);
|
||||
const agentDir = path.join(home, ".omp", "agent");
|
||||
@@ -69,7 +63,7 @@ function createOfflineOmpHome(
|
||||
[
|
||||
"providers:",
|
||||
" offline:",
|
||||
` baseUrl: ${baseUrl}`,
|
||||
" baseUrl: http://127.0.0.1:9/v1",
|
||||
" api: openai-completions",
|
||||
" auth: none",
|
||||
" models:",
|
||||
@@ -84,12 +78,6 @@ function createOfflineOmpHome(
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
if (options.askTimeoutSeconds !== undefined) {
|
||||
writeFileSync(
|
||||
path.join(agentDir, "config.yml"),
|
||||
`ask:\n timeout: ${options.askTimeoutSeconds}\n`,
|
||||
);
|
||||
}
|
||||
return home;
|
||||
}
|
||||
|
||||
@@ -127,110 +115,6 @@ async function createHarness(options: { ompHome?: string } = {}): Promise<Harnes
|
||||
return { daemon, client, cwd, paseoHomeRoot, staticDir };
|
||||
}
|
||||
|
||||
async function installedOmpVersion(): Promise<string | null> {
|
||||
const command = process.env.OMP_COMMAND?.trim() || "omp";
|
||||
const { stdout } = await execFileAsync(command, ["--version"], { timeout: 10_000 });
|
||||
return semver.coerce(stdout)?.version ?? null;
|
||||
}
|
||||
|
||||
interface ScriptedModel {
|
||||
baseUrl: string;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
async function readBody(request: IncomingMessage): Promise<string> {
|
||||
let body = "";
|
||||
for await (const chunk of request) body += String(chunk);
|
||||
return body;
|
||||
}
|
||||
|
||||
function sseChunk(delta: Record<string, unknown>, finishReason: string | null): string {
|
||||
const chunk = {
|
||||
id: "chatcmpl-scripted",
|
||||
object: "chat.completion.chunk",
|
||||
created: 0,
|
||||
model: "offline-1",
|
||||
choices: [{ index: 0, delta, finish_reason: finishReason }],
|
||||
};
|
||||
return `data: ${JSON.stringify(chunk)}\n\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* An OpenAI-compatible model that calls OMP's `ask` tool once with `html`, then
|
||||
* replies with the tool's result so the test can read what OMP received.
|
||||
*/
|
||||
async function startScriptedAskModel(html: string): Promise<ScriptedModel> {
|
||||
const server: Server = createServer((request, response) => {
|
||||
void readBody(request).then((body) => {
|
||||
const payload = JSON.parse(body || "{}") as {
|
||||
tools?: Array<{ function?: { name?: string } }>;
|
||||
messages?: Array<{ role?: string; content?: unknown }>;
|
||||
};
|
||||
const toolMessage = payload.messages?.find((message) => message.role === "tool");
|
||||
const offersAsk = payload.tools?.some((tool) => tool.function?.name === "ask") ?? false;
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
if (!toolMessage && offersAsk) {
|
||||
response.write(
|
||||
sseChunk(
|
||||
{
|
||||
role: "assistant",
|
||||
tool_calls: [
|
||||
{
|
||||
index: 0,
|
||||
id: "call_ask_1",
|
||||
type: "function",
|
||||
function: { name: "ask", arguments: JSON.stringify({ html }) },
|
||||
},
|
||||
],
|
||||
},
|
||||
null,
|
||||
),
|
||||
);
|
||||
response.write(sseChunk({}, "tool_calls"));
|
||||
} else {
|
||||
const result = toolMessage ? JSON.stringify(toolMessage.content) : "ok";
|
||||
response.write(sseChunk({ role: "assistant", content: `ASK_RESULT ${result}` }, null));
|
||||
response.write(sseChunk({}, "stop"));
|
||||
}
|
||||
response.end("data: [DONE]\n\n");
|
||||
return undefined;
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
return {
|
||||
baseUrl: `http://127.0.0.1:${port}/v1`,
|
||||
close: () => new Promise((resolve) => server.close(() => resolve())),
|
||||
};
|
||||
}
|
||||
|
||||
const COLOR_FORM =
|
||||
'<form><fieldset><legend>Which color do you prefer?</legend><label><input type="radio" name="color" value="Red" checked> Red</label><label><input type="radio" name="color" value="Blue"> Blue</label></fieldset><label>Why? <input name="why"></label></form>';
|
||||
|
||||
async function skipUnlessOmpSendsForms(context: { skip: (note?: string) => void }): Promise<void> {
|
||||
const version = await installedOmpVersion();
|
||||
if (!version || semver.lt(version, "19.1.0")) {
|
||||
context.skip(`OMP ${version ?? "unknown"} sends field-by-field ask requests, not forms`);
|
||||
}
|
||||
}
|
||||
|
||||
async function askWithForm(harness: Harness) {
|
||||
const agent = await harness.client.createAgent({
|
||||
cwd: harness.cwd,
|
||||
title: "html-ask-form",
|
||||
provider: "omp",
|
||||
model: "offline/offline-1",
|
||||
modeId: "full",
|
||||
});
|
||||
await harness.client.sendMessage(agent.id, "Ask me which color I prefer.");
|
||||
const pending = await harness.client.waitForAgentUpsert(
|
||||
agent.id,
|
||||
(snapshot) => snapshot.pendingPermissions.length > 0,
|
||||
60_000,
|
||||
);
|
||||
return { agentId: agent.id, permission: pending.pendingPermissions[0] };
|
||||
}
|
||||
|
||||
async function closeHarness(harness: Harness): Promise<void> {
|
||||
await harness.client.close().catch(() => undefined);
|
||||
await harness.daemon.close().catch(() => undefined);
|
||||
@@ -546,72 +430,6 @@ describe("daemon E2E (real OMP)", () => {
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"an OMP 19.1+ HTML ask form is answered from the question card",
|
||||
async (context) => {
|
||||
await skipUnlessOmpSendsForms(context);
|
||||
const model = await startScriptedAskModel(COLOR_FORM);
|
||||
const harness = await createHarness({
|
||||
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl }),
|
||||
});
|
||||
try {
|
||||
const { agentId, permission } = await askWithForm(harness);
|
||||
expect(permission).toMatchObject({
|
||||
kind: "question",
|
||||
input: {
|
||||
questions: [
|
||||
{
|
||||
question: "Which color do you prefer?",
|
||||
header: "color",
|
||||
options: [{ label: "Red", description: "Default" }, { label: "Blue" }],
|
||||
},
|
||||
{ question: "Why?", header: "why", options: [] },
|
||||
],
|
||||
},
|
||||
});
|
||||
await harness.client.respondToPermission(agentId, permission.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { color: "Blue", why: "calmer" } },
|
||||
});
|
||||
expect((await harness.client.waitForFinish(agentId, 60_000)).status).toBe("idle");
|
||||
const reply = await readAssistantText(harness, agentId);
|
||||
expect(reply).toContain("ASK_RESULT");
|
||||
expect(reply).toContain("Blue");
|
||||
expect(reply).toContain("calmer");
|
||||
} finally {
|
||||
await closeHarness(harness);
|
||||
await model.close();
|
||||
}
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"an OMP 19.1+ HTML ask that times out in OMP closes its question card",
|
||||
async (context) => {
|
||||
await skipUnlessOmpSendsForms(context);
|
||||
const model = await startScriptedAskModel(COLOR_FORM);
|
||||
const harness = await createHarness({
|
||||
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl, askTimeoutSeconds: 2 }),
|
||||
});
|
||||
try {
|
||||
const { agentId } = await askWithForm(harness);
|
||||
// OMP submits the preselected answers itself and sends `cancel` for the open dialog.
|
||||
const settled = await harness.client.waitForAgentUpsert(
|
||||
agentId,
|
||||
(snapshot) => snapshot.status === "idle" && snapshot.pendingPermissions.length === 0,
|
||||
60_000,
|
||||
);
|
||||
expect(settled.pendingPermissions).toEqual([]);
|
||||
expect(await readAssistantText(harness, agentId)).toContain("Red");
|
||||
} finally {
|
||||
await closeHarness(harness);
|
||||
await model.close();
|
||||
}
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"ask mode preserves multiline approval details",
|
||||
async () => {
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
import { createServer } from "node:http";
|
||||
import { createServer as createTcpServer } from "node:net";
|
||||
import { once } from "node:events";
|
||||
import { expect, test } from "vitest";
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
import {
|
||||
createDaemonListeners,
|
||||
createExtraListeners,
|
||||
inspectTailscaleNetwork,
|
||||
splitListen,
|
||||
} from "./listeners.js";
|
||||
|
||||
test.each([
|
||||
"/tmp/paseo,qa.sock",
|
||||
"unix:///tmp/paseo,127.0.0.1:12345",
|
||||
String.raw`\\.\pipe\paseo,qa`,
|
||||
String.raw`pipe://\\.\pipe\paseo,qa`,
|
||||
])("preserves the legacy socket or pipe path %s", (listen) => {
|
||||
expect(splitListen(listen)).toEqual([listen]);
|
||||
});
|
||||
|
||||
test("retries an occupied extra listener and serves the original HTTP handler", async () => {
|
||||
const blocker = createTcpServer().listen(0, "127.0.0.2");
|
||||
await once(blocker, "listening");
|
||||
const address = blocker.address();
|
||||
if (!address || typeof address === "string") throw new Error("Expected TCP");
|
||||
const extra = `127.0.0.2:${address.port}`;
|
||||
const http = createServer((_req, res) => res.end("shared"));
|
||||
const listeners = createExtraListeners(http, 25);
|
||||
try {
|
||||
await listeners.apply([extra]);
|
||||
expect(listeners.status()).toEqual([{ address: extra, state: "waiting" }]);
|
||||
await new Promise<void>((resolve) => blocker.close(() => resolve()));
|
||||
await expect.poll(() => listeners.status()).toEqual([{ address: extra, state: "listening" }]);
|
||||
expect(await (await fetch(`http://${extra}`)).text()).toBe("shared");
|
||||
await listeners.apply([]);
|
||||
expect(listeners.status()).toEqual([]);
|
||||
await expect(fetch(`http://${extra}`)).rejects.toThrow();
|
||||
} finally {
|
||||
await listeners.apply([]);
|
||||
blocker.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("requires a Tailscale interface name or IPv6 prefix alongside the IPv4 address", () => {
|
||||
function ipv4(address: string): NetworkInterfaceInfo {
|
||||
return {
|
||||
address,
|
||||
family: "IPv4",
|
||||
netmask: "255.255.255.255",
|
||||
internal: false,
|
||||
cidr: null,
|
||||
mac: "",
|
||||
};
|
||||
}
|
||||
expect(inspectTailscaleNetwork(() => ({ eth0: [ipv4("100.101.102.103")] }))).toEqual({
|
||||
addresses: [],
|
||||
otherAddresses: new Set(["100.101.102.103"]),
|
||||
});
|
||||
expect(inspectTailscaleNetwork(() => ({ tailscale0: [ipv4("100.101.102.103")] }))).toEqual({
|
||||
addresses: ["100.101.102.103"],
|
||||
otherAddresses: new Set(),
|
||||
});
|
||||
expect(
|
||||
inspectTailscaleNetwork(() => ({
|
||||
eth0: [ipv4("100.101.102.103")],
|
||||
utun4: [
|
||||
ipv4("100.120.121.122"),
|
||||
{
|
||||
address: "fd7a:115c:a1e0::123",
|
||||
family: "IPv6",
|
||||
netmask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||
cidr: null,
|
||||
internal: false,
|
||||
mac: "",
|
||||
scopeid: 0,
|
||||
},
|
||||
],
|
||||
})),
|
||||
).toEqual({ addresses: ["100.120.121.122"], otherAddresses: new Set(["100.101.102.103"]) });
|
||||
});
|
||||
|
||||
test.each(["100.101.102.103", "0.0.0.0"])(
|
||||
"recognizes Tailscale through main listener %s",
|
||||
(host) => {
|
||||
const listeners = createDaemonListeners({
|
||||
http: createServer(),
|
||||
listen: `${host}:6767`,
|
||||
overridden: false,
|
||||
getMain: () => ({ type: "tcp", host, port: 6767 }),
|
||||
getTailscaleNetwork: () => ({ addresses: ["100.101.102.103"], otherAddresses: new Set() }),
|
||||
});
|
||||
expect(listeners.status().tailscale).toMatchObject({
|
||||
state: "on",
|
||||
address: "100.101.102.103:6767",
|
||||
lockedBy: "main",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
{ type: "socket", path: "/tmp/paseo.sock" },
|
||||
{ type: "pipe", path: String.raw`\\.\pipe\paseo` },
|
||||
] as const)("reports a $type main listener separately from TCP", (main) => {
|
||||
const listeners = createDaemonListeners({
|
||||
http: createServer(),
|
||||
listen: main.path,
|
||||
overridden: false,
|
||||
getMain: () => main,
|
||||
getTailscaleNetwork: () => ({ addresses: ["100.101.102.103"], otherAddresses: new Set() }),
|
||||
});
|
||||
expect(listeners.status().tailscale).toMatchObject({
|
||||
state: "off",
|
||||
address: null,
|
||||
lockedBy: "main",
|
||||
mainIsSocket: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("shows the saved Tailscale listener waiting when the host has no Tailscale interface yet", async () => {
|
||||
const address = "100.127.255.254:6767";
|
||||
const listen = `127.0.0.1:6767,${address}`;
|
||||
const listeners = createDaemonListeners({
|
||||
http: createServer(),
|
||||
listen,
|
||||
overridden: false,
|
||||
getMain: () => ({ type: "tcp", host: "127.0.0.1", port: 6767 }),
|
||||
getTailscaleNetwork: () => ({ addresses: [], otherAddresses: new Set() }),
|
||||
});
|
||||
try {
|
||||
await listeners.apply(listen);
|
||||
expect(listeners.status()).toMatchObject({
|
||||
tailscale: { ip: null, address, state: "waiting" },
|
||||
extraListeners: [{ address, state: "waiting" }],
|
||||
});
|
||||
const change = listeners.prepareTailscaleChange(listen, false, undefined, false);
|
||||
expect(change).toMatchObject({ confirmationRequired: false, listen: "127.0.0.1:6767" });
|
||||
if (change.confirmationRequired) throw new Error("Unexpected confirmation");
|
||||
await change.apply();
|
||||
expect(listeners.status()).toMatchObject({
|
||||
tailscale: { ip: null, address: null, state: "unavailable" },
|
||||
extraListeners: [],
|
||||
});
|
||||
} finally {
|
||||
await listeners.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not count an extra listener on a non-Tailscale interface in the shared range", async () => {
|
||||
const address = "100.127.255.254";
|
||||
const endpoint = `${address}:6767`;
|
||||
const listen = `127.0.0.1:6767,${endpoint}`;
|
||||
const listeners = createDaemonListeners({
|
||||
http: createServer(),
|
||||
listen,
|
||||
overridden: false,
|
||||
getMain: () => ({ type: "tcp", host: "127.0.0.1", port: 6767 }),
|
||||
getTailscaleNetwork: () => ({ addresses: [], otherAddresses: new Set([address]) }),
|
||||
});
|
||||
try {
|
||||
await listeners.apply(listen);
|
||||
expect(listeners.status(endpoint)).toMatchObject({
|
||||
tailscale: {
|
||||
ip: null,
|
||||
address: null,
|
||||
state: "unavailable",
|
||||
disconnectsCurrentConnection: false,
|
||||
},
|
||||
extraListeners: [{ address: endpoint }],
|
||||
});
|
||||
} finally {
|
||||
await listeners.stop();
|
||||
}
|
||||
});
|
||||
@@ -1,337 +0,0 @@
|
||||
import type { Server as HttpServer } from "node:http";
|
||||
import { createServer, isIPv4, type Socket } from "node:net";
|
||||
import { networkInterfaces } from "node:os";
|
||||
|
||||
export function formatHostForHttpUrl(host: string): string {
|
||||
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
}
|
||||
|
||||
export type ListenTarget =
|
||||
| { type: "tcp"; host: string; port: number }
|
||||
| { type: "socket"; path: string }
|
||||
| { type: "pipe"; path: string };
|
||||
|
||||
// Matches a Windows drive-letter path like C:\ or D:\
|
||||
const WINDOWS_DRIVE_RE = /^[A-Za-z]:\\/;
|
||||
|
||||
function parseSocketTarget(listen: string): ListenTarget | undefined {
|
||||
// Windows named pipes: \\.\pipe\... or pipe://...
|
||||
if (listen.startsWith("\\\\.\\pipe\\") || listen.startsWith("pipe://")) {
|
||||
return {
|
||||
type: "pipe",
|
||||
path: listen.startsWith("pipe://") ? listen.slice("pipe://".length) : listen,
|
||||
};
|
||||
}
|
||||
// Explicit unix:// prefix
|
||||
if (listen.startsWith("unix://")) {
|
||||
return { type: "socket", path: listen.slice(7) };
|
||||
}
|
||||
// POSIX absolute path (/ or ~) — Unix socket
|
||||
if (listen.startsWith("/") || listen.startsWith("~")) {
|
||||
return { type: "socket", path: listen };
|
||||
}
|
||||
}
|
||||
|
||||
export function parseListenString(listen: string): ListenTarget {
|
||||
const socket = parseSocketTarget(listen);
|
||||
if (socket) return socket;
|
||||
if (WINDOWS_DRIVE_RE.test(listen)) {
|
||||
throw new Error(`Invalid listen string (Windows path is not a valid listen target): ${listen}`);
|
||||
}
|
||||
// Pure numeric — TCP port on 127.0.0.1
|
||||
const trimmed = listen.trim();
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const port = parseInt(trimmed, 10);
|
||||
return { type: "tcp", host: "127.0.0.1", port };
|
||||
}
|
||||
// host:port — TCP
|
||||
if (listen.includes(":")) {
|
||||
const lastColonIdx = listen.lastIndexOf(":");
|
||||
const host = listen.slice(0, lastColonIdx);
|
||||
const portStr = listen.slice(lastColonIdx + 1);
|
||||
const parsedPort = parseInt(portStr, 10);
|
||||
if (!Number.isFinite(parsedPort)) {
|
||||
throw new Error(`Invalid port in listen string: ${listen}`);
|
||||
}
|
||||
const cleanHost = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
||||
return { type: "tcp", host: cleanHost || "127.0.0.1", port: parsedPort };
|
||||
}
|
||||
throw new Error(`Invalid listen string: ${listen}`);
|
||||
}
|
||||
|
||||
export function formatListenTarget(listenTarget: ListenTarget | null): string | null {
|
||||
if (!listenTarget) {
|
||||
return null;
|
||||
}
|
||||
if (listenTarget.type === "tcp") {
|
||||
return `${formatHostForHttpUrl(listenTarget.host)}:${listenTarget.port}`;
|
||||
}
|
||||
return listenTarget.path;
|
||||
}
|
||||
|
||||
export function splitListen(listen: string): [main: string, ...extras: string[]] {
|
||||
if (parseSocketTarget(listen)) return [listen];
|
||||
const [main = "", ...extras] = listen.split(",").map((entry) => entry.trim());
|
||||
for (const entry of extras) parseExtra(entry);
|
||||
return [main, ...new Set(extras)];
|
||||
}
|
||||
|
||||
export function getMainListenAddress(listen: string): string {
|
||||
return parseSocketTarget(listen) ? listen : listen.split(",", 1)[0].trim();
|
||||
}
|
||||
|
||||
function parseExtra(address: string) {
|
||||
const target = parseListenString(address);
|
||||
if (
|
||||
target.type !== "tcp" ||
|
||||
target.port < 1 ||
|
||||
target.port > 65535 ||
|
||||
!/^.+:\d+$/.test(address)
|
||||
) {
|
||||
throw new Error(`Invalid extra TCP listen address: ${address}`);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
export function createExtraListeners(http: HttpServer, retryMs = 2_000) {
|
||||
const active = new Map<string, ReturnType<typeof open>>();
|
||||
function open(address: string) {
|
||||
const { port, host } = parseExtra(address);
|
||||
const sockets = new Set<Socket>();
|
||||
let retry: ReturnType<typeof setTimeout> | undefined;
|
||||
let stopped = false;
|
||||
const server = createServer((socket) => {
|
||||
sockets.add(socket);
|
||||
socket.once("close", () => sockets.delete(socket));
|
||||
http.emit("connection", socket);
|
||||
});
|
||||
function listen() {
|
||||
return new Promise<void>((resolve) => {
|
||||
const settled = () => {
|
||||
server.off("listening", settled);
|
||||
server.off("error", settled);
|
||||
server.off("close", settled);
|
||||
resolve();
|
||||
};
|
||||
server.once("listening", settled);
|
||||
server.once("error", settled);
|
||||
server.once("close", settled);
|
||||
server.listen(port, host);
|
||||
});
|
||||
}
|
||||
server.on("error", () => {
|
||||
if (!stopped) retry = setTimeout(() => void listen(), retryMs).unref();
|
||||
});
|
||||
return {
|
||||
ready: listen(),
|
||||
state: () => (server.listening ? ("listening" as const) : ("waiting" as const)),
|
||||
close() {
|
||||
stopped = true;
|
||||
clearTimeout(retry);
|
||||
server.close();
|
||||
// Let the request that removed this listener queue its response first.
|
||||
setImmediate(() => {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
async apply(addresses: readonly string[]) {
|
||||
const desired = new Set(addresses);
|
||||
for (const [address, listener] of active) {
|
||||
if (desired.has(address)) continue;
|
||||
listener.close();
|
||||
active.delete(address);
|
||||
}
|
||||
for (const address of desired) {
|
||||
if (!active.has(address)) active.set(address, open(address));
|
||||
}
|
||||
await Promise.all(Array.from(active.values(), (listener) => listener.ready));
|
||||
},
|
||||
status() {
|
||||
return Array.from(active, ([address, listener]) => ({ address, state: listener.state() }));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function isTailnetIPv4(address: string) {
|
||||
const [first, second = ""] = address.split(".");
|
||||
return isIPv4(address) && first === "100" && Number(second) >= 64 && Number(second) <= 127;
|
||||
}
|
||||
|
||||
export interface TailscaleNetwork {
|
||||
addresses: readonly string[];
|
||||
otherAddresses: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
// A saved address can outlive its interface. An address assigned to a different
|
||||
// interface belongs to that interface even when it is in the shared IPv4 range.
|
||||
function isTailscaleListener(target: ReturnType<typeof parseExtra>, network: TailscaleNetwork) {
|
||||
return (
|
||||
!network.otherAddresses.has(target.host) &&
|
||||
(network.addresses.includes(target.host) || isTailnetIPv4(target.host))
|
||||
);
|
||||
}
|
||||
|
||||
export function inspectTailscaleNetwork(readInterfaces = networkInterfaces): TailscaleNetwork {
|
||||
const tailscaleAddresses: string[] = [];
|
||||
const otherAddresses = new Set<string>();
|
||||
for (const [name, addresses] of Object.entries(readInterfaces())) {
|
||||
if (!addresses) continue;
|
||||
const isTailscale =
|
||||
/^tailscale/i.test(name) ||
|
||||
addresses.some(({ address }) => address.toLowerCase().startsWith("fd7a:115c:a1e0:"));
|
||||
for (const { address } of addresses) {
|
||||
if (!isTailnetIPv4(address)) continue;
|
||||
if (isTailscale) tailscaleAddresses.push(address);
|
||||
else otherAddresses.add(address);
|
||||
}
|
||||
}
|
||||
return {
|
||||
addresses: tailscaleAddresses.filter((address) => !otherAddresses.has(address)),
|
||||
otherAddresses,
|
||||
};
|
||||
}
|
||||
|
||||
function mainTailscaleEndpoint(main: ListenTarget | null, addresses: readonly string[]) {
|
||||
if (main?.type !== "tcp") return null;
|
||||
if (addresses.includes(main.host)) return `${main.host}:${main.port}`;
|
||||
const [ip] = addresses;
|
||||
return ip && ["0.0.0.0", "::"].includes(main.host) ? `${ip}:${main.port}` : null;
|
||||
}
|
||||
|
||||
export function createDaemonListeners(options: {
|
||||
http: HttpServer;
|
||||
listen: string;
|
||||
overridden: boolean;
|
||||
getMain: () => ListenTarget | null;
|
||||
getTailscaleNetwork?: () => TailscaleNetwork;
|
||||
}) {
|
||||
const {
|
||||
http,
|
||||
listen,
|
||||
overridden,
|
||||
getMain,
|
||||
getTailscaleNetwork = inspectTailscaleNetwork,
|
||||
} = options;
|
||||
const [startupMain] = splitListen(listen);
|
||||
const extras = createExtraListeners(http);
|
||||
let stopped = false;
|
||||
|
||||
async function applyLive(addresses: readonly string[]) {
|
||||
if (!stopped) await extras.apply(addresses);
|
||||
}
|
||||
|
||||
function describeTailscale() {
|
||||
const main = getMain();
|
||||
const network = getTailscaleNetwork();
|
||||
const ip = network.addresses[0] ?? null;
|
||||
const extraListeners = extras.status();
|
||||
const configured = extraListeners.flatMap((listener) => {
|
||||
const target = parseExtra(listener.address);
|
||||
if (main?.type !== "tcp" || !isTailscaleListener(target, network)) return [];
|
||||
return [{ ...listener, target }];
|
||||
});
|
||||
const current = configured.find(
|
||||
({ state, target }) => state === "listening" && network.addresses.includes(target.host),
|
||||
);
|
||||
const shown = current ?? configured[0];
|
||||
const mainEndpoint = mainTailscaleEndpoint(main, network.addresses);
|
||||
const address = mainEndpoint ?? (shown ? formatListenTarget(shown.target) : null);
|
||||
let state: "on" | "off" | "waiting" | "unavailable" = ip ? "off" : "unavailable";
|
||||
if (shown) state = current ? "on" : "waiting";
|
||||
if (mainEndpoint) state = "on";
|
||||
|
||||
let lockedBy: "main" | "launch" | undefined;
|
||||
if (mainEndpoint || main?.type !== "tcp") lockedBy = "main";
|
||||
if (overridden) lockedBy = "launch";
|
||||
return {
|
||||
main,
|
||||
network,
|
||||
configured,
|
||||
tailscale: {
|
||||
ip,
|
||||
address,
|
||||
state,
|
||||
...(lockedBy ? { lockedBy } : {}),
|
||||
...(main && main.type !== "tcp" ? { mainIsSocket: true as const } : {}),
|
||||
},
|
||||
extraListeners,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status(localEndpoint?: string) {
|
||||
const { tailscale, configured, extraListeners } = describeTailscale();
|
||||
const disconnectsCurrentConnection =
|
||||
!tailscale.lockedBy &&
|
||||
configured.some(({ target }) => formatListenTarget(target) === localEndpoint);
|
||||
return {
|
||||
tailscale: { ...tailscale, disconnectsCurrentConnection },
|
||||
extraListeners,
|
||||
};
|
||||
},
|
||||
async apply(persisted: string | undefined) {
|
||||
const [main, ...addresses] = splitListen(overridden ? listen : (persisted ?? listen));
|
||||
const before = extras.status().map(({ address }) => address);
|
||||
const applicable = getMain()?.type === "tcp" ? addresses : [];
|
||||
await applyLive(applicable);
|
||||
return {
|
||||
restartRequired: main !== startupMain,
|
||||
applied: JSON.stringify(before) !== JSON.stringify(applicable),
|
||||
};
|
||||
},
|
||||
stop() {
|
||||
stopped = true;
|
||||
return extras.apply([]);
|
||||
},
|
||||
prepareTailscaleChange(
|
||||
persisted: string | undefined,
|
||||
enabled: boolean,
|
||||
localEndpoint: string | undefined,
|
||||
confirmed: boolean,
|
||||
) {
|
||||
const { main, network, tailscale, configured, extraListeners } = describeTailscale();
|
||||
if (stopped || tailscale.lockedBy || main?.type !== "tcp") {
|
||||
throw new Error("Tailscale listen address cannot be changed");
|
||||
}
|
||||
const [first, ...saved] = splitListen(persisted ?? listen);
|
||||
const live = extraListeners.map(({ address }) => address);
|
||||
if (enabled) {
|
||||
if (configured.length) {
|
||||
return {
|
||||
confirmationRequired: false as const,
|
||||
listen: persisted ?? listen,
|
||||
apply: () => Promise.resolve(),
|
||||
};
|
||||
}
|
||||
if (!tailscale.ip) throw new Error("Tailscale is not running");
|
||||
if (parseSocketTarget(first)) throw new Error("The configured main listener is a socket");
|
||||
const address = `${tailscale.ip}:${main.port}`;
|
||||
const add = (addresses: string[]) =>
|
||||
addresses.some((entry) => formatListenTarget(parseExtra(entry)) === address)
|
||||
? addresses
|
||||
: [...addresses, address];
|
||||
return {
|
||||
confirmationRequired: false as const,
|
||||
listen: [first, ...add(saved)].join(","),
|
||||
apply: () => applyLive(add(live)),
|
||||
};
|
||||
}
|
||||
if (
|
||||
!confirmed &&
|
||||
configured.some(({ target }) => formatListenTarget(target) === localEndpoint)
|
||||
) {
|
||||
return { confirmationRequired: true as const };
|
||||
}
|
||||
const removed = new Set(configured.map(({ address }) => address));
|
||||
const remaining = saved.filter((entry) => !isTailscaleListener(parseExtra(entry), network));
|
||||
return {
|
||||
confirmationRequired: false as const,
|
||||
listen: [first, ...remaining].join(","),
|
||||
apply: () => applyLive(live.filter((address) => !removed.has(address))),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -639,7 +639,6 @@ export interface SessionOptions {
|
||||
serverId?: string;
|
||||
daemonVersion?: string;
|
||||
daemonRuntimeConfig?: DaemonRuntimeConfig;
|
||||
getSourceLocalEndpoint?: (source: object) => string | undefined;
|
||||
getWebSocketRuntimeMetrics?: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null;
|
||||
}
|
||||
|
||||
@@ -903,7 +902,6 @@ export class Session {
|
||||
private readonly agentConfigSession: AgentConfigSession;
|
||||
private readonly projectConfigSession: ProjectConfigSession;
|
||||
private readonly daemonSession: DaemonSession;
|
||||
private readonly getSourceLocalEndpoint?: (source: object) => string | undefined;
|
||||
private readonly hubExecutionController: HubExecutionController | null;
|
||||
private readonly workspaceScripts: WorkspaceScriptsService;
|
||||
private readonly messageReceipts: Pick<MessageReceipts, "send">;
|
||||
@@ -1202,7 +1200,6 @@ export class Session {
|
||||
projectRegistry: this.projectRegistry,
|
||||
logger: this.sessionLogger,
|
||||
});
|
||||
this.getSourceLocalEndpoint = options.getSourceLocalEndpoint;
|
||||
this.daemonSession = new DaemonSession({
|
||||
host: {
|
||||
emit: (msg) => this.emit(msg),
|
||||
@@ -2751,7 +2748,7 @@ export class Session {
|
||||
this.dispatchHubExecutionMessage(msg) ??
|
||||
this.dispatchCreationMessage(msg, source) ??
|
||||
this.dispatchAgentLifecycleMessage(msg) ??
|
||||
this.dispatchConfigMessage(msg, source) ??
|
||||
this.dispatchAgentConfigMessage(msg) ??
|
||||
this.dispatchCheckoutMessage(msg) ??
|
||||
this.dispatchWorkspaceLifecycleMessage(msg) ??
|
||||
this.dispatchWorkspaceFileMessage(msg, source) ??
|
||||
@@ -3348,10 +3345,7 @@ export class Session {
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchConfigMessage(
|
||||
msg: SessionInboundMessage,
|
||||
source?: object,
|
||||
): Promise<void> | undefined {
|
||||
private dispatchAgentConfigMessage(msg: SessionInboundMessage): Promise<void> | undefined {
|
||||
switch (msg.type) {
|
||||
case "set_agent_mode_request":
|
||||
return this.agentConfigSession.handleSetAgentModeRequest(msg);
|
||||
@@ -3372,6 +3366,21 @@ export class Session {
|
||||
},
|
||||
});
|
||||
return undefined;
|
||||
case "daemon.get_status.request":
|
||||
return this.daemonSession.handleGetStatusRequest(msg);
|
||||
case "daemon.get_pairing_offer.request":
|
||||
return this.daemonSession.handleGetPairingOfferRequest(msg);
|
||||
case "daemon.config.reload.request":
|
||||
return this.daemonSession.handleConfigReloadRequest(msg);
|
||||
case "hub.management.daemon.connect.request":
|
||||
case "hub.management.daemon.get_status.request":
|
||||
case "hub.management.daemon.disconnect.request":
|
||||
case "hub.management.daemon.permissions.update.request":
|
||||
return this.daemonSession.handleHubRelationshipRequest(msg);
|
||||
case "diagnostics.request":
|
||||
return this.daemonSession.handleDiagnosticsRequest(msg);
|
||||
case "daemon.update.request":
|
||||
return this.daemonSession.handleUpdateRequest(msg);
|
||||
case "set_daemon_config_request":
|
||||
return this.daemonConfigStore.patch(msg.config).then((config) => {
|
||||
return this.emit({
|
||||
@@ -3386,39 +3395,6 @@ export class Session {
|
||||
return this.projectConfigSession.handleReadProjectConfigRequest(msg);
|
||||
case "write_project_config_request":
|
||||
return this.projectConfigSession.handleWriteProjectConfigRequest(msg);
|
||||
default:
|
||||
return this.dispatchDaemonMessage(msg, source);
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchDaemonMessage(
|
||||
msg: SessionInboundMessage,
|
||||
source?: object,
|
||||
): Promise<void> | undefined {
|
||||
switch (msg.type) {
|
||||
case "daemon.get_status.request":
|
||||
return this.daemonSession.handleGetStatusRequest(
|
||||
msg,
|
||||
source && this.getSourceLocalEndpoint?.(source),
|
||||
);
|
||||
case "daemon.tailscale.set.request":
|
||||
return this.daemonSession.handleSetTailscaleRequest(
|
||||
msg,
|
||||
source && this.getSourceLocalEndpoint?.(source),
|
||||
);
|
||||
case "daemon.get_pairing_offer.request":
|
||||
return this.daemonSession.handleGetPairingOfferRequest(msg);
|
||||
case "daemon.config.reload.request":
|
||||
return this.daemonSession.handleConfigReloadRequest(msg);
|
||||
case "hub.management.daemon.connect.request":
|
||||
case "hub.management.daemon.get_status.request":
|
||||
case "hub.management.daemon.disconnect.request":
|
||||
case "hub.management.daemon.permissions.update.request":
|
||||
return this.daemonSession.handleHubRelationshipRequest(msg);
|
||||
case "diagnostics.request":
|
||||
return this.daemonSession.handleDiagnosticsRequest(msg);
|
||||
case "daemon.update.request":
|
||||
return this.daemonSession.handleUpdateRequest(msg);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { createDaemonListeners } from "../../listeners.js";
|
||||
import type { DaemonConfigStore } from "../../daemon-config-store.js";
|
||||
import type pino from "pino";
|
||||
import type { ProviderAvailability } from "../../agent/agent-manager.js";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js";
|
||||
@@ -21,8 +19,6 @@ export interface DaemonRuntimeConfig {
|
||||
worktreesRoot?: string;
|
||||
appBaseUrl?: string;
|
||||
desktopManaged?: boolean;
|
||||
getListenStatus?: ReturnType<typeof createDaemonListeners>["status"];
|
||||
setTailscaleEnabled?: DaemonConfigStore["setTailscaleEnabled"];
|
||||
getRelayConfig(): {
|
||||
enabled: boolean;
|
||||
endpoint: string;
|
||||
@@ -180,22 +176,8 @@ export class DaemonSession {
|
||||
}
|
||||
}
|
||||
|
||||
async handleSetTailscaleRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "daemon.tailscale.set.request" }>,
|
||||
localEndpoint?: string,
|
||||
): Promise<void> {
|
||||
const setEnabled = this.daemonRuntimeConfig?.setTailscaleEnabled;
|
||||
if (!setEnabled) throw new Error("Tailscale is unavailable");
|
||||
const result = await setEnabled(msg.enabled, localEndpoint, msg.confirmed === true);
|
||||
this.host.emit({
|
||||
type: "daemon.tailscale.set.response",
|
||||
payload: { requestId: msg.requestId, ...result },
|
||||
});
|
||||
}
|
||||
|
||||
async handleGetStatusRequest(
|
||||
msg: Extract<SessionInboundMessage, { type: "daemon.get_status.request" }>,
|
||||
localEndpoint?: string,
|
||||
): Promise<void> {
|
||||
// Read outside the degraded-status fallback below: a status that cannot say whether
|
||||
// terminal cleanup finished must fail the request, not report that nothing is left.
|
||||
@@ -205,9 +187,7 @@ export class DaemonSession {
|
||||
const terminalsUnavailable = this.getTerminalsUnavailable();
|
||||
try {
|
||||
const pidInfo = await getPidLockInfo(this.paseoHome);
|
||||
const availability =
|
||||
msg.includeProviders === false ? [] : await this.listProviderAvailability();
|
||||
const providers = availability.map((p) => ({
|
||||
const providers = (await this.listProviderAvailability()).map((p) => ({
|
||||
provider: p.provider,
|
||||
available: p.available,
|
||||
error: p.error ?? null,
|
||||
@@ -225,7 +205,6 @@ export class DaemonSession {
|
||||
relay: this.daemonRuntimeConfig?.getRelayConfig() ?? null,
|
||||
providers,
|
||||
terminalCleanupUnconfirmed,
|
||||
...this.daemonRuntimeConfig?.getListenStatus?.(localEndpoint),
|
||||
...(terminalsUnavailable ? { terminalsUnavailable } : {}),
|
||||
},
|
||||
});
|
||||
@@ -244,7 +223,6 @@ export class DaemonSession {
|
||||
relay: null,
|
||||
providers: [],
|
||||
terminalCleanupUnconfirmed,
|
||||
...this.daemonRuntimeConfig?.getListenStatus?.(localEndpoint),
|
||||
...(terminalsUnavailable ? { terminalsUnavailable } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -14,17 +14,14 @@ import type { AgentClient, AgentProvider } from "../agent/agent-sdk-types.js";
|
||||
import { createTestAgentClients } from "./fake-agent-client.js";
|
||||
import type { PushNotificationSender } from "../push/index.js";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import type { TailscaleNetwork } from "../listeners.js";
|
||||
|
||||
interface TestPaseoDaemonOptions {
|
||||
daemonVersion?: string;
|
||||
desktopManaged?: boolean;
|
||||
downloadTokenTtlMs?: number;
|
||||
corsAllowedOrigins?: string[];
|
||||
hostnames?: PaseoDaemonConfig["hostnames"];
|
||||
listen?: string;
|
||||
listenPort?: number;
|
||||
getTailscaleNetwork?: () => TailscaleNetwork;
|
||||
logger?: Parameters<typeof createPaseoDaemon>[1];
|
||||
mcpEnabled?: boolean;
|
||||
mcpDebug?: boolean;
|
||||
@@ -113,7 +110,6 @@ export async function createTestPaseoDaemon(
|
||||
await prepareTestDaemonConfig(options);
|
||||
const logger = options.logger ?? pino({ level: "silent" });
|
||||
const daemon = await createPaseoDaemon(config, logger, {
|
||||
getTailscaleNetwork: options.getTailscaleNetwork,
|
||||
builtinPlugins: options.builtinPlugins ?? new BuiltinPluginLoader(undefined, []),
|
||||
lazyTerminalWorker: options.lazyTerminalWorker ?? true,
|
||||
serverFeatureOverrides: {
|
||||
@@ -199,7 +195,7 @@ async function prepareTestDaemonConfig(
|
||||
daemonVersion: options.daemonVersion,
|
||||
desktopManaged: options.desktopManaged,
|
||||
corsAllowedOrigins: options.corsAllowedOrigins ?? [],
|
||||
hostnames: options.hostnames ?? true,
|
||||
hostnames: true,
|
||||
mcpEnabled: options.mcpEnabled ?? true,
|
||||
staticDir,
|
||||
mcpDebug: options.mcpDebug ?? false,
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createTestPaseoDaemon } from "./paseo-daemon.js";
|
||||
|
||||
const [, , origin] = process.argv;
|
||||
if (!origin) throw new Error("Expected the app origin");
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
corsAllowedOrigins: [origin],
|
||||
getTailscaleNetwork: () => ({ addresses: ["127.0.0.2"], otherAddresses: new Set() }),
|
||||
});
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(daemon.paseoHome, "config.json"),
|
||||
JSON.stringify({ version: 1, daemon: { listen: `127.0.0.1:${daemon.port}` } }),
|
||||
);
|
||||
process.once("SIGTERM", async () => {
|
||||
await daemon.close();
|
||||
process.exit(0);
|
||||
});
|
||||
process.send?.({ port: daemon.port, serverId: daemon.daemon.getServerId() });
|
||||
} catch (error) {
|
||||
await daemon.close();
|
||||
throw error;
|
||||
}
|
||||
@@ -579,7 +579,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
private readonly hostLinks = new Map<WebSocketLike, DaemonLinkEndpoint>();
|
||||
private readonly pendingConnections: Map<WebSocketLike, PendingConnection> = new Map();
|
||||
private readonly sessions: Map<WebSocketLike, SessionConnection> = new Map();
|
||||
private readonly socketLocalEndpoints = new WeakMap<object, string>();
|
||||
private readonly socketIdentities: Map<WebSocketLike, WebSocketConnectionIdentity> = new Map();
|
||||
private readonly externalSessionsByKey: Map<string, ReconnectableSessionConnection> = new Map();
|
||||
private readonly pluginSocketIds = new WeakMap<WebSocketLike, string>();
|
||||
@@ -1557,8 +1556,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
|
||||
const requestMetadata = extractSocketRequestMetadata(request);
|
||||
const identity = createWebSocketConnectionIdentity(requestMetadata, metadata);
|
||||
if (requestMetadata.localEndpoint)
|
||||
this.socketLocalEndpoints.set(ws, requestMetadata.localEndpoint);
|
||||
this.socketIdentities.set(ws, identity);
|
||||
const connectionLogger = this.logger.child(toConnectionLogFields(identity));
|
||||
|
||||
@@ -1694,7 +1691,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
private createSocketSession(options: SocketSessionOptions): Session {
|
||||
return new Session({
|
||||
connectedHosts: this.connectedHosts,
|
||||
getSourceLocalEndpoint: (source) => this.socketLocalEndpoints.get(source),
|
||||
getConnectedHostBufferedAmount: () => {
|
||||
let total = 0;
|
||||
for (const socket of this.sessions.keys()) {
|
||||
@@ -2143,10 +2139,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
...(this.advertiseDaemonStatusRpc ? { daemonStatusRpc: true } : {}),
|
||||
// COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14.
|
||||
daemonConfigReload: true,
|
||||
// COMPAT(tailscale): added in v0.16.0, remove after 2027-05-25 once daemon floor >= v0.16.0.
|
||||
...(this.advertiseDaemonStatusRpc && this.daemonRuntimeConfig?.setTailscaleEnabled
|
||||
? { tailscale: true }
|
||||
: {}),
|
||||
// COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18.
|
||||
speechSettings: true,
|
||||
// COMPAT(relayConfig): added in v0.2.6, remove gate after 2027-01-31.
|
||||
@@ -3188,7 +3180,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
}
|
||||
|
||||
interface SocketRequestMetadata {
|
||||
localEndpoint?: string;
|
||||
host?: string;
|
||||
origin?: string;
|
||||
userAgent?: string;
|
||||
@@ -3266,8 +3257,6 @@ function extractSocketRequestMetadata(request: unknown): SocketRequestMetadata {
|
||||
url?: unknown;
|
||||
socket?: {
|
||||
remoteAddress?: unknown;
|
||||
localAddress?: unknown;
|
||||
localPort?: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -3279,10 +3268,6 @@ function extractSocketRequestMetadata(request: unknown): SocketRequestMetadata {
|
||||
typeof record.socket?.remoteAddress === "string" ? record.socket.remoteAddress : undefined;
|
||||
|
||||
return {
|
||||
...(typeof record.socket?.localAddress === "string" &&
|
||||
typeof record.socket.localPort === "number"
|
||||
? { localEndpoint: `${record.socket.localAddress}:${record.socket.localPort}` }
|
||||
: {}),
|
||||
...(host ? { host } : {}),
|
||||
...(origin ? { origin } : {}),
|
||||
...(userAgent ? { userAgent } : {}),
|
||||
|
||||
@@ -137,6 +137,36 @@ test("a fresh checkout read makes a newly initialized repository available to ca
|
||||
expect(realpathSync.native(repoRoot)).toBe(realpathSync.native(repo));
|
||||
}, 30_000);
|
||||
|
||||
test("a checkout read for reconciliation never scans the working tree", async () => {
|
||||
const root = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-checkout-read-")));
|
||||
const repo = path.join(root, "repo");
|
||||
mkdirSync(repo);
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: repo, stdio: "pipe" });
|
||||
git("init", "-b", "main");
|
||||
git("config", "user.email", "test@example.com");
|
||||
git("config", "user.name", "Test");
|
||||
writeFileSync(path.join(repo, "README.md"), "base\n");
|
||||
git("add", ".");
|
||||
git("commit", "-m", "base");
|
||||
const service = new WorkspaceGitServiceImpl({
|
||||
logger: pino({ enabled: false }),
|
||||
paseoHome: path.join(root, "home"),
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await service.dispose();
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
startGitCommandMetrics();
|
||||
const checkout = await service.getCheckout(repo, { priority: "background" });
|
||||
const verbs = stopGitCommandMetrics().commands.map((command) => command.args[0]);
|
||||
|
||||
expect(checkout).toMatchObject({ isGit: true, currentBranch: "main" });
|
||||
expect(verbs.length).toBeGreaterThan(0);
|
||||
expect(verbs.filter((verb) => ["status", "ls-files", "rev-list"].includes(verb))).toEqual([]);
|
||||
}, 30_000);
|
||||
|
||||
test("recursive observation updates tracked state and prunes ignored storms", async () => {
|
||||
const tempDir = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-git-observation-")));
|
||||
const repoDir = path.join(tempDir, "repo");
|
||||
|
||||
@@ -429,7 +429,7 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => {
|
||||
|
||||
test("getCheckout surfaces an unexpected Git read failure", async () => {
|
||||
const service = createService({
|
||||
getCheckoutStatus: vi.fn(async () => {
|
||||
getCheckoutIdentity: vi.fn(async () => {
|
||||
throw new Error("Git read failed");
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ import pLimit from "p-limit";
|
||||
import type pino from "pino";
|
||||
import type { ForgeWeb, ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages";
|
||||
import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote";
|
||||
import type { CheckoutReadSession } from "../utils/checkout-read-session.js";
|
||||
import type { CheckoutContext, UpstreamState } from "../utils/checkout-git.js";
|
||||
import {
|
||||
type BranchCheckoutResolution,
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
getCheckoutRefDerivedState,
|
||||
getCheckoutSnapshotFacts,
|
||||
getCheckoutShortstat,
|
||||
getCheckoutIdentity,
|
||||
getCheckoutStatus,
|
||||
getCheckoutWorktreeState,
|
||||
getPullRequestStatus,
|
||||
@@ -367,6 +369,7 @@ export type WorkspaceGitSnapshotOptions =
|
||||
type WorkspaceGitRefreshOrigin = "demand" | "observation";
|
||||
|
||||
export interface WorkspaceGitCheckoutReadOptions {
|
||||
readSession?: CheckoutReadSession;
|
||||
/** Git lane for the fresh checkout read; defaults to the caller's ambient lane. */
|
||||
priority?: GitProcessPriority;
|
||||
}
|
||||
@@ -417,6 +420,7 @@ interface WorkspaceGitServiceDependencies {
|
||||
subscribe: SubscribeToFileChanges;
|
||||
getCheckoutSnapshotFacts: typeof getCheckoutSnapshotFacts;
|
||||
getCheckoutRefDerivedState: typeof getCheckoutRefDerivedState;
|
||||
getCheckoutIdentity: typeof getCheckoutIdentity;
|
||||
getCheckoutStatus: typeof getCheckoutStatus;
|
||||
getCheckoutShortstat: typeof getCheckoutShortstat;
|
||||
getCheckoutWorktreeState: typeof getCheckoutWorktreeState;
|
||||
@@ -637,6 +641,7 @@ function buildDefaultWorkspaceGitServiceDeps(
|
||||
subscribe,
|
||||
getCheckoutSnapshotFacts,
|
||||
getCheckoutRefDerivedState,
|
||||
getCheckoutIdentity,
|
||||
getCheckoutStatus,
|
||||
getCheckoutShortstat,
|
||||
getCheckoutWorktreeState,
|
||||
@@ -875,16 +880,17 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
): Promise<ProjectCheckoutLitePayload> {
|
||||
this.assertNotDisposed();
|
||||
const normalizedCwd = resolve(cwd);
|
||||
const status = await this.deps.getCheckoutStatus(normalizedCwd, {
|
||||
const identity = await this.deps.getCheckoutIdentity(normalizedCwd, {
|
||||
paseoHome: this.paseoHome,
|
||||
worktreesRoot: this.worktreesRoot,
|
||||
logger: this.logger,
|
||||
readSession: options?.readSession,
|
||||
...(options?.priority
|
||||
? { runGitCommand: createRunGitCommand("checkout-read", { priority: options.priority }) }
|
||||
: {}),
|
||||
});
|
||||
const cached = this.getCachedSnapshot(normalizedCwd);
|
||||
if (cached && cached.git.isGit !== status.isGit) {
|
||||
if (cached && cached.git.isGit !== identity.isGit) {
|
||||
// A fresh checkout read discovered a repository transition. Keep the
|
||||
// shared snapshot current before exposing the new project capability.
|
||||
await this.getSnapshot(normalizedCwd, {
|
||||
@@ -893,7 +899,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
reason: "checkout-classification-changed",
|
||||
});
|
||||
}
|
||||
if (!status.isGit) {
|
||||
if (!identity.isGit) {
|
||||
return checkoutLiteFromGitSnapshot(normalizedCwd, {
|
||||
isGit: false,
|
||||
currentBranch: null,
|
||||
@@ -905,11 +911,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
}
|
||||
return checkoutLiteFromGitSnapshot(normalizedCwd, {
|
||||
isGit: true,
|
||||
currentBranch: status.currentBranch,
|
||||
remoteUrl: status.remoteUrl,
|
||||
repoRoot: status.repoRoot,
|
||||
isPaseoOwnedWorktree: status.isPaseoOwnedWorktree,
|
||||
mainRepoRoot: status.mainRepoRoot,
|
||||
currentBranch: identity.currentBranch,
|
||||
remoteUrl: identity.remoteUrl,
|
||||
repoRoot: identity.repoRoot,
|
||||
isPaseoOwnedWorktree: identity.isPaseoOwnedWorktree,
|
||||
mainRepoRoot: identity.mainRepoRoot,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages";
|
||||
@@ -6,6 +7,10 @@ import { afterEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { createTestLogger } from "../test-utils/test-logger.js";
|
||||
import { areEquivalentPaths } from "../utils/path.js";
|
||||
import {
|
||||
WorkspaceGitServiceImpl,
|
||||
type WorkspaceGitCheckoutReadOptions,
|
||||
} from "./workspace-git-service.js";
|
||||
import { deriveProjectKey } from "./project-key.js";
|
||||
import {
|
||||
createPersistedProjectRecord,
|
||||
@@ -175,10 +180,19 @@ class ObservedPlacements {
|
||||
private readonly service: WorkspaceReconciliationService;
|
||||
private started = false;
|
||||
private checkoutReadCount = 0;
|
||||
private readonly checkoutReadCwds: string[] = [];
|
||||
|
||||
constructor(private readonly specs: ProjectSpec[]) {
|
||||
private readonly gitService: WorkspaceGitServiceImpl | null;
|
||||
|
||||
constructor(
|
||||
private readonly specs: ProjectSpec[],
|
||||
realGit = false,
|
||||
) {
|
||||
cleanupPaths.push(this.home);
|
||||
const logger = createTestLogger();
|
||||
this.gitService = realGit
|
||||
? new WorkspaceGitServiceImpl({ logger, paseoHome: this.absolute("paseo-home") })
|
||||
: null;
|
||||
this.projects = new ObservedProjectRegistry(path.join(this.home, "projects.json"), logger);
|
||||
this.workspaces = new ObservedWorkspaceRegistry(
|
||||
path.join(this.home, "workspaces.json"),
|
||||
@@ -194,7 +208,7 @@ class ObservedPlacements {
|
||||
this.service = new WorkspaceReconciliationService({
|
||||
projectRegistry: this.projects,
|
||||
workspaceRegistry: this.workspaces,
|
||||
workspaceGitService: { getCheckout: async (cwd) => this.readCheckout(cwd) },
|
||||
workspaceGitService: { getCheckout: async (cwd, options) => this.readCheckout(cwd, options) },
|
||||
logger,
|
||||
watchProjectRoot,
|
||||
clock: this.clock,
|
||||
@@ -248,6 +262,31 @@ class ObservedPlacements {
|
||||
this.activeWatch(root)?.onChange("rename", filename);
|
||||
}
|
||||
|
||||
git(root: string, ...args: string[]): void {
|
||||
execFileSync("git", args, { cwd: this.absolute(root), stdio: "pipe" });
|
||||
}
|
||||
|
||||
rename(from: string, to: string): void {
|
||||
renameSync(this.absolute(from), this.absolute(to));
|
||||
}
|
||||
|
||||
link(alias: string, target: string): void {
|
||||
symlinkSync(
|
||||
this.absolute(target),
|
||||
this.absolute(alias),
|
||||
process.platform === "win32" ? "junction" : "dir",
|
||||
);
|
||||
}
|
||||
|
||||
async project(projectId: string) {
|
||||
return this.projects.get(projectId);
|
||||
}
|
||||
|
||||
async disposeGit(): Promise<void> {
|
||||
this.dispose();
|
||||
await this.gitService?.dispose();
|
||||
}
|
||||
|
||||
makeProjectGit(projectId: string, branch = "main"): void {
|
||||
const rootPath = this.rootByProjectId.get(projectId);
|
||||
if (!rootPath) throw new Error(`Unknown project: ${projectId}`);
|
||||
@@ -324,6 +363,11 @@ class ObservedPlacements {
|
||||
return this.checkoutReadCount;
|
||||
}
|
||||
|
||||
/** Home-relative directories read since the last call, with portable separators. */
|
||||
takeCheckoutReads(): string[] {
|
||||
return this.checkoutReadCwds.splice(0).sort();
|
||||
}
|
||||
|
||||
get pendingTimers(): number {
|
||||
return this.clock.pendingCount;
|
||||
}
|
||||
@@ -368,8 +412,13 @@ class ObservedPlacements {
|
||||
}
|
||||
}
|
||||
|
||||
private async readCheckout(cwd: string): Promise<ProjectCheckoutLitePayload> {
|
||||
private async readCheckout(
|
||||
cwd: string,
|
||||
options?: WorkspaceGitCheckoutReadOptions,
|
||||
): Promise<ProjectCheckoutLitePayload> {
|
||||
this.checkoutReadCount += 1;
|
||||
this.checkoutReadCwds.push(path.relative(this.home, cwd).split(path.sep).join("/"));
|
||||
if (this.gitService) return this.gitService.getCheckout(cwd, options);
|
||||
const configured = [...this.checkoutByCwd.entries()].find(([root]) =>
|
||||
areEquivalentPaths(root, cwd),
|
||||
)?.[1];
|
||||
@@ -398,6 +447,18 @@ class ObservedPlacements {
|
||||
}
|
||||
}
|
||||
|
||||
/** Projects `a`, `b` and `c`, each rooted at `repo-<name>` with its own worktrees. */
|
||||
function threeProjects(worktreeCount: number): ProjectSpec[] {
|
||||
return ["a", "b", "c"].map((name) => ({
|
||||
id: `project-${name}`,
|
||||
root: `repo-${name}`,
|
||||
workspaces: Array.from({ length: worktreeCount }, (_, index) => ({
|
||||
id: `${name}${index + 1}`,
|
||||
cwd: `repo-${name}/worktree-${index + 1}`,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
describe("observed workspace placement", () => {
|
||||
test("installs and publishes a new project before add resolves without Git feedback", async () => {
|
||||
const observed = new ObservedPlacements([]);
|
||||
@@ -462,6 +523,329 @@ describe("observed workspace placement", () => {
|
||||
observed.dispose();
|
||||
});
|
||||
|
||||
test("reads only the workspaces of the project whose Git directory changed", async () => {
|
||||
const observed = new ObservedPlacements(threeProjects(3));
|
||||
await observed.start();
|
||||
|
||||
observed.change("repo-b", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(observed.takeCheckoutReads()).toEqual([
|
||||
"repo-b",
|
||||
"repo-b/worktree-1",
|
||||
"repo-b/worktree-2",
|
||||
"repo-b/worktree-3",
|
||||
]);
|
||||
observed.dispose();
|
||||
});
|
||||
|
||||
test("updates nested projects and workspaces when a parent directory becomes a Git repository", async () => {
|
||||
const observed = new ObservedPlacements([
|
||||
{ id: "parent", root: "repo", workspaces: [{ id: "parent-ws", cwd: "repo" }] },
|
||||
{ id: "nested", root: "repo/sub", workspaces: [{ id: "nested-ws", cwd: "repo/sub" }] },
|
||||
{ id: "outside", root: "outside", workspaces: [{ id: "attached-ws", cwd: "repo/sub" }] },
|
||||
{ id: "unrelated", root: "repo-other" },
|
||||
]);
|
||||
await observed.start();
|
||||
try {
|
||||
observed.makeProjectGit("parent");
|
||||
observed.makeProjectGit("nested");
|
||||
|
||||
observed.change("repo", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(observed.projectUpdates).toContainEqual({
|
||||
kind: "upsert",
|
||||
project: expect.objectContaining({ projectId: "nested", kind: "git" }),
|
||||
});
|
||||
expect(await observed.placement("nested-ws")).toMatchObject({ kind: "local_checkout" });
|
||||
expect(await observed.placement("attached-ws")).toMatchObject({ kind: "local_checkout" });
|
||||
expect(observed.workspaceBatches.map((batch) => batch.sort())).toEqual([
|
||||
["attached-ws", "nested-ws", "parent-ws"],
|
||||
]);
|
||||
expect(observed.takeCheckoutReads()).toEqual(["repo", "repo/sub"]);
|
||||
} finally {
|
||||
observed.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test("updates a separately registered directory alias when its parent becomes a Git repo", async () => {
|
||||
const observed = new ObservedPlacements([{ id: "repo", root: "repo" }], true);
|
||||
try {
|
||||
await observed.start();
|
||||
await observed.add({ id: "sub", root: "repo/sub" });
|
||||
observed.link("alias", "repo/sub");
|
||||
await observed.add({
|
||||
id: "alias",
|
||||
root: "alias",
|
||||
workspaces: [{ id: "alias-ws", cwd: "alias" }],
|
||||
});
|
||||
const savedProject = await observed.project("alias");
|
||||
const savedWorkspace = await observed.placement("alias-ws");
|
||||
observed.git("repo", "init", "-b", "main");
|
||||
observed.change("repo", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(await observed.project("alias")).toMatchObject({
|
||||
kind: "git",
|
||||
rootPath: savedProject?.rootPath,
|
||||
});
|
||||
expect(await observed.placement("alias-ws")).toMatchObject({
|
||||
kind: "local_checkout",
|
||||
cwd: savedWorkspace?.cwd,
|
||||
});
|
||||
expect(observed.workspaceBatches.flat()).toContain("alias-ws");
|
||||
} finally {
|
||||
await observed.disposeGit();
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["removal", "replacement"])(
|
||||
"updates a separately registered linked worktree after updates and metadata %s",
|
||||
async (change) => {
|
||||
const observed = new ObservedPlacements(
|
||||
[
|
||||
{ id: "repo", root: "repo", workspaces: [{ id: "main-ws", cwd: "repo" }] },
|
||||
{
|
||||
id: "unrelated",
|
||||
root: "repo-other",
|
||||
workspaces: [{ id: "other-ws", cwd: "repo-other" }],
|
||||
},
|
||||
],
|
||||
true,
|
||||
);
|
||||
try {
|
||||
await observed.start();
|
||||
observed.git("repo", "init", "-b", "main");
|
||||
observed.git(
|
||||
"repo",
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"commit",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
"initial",
|
||||
);
|
||||
observed.git("repo", "remote", "add", "origin", "https://github.com/acme/old.git");
|
||||
observed.git("repo", "worktree", "add", "-b", "feature", "../linked");
|
||||
await observed.add({
|
||||
id: "linked",
|
||||
root: "linked",
|
||||
workspaces: [{ id: "linked-ws", cwd: "linked" }],
|
||||
});
|
||||
observed.git("repo-other", "init", "-b", "main");
|
||||
observed.change("linked", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
expect(await observed.placement("linked-ws")).toMatchObject({ branch: "feature" });
|
||||
const oldKey = (await observed.project("linked"))?.projectKey;
|
||||
observed.takeCheckoutReads();
|
||||
|
||||
observed.git("repo", "remote", "set-url", "origin", "https://github.com/acme/new.git");
|
||||
observed.git("repo", "branch", "-m", "feature", "renamed");
|
||||
observed.change("repo", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(await observed.placement("linked-ws")).toMatchObject({ branch: "renamed" });
|
||||
const linkedProject = await observed.project("linked");
|
||||
expect(linkedProject?.projectKey).toEqual((await observed.project("repo"))?.projectKey);
|
||||
expect(linkedProject?.projectKey).not.toEqual(oldKey);
|
||||
expect(observed.takeCheckoutReads()).toEqual(["linked", "repo"]);
|
||||
expect(await observed.project("unrelated")).toMatchObject({ kind: "non_git" });
|
||||
expect(await observed.placement("other-ws")).toMatchObject({ kind: "directory" });
|
||||
|
||||
observed.rename("repo/.git", "repo/.git-backup");
|
||||
if (change === "replacement") observed.git("repo", "init", "-b", "main");
|
||||
observed.change("repo", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(await observed.project("linked")).toMatchObject({ kind: "non_git" });
|
||||
expect(await observed.placement("linked-ws")).toMatchObject({ kind: "directory" });
|
||||
expect(observed.takeCheckoutReads()).toEqual(["linked", "repo"]);
|
||||
} finally {
|
||||
await observed.disposeGit();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("skips independent nested repositories and workspaces attached from other repositories", async () => {
|
||||
const observed = new ObservedPlacements(
|
||||
[
|
||||
{
|
||||
id: "outer",
|
||||
root: "outer",
|
||||
workspaces: [
|
||||
{ id: "outer-ws", cwd: "outer" },
|
||||
{ id: "foreign-ws", cwd: "foreign" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "nested",
|
||||
root: "outer/independent",
|
||||
workspaces: [
|
||||
{ id: "nested-ws", cwd: "outer/independent" },
|
||||
{ id: "nested-linked-ws", cwd: "independent-linked" },
|
||||
],
|
||||
},
|
||||
],
|
||||
true,
|
||||
);
|
||||
try {
|
||||
await observed.start();
|
||||
for (const root of ["outer", "outer/independent", "foreign"]) {
|
||||
observed.git(root, "init", "-b", "main");
|
||||
}
|
||||
observed.git(
|
||||
"outer/independent",
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
"initial",
|
||||
);
|
||||
observed.git(
|
||||
"outer/independent",
|
||||
"worktree",
|
||||
"add",
|
||||
"-b",
|
||||
"feature",
|
||||
"../../independent-linked",
|
||||
);
|
||||
observed.change("outer", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(observed.takeCheckoutReads()).toEqual(["outer"]);
|
||||
expect(await observed.placement("outer-ws")).toMatchObject({ kind: "local_checkout" });
|
||||
for (const id of ["foreign-ws", "nested-ws", "nested-linked-ws"]) {
|
||||
expect(await observed.placement(id)).toMatchObject({ kind: "directory" });
|
||||
}
|
||||
} finally {
|
||||
await observed.disposeGit();
|
||||
}
|
||||
});
|
||||
|
||||
test("skips a submodule and its linked checkout when the parent Git directory is intact", async () => {
|
||||
const observed = new ObservedPlacements(
|
||||
[{ id: "outer", root: "outer", workspaces: [{ id: "outer-ws", cwd: "outer" }] }],
|
||||
true,
|
||||
);
|
||||
try {
|
||||
await observed.start();
|
||||
await observed.add({ id: "source", root: "source" });
|
||||
observed.git("source", "init", "-b", "main");
|
||||
observed.git(
|
||||
"source",
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
"initial",
|
||||
);
|
||||
observed.git("outer", "init", "-b", "main");
|
||||
observed.git(
|
||||
"outer",
|
||||
"-c",
|
||||
"protocol.file.allow=always",
|
||||
"submodule",
|
||||
"add",
|
||||
"../source",
|
||||
"sub",
|
||||
);
|
||||
observed.git("outer/sub", "worktree", "add", "-b", "feature", "../../sub-linked");
|
||||
await observed.add({ id: "sub", root: "outer/sub" });
|
||||
await observed.add({ id: "sub-linked", root: "sub-linked" });
|
||||
|
||||
observed.change("outer", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(observed.takeCheckoutReads()).toEqual(["outer"]);
|
||||
observed.rename("outer/.git", "outer/.git-backup");
|
||||
observed.change("outer", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(observed.takeCheckoutReads()).toEqual(["outer", "outer/sub", "sub-linked"]);
|
||||
} finally {
|
||||
await observed.disposeGit();
|
||||
}
|
||||
});
|
||||
|
||||
test("turns Git changes under several roots into one read per changed root", async () => {
|
||||
const observed = new ObservedPlacements(threeProjects(1));
|
||||
await observed.start();
|
||||
|
||||
for (const root of ["repo-a", "repo-c", "repo-a", "repo-c", "repo-a"]) {
|
||||
observed.change(root, ".git");
|
||||
}
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(observed.takeCheckoutReads()).toEqual([
|
||||
"repo-a",
|
||||
"repo-a/worktree-1",
|
||||
"repo-c",
|
||||
"repo-c/worktree-1",
|
||||
]);
|
||||
observed.dispose();
|
||||
});
|
||||
|
||||
test("a change that lands during a pass queues a pass for only that root", async () => {
|
||||
const observed = new ObservedPlacements(threeProjects(1));
|
||||
await observed.start();
|
||||
observed.makeProjectGit("project-a");
|
||||
observed.makeProjectGit("project-b");
|
||||
const firstPassRead = observed.holdNextReconciliation();
|
||||
const firstBatch = observed.waitForWorkspaceBatch();
|
||||
const secondBatch = firstBatch.then(() => observed.waitForWorkspaceBatch());
|
||||
|
||||
observed.change("repo-a", ".git");
|
||||
const firstPass = observed.advanceBy(DEBOUNCE_MS);
|
||||
await firstPassRead.started;
|
||||
observed.change("repo-b", ".git");
|
||||
observed.change("repo-b", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
firstPassRead.release();
|
||||
await firstPass;
|
||||
await secondBatch;
|
||||
|
||||
expect(observed.workspaceBatches).toEqual([["a1"], ["b1"]]);
|
||||
expect(observed.takeCheckoutReads()).toEqual([
|
||||
"repo-a",
|
||||
"repo-a/worktree-1",
|
||||
"repo-b",
|
||||
"repo-b/worktree-1",
|
||||
]);
|
||||
observed.dispose();
|
||||
});
|
||||
|
||||
test("keeps the changed roots of a failed pass for the next one", async () => {
|
||||
const observed = new ObservedPlacements([
|
||||
{ id: "project-a", root: "repo-a", workspaces: [{ id: "a1", cwd: "repo-a" }] },
|
||||
{ id: "project-b", root: "repo-b", workspaces: [{ id: "b1", cwd: "repo-b" }] },
|
||||
]);
|
||||
await observed.start();
|
||||
observed.makeProjectGit("project-a");
|
||||
observed.failNextReconciliation(new Error("registry unavailable"));
|
||||
|
||||
observed.change("repo-a", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
observed.change("repo-b", ".git");
|
||||
await observed.advanceBy(DEBOUNCE_MS);
|
||||
|
||||
expect(observed.takeCheckoutReads()).toEqual(["repo-a", "repo-b"]);
|
||||
expect((await observed.placement("a1"))?.kind).toBe("local_checkout");
|
||||
observed.dispose();
|
||||
});
|
||||
|
||||
test("recovers errored and temporarily unavailable watchers on the periodic pass", async () => {
|
||||
const observed = new ObservedPlacements([
|
||||
{ id: "project-errored", root: "errored" },
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { watch as watchPath } from "node:fs";
|
||||
import { realpath, watch as watchPath } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
import { setImmediate as yieldToLoop } from "node:timers/promises";
|
||||
import pLimit from "p-limit";
|
||||
import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages";
|
||||
@@ -11,15 +13,20 @@ import type {
|
||||
PersistedWorkspaceRecord,
|
||||
} from "./workspace-registry.js";
|
||||
import type { WorkspaceGitService } from "./workspace-git-service.js";
|
||||
import { areEquivalentPaths } from "../utils/path.js";
|
||||
import { areEquivalentPaths, createPathContainmentMatcher } from "../utils/path.js";
|
||||
import {
|
||||
deriveProjectKind,
|
||||
reconcileWorkspacePlacement,
|
||||
type MutableWorkspacePlacement,
|
||||
} from "./workspace-registry-model.js";
|
||||
import { workspaceIdsForProjects } from "./workspace-directory.js";
|
||||
import { CheckoutReadSession } from "../utils/checkout-read-session.js";
|
||||
import { getGitCommonDirForWorktreeRoot } from "../utils/worktree-metadata.js";
|
||||
import { deriveProjectKey } from "./project-key.js";
|
||||
|
||||
const resolveRealpath = promisify(realpath);
|
||||
const resolveNativeRealpath = promisify(realpath.native);
|
||||
|
||||
const DEFAULT_RESCAN_INTERVAL_MS = 5 * 60_000;
|
||||
const DEFAULT_DEBOUNCE_MS = 100;
|
||||
const INSPECTION_CONCURRENCY = 2;
|
||||
@@ -110,7 +117,7 @@ export interface WorkspaceReconciliationServiceOptions {
|
||||
interface ProjectReconciliationInput {
|
||||
project: PersistedProjectRecord;
|
||||
siblings: PersistedWorkspaceRecord[];
|
||||
currentGit: ProjectCheckoutLitePayload;
|
||||
currentGit: ProjectCheckoutLitePayload | null;
|
||||
readCheckout: (cwd: string) => Promise<ProjectCheckoutLitePayload>;
|
||||
changes: ReconciliationChange[];
|
||||
}
|
||||
@@ -120,15 +127,27 @@ interface CachedCheckoutRead {
|
||||
checkout: Promise<ProjectCheckoutLitePayload>;
|
||||
}
|
||||
|
||||
interface ResolvedPath {
|
||||
path: string;
|
||||
missing: boolean;
|
||||
}
|
||||
|
||||
interface CheckoutDirectory {
|
||||
path: string;
|
||||
repository: { root: string; commonDir: ResolvedPath } | null;
|
||||
}
|
||||
|
||||
type DirectoryInspection = DirectoryState | CheckoutDirectory;
|
||||
|
||||
export type DirectoryState = "directory" | "missing" | "unreadable";
|
||||
|
||||
export class WorkspaceReconciliationService {
|
||||
// Timed-out fs operations retain their slot until the OS returns. Never use
|
||||
// the deadline to admit more work into libuv's shared threadpool.
|
||||
private readonly timedOutPaths = new Set<string>();
|
||||
private readonly timedOutPaths = new Map<string, string>();
|
||||
private inspectionSaturated = false;
|
||||
private readonly inspectionWaiters = new Set<() => void>();
|
||||
private readonly pendingInspections = new Map<string, Promise<DirectoryState>>();
|
||||
private readonly pendingInspections = new Map<string, Promise<DirectoryInspection>>();
|
||||
private readonly directoryInspection: (targetPath: string) => Promise<DirectoryState>;
|
||||
private readonly inspectionTimeoutMs: number;
|
||||
private readonly serverId: string | undefined;
|
||||
@@ -151,6 +170,9 @@ export class WorkspaceReconciliationService {
|
||||
private disposed = false;
|
||||
private started = false;
|
||||
private reconciling = false;
|
||||
// Project roots whose `.git` changed since the last observed pass. A metadata
|
||||
// pass reads only these; the periodic full pass covers everything else.
|
||||
private readonly changedRoots = new Set<string>();
|
||||
private reconcileQueuedMode: "metadata" | "full" | null = null;
|
||||
|
||||
constructor(options: WorkspaceReconciliationServiceOptions) {
|
||||
@@ -211,17 +233,33 @@ export class WorkspaceReconciliationService {
|
||||
this.watchers.length = 0;
|
||||
}
|
||||
|
||||
/** Reconciles mutable Git facts only; never archives missing records. */
|
||||
async reconcileGitMetadata(): Promise<ReconciliationResult> {
|
||||
/**
|
||||
* Reconciles mutable Git facts only; never archives missing records. With
|
||||
* `rootPaths`, read projects and workspaces whose checkouts can change under those paths.
|
||||
*/
|
||||
async reconcileGitMetadata(options?: { rootPaths?: string[] }): Promise<ReconciliationResult> {
|
||||
const start = Date.now();
|
||||
const changes: ReconciliationChange[] = [];
|
||||
const [projects, workspaces] = await Promise.all([
|
||||
const [allProjects, workspaces] = await Promise.all([
|
||||
this.projectRegistry.list(),
|
||||
this.workspaceRegistry.listActive(),
|
||||
]);
|
||||
const projects = allProjects.filter((project) => !project.archivedAt);
|
||||
const activeWorkspaces = workspaces.filter((workspace) => !workspace.archivedAt);
|
||||
const affectedDirectories = options?.rootPaths
|
||||
? await findAffectedCheckoutDirectories(
|
||||
options.rootPaths,
|
||||
[
|
||||
...projects.map((project) => project.rootPath),
|
||||
...activeWorkspaces.map((workspace) => workspace.cwd),
|
||||
],
|
||||
(path, read) => this.inspectPath(path, "scope", read),
|
||||
)
|
||||
: null;
|
||||
const isAffectedDirectory = (cwd: string) => affectedDirectories?.has(cwd) ?? true;
|
||||
const workspacesByProject = new Map<string, PersistedWorkspaceRecord[]>();
|
||||
const workspaceStates = await mapBounded(
|
||||
workspaces.filter((w) => !w.archivedAt),
|
||||
activeWorkspaces.filter((workspace) => isAffectedDirectory(workspace.cwd)),
|
||||
async (workspace) => ({ workspace, state: await this.inspectDirectory(workspace.cwd) }),
|
||||
);
|
||||
for (const { workspace, state } of workspaceStates) {
|
||||
@@ -232,13 +270,17 @@ export class WorkspaceReconciliationService {
|
||||
workspacesByProject.set(workspace.projectId, siblings);
|
||||
}
|
||||
const projectStates = await mapBounded(
|
||||
projects.filter((p) => !p.archivedAt),
|
||||
projects.filter(
|
||||
(project) =>
|
||||
isAffectedDirectory(project.rootPath) || workspacesByProject.has(project.projectId),
|
||||
),
|
||||
async (project) => ({ project, state: await this.inspectDirectory(project.rootPath) }),
|
||||
);
|
||||
await this.reconcileGitMetadataForProjects(
|
||||
projectStates.filter(({ state }) => state === "directory").map(({ project }) => project),
|
||||
workspacesByProject,
|
||||
changes,
|
||||
isAffectedDirectory,
|
||||
);
|
||||
if (changes.length > 0) this.onChanges?.(changes);
|
||||
return { changesApplied: changes, durationMs: Date.now() - start };
|
||||
@@ -348,13 +390,15 @@ export class WorkspaceReconciliationService {
|
||||
projectsToReconcile: PersistedProjectRecord[],
|
||||
workspacesByProject: Map<string, PersistedWorkspaceRecord[]>,
|
||||
changes: ReconciliationChange[],
|
||||
isAffectedDirectory: (cwd: string) => boolean = () => true,
|
||||
): Promise<void> {
|
||||
const checkoutReads: CachedCheckoutRead[] = [];
|
||||
const checkoutReadLimit = pLimit(CHECKOUT_READ_CONCURRENCY);
|
||||
const readSession = new CheckoutReadSession();
|
||||
const readCheckout = (cwd: string): Promise<ProjectCheckoutLitePayload> => {
|
||||
const existing = checkoutReads.find((read) => areEquivalentPaths(read.cwd, cwd));
|
||||
if (existing) return existing.checkout;
|
||||
const checkout = checkoutReadLimit(() => this.readCheckout(cwd));
|
||||
const checkout = checkoutReadLimit(() => this.readCheckout(cwd, readSession));
|
||||
checkoutReads.push({ cwd, checkout });
|
||||
return checkout;
|
||||
};
|
||||
@@ -369,7 +413,7 @@ export class WorkspaceReconciliationService {
|
||||
await Promise.all(
|
||||
roots.map(async ({ rootPath, projects }) => {
|
||||
try {
|
||||
const rootGit = await readCheckout(rootPath);
|
||||
const rootGit = isAffectedDirectory(rootPath) ? await readCheckout(rootPath) : null;
|
||||
await Promise.all(
|
||||
projects.map((project) =>
|
||||
this.reconcileProject({
|
||||
@@ -402,39 +446,7 @@ export class WorkspaceReconciliationService {
|
||||
);
|
||||
const project = await this.projectRegistry.get(input.project.projectId);
|
||||
if (!project || project.archivedAt || project.rootPath !== input.project.rootPath) return;
|
||||
const projectUpdates: Partial<Pick<PersistedProjectRecord, "kind" | "projectKey">> = {};
|
||||
const mappedKind = deriveProjectKind(currentGit);
|
||||
const projectKey = deriveProjectKey({
|
||||
rootPath: project.rootPath,
|
||||
remoteUrl: currentGit.remoteUrl,
|
||||
worktreeRoot: currentGit.worktreeRoot,
|
||||
mainRepoRoot: currentGit.mainRepoRoot,
|
||||
serverId: this.serverId,
|
||||
});
|
||||
|
||||
if (project.kind !== mappedKind) {
|
||||
projectUpdates.kind = mappedKind;
|
||||
}
|
||||
if (project.projectKey !== projectKey) {
|
||||
projectUpdates.projectKey = projectKey;
|
||||
}
|
||||
|
||||
if (Object.keys(projectUpdates).length > 0) {
|
||||
const timestamp = new Date().toISOString();
|
||||
let applied = false;
|
||||
await this.projectRegistry.update(project.projectId, (current) => {
|
||||
if (current.archivedAt || current.rootPath !== project.rootPath) return current;
|
||||
applied = true;
|
||||
return { ...current, ...projectUpdates, updatedAt: timestamp };
|
||||
});
|
||||
if (applied)
|
||||
changes.push({
|
||||
kind: "project_updated",
|
||||
projectId: project.projectId,
|
||||
directory: project.rootPath,
|
||||
fields: projectUpdates,
|
||||
});
|
||||
}
|
||||
if (currentGit) await this.reconcileProjectMetadata(project, currentGit, changes);
|
||||
|
||||
await Promise.all(
|
||||
workspaceCheckouts.map(async (entry) => {
|
||||
@@ -468,6 +480,46 @@ export class WorkspaceReconciliationService {
|
||||
);
|
||||
}
|
||||
|
||||
private async reconcileProjectMetadata(
|
||||
project: PersistedProjectRecord,
|
||||
currentGit: ProjectCheckoutLitePayload,
|
||||
changes: ReconciliationChange[],
|
||||
): Promise<void> {
|
||||
const projectUpdates: Partial<Pick<PersistedProjectRecord, "kind" | "projectKey">> = {};
|
||||
const mappedKind = deriveProjectKind(currentGit);
|
||||
const projectKey = deriveProjectKey({
|
||||
rootPath: project.rootPath,
|
||||
remoteUrl: currentGit.remoteUrl,
|
||||
worktreeRoot: currentGit.worktreeRoot,
|
||||
mainRepoRoot: currentGit.mainRepoRoot,
|
||||
serverId: this.serverId,
|
||||
});
|
||||
|
||||
if (project.kind !== mappedKind) {
|
||||
projectUpdates.kind = mappedKind;
|
||||
}
|
||||
if (project.projectKey !== projectKey) {
|
||||
projectUpdates.projectKey = projectKey;
|
||||
}
|
||||
|
||||
if (Object.keys(projectUpdates).length > 0) {
|
||||
const timestamp = new Date().toISOString();
|
||||
let applied = false;
|
||||
await this.projectRegistry.update(project.projectId, (current) => {
|
||||
if (current.archivedAt || current.rootPath !== project.rootPath) return current;
|
||||
applied = true;
|
||||
return { ...current, ...projectUpdates, updatedAt: timestamp };
|
||||
});
|
||||
if (applied)
|
||||
changes.push({
|
||||
kind: "project_updated",
|
||||
projectId: project.projectId,
|
||||
directory: project.rootPath,
|
||||
fields: projectUpdates,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async syncProjectRootWatches(): Promise<void> {
|
||||
if (this.disposed) return;
|
||||
const projects = await this.projectRegistry.list();
|
||||
@@ -496,6 +548,7 @@ export class WorkspaceReconciliationService {
|
||||
{ recursive: false },
|
||||
(_event, filename) => {
|
||||
if (filename === null || filename.toString() === ".git") {
|
||||
this.changedRoots.add(project.rootPath);
|
||||
this.scheduleObservedReconciliation();
|
||||
}
|
||||
},
|
||||
@@ -539,28 +592,20 @@ export class WorkspaceReconciliationService {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Take the roots that changed so far. Events arriving during this pass
|
||||
// land in a fresh set and queue one more pass for just those roots.
|
||||
const rootPaths = [...this.changedRoots];
|
||||
this.changedRoots.clear();
|
||||
if (mode === "metadata" && rootPaths.length === 0) return;
|
||||
this.reconciling = true;
|
||||
try {
|
||||
await this.syncProjectRootWatches();
|
||||
const result = mode === "full" ? await this.runOnce() : await this.reconcileGitMetadata();
|
||||
const workspaceIds = new Set<string>();
|
||||
const projectIds = new Set<string>();
|
||||
for (const change of result.changesApplied) {
|
||||
if (change.kind === "workspace_updated" || change.kind === "workspace_archived") {
|
||||
workspaceIds.add(change.workspaceId);
|
||||
}
|
||||
if (change.kind === "project_updated") projectIds.add(change.projectId);
|
||||
}
|
||||
if (projectIds.size > 0) {
|
||||
const workspaces = await this.workspaceRegistry.listActive();
|
||||
for (const workspaceId of workspaceIdsForProjects(workspaces, projectIds)) {
|
||||
workspaceIds.add(workspaceId);
|
||||
}
|
||||
}
|
||||
if (!this.disposed && workspaceIds.size > 0) {
|
||||
await this.onWorkspacesChanged?.(Array.from(workspaceIds));
|
||||
}
|
||||
const result =
|
||||
mode === "full" ? await this.runOnce() : await this.reconcileGitMetadata({ rootPaths });
|
||||
await this.publishChangedWorkspaces(result);
|
||||
} catch (error) {
|
||||
// A failed pass keeps its roots pending for the next pass.
|
||||
for (const rootPath of rootPaths) this.changedRoots.add(rootPath);
|
||||
if (!this.disposed) {
|
||||
this.logger.warn({ err: error }, "Workspace reconciliation failed");
|
||||
}
|
||||
@@ -574,7 +619,30 @@ export class WorkspaceReconciliationService {
|
||||
}
|
||||
}
|
||||
|
||||
private async readCheckout(cwd: string): Promise<ProjectCheckoutLitePayload> {
|
||||
private async publishChangedWorkspaces(result: ReconciliationResult): Promise<void> {
|
||||
const workspaceIds = new Set<string>();
|
||||
const projectIds = new Set<string>();
|
||||
for (const change of result.changesApplied) {
|
||||
if (change.kind === "workspace_updated" || change.kind === "workspace_archived") {
|
||||
workspaceIds.add(change.workspaceId);
|
||||
}
|
||||
if (change.kind === "project_updated") projectIds.add(change.projectId);
|
||||
}
|
||||
if (projectIds.size > 0) {
|
||||
const workspaces = await this.workspaceRegistry.listActive();
|
||||
for (const workspaceId of workspaceIdsForProjects(workspaces, projectIds)) {
|
||||
workspaceIds.add(workspaceId);
|
||||
}
|
||||
}
|
||||
if (!this.disposed && workspaceIds.size > 0) {
|
||||
await this.onWorkspacesChanged?.(Array.from(workspaceIds));
|
||||
}
|
||||
}
|
||||
|
||||
private async readCheckout(
|
||||
cwd: string,
|
||||
readSession: CheckoutReadSession,
|
||||
): Promise<ProjectCheckoutLitePayload> {
|
||||
if (!this.workspaceGitService) {
|
||||
return {
|
||||
cwd,
|
||||
@@ -588,7 +656,7 @@ export class WorkspaceReconciliationService {
|
||||
}
|
||||
// Reconciliation converges in the background; it must not queue ahead of
|
||||
// Git work a user is waiting for.
|
||||
return this.workspaceGitService.getCheckout(cwd, { priority: "background" });
|
||||
return this.workspaceGitService.getCheckout(cwd, { priority: "background", readSession });
|
||||
}
|
||||
|
||||
private wakeInspectionWaiters(): void {
|
||||
@@ -597,21 +665,33 @@ export class WorkspaceReconciliationService {
|
||||
}
|
||||
|
||||
private async inspectDirectory(targetPath: string): Promise<DirectoryState> {
|
||||
const result = await this.inspectPath(targetPath, "directory", () =>
|
||||
this.directoryInspection(targetPath),
|
||||
);
|
||||
return typeof result === "string" ? result : "directory";
|
||||
}
|
||||
|
||||
private async inspectPath(
|
||||
targetPath: string,
|
||||
purpose: "directory" | "scope",
|
||||
read: () => Promise<DirectoryInspection>,
|
||||
): Promise<DirectoryInspection> {
|
||||
const key = `${purpose}:${targetPath}`;
|
||||
// A healthy in-flight inspection owns capacity temporarily. Wait for it;
|
||||
// only unresolved operations that have all timed out justify skipping paths.
|
||||
while (
|
||||
!this.disposed &&
|
||||
!this.pendingInspections.has(targetPath) &&
|
||||
!this.pendingInspections.has(key) &&
|
||||
this.pendingInspections.size >= INSPECTION_CONCURRENCY
|
||||
) {
|
||||
if (this.timedOutPaths.size === INSPECTION_CONCURRENCY) return "unreadable";
|
||||
await new Promise<void>((resolve) => this.inspectionWaiters.add(resolve));
|
||||
}
|
||||
if (this.disposed) return "unreadable";
|
||||
let pending = this.pendingInspections.get(targetPath);
|
||||
let pending = this.pendingInspections.get(key);
|
||||
if (!pending) {
|
||||
pending = Promise.resolve()
|
||||
.then(() => this.directoryInspection(targetPath))
|
||||
.then(read)
|
||||
.catch((error) => {
|
||||
if (isMissingPathError(error)) return "missing" as const;
|
||||
this.logger.warn(
|
||||
@@ -621,8 +701,8 @@ export class WorkspaceReconciliationService {
|
||||
return "unreadable" as const;
|
||||
})
|
||||
.finally(() => {
|
||||
this.pendingInspections.delete(targetPath);
|
||||
this.timedOutPaths.delete(targetPath);
|
||||
this.pendingInspections.delete(key);
|
||||
this.timedOutPaths.delete(key);
|
||||
this.wakeInspectionWaiters();
|
||||
if (this.inspectionSaturated && this.timedOutPaths.size === 0) {
|
||||
this.inspectionSaturated = false;
|
||||
@@ -632,20 +712,20 @@ export class WorkspaceReconciliationService {
|
||||
);
|
||||
}
|
||||
});
|
||||
this.pendingInspections.set(targetPath, pending);
|
||||
this.pendingInspections.set(key, pending);
|
||||
}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
pending,
|
||||
new Promise<DirectoryState>((resolve) => {
|
||||
new Promise<DirectoryInspection>((resolve) => {
|
||||
timer = setTimeout(() => {
|
||||
this.timedOutPaths.add(targetPath);
|
||||
this.timedOutPaths.set(key, targetPath);
|
||||
this.wakeInspectionWaiters();
|
||||
if (!this.inspectionSaturated && this.timedOutPaths.size === INSPECTION_CONCURRENCY) {
|
||||
this.inspectionSaturated = true;
|
||||
this.logger.warn(
|
||||
{ paths: [...this.timedOutPaths] },
|
||||
{ paths: [...this.timedOutPaths.values()] },
|
||||
"Workspace directory inspection saturated; preserving uninspected workspaces",
|
||||
);
|
||||
}
|
||||
@@ -663,6 +743,91 @@ export class WorkspaceReconciliationService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve saved directories for selection only. The registries keep their original paths.
|
||||
* Looking up the nearest .git entry and commondir uses bounded filesystem reads, so a
|
||||
* watcher event does not start Git processes in repositories it is about to exclude.
|
||||
*/
|
||||
async function findAffectedCheckoutDirectories(
|
||||
changedRoots: string[],
|
||||
candidates: string[],
|
||||
inspect: (path: string, read: () => Promise<CheckoutDirectory>) => Promise<DirectoryInspection>,
|
||||
): Promise<Set<string>> {
|
||||
const resolved = new Map<string, Promise<ResolvedPath>>();
|
||||
const resolvePath = (path: string) => {
|
||||
let result = resolved.get(path);
|
||||
if (!result) {
|
||||
result = resolveRealpath(path)
|
||||
.catch(() => resolveNativeRealpath(path))
|
||||
.then(
|
||||
(resolvedPath) => ({ path: resolvedPath, missing: false }),
|
||||
(error) => ({ path, missing: isMissingPathError(error) }),
|
||||
);
|
||||
resolved.set(path, result);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const gitDirectories = new Map<string, Promise<string | null>>();
|
||||
const findRepository = async (cwd: string): Promise<CheckoutDirectory["repository"]> => {
|
||||
for (let current = cwd; ; current = dirname(current)) {
|
||||
let result = gitDirectories.get(current);
|
||||
if (!result) {
|
||||
result = getGitCommonDirForWorktreeRoot(current);
|
||||
gitDirectories.set(current, result);
|
||||
}
|
||||
const gitDir = await result;
|
||||
if (gitDir) return { root: current, commonDir: await resolvePath(gitDir) };
|
||||
if (dirname(current) === current) return null;
|
||||
}
|
||||
};
|
||||
|
||||
const inspectCheckoutDirectory = (directory: string) =>
|
||||
inspect(directory, async () => {
|
||||
const { path } = await resolvePath(directory);
|
||||
return { path, repository: await findRepository(path) };
|
||||
});
|
||||
const dirty = await mapBounded(changedRoots, inspectCheckoutDirectory);
|
||||
const roots = dirty.map((entry, index) =>
|
||||
typeof entry === "string" ? changedRoots[index]! : entry.path,
|
||||
);
|
||||
const tree = createPathContainmentMatcher({
|
||||
roots,
|
||||
compareAsWindows: process.platform === "win32",
|
||||
});
|
||||
const commonDirs = dirty.flatMap((entry) =>
|
||||
typeof entry !== "string" && entry.repository ? [entry.repository.commonDir.path] : [],
|
||||
);
|
||||
const gitEntries = createPathContainmentMatcher({
|
||||
roots: roots.map((root) => join(root, ".git")),
|
||||
compareAsWindows: process.platform === "win32",
|
||||
});
|
||||
const repositories = createPathContainmentMatcher({
|
||||
roots: commonDirs,
|
||||
compareAsWindows: process.platform === "win32",
|
||||
});
|
||||
const affected = new Set<string>();
|
||||
await mapBounded([...new Set(candidates)], async (candidate) => {
|
||||
const entry = await inspectCheckoutDirectory(candidate);
|
||||
const path = typeof entry === "string" ? candidate : entry.path;
|
||||
const repository = typeof entry === "string" ? null : entry.repository;
|
||||
const commonDir = repository?.commonDir;
|
||||
// A broken checkout can still point beneath the changed .git entry after
|
||||
// removal or replacement. Existing submodule metadata has its own identity.
|
||||
const sharesMetadata =
|
||||
commonDir &&
|
||||
(repositories.matchesExact(commonDir.path) ||
|
||||
(commonDir.missing && gitEntries.matches(commonDir.path)));
|
||||
// A surviving nested repository provides its own metadata even if its
|
||||
// parent gains or loses a .git entry.
|
||||
const hasIndependentNestedRepository =
|
||||
repository && tree.matches(repository.root) && !tree.matchesExact(repository.root);
|
||||
if (sharesMetadata || (tree.matches(path) && !hasIndependentNestedRepository)) {
|
||||
affected.add(candidate);
|
||||
}
|
||||
});
|
||||
return affected;
|
||||
}
|
||||
|
||||
function isMissingPathError(error: unknown): boolean {
|
||||
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
||||
return error.code === "ENOENT" || error.code === "ENOTDIR";
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { getCheckoutIdentity, getCheckoutStatus } from "./checkout-git.js";
|
||||
import { CheckoutReadSession } from "./checkout-read-session.js";
|
||||
import { writePaseoWorktreeMetadata } from "./worktree-metadata.js";
|
||||
import { createWorktree } from "./worktree.js";
|
||||
import { startGitCommandMetrics, stopGitCommandMetrics } from "./run-git-command.js";
|
||||
|
||||
function git(cwd: string, ...args: string[]): void {
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd, stdio: "ignore" });
|
||||
}
|
||||
|
||||
describe("getCheckoutIdentity", () => {
|
||||
let tempDir: string;
|
||||
let paseoHome: string;
|
||||
let repoDir: string;
|
||||
let linkedDir: string;
|
||||
let plainDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = realpathSync(mkdtempSync(join(tmpdir(), "checkout-identity-")));
|
||||
paseoHome = join(tempDir, "paseo-home");
|
||||
repoDir = join(tempDir, "repo");
|
||||
linkedDir = join(tempDir, "linked");
|
||||
plainDir = join(tempDir, "plain");
|
||||
mkdirSync(paseoHome);
|
||||
mkdirSync(repoDir);
|
||||
mkdirSync(plainDir);
|
||||
git(repoDir, "init", "-b", "main");
|
||||
git(repoDir, "config", "user.email", "test@test.com");
|
||||
git(repoDir, "config", "user.name", "Test");
|
||||
writeFileSync(join(repoDir, "tracked.txt"), "tracked\n");
|
||||
git(repoDir, "add", ".");
|
||||
git(repoDir, "commit", "-m", "initial");
|
||||
git(repoDir, "remote", "add", "origin", "https://github.com/acme/widgets.git");
|
||||
git(repoDir, "worktree", "add", "-b", "feature", linkedDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("reports the same identity as the full status for a checkout, linked and Paseo worktrees and a plain folder", async () => {
|
||||
const paseoWorktree = await createWorktree({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "alpha",
|
||||
source: { kind: "branch-off", baseBranch: "main", branchName: "alpha" },
|
||||
paseoHome,
|
||||
});
|
||||
for (const cwd of [repoDir, linkedDir, paseoWorktree.worktreePath]) {
|
||||
const status = await getCheckoutStatus(cwd, { paseoHome });
|
||||
const identity = await getCheckoutIdentity(cwd, { paseoHome });
|
||||
if (!status.isGit) throw new Error(`${cwd} should be a git checkout`);
|
||||
expect(identity).toEqual({
|
||||
isGit: true,
|
||||
repoRoot: status.repoRoot,
|
||||
mainRepoRoot: status.mainRepoRoot,
|
||||
currentBranch: status.currentBranch,
|
||||
remoteUrl: status.remoteUrl,
|
||||
isPaseoOwnedWorktree: status.isPaseoOwnedWorktree,
|
||||
});
|
||||
}
|
||||
const mainRepoRoot = await realpath(repoDir);
|
||||
expect(await getCheckoutIdentity(linkedDir, { paseoHome })).toMatchObject({
|
||||
currentBranch: "feature",
|
||||
mainRepoRoot,
|
||||
});
|
||||
expect(await getCheckoutIdentity(paseoWorktree.worktreePath, { paseoHome })).toMatchObject({
|
||||
isPaseoOwnedWorktree: true,
|
||||
mainRepoRoot,
|
||||
});
|
||||
expect(await getCheckoutIdentity(plainDir, { paseoHome })).toEqual({ isGit: false });
|
||||
});
|
||||
|
||||
it("reads Git worktree registration once for all marked worktrees in a batch", async () => {
|
||||
const second = join(tempDir, "second");
|
||||
git(repoDir, "worktree", "add", "-b", "second", second);
|
||||
await writePaseoWorktreeMetadata(linkedDir, { baseRefName: "main" });
|
||||
await writePaseoWorktreeMetadata(second, { baseRefName: "main" });
|
||||
|
||||
const readSession = new CheckoutReadSession();
|
||||
startGitCommandMetrics();
|
||||
try {
|
||||
const checkouts = await Promise.all([
|
||||
getCheckoutIdentity(linkedDir, { paseoHome, readSession }),
|
||||
getCheckoutIdentity(second, { paseoHome, readSession }),
|
||||
]);
|
||||
expect(checkouts).toMatchObject([
|
||||
{ isGit: true, currentBranch: "feature", isPaseoOwnedWorktree: true },
|
||||
{ isGit: true, currentBranch: "second", isPaseoOwnedWorktree: true },
|
||||
]);
|
||||
const worktreeLists = stopGitCommandMetrics().commands.filter(
|
||||
(command) => command.args[0] === "worktree" && command.args[1] === "list",
|
||||
);
|
||||
expect(worktreeLists).toHaveLength(1);
|
||||
} finally {
|
||||
stopGitCommandMetrics();
|
||||
}
|
||||
});
|
||||
|
||||
it("shares worktree registration and main checkout discovery in a bare repository", async () => {
|
||||
const bare = join(tempDir, "shared.git");
|
||||
const main = join(tempDir, "main");
|
||||
const first = join(tempDir, "first");
|
||||
const second = join(tempDir, "second");
|
||||
git(repoDir, "clone", "--bare", repoDir, bare);
|
||||
git(bare, "worktree", "add", main, "main");
|
||||
git(bare, "worktree", "add", "-b", "first", first);
|
||||
git(bare, "worktree", "add", "-b", "second", second);
|
||||
await writePaseoWorktreeMetadata(first, { baseRefName: "main" });
|
||||
await writePaseoWorktreeMetadata(second, { baseRefName: "main" });
|
||||
|
||||
const readSession = new CheckoutReadSession();
|
||||
startGitCommandMetrics();
|
||||
try {
|
||||
const checkouts = await Promise.all(
|
||||
[main, first, second].map((cwd) => getCheckoutIdentity(cwd, { paseoHome, readSession })),
|
||||
);
|
||||
const mainRepoRoot = await realpath(main);
|
||||
expect(checkouts).toMatchObject([
|
||||
{ currentBranch: "main", isPaseoOwnedWorktree: false, mainRepoRoot: null },
|
||||
{ currentBranch: "first", isPaseoOwnedWorktree: true, mainRepoRoot },
|
||||
{ currentBranch: "second", isPaseoOwnedWorktree: true, mainRepoRoot },
|
||||
]);
|
||||
const worktreeLists = stopGitCommandMetrics().commands.filter(
|
||||
(command) => command.args[0] === "worktree" && command.args[1] === "list",
|
||||
);
|
||||
expect(worktreeLists).toHaveLength(1);
|
||||
} finally {
|
||||
stopGitCommandMetrics();
|
||||
}
|
||||
});
|
||||
|
||||
it("never scans the working tree or compares commits", async () => {
|
||||
startGitCommandMetrics();
|
||||
await getCheckoutIdentity(repoDir, { paseoHome });
|
||||
await getCheckoutIdentity(linkedDir, { paseoHome });
|
||||
const verbs = stopGitCommandMetrics().commands.map((command) => command.args[0]);
|
||||
|
||||
expect(verbs.length).toBeGreaterThan(0);
|
||||
expect(
|
||||
verbs.filter((verb) => ["status", "ls-files", "rev-list", "diff"].includes(verb)),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -39,11 +39,16 @@ import {
|
||||
ForgeCliMissingError,
|
||||
ForgeCommandError,
|
||||
} from "../services/forge-cli-command.js";
|
||||
import type { CheckoutReadSession } from "./checkout-read-session.js";
|
||||
import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-path.js";
|
||||
import { runGitCommand, type RunGitCommand } from "./run-git-command.js";
|
||||
import { readGitFileContents, readGitFileContentAtRef } from "./git-file-contents.js";
|
||||
import { unquoteGitPath } from "./git-quoted-path.js";
|
||||
import { isPaseoOwnedWorktreeCwd, resolvePaseoWorktreesBaseRoot } from "./worktree.js";
|
||||
import {
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
readWorktreeRegistration,
|
||||
resolvePaseoWorktreesBaseRoot,
|
||||
} from "./worktree.js";
|
||||
import {
|
||||
branchNameFromRef,
|
||||
findPaseoWorktreeRootForCwd,
|
||||
@@ -975,6 +980,7 @@ export interface CheckoutContext {
|
||||
worktreesRoot?: string;
|
||||
logger?: Pick<Logger, "trace" | "warn">;
|
||||
facts?: CheckoutSnapshotFacts | null;
|
||||
readSession?: CheckoutReadSession;
|
||||
runGitCommand?: RunGitCommand;
|
||||
// `git config --get` results shared by the lookups of one snapshot, keyed by config key.
|
||||
// Several lookups read the same keys; this keeps each to one process.
|
||||
@@ -1157,6 +1163,19 @@ async function getMainRepoRootFromCommonDir(
|
||||
return dirname(normalized);
|
||||
}
|
||||
|
||||
const session = context?.readSession;
|
||||
if (session) {
|
||||
return session.readMainCheckout(normalized, async () => {
|
||||
const { entries } = await readWorktreeRegistration(
|
||||
cwd,
|
||||
normalized,
|
||||
session,
|
||||
getRunGitCommand(context),
|
||||
);
|
||||
return selectMainCheckout(entries, normalized, context);
|
||||
});
|
||||
}
|
||||
|
||||
const { stdout: worktreeOut } = await getRunGitCommand(context)(
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
@@ -1164,7 +1183,14 @@ async function getMainRepoRootFromCommonDir(
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
},
|
||||
);
|
||||
const worktrees = parseWorktreeList(worktreeOut);
|
||||
return selectMainCheckout(parseWorktreeList(worktreeOut), normalized, context);
|
||||
}
|
||||
|
||||
async function selectMainCheckout(
|
||||
worktrees: readonly Pick<GitWorktreeEntry, "path" | "isBare">[],
|
||||
normalized: string,
|
||||
context?: CheckoutContext,
|
||||
): Promise<string> {
|
||||
const paseoPaths = new Set(
|
||||
(
|
||||
await Promise.all(
|
||||
@@ -1312,6 +1338,8 @@ async function getPaseoWorktreeForCwd(
|
||||
paseoHome: options.context?.paseoHome,
|
||||
worktreesRoot: options.context?.worktreesRoot,
|
||||
knownGitCommonDir: options.knownGitCommonDir,
|
||||
readSession: options.context?.readSession,
|
||||
runGitCommand: options.context?.runGitCommand,
|
||||
});
|
||||
if (!ownership.allowed) {
|
||||
return { isPaseoOwnedWorktree: false };
|
||||
@@ -2061,7 +2089,8 @@ interface CheckoutInspectionContext {
|
||||
|
||||
async function inspectCheckoutContext(
|
||||
cwd: string,
|
||||
context?: CheckoutContext,
|
||||
context: CheckoutContext | undefined,
|
||||
options: { includeAbsoluteGitDir: boolean },
|
||||
): Promise<CheckoutInspectionContext | null> {
|
||||
const root = await getWorktreeRoot(cwd, context);
|
||||
if (!root) {
|
||||
@@ -2071,7 +2100,7 @@ async function inspectCheckoutContext(
|
||||
const [currentBranch, remoteUrl, absoluteGitDir, gitCommonDir] = await Promise.all([
|
||||
getCurrentBranch(cwd, context),
|
||||
getOriginRemoteUrl(cwd, context),
|
||||
resolveAbsoluteGitDir(cwd, context),
|
||||
options.includeAbsoluteGitDir ? resolveAbsoluteGitDir(cwd, context) : null,
|
||||
resolveGitCommonDir(cwd, context),
|
||||
]);
|
||||
const paseoWorktree = await getPaseoWorktreeForCwd(cwd, {
|
||||
@@ -2316,7 +2345,7 @@ async function collectCheckoutSnapshotFacts(
|
||||
cwd: string,
|
||||
context: CheckoutContext,
|
||||
): Promise<CheckoutSnapshotFacts> {
|
||||
const inspected = await inspectCheckoutContext(cwd, context);
|
||||
const inspected = await inspectCheckoutContext(cwd, context, { includeAbsoluteGitDir: true });
|
||||
if (!inspected) {
|
||||
return { isGit: false };
|
||||
}
|
||||
@@ -2551,6 +2580,60 @@ async function getUntrackedDiffText(
|
||||
};
|
||||
}
|
||||
|
||||
export type CheckoutIdentity =
|
||||
| { isGit: false }
|
||||
| {
|
||||
isGit: true;
|
||||
repoRoot: string;
|
||||
mainRepoRoot: string | null;
|
||||
currentBranch: string | null;
|
||||
remoteUrl: string | null;
|
||||
isPaseoOwnedWorktree: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a checkout is, without the state of its files. Reports the same identity fields as
|
||||
* `getCheckoutStatus` but never scans the working tree (`status`), compares against a base, or
|
||||
* counts commits, so reading many checkouts in the background stays cheap.
|
||||
*/
|
||||
export async function getCheckoutIdentity(
|
||||
cwd: string,
|
||||
context?: CheckoutContext,
|
||||
): Promise<CheckoutIdentity> {
|
||||
const inspected = await inspectCheckoutContext(cwd, context, { includeAbsoluteGitDir: false });
|
||||
if (!inspected) {
|
||||
return { isGit: false };
|
||||
}
|
||||
const { worktreeRoot, currentBranch, remoteUrl, paseoWorktree } = inspected;
|
||||
const mainRepoRoot = await getMainRepoRootFromCommonDir(
|
||||
cwd,
|
||||
inspected.gitCommonDir,
|
||||
context,
|
||||
).catch(() => null);
|
||||
// `getCheckoutStatus` reports a worktree as Paseo-owned only when it also resolves a base.
|
||||
const isPaseoOwnedWorktree =
|
||||
paseoWorktree.isPaseoOwnedWorktree &&
|
||||
Boolean(
|
||||
storedBaseRefFromMetadata(await readPaseoWorktreeMetadata(worktreeRoot)) ??
|
||||
(await resolveBaseRef(cwd, context)),
|
||||
);
|
||||
const isLinkedCheckout = mainRepoRoot !== null && resolve(mainRepoRoot) !== resolve(worktreeRoot);
|
||||
let reportedMainRepoRoot: string | null = null;
|
||||
if (isPaseoOwnedWorktree) {
|
||||
reportedMainRepoRoot = mainRepoRoot ?? worktreeRoot;
|
||||
} else if (isLinkedCheckout) {
|
||||
reportedMainRepoRoot = mainRepoRoot;
|
||||
}
|
||||
return {
|
||||
isGit: true,
|
||||
repoRoot: worktreeRoot,
|
||||
mainRepoRoot: reportedMainRepoRoot,
|
||||
currentBranch,
|
||||
remoteUrl,
|
||||
isPaseoOwnedWorktree,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getCheckoutStatus(
|
||||
cwd: string,
|
||||
context?: CheckoutContext,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
export interface WorktreeRegistration {
|
||||
entries: readonly { path: string; isBare?: boolean }[];
|
||||
contains(canonicalCheckoutPath: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** Shares repository-wide reads for the lifetime of one checkout reconciliation pass. */
|
||||
export class CheckoutReadSession {
|
||||
private readonly worktrees = new Map<string, Promise<WorktreeRegistration>>();
|
||||
private readonly mainCheckouts = new Map<string, Promise<string>>();
|
||||
|
||||
readWorktrees(
|
||||
repository: string,
|
||||
read: () => Promise<WorktreeRegistration>,
|
||||
): Promise<WorktreeRegistration> {
|
||||
return readOnce(this.worktrees, repository, read);
|
||||
}
|
||||
|
||||
readMainCheckout(repository: string, read: () => Promise<string>): Promise<string> {
|
||||
return readOnce(this.mainCheckouts, repository, read);
|
||||
}
|
||||
}
|
||||
|
||||
function readOnce<T>(
|
||||
reads: Map<string, Promise<T>>,
|
||||
key: string,
|
||||
read: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
let result = reads.get(key);
|
||||
if (!result) {
|
||||
result = read().catch((error) => {
|
||||
reads.delete(key);
|
||||
throw error;
|
||||
});
|
||||
reads.set(key, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -177,6 +177,22 @@ async function getGitDirForWorktreeRoot(worktreeRoot: string): Promise<string> {
|
||||
return gitPath;
|
||||
}
|
||||
|
||||
/** Locate the admin directory used for shared refs and configuration. */
|
||||
export async function getGitCommonDirForWorktreeRoot(worktreeRoot: string): Promise<string | null> {
|
||||
let gitDir: string;
|
||||
try {
|
||||
gitDir = await getGitDirForWorktreeRoot(worktreeRoot);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const commonDir = (await readBoundedFile(join(gitDir, "commondir"))).trim();
|
||||
return commonDir ? resolve(gitDir, commonDir) : gitDir;
|
||||
} catch {
|
||||
return gitDir;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPaseoWorktreeMetadataPath(worktreeRoot: string): Promise<string> {
|
||||
const gitDir = await getGitDirForWorktreeRoot(worktreeRoot);
|
||||
return join(gitDir, "paseo", "worktree.json");
|
||||
|
||||
@@ -36,12 +36,13 @@ import {
|
||||
writePaseoWorktreeRuntimeMetadata,
|
||||
} from "./worktree-metadata.js";
|
||||
import { runWithRepositoryRoot } from "./git-repository-discovery.js";
|
||||
import { runGitCommand } from "./run-git-command.js";
|
||||
import { runGitCommand, type RunGitCommand } from "./run-git-command.js";
|
||||
import { getCurrentBranch, resolveRepositoryDefaultBranch } from "./checkout-git.js";
|
||||
import { spawnProcess } from "./spawn.js";
|
||||
import { applyLaunchWrap } from "./launch-wrap.js";
|
||||
import { resolvePaseoHome } from "../server/paseo-home.js";
|
||||
import { createExternalProcessEnv } from "../server/paseo-env.js";
|
||||
import type { CheckoutReadSession, WorktreeRegistration } from "./checkout-read-session.js";
|
||||
import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-path.js";
|
||||
import {
|
||||
createRealpathAwarePathMatcher,
|
||||
@@ -244,6 +245,8 @@ export interface PaseoWorktreeOwnership {
|
||||
|
||||
export interface PaseoWorktreeOwnershipOptions extends WorktreeRootOptions {
|
||||
knownGitCommonDir?: string | null;
|
||||
readSession?: CheckoutReadSession;
|
||||
runGitCommand?: RunGitCommand;
|
||||
}
|
||||
|
||||
export interface WorktreeRootOptions {
|
||||
@@ -1123,7 +1126,7 @@ export async function isPaseoOwnedWorktreeCwd(
|
||||
// is not proof — it lives in a git admin dir a user can copy into a
|
||||
// hand-made directory that git does not know about.
|
||||
if (options?.knownGitCommonDir !== null) {
|
||||
const metadataProof = await resolveMetadataOwnedWorktree(cwd, repoRoot);
|
||||
const metadataProof = await resolveMetadataOwnedWorktree(cwd, repoRoot, options);
|
||||
if (metadataProof) {
|
||||
return {
|
||||
allowed: true,
|
||||
@@ -1164,6 +1167,7 @@ export async function isPaseoOwnedWorktreeCwd(
|
||||
async function resolveMetadataOwnedWorktree(
|
||||
cwd: string,
|
||||
repoRoot: string | undefined,
|
||||
options?: PaseoWorktreeOwnershipOptions,
|
||||
): Promise<{ worktreePath: string; worktreeRoot: string } | null> {
|
||||
try {
|
||||
const root = await findPaseoWorktreeRootForCwd(cwd);
|
||||
@@ -1171,23 +1175,69 @@ async function resolveMetadataOwnedWorktree(
|
||||
const candidate = await normalizePathForOwnership(root);
|
||||
if (repoRoot !== undefined && candidate === (await normalizePathForOwnership(repoRoot)))
|
||||
return null;
|
||||
const { entries } = await readGitWorktreeEntries(candidate);
|
||||
for (const entry of entries) {
|
||||
if ((await normalizePathForOwnership(entry.path)) === candidate) {
|
||||
return { worktreePath: candidate, worktreeRoot: dirname(candidate) };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return (await isRegisteredGitWorktree(candidate, options))
|
||||
? { worktreePath: candidate, worktreeRoot: dirname(candidate) }
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function isRegisteredGitWorktree(
|
||||
candidate: string,
|
||||
options?: PaseoWorktreeOwnershipOptions,
|
||||
): Promise<boolean> {
|
||||
if (options?.readSession && options.knownGitCommonDir) {
|
||||
const registration = await readWorktreeRegistration(
|
||||
candidate,
|
||||
options.knownGitCommonDir,
|
||||
options.readSession,
|
||||
options.runGitCommand,
|
||||
);
|
||||
return registration.contains(candidate);
|
||||
}
|
||||
const { entries } = await readGitWorktreeEntries(candidate);
|
||||
for (const entry of entries) {
|
||||
if ((await normalizePathForOwnership(entry.path)) === candidate) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function readWorktreeRegistration(
|
||||
cwd: string,
|
||||
gitCommonDir: string,
|
||||
session: CheckoutReadSession,
|
||||
run: RunGitCommand = runGitCommand,
|
||||
): Promise<WorktreeRegistration> {
|
||||
const repository = await normalizePathForOwnership(gitCommonDir);
|
||||
return session.readWorktrees(repository, async () => {
|
||||
const { entries } = await readGitWorktreeEntries(cwd, run);
|
||||
const registeredPaths = new Set(entries.map((entry) => resolve(entry.path)));
|
||||
const resolvedPaths = new Map<string, Promise<string>>();
|
||||
return {
|
||||
entries,
|
||||
async contains(candidate) {
|
||||
if (registeredPaths.has(candidate)) return true;
|
||||
for (const path of registeredPaths) {
|
||||
let canonical = resolvedPaths.get(path);
|
||||
if (!canonical) {
|
||||
canonical = normalizePathForOwnership(path);
|
||||
resolvedPaths.set(path, canonical);
|
||||
}
|
||||
if ((await canonical) === candidate) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
type ParsedPaseoWorktreeInfo = Omit<PaseoWorktreeInfo, "createdAt">;
|
||||
|
||||
interface ParsedWorktreeEntry extends ParsedPaseoWorktreeInfo {
|
||||
/** A bare repository or a worktree whose directory is gone; nothing can work there. */
|
||||
unusable?: true;
|
||||
isBare?: true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1198,8 +1248,9 @@ interface ParsedWorktreeEntry extends ParsedPaseoWorktreeInfo {
|
||||
*/
|
||||
async function readGitWorktreeEntries(
|
||||
cwd: string,
|
||||
run: RunGitCommand = runGitCommand,
|
||||
): Promise<{ entries: ParsedWorktreeEntry[]; exact: boolean }> {
|
||||
const nulResult = await runGitCommand(["worktree", "list", "--porcelain", "-z"], {
|
||||
const nulResult = await run(["worktree", "list", "--porcelain", "-z"], {
|
||||
cwd,
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
acceptExitCodes: [0, 129],
|
||||
@@ -1210,7 +1261,7 @@ async function readGitWorktreeEntries(
|
||||
exact: true,
|
||||
};
|
||||
}
|
||||
const { stdout } = await runGitCommand(["worktree", "list", "--porcelain"], {
|
||||
const { stdout } = await run(["worktree", "list", "--porcelain"], {
|
||||
cwd,
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
});
|
||||
@@ -1247,7 +1298,10 @@ function parseWorktreeEntriesTokens(
|
||||
current.branchName = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref;
|
||||
} else if (token.startsWith("HEAD ")) {
|
||||
current.head = token.slice("HEAD ".length).trim();
|
||||
} else if (token === "bare" || token.startsWith("prunable")) {
|
||||
} else if (token === "bare") {
|
||||
current.isBare = true;
|
||||
current.unusable = true;
|
||||
} else if (token.startsWith("prunable")) {
|
||||
current.unusable = true;
|
||||
} else if ((lineDelimited ? token.trim() : token).length === 0) {
|
||||
if (current.path) {
|
||||
@@ -1340,7 +1394,7 @@ async function listPaseoWorktreesAtRepositoryRoot({
|
||||
const roots = await ownershipPathVariants(projectWorktreesRoot);
|
||||
const worktrees: PaseoWorktreeInfo[] = [];
|
||||
// Inspect foreign paths sequentially; a large worktree list must not consume the FS pool.
|
||||
for (const { unusable: _unusable, ...entry } of entries) {
|
||||
for (const { unusable: _unusable, isBare: _isBare, ...entry } of entries) {
|
||||
const path = await normalizePathForOwnership(entry.path);
|
||||
if (
|
||||
!roots.some((root) => getRelativePathInsideRoot(root, path) !== null) &&
|
||||
|
||||
@@ -74,23 +74,10 @@ Runtime-safe settings include relay enablement, MCP settings, browser tools, hos
|
||||
|
||||
New homes keep relay disabled when you remove `daemon.relay.enabled`. A daemon whose config already omitted this field when it started keeps the legacy relay-enabled behavior for compatibility. Set `daemon.relay.enabled` explicitly when editing an older config.
|
||||
|
||||
Idle runtime cleanup, the main listen address, authentication, relay endpoints and TLS, worktree allocation, service-proxy addresses, the bundled web UI, logging, speech, voice, credentials, and local model settings require a restart. Reload applies other valid edits in the same file before reporting those paths.
|
||||
Idle runtime cleanup, listen addresses, authentication, relay endpoints and TLS, worktree allocation, service-proxy addresses, the bundled web UI, logging, speech, voice, credentials, and local model settings require a restart. Reload applies other valid edits in the same file before reporting those paths.
|
||||
|
||||
Deployment environment variables and legacy supervisor flags remain authoritative. Reload reports a changed file setting under `overrideControlledPaths` when a launch override prevents it from taking effect. This includes startup settings such as listen addresses, passwords, relay endpoints and TLS, service-proxy and web UI settings, logging, speech, and voice configuration. List settings such as hostnames and CORS origins still append across sources, so values from `config.json` continue to apply. Stop and relaunch the deployment without the override to make the file value authoritative.
|
||||
|
||||
## Listen addresses
|
||||
|
||||
Set `daemon.listen` to one TCP address or a comma-separated list of TCP addresses, such as
|
||||
`127.0.0.1:6767,100.101.102.103:6767`. A Unix socket or named pipe path is always one address, even
|
||||
if it contains a comma. `PASEO_LISTEN` and `--listen` accept the same forms.
|
||||
|
||||
The first address is the main listener. Restart after changing it. Run `paseo reload` to
|
||||
apply changes to extra TCP listeners while the daemon is running. The daemon retries
|
||||
extra addresses that are unavailable and reports their state in `paseo daemon status`.
|
||||
Removing an extra address disconnects clients using it.
|
||||
|
||||
Use a single address before downgrading to a daemon version that predates listen lists.
|
||||
|
||||
## Agent providers
|
||||
|
||||
Agent providers, both the first-class ones Paseo ships with and custom entries you add under `agents.providers`, are documented on their own page.
|
||||
|
||||
@@ -72,22 +72,10 @@ paseo daemon restart
|
||||
|
||||
当你删除 `daemon.relay.enabled` 时,新的主目录会保持中继关闭。如果 daemon 启动时其配置就已经省略了这个字段,它会为了兼容而保持旧版的中继开启行为。编辑较旧的配置时,请显式设置 `daemon.relay.enabled`。
|
||||
|
||||
空闲运行时清理、主监听地址、身份验证、中继端点和 TLS、worktree 分配、服务代理地址、内置的 Web UI、日志、语音合成与识别、语音、凭据以及本地模型设置都需要重启。重新加载会先应用同一文件中的其他有效编辑,再报告这些路径。
|
||||
空闲运行时清理、监听地址、身份验证、中继端点和 TLS、worktree 分配、服务代理地址、内置的 Web UI、日志、语音合成与识别、语音、凭据以及本地模型设置都需要重启。重新加载会先应用同一文件中的其他有效编辑,再报告这些路径。
|
||||
|
||||
部署环境变量和旧版进程管理器参数仍然具有最终决定权。当某个启动覆盖项阻止了文件中已更改的设置生效时,重新加载会在 `overrideControlledPaths` 下报告它。这包括启动设置,例如监听地址、密码、中继端点和 TLS、服务代理和 Web UI 设置、日志、语音合成与识别以及语音配置。主机名和 CORS 来源等列表设置仍然在各个来源之间追加,因此 `config.json` 中的值继续生效。要让文件中的值具有决定权,请停止该部署并在不带覆盖项的情况下重新启动。
|
||||
|
||||
## 监听地址 {#listen-addresses}
|
||||
|
||||
将 `daemon.listen` 设为一个 TCP 地址,或用逗号分隔多个 TCP 地址,例如
|
||||
`127.0.0.1:6767,100.101.102.103:6767`。Unix 套接字或命名管道的路径即使包含逗号,也始终是一个地址。
|
||||
`PASEO_LISTEN` 和 `--listen` 支持相同的格式。
|
||||
|
||||
第一个地址是主监听地址。更改后请重启 daemon。运行 `paseo reload`,即可在 daemon 运行时应用额外 TCP 监听地址的更改。
|
||||
daemon 会重试暂时不可用的额外地址,并在 `paseo daemon status` 中显示它们的状态。
|
||||
移除额外地址会断开使用该地址的客户端连接。
|
||||
|
||||
如果要降级到仅支持单个监听地址的 daemon 版本,请先将配置改为单个地址。
|
||||
|
||||
## Agent Provider {#agent-providers}
|
||||
|
||||
Agent Provider,包括 Paseo 自带的一等 Provider 和你在 `agents.providers` 下添加的自定义条目,都在单独的页面中介绍。
|
||||
|
||||
@@ -57,7 +57,7 @@ Relay is disabled until you enable it.
|
||||
|
||||
### Enable relay from Paseo Desktop
|
||||
|
||||
1. Open **Settings → your host → Devices → Relay**.
|
||||
1. Open **Settings → your host → Pair a device**.
|
||||
2. Select **Enable relay**.
|
||||
3. Scan the QR code with Paseo on your phone, or copy the pairing link and paste it into the phone app.
|
||||
|
||||
@@ -75,10 +75,49 @@ Confirm when prompted. Paseo prints a QR code and pairing link. Scan the QR code
|
||||
|
||||
Install [Tailscale](https://tailscale.com/download) on the daemon machine and your phone. Sign in to the same tailnet on both devices.
|
||||
|
||||
1. On a device already connected to the host, open **Settings → your host → Devices**. You can also use the phone step during setup.
|
||||
2. Turn on **Tailscale** and copy the address.
|
||||
3. In Paseo on your phone, open **Settings → Add host → Direct connection**.
|
||||
4. Enter the IP in **Host** and the number after it in **Port**. Leave **Use SSL** off, then select **Connect**.
|
||||
### 1. Find the daemon machine's Tailscale IP
|
||||
|
||||
Run this on the daemon machine:
|
||||
|
||||
```bash
|
||||
tailscale ip -4
|
||||
```
|
||||
|
||||
Copy the address it prints. The example below uses `100.101.102.103`.
|
||||
|
||||
### 2. Configure the daemon
|
||||
|
||||
Open `~/.paseo/config.json` and set `daemon.listen` to the Tailscale IP:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://paseo.sh/schemas/paseo.config.v1.json",
|
||||
"version": 1,
|
||||
"daemon": {
|
||||
"listen": "100.101.102.103:6767"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Keep the other settings already in the file. If it has a `daemon` object, add `listen` inside that object.
|
||||
|
||||
To restrict access with a password, see [Password authentication](/docs/configuration#password-authentication).
|
||||
|
||||
Restart the daemon:
|
||||
|
||||
```bash
|
||||
paseo daemon restart
|
||||
```
|
||||
|
||||
If Paseo Desktop manages the daemon, use **Settings → your host → Overview → Restart daemon**.
|
||||
|
||||
### 3. Connect the phone app
|
||||
|
||||
1. Connect Tailscale on your phone.
|
||||
2. Open Paseo and go to **Settings → Add host → Direct connection**.
|
||||
3. Enter the Tailscale IP in **Host**.
|
||||
4. Enter `6767` in **Port**.
|
||||
5. Leave **Use SSL** off and select **Connect**.
|
||||
|
||||
If the host was already paired through the relay, Paseo adds the direct connection to the same host.
|
||||
|
||||
@@ -89,4 +128,4 @@ If the host was already paired through the relay, Paseo adds the direct connecti
|
||||
- **SSH connects but Paseo reports "Password required":** The remote daemon is password-protected. Remove the SSH connection from the host and add it again, this time entering the daemon password in **Daemon password**.
|
||||
- **Connection timed out:** Check that Tailscale is connected on both devices and that you used the daemon machine's Tailscale IP.
|
||||
- **Connection refused:** Run `paseo daemon status` and confirm the daemon is running on the configured IP and port.
|
||||
- **Config change has no effect:** Run `paseo reload`. Restart if the command reports a change to the main listen address.
|
||||
- **Config change has no effect:** Run `paseo reload`. `daemon.listen` is a startup setting, so restart when the command reports it.
|
||||
|
||||
@@ -55,7 +55,7 @@ paseo --host 'ssh://user@host?daemonPort=7777' ls -a
|
||||
|
||||
### 在 Paseo 桌面端启用中继 {#enable-relay-from-paseo-desktop}
|
||||
|
||||
1. 打开 **设置 → 你的主机 → 设备 → 中继**。
|
||||
1. 打开 **设置 → 你的主机 → 配对设备**。
|
||||
2. 选择 **启用中继**。
|
||||
3. 用手机上的 Paseo 扫描二维码,或者复制配对链接并粘贴到手机应用中。
|
||||
|
||||
@@ -73,12 +73,51 @@ paseo daemon pair
|
||||
|
||||
在 daemon 所在的机器和你的手机上安装 [Tailscale](https://tailscale.com/download),并在两台设备上登录同一个 tailnet。
|
||||
|
||||
1. 在已连接到主机的设备上,打开 **设置 → 你的主机 → 设备**。你也可以在初始设置的手机步骤中操作。
|
||||
2. 打开 **Tailscale** 并复制地址。
|
||||
3. 在手机上的 Paseo 中,打开 **设置 → 添加主机 → 直接连接**。
|
||||
4. 在 **Host** 中输入 IP,在 **端口** 中输入端口号。保持 **使用 SSL** 关闭,然后选择 **连接**。
|
||||
### 1. 找到 daemon 机器的 Tailscale IP {#1-find-the-daemon-machines-tailscale-ip}
|
||||
|
||||
如果你已通过中继配对此主机,Paseo 会将直连添加到同一主机。
|
||||
在 daemon 机器上运行:
|
||||
|
||||
```bash
|
||||
tailscale ip -4
|
||||
```
|
||||
|
||||
复制它打印出的地址。下面的示例使用 `100.101.102.103`。
|
||||
|
||||
### 2. 配置 daemon {#2-configure-the-daemon}
|
||||
|
||||
打开 `~/.paseo/config.json`,把 `daemon.listen` 设置为 Tailscale IP:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://paseo.sh/schemas/paseo.config.v1.json",
|
||||
"version": 1,
|
||||
"daemon": {
|
||||
"listen": "100.101.102.103:6767"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
保留文件中已有的其他设置。如果文件中已有 `daemon` 对象,请把 `listen` 加到该对象中。
|
||||
|
||||
如需用密码限制访问,请参见[密码认证](/docs/configuration#password-authentication)。
|
||||
|
||||
重启 daemon:
|
||||
|
||||
```bash
|
||||
paseo daemon restart
|
||||
```
|
||||
|
||||
如果 daemon 由 Paseo 桌面端管理,请使用 **设置 → 你的主机 → 概览 → 重启 Daemon**。
|
||||
|
||||
### 3. 连接手机应用 {#3-connect-the-phone-app}
|
||||
|
||||
1. 在手机上连接 Tailscale。
|
||||
2. 打开 Paseo,进入 **设置 → 添加主机 → 直接连接**。
|
||||
3. 在 **Host** 中输入 Tailscale IP。
|
||||
4. 在 **端口** 中输入 `6767`。
|
||||
5. 保持 **使用 SSL** 关闭,然后选择 **连接**。
|
||||
|
||||
如果该主机已经通过中继配对过,Paseo 会把直连添加到同一个主机上。
|
||||
|
||||
## 故障排查 {#troubleshooting}
|
||||
|
||||
@@ -87,4 +126,4 @@ paseo daemon pair
|
||||
- **SSH 能连上但 Paseo 报告 “Password required”**:远程 daemon 受密码保护。从主机中移除这个 SSH 连接并重新添加,这次在 **守护进程密码** 中输入 daemon 密码。
|
||||
- **连接超时**:检查两台设备上的 Tailscale 是否都已连接,以及你使用的是否是 daemon 机器的 Tailscale IP。
|
||||
- **连接被拒绝**:运行 `paseo daemon status`,确认 daemon 正在配置的 IP 和端口上运行。
|
||||
- **配置修改没有生效**:运行 `paseo reload`。如果命令报告主监听地址发生变化,请重启。
|
||||
- **配置修改没有生效**:运行 `paseo reload`。`daemon.listen` 是启动时生效的设置,所以当命令提示时请重启。
|
||||
|
||||
Reference in New Issue
Block a user