diff --git a/docs/glossary.md b/docs/glossary.md index 16f760ef40..666e38ffa9 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -10,6 +10,7 @@ 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. diff --git a/packages/app/e2e/browser/onboarding.spec.ts b/packages/app/e2e/browser/onboarding.spec.ts index e1b5bac3f4..92978712d9 100644 --- a/packages/app/e2e/browser/onboarding.spec.ts +++ b/packages/app/e2e/browser/onboarding.spec.ts @@ -15,7 +15,7 @@ import { closeRelayPairing, emptyHome, loadingScreen, - openTailscaleDocsFromSetup, + expectTailscaleSwitchDisabled, paseoToolsSwitch, pickTheme, projectSuggestion, @@ -403,12 +403,10 @@ test("setup choices carry over to Settings and the phone step pairs over relay", await continueSetup(page); }); - await test.step("Phone offers Tailscale docs and pairs over relay in its own modal", async () => { + await test.step("Phone shows a disabled Tailscale switch and pairs over relay", async () => { await expectSetupStep(page, "Take your agents with you"); await page.screenshot({ path: testInfo.outputPath("5-phone.png") }); - expect(await openTailscaleDocsFromSetup(page)).toBe( - "https://paseo.sh/docs/connectivity#tailscale", - ); + await expectTailscaleSwitchDisabled(page); const pairing = await openRelayPairingFromSetup(page); await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible(); await enableRelayAndExpectOffer(page); diff --git a/packages/app/e2e/browser/pair-device-relay.spec.ts b/packages/app/e2e/browser/pair-device-relay.spec.ts index dbd3814d38..918a5befb7 100644 --- a/packages/app/e2e/browser/pair-device-relay.spec.ts +++ b/packages/app/e2e/browser/pair-device-relay.spec.ts @@ -1,7 +1,24 @@ +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, @@ -37,3 +54,59 @@ 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(); + } +}); diff --git a/packages/app/e2e/mobile/pair-device/android.mjs b/packages/app/e2e/mobile/pair-device/android.mjs index 7ab660c2b0..4a416109b6 100644 --- a/packages/app/e2e/mobile/pair-device/android.mjs +++ b/packages/app/e2e/mobile/pair-device/android.mjs @@ -1,4 +1,4 @@ -// Start on Settings > Host > Pair device with relay enabled in the Android app. +// Start on Settings > Host > Devices with relay enabled in the Android app. // node packages/app/e2e/mobile/pair-device/android.mjs import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; @@ -13,11 +13,7 @@ function ad(...args) { }); } -ad( - "press", - 'label="Pair a device, Scan a QR code or copy a link to connect your phone to this host"', - "--settle", -); +ad("press", 'label="Relay"', "--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"); diff --git a/packages/app/e2e/support/helpers/isolated-host-daemon.ts b/packages/app/e2e/support/helpers/isolated-host-daemon.ts index e1df2f8f62..3f02e7c55a 100644 --- a/packages/app/e2e/support/helpers/isolated-host-daemon.ts +++ b/packages/app/e2e/support/helpers/isolated-host-daemon.ts @@ -1,4 +1,5 @@ import { promisify } from "node:util"; +import { once } from "node:events"; import { spawn, execFile, @@ -11,6 +12,7 @@ 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"; @@ -64,12 +66,14 @@ export async function getAvailableHostDaemonPort(): Promise { * 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. + * EADDRINUSE. Only the daemon's own status reports its server id. Published + * daemons can serve status before they accept WebSocket upgrades. */ async function waitForServer( port: number, child: ChildProcess, identity: { serverId: string; paseoHome: string }, + published: boolean, ): Promise { const deadline = Date.now() + 90_000; let lastError: unknown = null; @@ -82,7 +86,10 @@ async function waitForServer( } try { const serverId = await readServerId(port, identity.paseoHome); - if (serverId === identity.serverId) return; + if (serverId === identity.serverId) { + if (published) await checkWebSocketUpgrade(port); + return; + } lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`); } catch (error) { lastError = error; @@ -97,6 +104,12 @@ async function waitForServer( ); } +async function checkWebSocketUpgrade(port: number): Promise { + 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 @@ -246,7 +259,7 @@ export async function startIsolatedHostDaemon( }); try { - await waitForServer(port, spawned, { serverId, paseoHome }); + await waitForServer(port, spawned, { serverId, paseoHome }, Boolean(publishedPackageRoot)); return spawned; } catch (error) { throw new Error( diff --git a/packages/app/e2e/support/helpers/onboarding.ts b/packages/app/e2e/support/helpers/onboarding.ts index 0b8d89021b..f22311acfd 100644 --- a/packages/app/e2e/support/helpers/onboarding.ts +++ b/packages/app/e2e/support/helpers/onboarding.ts @@ -161,7 +161,7 @@ export async function finishSetup(page: Page): Promise { /** Opens the Phone step's Relay row: the pair device modal, over setup. */ export async function openRelayPairingFromSetup(page: Page): Promise { await setupModal(page).getByRole("button", { name: "Relay", exact: true }).click(); - const pairing = page.getByTestId("onboarding-pair-device-card"); + const pairing = page.getByTestId("devices-relay-pairing"); await expect(pairing).toBeVisible(); return pairing; } @@ -171,20 +171,9 @@ export async function closeRelayPairing(pairing: Locator): Promise { await expect(pairing).toHaveCount(0); } -/** Clicks the Phone step's Tailscale row and returns the docs page it opened. */ -export async function openTailscaleDocsFromSetup(page: Page): Promise { - await page - .context() - .route("https://paseo.sh/**", (route) => - route.fulfill({ contentType: "text/html", body: "Paseo docs" }), - ); - 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 async function expectTailscaleSwitchDisabled(page: Page): Promise { + const setup = setupModal(page); + await expect(setup.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled(); } export interface SetupHost { diff --git a/packages/app/e2e/support/helpers/pair-device.ts b/packages/app/e2e/support/helpers/pair-device.ts index 46cdda5ed9..75ec2b184f 100644 --- a/packages/app/e2e/support/helpers/pair-device.ts +++ b/packages/app/e2e/support/helpers/pair-device.ts @@ -9,6 +9,8 @@ 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 { @@ -60,9 +62,33 @@ export async function prepareLocalPairingHost( await preparePairingHost(page, daemon, additionalHosts); } +type PairingHost = + | Pick + | Pick; + export async function preparePairingHost( page: Page, - daemon: IsolatedHostDaemon | OutdatedDaemon, + daemon: PairingHost, + additionalHosts: PairingHostInput[] = [], +): Promise { + 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 { + await openAppOnPairingHost(page, daemon); + await showSetupAgainFromSettings(page); + await goToSetupStep(page, "Mobile"); +} + +async function openAppOnPairingHost( + page: Page, + daemon: PairingHost, additionalHosts: PairingHostInput[] = [], ): Promise { await seedSavedSettingsHosts(page, [ @@ -74,20 +100,271 @@ export async function preparePairingHost( ...additionalHosts, ]); await gotoAppShell(page); - 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 enableTailscale(page: Page): Promise { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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> { + 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, +): Promise { + 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 | 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 { + 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(); } export async function openPairDeviceModal(page: Page): Promise { - await page.getByRole("button", { name: /Pair a device/ }).click(); - await expect(page.getByTestId("host-page-pair-device-card")).toBeVisible(); + await page.getByRole("button", { name: "Relay", exact: true }).click(); + await expect(page.getByTestId("devices-relay-pairing")).toBeVisible(); } export async function expectRelayConsent(page: Page): Promise { - const modal = page.getByTestId("host-page-pair-device-card"); + const modal = page.getByTestId("devices-relay-pairing"); 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(); @@ -99,7 +376,7 @@ export async function expectRelayConsent(page: Page): Promise { export async function declineRelay(page: Page): Promise { await page.getByRole("button", { name: "Not now", exact: true }).click(); - await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0); + await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0); } export async function enableRelayAndExpectOffer(page: Page): Promise { @@ -124,10 +401,10 @@ export async function expectPairingOffer(page: Page): Promise { export async function closePairDeviceModal(page: Page): Promise { await page - .getByTestId("host-page-pair-device-card") + .getByTestId("devices-relay-pairing") .getByRole("button", { name: "Close", exact: true }) .click(); - await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0); + await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0); } export async function reloadAndOpenPairDevice(page: Page): Promise { @@ -145,7 +422,7 @@ export async function enableRelayAndExpectFailure( expectedError = "Relay is controlled by a daemon launch override", ): Promise { await page.getByRole("button", { name: "Enable relay", exact: true }).click(); - const modal = page.getByTestId("host-page-pair-device-card"); + const modal = page.getByTestId("devices-relay-pairing"); 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); @@ -155,7 +432,7 @@ export async function retryRelayAndExpectFailure( page: Page, expectedError = "Relay is controlled by a daemon launch override", ): Promise { - const modal = page.getByTestId("host-page-pair-device-card"); + const modal = page.getByTestId("devices-relay-pairing"); 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(); @@ -173,7 +450,7 @@ export async function openPairDeviceFromHome(page: Page): Promise { } export async function expectRelayUpdateRequired(page: Page): Promise { - const modal = page.getByTestId("host-page-pair-device-card"); + const modal = page.getByTestId("devices-relay-pairing"); await expect( modal.getByText("Update the host to enable relay from Paseo Desktop."), ).toBeVisible(); @@ -195,15 +472,15 @@ export function observePairingOfferRequests(page: Page, daemon: OutdatedDaemon): } export async function expectPairingDisconnected(page: Page): Promise { - const modal = page.getByTestId("host-page-pair-device-card"); + const modal = page.getByTestId("devices-relay-pairing"); 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 { await selectSettingsHost(page, serverId); - await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "pair-device")); - await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible(); + await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices")); + await expect(page.getByTestId("devices-relay")).toBeVisible(); } export async function openRelaySecurityDocs(page: Page): Promise { diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index bd6664f067..59aa566fce 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -66,7 +66,7 @@ export type SettingsSection = keyof typeof SECTION_LABELS; type HostSection = | "projects" | "connections" - | "pair-device" + | "devices" | "agents" | "metadata" | "voice" diff --git a/packages/app/e2e/support/helpers/tailscale-daemon.ts b/packages/app/e2e/support/helpers/tailscale-daemon.ts new file mode 100644 index 0000000000..8d9bd4043a --- /dev/null +++ b/packages/app/e2e/support/helpers/tailscale-daemon.ts @@ -0,0 +1,33 @@ +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; + } +} diff --git a/packages/app/src/app/settings/hosts/[serverId]/[hostSection].tsx b/packages/app/src/app/settings/hosts/[serverId]/[hostSection].tsx index dd870e6817..7f8b4c21ef 100644 --- a/packages/app/src/app/settings/hosts/[serverId]/[hostSection].tsx +++ b/packages/app/src/app/settings/hosts/[serverId]/[hostSection].tsx @@ -1,8 +1,8 @@ -import { useLocalSearchParams } from "expo-router"; +import { Redirect, useLocalSearchParams } from "expo-router"; import { useMemo } from "react"; import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary"; import SettingsScreen from "@/screens/settings-screen"; -import { normalizeHostSectionSlug } from "@/utils/host-routes"; +import { buildSettingsHostSectionRoute, normalizeHostSectionSlug } from "@/utils/host-routes"; export default function SettingsHostSectionRoute() { const params = useLocalSearchParams<{ serverId?: string; hostSection?: string }>(); @@ -11,6 +11,10 @@ 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 ; + } + return ( diff --git a/packages/app/src/components/settings/collapsible-row.tsx b/packages/app/src/components/settings/collapsible-row.tsx index d219c3abd5..00b54ac3c7 100644 --- a/packages/app/src/components/settings/collapsible-row.tsx +++ b/packages/app/src/components/settings/collapsible-row.tsx @@ -1,9 +1,7 @@ -import { Children, isValidElement, useCallback, useMemo, useState, type ReactNode } from "react"; +import { useCallback, useMemo, useState, type ReactNode } from "react"; import { View } from "react-native"; -import { StyleSheet } from "react-native-unistyles"; import { isWeb } from "@/constants/platform"; -import { settingsStyles } from "@/styles/settings"; -import { NestedSettingsRows } from "./row-density"; +import { SettingsRowChildren } from "./row-children"; import { SettingsRowHeader } from "./row-header"; interface SettingsCollapsibleRowProps { @@ -48,27 +46,7 @@ export function SettingsCollapsibleRow({ webAccessibilityProps={webExpandedProps} testID={testID ? `${testID}-toggle` : undefined} /> - {expanded ? ( - - - {Children.toArray(children).map((child, index) => ( - - {child} - - ))} - - - ) : null} + {expanded ? {children} : null} ); } - -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, - }, -})); diff --git a/packages/app/src/components/settings/index.tsx b/packages/app/src/components/settings/index.tsx index f8153b0ff2..e85c4f9b91 100644 --- a/packages/app/src/components/settings/index.tsx +++ b/packages/app/src/components/settings/index.tsx @@ -25,7 +25,10 @@ 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"; @@ -36,11 +39,16 @@ 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. */ +/** + * 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. + */ 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; } interface AppSettingsRowProps extends Omit, AppRowExtras { @@ -67,6 +75,7 @@ export function SettingsRow({ leading, labelAccessory, hint, + link, error, children, testID, @@ -74,20 +83,17 @@ 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 ( {leading ? {leading} : null} - {labelAccessory ? ( - - {label} - {labelAccessory} - - ) : ( - {label} - )} + {typeof hint === "string" ? {hint} : hint} + {link ? ( + + + + ) : null} {error ? ( {error} @@ -103,7 +109,15 @@ export function SettingsRow({ ); } -export function SettingsSwitch({ value, onValueChange, disabled, ...row }: SettingsSwitchProps) { +/** 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 & + Partial> & + AppRowExtras & { value: boolean | null }) { return ( - - - - - - - + ); } diff --git a/packages/app/src/screens/open-project-screen.tsx b/packages/app/src/screens/open-project-screen.tsx index 0f55a9eeb3..2c0784abbe 100644 --- a/packages/app/src/screens/open-project-screen.tsx +++ b/packages/app/src/screens/open-project-screen.tsx @@ -19,7 +19,7 @@ import { HEADER_TOP_PADDING_MOBILE, } from "@/constants/layout"; import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; -import { PairDeviceModal } from "@/desktop/components/pair-device-modal"; +import { PairDeviceModal } from "@/devices"; import { buildSettingsHostSectionRoute } from "@/utils/host-routes"; import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region"; diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index ad6eeb0e4b..59d6f472fb 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -102,7 +102,7 @@ import { } from "@/i18n/locales"; import { HostConnectionsPage, - HostPairDevicePage, + HostDevicesPage, 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: "pair-device", labelKey: "openProject.tiles.pairDevice.title", icon: Smartphone }, + { id: "devices", labelKey: "devices.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 ; case "connections": return ; - case "pair-device": - return ; + case "devices": + return ; case "agents": return ; case "agent-profiles": diff --git a/packages/app/src/screens/settings/host-page.tsx b/packages/app/src/screens/settings/host-page.tsx index 8a1f8c75e5..417a849ce4 100644 --- a/packages/app/src/screens/settings/host-page.tsx +++ b/packages/app/src/screens/settings/host-page.tsx @@ -2,7 +2,6 @@ import { ArrowDown, ArrowUp, ArrowUpToLine, - ChevronRight, Globe, Monitor, Pencil, @@ -14,7 +13,7 @@ import { import type { TFunction } from "i18next"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; -import { Alert, Pressable, Text, View } from "react-native"; +import { Alert, Text, View } from "react-native"; import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles"; import type { TerminalProfile } from "@getpaseo/protocol/messages"; import { @@ -38,7 +37,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 { PairDeviceModal } from "@/desktop/components/pair-device-modal"; +import { WaysToConnect } from "@/devices"; import { useDaemonConfig } from "@/hooks/use-daemon-config"; import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon"; import { @@ -265,19 +264,14 @@ export function HostConnectionsPage({ serverId }: { serverId: string }) { ); } -export function HostPairDevicePage({ serverId }: { serverId: string }) { - const { t } = useTranslation(); +export function HostDevicesPage({ serverId }: { serverId: string }) { const host = useHostProfile(serverId); if (!host) { return ; } - return ( - - - - ); + return ; } export function HostAgentsPage({ serverId }: { serverId: string }) { @@ -1130,39 +1124,6 @@ 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 ( - - - - {t("settings.host.pairDevices.rowTitle")} - {t("settings.host.pairDevices.rowHint")} - - - - - - - ); -} - function RemoveHostSection({ host, isLocalDaemon, diff --git a/packages/app/src/utils/host-routes.test.ts b/packages/app/src/utils/host-routes.test.ts index 2defc505f6..06d0d9200d 100644 --- a/packages/app/src/utils/host-routes.test.ts +++ b/packages/app/src/utils/host-routes.test.ts @@ -246,7 +246,8 @@ describe("global routes", () => { describe("host settings section slugs", () => { it("keeps current host settings sections", () => { expect(normalizeHostSectionSlug("connections")).toBe("connections"); - expect(normalizeHostSectionSlug("pair-device")).toBe("pair-device"); + expect(normalizeHostSectionSlug("devices")).toBe("devices"); + expect(normalizeHostSectionSlug("pair-device")).toBe("devices"); expect(normalizeHostSectionSlug("agents")).toBe("agents"); expect(normalizeHostSectionSlug("metadata")).toBe("metadata"); expect(normalizeHostSectionSlug("workspaces")).toBe("workspaces"); diff --git a/packages/app/src/utils/host-routes.ts b/packages/app/src/utils/host-routes.ts index dfbee07821..f77d0d8a1c 100644 --- a/packages/app/src/utils/host-routes.ts +++ b/packages/app/src/utils/host-routes.ts @@ -515,7 +515,7 @@ export function isSettingsSectionSlug(value: string): value is SettingsSectionSl export const HOST_SECTION_SLUGS = [ "projects", "connections", - "pair-device", + "devices", "agents", "agent-profiles", "metadata", @@ -531,6 +531,7 @@ export const HOST_SECTION_SLUGS = [ export type HostSectionSlug = (typeof HOST_SECTION_SLUGS)[number]; const LEGACY_HOST_SECTION_SLUGS: Record = { + "pair-device": "devices", orchestration: "agents", daemon: "host", }; diff --git a/packages/cli/src/commands/daemon/status.ts b/packages/cli/src/commands/daemon/status.ts index cd499ea6cb..f9be1874e8 100644 --- a/packages/cli/src/commands/daemon/status.ts +++ b/packages/cli/src/commands/daemon/status.ts @@ -6,7 +6,11 @@ import { isSameDaemonInstance, DaemonInstanceError, } from "@getpaseo/server/daemon-control"; -import { readPersistedConfig, resolveConfigFromPersisted } from "@getpaseo/server/configuration"; +import { + readPersistedConfig, + resolveConfigFromPersisted, + getMainListenAddress, +} 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"; @@ -103,6 +107,8 @@ async function probeDaemonStatus( daemonNode: status.nodePath, providers: status.providers, relay: status.relay, + tailscale: status.tailscale, + extraListeners: status.extraListeners, ...(status.terminalsUnavailable ? { terminals: status.terminalsUnavailable } : {}), }; } @@ -127,7 +133,7 @@ function localStatus(home: string, instance: Awaited { + 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 { if (!this.lastServerInfoMessage) throw new DaemonConnectionError("Transport not connected"); if (this.lastServerInfoMessage?.features?.daemonStatusRpc !== true) { @@ -6133,6 +6146,7 @@ export class DaemonClient { requestId: options?.requestId, message: { type: "daemon.get_status.request", + includeProviders: options?.includeProviders, }, responseType: "daemon.get_status.response", timeout: options?.timeout, diff --git a/packages/desktop/e2e/settings-memory.electron.mjs b/packages/desktop/e2e/settings-memory.electron.mjs index 95ab39b6ce..d58f152172 100644 --- a/packages/desktop/e2e/settings-memory.electron.mjs +++ b/packages/desktop/e2e/settings-memory.electron.mjs @@ -23,7 +23,7 @@ const SETTINGS_DESTINATIONS = [ "Overview", "Projects", "Connections", - "Pair device", + "Devices", "Agents", "Metadata", "Workspaces", diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index d3660496a3..266c7cb63a 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -1552,9 +1552,17 @@ 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({ @@ -3622,6 +3630,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ SendAgentMessageRequestSchema, WaitForFinishRequestSchema, DaemonGetStatusRequestSchema, + DaemonTailscaleSetRequestSchema, DaemonGetPairingOfferRequestSchema, DaemonConfigReloadRequestSchema, HubManagementDaemonConnectRequestSchema, @@ -4046,6 +4055,7 @@ 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. @@ -5577,6 +5587,32 @@ 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 @@ -5588,6 +5624,8 @@ 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(), @@ -7802,6 +7840,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ SendAgentMessageResponseMessageSchema, SetVoiceModeResponseMessageSchema, DaemonGetStatusResponseSchema, + DaemonTailscaleSetResponseSchema, DaemonGetPairingOfferResponseSchema, DaemonConfigReloadResponseSchema, HubManagementDaemonConnectResponseSchema, @@ -8564,3 +8603,6 @@ export function parseServerInfoStatusPayload(payload: unknown): ServerInfoStatus } return parsed.data; } + +export type TailscaleStatus = z.infer; +export type DaemonTailscaleSetResponse = z.infer; diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index 4374a5e32d..d679c55547 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -82,6 +82,7 @@ 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", @@ -336,6 +337,7 @@ 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", diff --git a/packages/server/src/server/bootstrap.smoke.test.ts b/packages/server/src/server/bootstrap.smoke.test.ts index a935036459..2a3bc04839 100644 --- a/packages/server/src/server/bootstrap.smoke.test.ts +++ b/packages/server/src/server/bootstrap.smoke.test.ts @@ -68,6 +68,302 @@ 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> | 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((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" } }, @@ -930,6 +1226,47 @@ 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", @@ -937,7 +1274,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"); + const socketPath = path.join(paseoHomeRoot, "run", "paseo.sock,127.0.0.1:12345"); await mkdir(path.dirname(socketPath), { recursive: true }); await mkdir(paseoHome, { recursive: true }); const logger = pino({ level: "silent" }); @@ -967,6 +1304,7 @@ 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, diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index ac1ac49e28..3007c7ae2c 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -25,10 +25,16 @@ import type { Logger } from "pino"; import { z } from "zod"; import { createBranchChangeRouteHandler } from "./script-route-branch-handler.js"; -export type ListenTarget = - | { type: "tcp"; host: string; port: number } - | { type: "socket"; path: string } - | { type: "pipe"; path: string }; +import { + createDaemonListeners, + parseListenString, + formatListenTarget, + formatHostForHttpUrl, + splitListen, + type ListenTarget, + type TailscaleNetwork, +} from "./listeners.js"; +export { parseListenString, formatListenTarget, type ListenTarget } from "./listeners.js"; function resolveBoundListenTarget( listenTarget: ListenTarget, @@ -50,60 +56,6 @@ 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): Promise; @@ -173,6 +125,7 @@ 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"; @@ -270,10 +223,6 @@ 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"; @@ -522,6 +471,7 @@ export interface PaseoDaemon { export interface PaseoDaemonDependencies { builtinPlugins?: BuiltinPluginLoader; lazyTerminalWorker?: boolean; + getTailscaleNetwork?: () => TailscaleNetwork; hubRelationshipRemote?: HubRelationshipRemote; hubRelationshipClock?: HubRelationshipClock; hubRelationshipRetryPolicy?: HubRelationshipRetryPolicy; @@ -588,6 +538,10 @@ 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 ?? {}; @@ -677,6 +631,9 @@ export async function createPaseoDaemon( }); return { mutable: createInitialMutableDaemonConfig(reloaded), + listen: config.configReload + ? resolveListenAddress(resolveReloadEnv(config), config.configReload.cli, persisted) + : persisted.daemon?.listen, overrideControlledPaths: reloaded.overrideControlledPaths, }; }, @@ -731,7 +688,7 @@ export async function createPaseoDaemon( // pattern. const agentMcpAuthToken = randomUUID(); - const listenTarget = parseListenString(config.listen); + const listenTarget = parseListenString(splitListen(config.listen)[0]); const app = express(); app.set("trust proxy", resolveExpressTrustProxySetting(config)); @@ -802,17 +759,17 @@ export async function createPaseoDaemon( app.use(serviceProxy.middleware()); // Host allowlist / DNS rebinding protection (vite-like semantics). - // For non-TCP (unix sockets), skip host validation. - if (listenTarget.type === "tcp") { - app.use((req, res, next) => { + // Validate the accepted connection so extra TCP listeners also enforce the allowlist. + app.use((req, res, next) => { + if (req.socket.localPort !== undefined) { 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 = [ @@ -953,6 +910,14 @@ 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 @@ -1960,6 +1925,9 @@ 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; @@ -1992,6 +1960,7 @@ 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({ @@ -2055,6 +2024,7 @@ 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((resolve) => httpServer.close(() => resolve())); @@ -2130,6 +2100,7 @@ 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(); } diff --git a/packages/server/src/server/config.ts b/packages/server/src/server/config.ts index 5340bbbcd3..b5736e6a30 100644 --- a/packages/server/src/server/config.ts +++ b/packages/server/src/server/config.ts @@ -34,6 +34,7 @@ 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"; @@ -474,11 +475,11 @@ function resolveTrustedProxiesConfig( } // PASEO_LISTEN can be: -// - host:port (TCP) +// - host:port (TCP), with optional comma-separated extra TCP listeners // - /path/to/socket (Unix socket) // - unix:///path/to/socket (Unix socket) // Default is TCP at 127.0.0.1:6767 -function resolveListenAddress( +export function resolveListenAddress( env: NodeJS.ProcessEnv, cli: CliConfigOverrides | undefined, persisted: ReturnType, diff --git a/packages/server/src/server/daemon-config-store.ts b/packages/server/src/server/daemon-config-store.ts index ba2e51a111..0c102d457b 100644 --- a/packages/server/src/server/daemon-config-store.ts +++ b/packages/server/src/server/daemon-config-store.ts @@ -1,3 +1,4 @@ +import type { createDaemonListeners } from "./listeners.js"; import { loadPersistedConfig, savePersistedConfigAsync, @@ -69,6 +70,7 @@ export interface DaemonConfigReloadResult { export interface DaemonConfigReloadSource { resolve(persisted: PersistedConfig): { mutable: MutableDaemonConfig; + listen?: string; overrideControlledPaths: readonly string[]; }; } @@ -423,6 +425,7 @@ export class DaemonConfigStore { private readonly reloadSource: DaemonConfigReloadSource | undefined; private readonly startupPersisted: PersistedConfig; private readonly speechOwner: SpeechSettingsOwner | undefined; + private listeners?: ReturnType; private lastKnownPersisted: PersistedConfig; constructor( @@ -567,6 +570,41 @@ export class DaemonConfigStore { ); } + public attachListeners(listeners: ReturnType) { + 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 { return this.enqueue(() => this.reloadPersisted()); } @@ -609,8 +647,11 @@ 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))) @@ -620,6 +661,11 @@ 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), ); diff --git a/packages/server/src/server/listeners.test.ts b/packages/server/src/server/listeners.test.ts new file mode 100644 index 0000000000..4866704318 --- /dev/null +++ b/packages/server/src/server/listeners.test.ts @@ -0,0 +1,174 @@ +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((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(); + } +}); diff --git a/packages/server/src/server/listeners.ts b/packages/server/src/server/listeners.ts new file mode 100644 index 0000000000..59c33b105f --- /dev/null +++ b/packages/server/src/server/listeners.ts @@ -0,0 +1,337 @@ +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>(); + function open(address: string) { + const { port, host } = parseExtra(address); + const sockets = new Set(); + let retry: ReturnType | 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((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; +} + +// 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, 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(); + 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))), + }; + }, + }; +} diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 105a1885fc..2a56f2eed5 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -639,6 +639,7 @@ export interface SessionOptions { serverId?: string; daemonVersion?: string; daemonRuntimeConfig?: DaemonRuntimeConfig; + getSourceLocalEndpoint?: (source: object) => string | undefined; getWebSocketRuntimeMetrics?: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null; } @@ -902,6 +903,7 @@ 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; @@ -1200,6 +1202,7 @@ export class Session { projectRegistry: this.projectRegistry, logger: this.sessionLogger, }); + this.getSourceLocalEndpoint = options.getSourceLocalEndpoint; this.daemonSession = new DaemonSession({ host: { emit: (msg) => this.emit(msg), @@ -2748,7 +2751,7 @@ export class Session { this.dispatchHubExecutionMessage(msg) ?? this.dispatchCreationMessage(msg, source) ?? this.dispatchAgentLifecycleMessage(msg) ?? - this.dispatchAgentConfigMessage(msg) ?? + this.dispatchConfigMessage(msg, source) ?? this.dispatchCheckoutMessage(msg) ?? this.dispatchWorkspaceLifecycleMessage(msg) ?? this.dispatchWorkspaceFileMessage(msg, source) ?? @@ -3345,7 +3348,10 @@ export class Session { } } - private dispatchAgentConfigMessage(msg: SessionInboundMessage): Promise | undefined { + private dispatchConfigMessage( + msg: SessionInboundMessage, + source?: object, + ): Promise | undefined { switch (msg.type) { case "set_agent_mode_request": return this.agentConfigSession.handleSetAgentModeRequest(msg); @@ -3366,21 +3372,6 @@ 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({ @@ -3395,6 +3386,39 @@ 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 | 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; } diff --git a/packages/server/src/server/session/daemon/daemon-session.ts b/packages/server/src/server/session/daemon/daemon-session.ts index 585fa45573..e1e1bae350 100644 --- a/packages/server/src/server/session/daemon/daemon-session.ts +++ b/packages/server/src/server/session/daemon/daemon-session.ts @@ -1,3 +1,5 @@ +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"; @@ -19,6 +21,8 @@ export interface DaemonRuntimeConfig { worktreesRoot?: string; appBaseUrl?: string; desktopManaged?: boolean; + getListenStatus?: ReturnType["status"]; + setTailscaleEnabled?: DaemonConfigStore["setTailscaleEnabled"]; getRelayConfig(): { enabled: boolean; endpoint: string; @@ -176,8 +180,22 @@ export class DaemonSession { } } + async handleSetTailscaleRequest( + msg: Extract, + localEndpoint?: string, + ): Promise { + 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, + localEndpoint?: string, ): Promise { // 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. @@ -187,7 +205,9 @@ export class DaemonSession { const terminalsUnavailable = this.getTerminalsUnavailable(); try { const pidInfo = await getPidLockInfo(this.paseoHome); - const providers = (await this.listProviderAvailability()).map((p) => ({ + const availability = + msg.includeProviders === false ? [] : await this.listProviderAvailability(); + const providers = availability.map((p) => ({ provider: p.provider, available: p.available, error: p.error ?? null, @@ -205,6 +225,7 @@ export class DaemonSession { relay: this.daemonRuntimeConfig?.getRelayConfig() ?? null, providers, terminalCleanupUnconfirmed, + ...this.daemonRuntimeConfig?.getListenStatus?.(localEndpoint), ...(terminalsUnavailable ? { terminalsUnavailable } : {}), }, }); @@ -223,6 +244,7 @@ export class DaemonSession { relay: null, providers: [], terminalCleanupUnconfirmed, + ...this.daemonRuntimeConfig?.getListenStatus?.(localEndpoint), ...(terminalsUnavailable ? { terminalsUnavailable } : {}), }, }); diff --git a/packages/server/src/server/test-utils/paseo-daemon.ts b/packages/server/src/server/test-utils/paseo-daemon.ts index e989b72ef3..da8e78b8a6 100644 --- a/packages/server/src/server/test-utils/paseo-daemon.ts +++ b/packages/server/src/server/test-utils/paseo-daemon.ts @@ -14,14 +14,17 @@ 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[1]; mcpEnabled?: boolean; mcpDebug?: boolean; @@ -110,6 +113,7 @@ 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: { @@ -195,7 +199,7 @@ async function prepareTestDaemonConfig( daemonVersion: options.daemonVersion, desktopManaged: options.desktopManaged, corsAllowedOrigins: options.corsAllowedOrigins ?? [], - hostnames: true, + hostnames: options.hostnames ?? true, mcpEnabled: options.mcpEnabled ?? true, staticDir, mcpDebug: options.mcpDebug ?? false, diff --git a/packages/server/src/server/test-utils/tailscale-daemon.ts b/packages/server/src/server/test-utils/tailscale-daemon.ts new file mode 100644 index 0000000000..b857f2d170 --- /dev/null +++ b/packages/server/src/server/test-utils/tailscale-daemon.ts @@ -0,0 +1,25 @@ +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; +} diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index c4c1e82e22..dca1300643 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -579,6 +579,7 @@ export class VoiceAssistantWebSocketServer { private readonly hostLinks = new Map(); private readonly pendingConnections: Map = new Map(); private readonly sessions: Map = new Map(); + private readonly socketLocalEndpoints = new WeakMap(); private readonly socketIdentities: Map = new Map(); private readonly externalSessionsByKey: Map = new Map(); private readonly pluginSocketIds = new WeakMap(); @@ -1556,6 +1557,8 @@ 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)); @@ -1691,6 +1694,7 @@ 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()) { @@ -2139,6 +2143,10 @@ 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. @@ -3180,6 +3188,7 @@ export class VoiceAssistantWebSocketServer { } interface SocketRequestMetadata { + localEndpoint?: string; host?: string; origin?: string; userAgent?: string; @@ -3257,6 +3266,8 @@ function extractSocketRequestMetadata(request: unknown): SocketRequestMetadata { url?: unknown; socket?: { remoteAddress?: unknown; + localAddress?: unknown; + localPort?: unknown; }; }; @@ -3268,6 +3279,10 @@ 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 } : {}), diff --git a/public-docs/configuration.md b/public-docs/configuration.md index f89a12dcf7..14a36520ee 100644 --- a/public-docs/configuration.md +++ b/public-docs/configuration.md @@ -74,10 +74,23 @@ 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, 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. +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. 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. diff --git a/public-docs/configuration.zh-CN.md b/public-docs/configuration.zh-CN.md index 532b763907..965c570147 100644 --- a/public-docs/configuration.zh-CN.md +++ b/public-docs/configuration.zh-CN.md @@ -72,10 +72,22 @@ 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` 下添加的自定义条目,都在单独的页面中介绍。 diff --git a/public-docs/connectivity.md b/public-docs/connectivity.md index ce947c8c5e..ad4b603355 100644 --- a/public-docs/connectivity.md +++ b/public-docs/connectivity.md @@ -57,7 +57,7 @@ Relay is disabled until you enable it. ### Enable relay from Paseo Desktop -1. Open **Settings → your host → Pair a device**. +1. Open **Settings → your host → Devices → Relay**. 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,49 +75,10 @@ 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. 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**. +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**. If the host was already paired through the relay, Paseo adds the direct connection to the same host. @@ -128,4 +89,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`. `daemon.listen` is a startup setting, so restart when the command reports it. +- **Config change has no effect:** Run `paseo reload`. Restart if the command reports a change to the main listen address. diff --git a/public-docs/connectivity.zh-CN.md b/public-docs/connectivity.zh-CN.md index 0422719a0f..5a4a356ae2 100644 --- a/public-docs/connectivity.zh-CN.md +++ b/public-docs/connectivity.zh-CN.md @@ -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,51 +73,12 @@ paseo daemon pair 在 daemon 所在的机器和你的手机上安装 [Tailscale](https://tailscale.com/download),并在两台设备上登录同一个 tailnet。 -### 1. 找到 daemon 机器的 Tailscale IP {#1-find-the-daemon-machines-tailscale-ip} +1. 在已连接到主机的设备上,打开 **设置 → 你的主机 → 设备**。你也可以在初始设置的手机步骤中操作。 +2. 打开 **Tailscale** 并复制地址。 +3. 在手机上的 Paseo 中,打开 **设置 → 添加主机 → 直接连接**。 +4. 在 **Host** 中输入 IP,在 **端口** 中输入端口号。保持 **使用 SSL** 关闭,然后选择 **连接**。 -在 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 会把直连添加到同一个主机上。 +如果你已通过中继配对此主机,Paseo 会将直连添加到同一主机。 ## 故障排查 {#troubleshooting} @@ -126,4 +87,4 @@ paseo daemon restart - **SSH 能连上但 Paseo 报告 “Password required”**:远程 daemon 受密码保护。从主机中移除这个 SSH 连接并重新添加,这次在 **守护进程密码** 中输入 daemon 密码。 - **连接超时**:检查两台设备上的 Tailscale 是否都已连接,以及你使用的是否是 daemon 机器的 Tailscale IP。 - **连接被拒绝**:运行 `paseo daemon status`,确认 daemon 正在配置的 IP 和端口上运行。 -- **配置修改没有生效**:运行 `paseo reload`。`daemon.listen` 是启动时生效的设置,所以当命令提示时请重启。 +- **配置修改没有生效**:运行 `paseo reload`。如果命令报告主监听地址发生变化,请重启。