feat(devices): enable Tailscale from host settings

Let users connect a phone over Tailscale without editing daemon configuration or restarting the host. Keep the main listener available while the Tailscale listener changes.
This commit is contained in:
Mohamed Boudra
2026-11-25 13:14:28 +01:00
parent 019f87804e
commit 1c7dea109a
53 changed files with 1867 additions and 466 deletions
+1
View File
@@ -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.
+3 -5
View File
@@ -15,7 +15,7 @@ import {
closeRelayPairing,
emptyHome,
loadingScreen,
openTailscaleDocsFromSetup,
expectTailscaleLockedByLaunch,
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 the Tailscale launch lock 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 expectTailscaleLockedByLaunch(page);
const pairing = await openRelayPairingFromSetup(page);
await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible();
await enableRelayAndExpectOffer(page);
@@ -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,57 @@ 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");
if (!baseURL) throw new Error("Expected the app base URL");
const daemon = await startTailscaleTestDaemon(baseURL);
try {
await preparePairingHost(page, daemon);
await enableTailscale(page);
await expectTailscaleAddress(page, daemon.tailscaleAddress);
await page.screenshot({ path: testInfo.outputPath("devices.png") });
await test.step("While its status loads, the row never shows Tailscale off", async () => {
const address = daemon.tailscaleAddress;
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 300);
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
restoreSpeed();
});
await disableTailscale(page, daemon.tailscaleAddress);
await test.step("Over Tailscale, turning it off asks first and Cancel changes nothing", async () => {
await enableTailscale(page);
await connectThroughTailscale(page, daemon);
await cancelTailscaleTurnOff(page, daemon.tailscaleAddress);
});
await test.step("Confirming turns it off and cuts this connection", async () => {
await confirmTailscaleTurnOff(page, daemon.tailscaleAddress);
});
} finally {
await daemon.close();
}
});
@@ -1,4 +1,4 @@
// Start on Settings > Host > 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 <agent-device-session>
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");
+5 -15
View File
@@ -161,7 +161,7 @@ export async function finishSetup(page: Page): Promise<void> {
/** Opens the Phone step's Relay row: the pair device modal, over setup. */
export async function openRelayPairingFromSetup(page: Page): Promise<Locator> {
await setupModal(page).getByRole("button", { name: "Relay", exact: true }).click();
const pairing = page.getByTestId("onboarding-pair-device-card");
const pairing = page.getByTestId("devices-relay-pairing");
await expect(pairing).toBeVisible();
return pairing;
}
@@ -171,20 +171,10 @@ export async function closeRelayPairing(pairing: Locator): Promise<void> {
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<string> {
await page
.context()
.route("https://paseo.sh/**", (route) =>
route.fulfill({ contentType: "text/html", body: "<title>Paseo docs</title>" }),
);
const popup = page.waitForEvent("popup");
await setupModal(page).getByRole("link", { name: "Tailscale, Docs", exact: true }).click();
const docs = await popup;
await docs.waitForLoadState("domcontentloaded");
const url = docs.url();
await docs.close();
return url;
export async function expectTailscaleLockedByLaunch(page: Page): Promise<void> {
const setup = setupModal(page);
await expect(setup.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
await expect(setup.getByText("Controlled by the command that starts this host")).toBeVisible();
}
export interface SetupHost {
+295 -18
View File
@@ -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<IsolatedHostDaemon, "serverId" | "port">
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
export async function preparePairingHost(
page: Page,
daemon: IsolatedHostDaemon | OutdatedDaemon,
daemon: PairingHost,
additionalHosts: PairingHostInput[] = [],
): Promise<void> {
await openAppOnPairingHost(page, daemon, additionalHosts);
await openSettings(page);
await openSettingsHost(page, daemon.serverId);
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
await openSettingsHostSection(page, daemon.serverId, "devices");
await expect(page.getByTestId("devices-relay")).toBeVisible();
}
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
export async function openSetupMobileStep(page: Page, daemon: PairingHost): Promise<void> {
await openAppOnPairingHost(page, daemon);
await showSetupAgainFromSettings(page);
await goToSetupStep(page, "Mobile");
}
async function openAppOnPairingHost(
page: Page,
daemon: PairingHost,
additionalHosts: PairingHostInput[] = [],
): Promise<void> {
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<void> {
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
await expect(toggle).toBeEnabled();
await expect(toggle).not.toBeChecked();
await toggle.click();
await expect(toggle).toBeChecked();
}
export async function expectTailscaleAddress(page: Page, address: string): Promise<void> {
const row = tailscaleAddressRow(page, address);
await expect(row).toBeVisible();
await expect(
row.getByText("On a phone with Tailscale, add a host at this address"),
).toBeVisible();
await expect(row.getByRole("button", { name: "Copy", exact: true })).toBeVisible();
const response = await fetch(`http://${address}/api/health`);
expect(response.ok).toBe(true);
}
/** The switch shows off as soon as it is tapped; the host stops listening when its answer lands. */
async function expectHostUnreachableAt(address: string): Promise<void> {
await expect
.poll(() =>
fetch(`http://${address}/api/health`).then(
() => "reachable",
() => "unreachable",
),
)
.toBe("unreachable");
}
function tailscaleAddressRow(page: Page, address: string) {
return page.getByTestId("devices-tailscale-address").filter({ hasText: address });
}
export async function disableTailscale(page: Page, address: string): Promise<void> {
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
await expect(toggle).toBeEnabled();
await toggle.click();
await expect(toggle).not.toBeChecked();
await expect(tailscaleAddressRow(page, address)).toHaveCount(0);
await expectHostUnreachableAt(address);
}
/** Reopens the host over its Tailscale address, as a phone on the tailnet would reach it. */
export async function connectThroughTailscale(
page: Page,
daemon: { serverId: string; tailscaleAddress: string },
): Promise<void> {
await preparePairingHost(page, { serverId: daemon.serverId, endpoint: daemon.tailscaleAddress });
await expectTailscaleAddress(page, daemon.tailscaleAddress);
}
const TURN_OFF_QUESTION =
"Turn off Tailscale?\n\nThis device is connected through Tailscale and will lose its connection to the host.";
/**
* Taps the switch off over the Tailscale connection and cancels the question. Every state the row
* commits from the tap to after Cancel must still show Tailscale on with its address: nothing
* changes until the user confirms.
*/
export async function cancelTailscaleTurnOff(page: Page, address: string): Promise<void> {
const row = await recordTailscaleRow(page);
const question = answerNextDialog(page, "dismiss");
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
expect(await question).toBe(TURN_OFF_QUESTION);
await page.waitForTimeout(500);
expect(new Set((await row()).map((state) => `${state.value} ${state.address}`))).toEqual(
new Set(["on true"]),
);
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
await expect(tailscaleAddressRow(page, address)).toBeVisible();
expect((await fetch(`http://${address}/api/health`)).ok).toBe(true);
}
/**
* Confirms turning Tailscale off over the Tailscale connection, which cuts this app off the host.
* Without the host the row shows no value at all, on or off.
*/
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
const question = answerNextDialog(page, "accept");
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
expect(await question).toBe(TURN_OFF_QUESTION);
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
await expectHostUnreachableAt(address);
}
function answerNextDialog(page: Page, answer: "accept" | "dismiss"): Promise<string> {
return new Promise((resolve) => {
page.once("dialog", async (dialog) => {
resolve(dialog.message());
await (answer === "accept" ? dialog.accept() : dialog.dismiss());
});
});
}
interface TailscaleRowState {
/** `none` while the row shows no value yet. */
value: "on" | "off" | "none";
address: boolean;
hint: string;
labelTop: number;
hintTop: number;
}
/**
* Records every state the Tailscale row commits, painted or not: from now on in this page, and
* from the first paint of every page load after it. Recording again starts a new record.
*/
async function recordTailscaleRow(page: Page): Promise<() => Promise<TailscaleRowState[]>> {
const record = () => {
const host = window as unknown as {
tailscaleRow?: { states: unknown[]; last: string; sample(): void };
};
if (host.tailscaleRow) {
host.tailscaleRow.states = [];
host.tailscaleRow.last = "";
host.tailscaleRow.sample();
return;
}
const isVisibleText = (element: Element, text?: string) =>
element.childElementCount === 0 &&
(text === undefined
? (element.textContent ?? "").trim() !== ""
: element.textContent === text) &&
element.getBoundingClientRect().height > 0;
const readValue = (toggle: Element | null) => {
if (!toggle) return "none";
return toggle.getAttribute("aria-checked") === "true" ? "on" : "off";
};
const read = () => {
const label = [...document.querySelectorAll("div, span")].find((element) =>
isVisibleText(element, "Tailscale"),
);
if (!label) return null;
let row: Element = label;
while (row.parentElement && !(row as HTMLElement).innerText.includes("\n")) {
row = row.parentElement;
}
const hint = [...row.querySelectorAll("div, span")].find(
(element) => element !== label && isVisibleText(element),
);
const toggle = document.querySelector('[role="switch"][aria-label="Tailscale"]');
return {
value: readValue(toggle),
address: document.querySelector('[data-testid="devices-tailscale-address"]') !== null,
hint: hint?.textContent ?? "",
labelTop: Math.round(label.getBoundingClientRect().top),
hintTop: Math.round(hint?.getBoundingClientRect().top ?? -1),
};
};
const recorder = {
states: [] as unknown[],
last: "",
sample() {
const state = read();
const key = JSON.stringify(state);
if (state && key !== recorder.last) recorder.states.push(state);
recorder.last = key;
},
};
host.tailscaleRow = recorder;
new MutationObserver(() => recorder.sample()).observe(document, {
subtree: true,
childList: true,
characterData: true,
attributes: true,
});
};
await page.addInitScript(record);
await page.evaluate(record);
return () =>
page.evaluate(
() =>
(window as unknown as { tailscaleRow: { states: TailscaleRowState[] } }).tailscaleRow
.states,
);
}
/**
* Runs `open`, which first shows the Tailscale row of a host with Tailscale on, and checks the row
* from its first state to its last: it starts with no value, never shows Tailscale off, and its
* label and hint keep their text and place until it settles on, with the address below.
*/
export async function expectTailscaleRowLoadsOn(
page: Page,
address: string,
open: () => Promise<void>,
): Promise<void> {
const row = await recordTailscaleRow(page);
await open();
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
await expect(tailscaleAddressRow(page, address)).toBeVisible();
const states = await row();
expect(states[0]?.value).toBe("none");
expect(states.filter((state) => state.value === "off")).toEqual([]);
expect(
new Set(states.map(({ hint, labelTop, hintTop }) => `${hint} ${labelTop} ${hintTop}`)).size,
).toBe(1);
expect(states.at(-1)).toMatchObject({ value: "on", address: true });
}
/**
* Holds every message between the app and the host on `port` for `ms` in each direction, as on a
* slow network. The returned function brings the connection back to full speed.
*/
export async function slowConnectionToHost(
page: Page,
port: number,
ms: number,
): Promise<() => void> {
let delay = ms;
await page.routeWebSocket(wsRoutePatternForPort(String(port)), (app) => {
const host = app.connectToServer();
app.onMessage(
deliverInOrderAfter(
() => delay,
(message) => host.send(message),
),
);
host.onMessage(
deliverInOrderAfter(
() => delay,
(message) => app.send(message),
),
);
});
return () => {
delay = 0;
};
}
function deliverInOrderAfter(
delay: () => number,
deliver: (message: string | Buffer) => void,
): (message: string | Buffer) => void {
const queue: { at: number; message: string | Buffer }[] = [];
let timer: ReturnType<typeof setTimeout> | null = null;
const flush = () => {
timer = null;
while (queue[0] && queue[0].at <= Date.now()) deliver(queue.shift()!.message);
if (queue[0]) timer = setTimeout(flush, queue[0].at - Date.now());
};
return (message) => {
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
if (!timer) flush();
};
}
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
await expect(page.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
}
export async function openPairDeviceModal(page: Page): Promise<void> {
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<void> {
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<void> {
export async function declineRelay(page: Page): Promise<void> {
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<void> {
@@ -124,10 +401,10 @@ export async function expectPairingOffer(page: Page): Promise<void> {
export async function closePairDeviceModal(page: Page): Promise<void> {
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<void> {
@@ -145,7 +422,7 @@ export async function enableRelayAndExpectFailure(
expectedError = "Relay is controlled by a daemon launch override",
): Promise<void> {
await page.getByRole("button", { name: "Enable relay", exact: true }).click();
const modal = page.getByTestId("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<void> {
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<void> {
}
export async function expectRelayUpdateRequired(page: Page): Promise<void> {
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<void> {
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<void> {
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<void> {
+1 -1
View File
@@ -66,7 +66,7 @@ export type SettingsSection = keyof typeof SECTION_LABELS;
type HostSection =
| "projects"
| "connections"
| "pair-device"
| "devices"
| "agents"
| "metadata"
| "voice"
@@ -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;
}
}
@@ -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 <Redirect href={buildSettingsHostSectionRoute(serverId, "devices")} />;
}
return (
<HostRouteBootstrapBoundary>
<SettingsScreen view={view} />
@@ -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 ? (
<View style={styles.children}>
<NestedSettingsRows>
{Children.toArray(children).map((child, index) => (
<View
key={isValidElement(child) ? child.key : index}
style={settingsStyles.rowBorder}
>
{child}
</View>
))}
</NestedSettingsRows>
</View>
) : null}
{expanded ? <SettingsRowChildren>{children}</SettingsRowChildren> : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
// The revealed rows keep the card's rails; the tint is what groups them under their header.
children: {
backgroundColor: theme.colors.surface0,
},
}));
+25 -35
View File
@@ -7,7 +7,7 @@ import {
useRef,
type ReactNode,
} from "react";
import { Text, View } from "react-native";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import type {
SettingsRowProps,
@@ -26,6 +26,8 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { settingsStyles } from "@/styles/settings";
import { ControlSizeProvider } from "@/components/ui/control-size";
import { useSettingsRowLayout } from "./row-density";
import { SettingsRowLabel, type SettingsRowLink } 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 +38,15 @@ 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;
link?: SettingsRowLink;
}
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
@@ -62,37 +68,15 @@ export function SettingsCard({ children, testID }: { children: ReactNode; testID
);
}
export function SettingsRow({
label,
leading,
labelAccessory,
hint,
error,
children,
testID,
}: AppSettingsRowProps) {
export function SettingsRow({ leading, children, testID, ...text }: AppSettingsRowProps) {
const compact = useIsCompactFormFactor();
const layout = useSettingsRowLayout();
const rowStyle = useMemo(() => [layout.row, compact && styles.compactRow], [compact, layout]);
const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]);
return (
<View style={rowStyle} testID={testID}>
{leading ? <View style={styles.leading}>{leading}</View> : null}
<View style={styles.label}>
{labelAccessory ? (
<View style={styles.labelRow}>
<Text style={accessoryTitleStyle}>{label}</Text>
{labelAccessory}
</View>
) : (
<Text style={layout.title}>{label}</Text>
)}
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
{error ? (
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
{error}
</Text>
) : null}
<SettingsRowLabel {...text} />
</View>
{children ? (
<View style={styles.control}>
@@ -103,7 +87,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<SettingsSwitchProps, "onValueChange" | "value"> &
Partial<Pick<SettingsSwitchProps, "onValueChange">> &
AppRowExtras & { value: boolean | null }) {
return (
<SettingsRow {...row}>
<Switch
@@ -204,7 +196,12 @@ export function SettingsInput({
);
}
export function SettingsAction({ actionLabel, onPress, disabled, ...row }: SettingsActionProps) {
export function SettingsAction({
actionLabel,
onPress,
disabled,
...row
}: SettingsActionProps & AppRowExtras) {
return (
<SettingsRow {...row}>
<Button variant="outline" onPress={onPress} disabled={disabled}>
@@ -221,13 +218,6 @@ const styles = StyleSheet.create((theme) => ({
// The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds.
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
labelRow: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[2],
},
accessoryLabel: { flexShrink: 1, minWidth: 0 },
control: { flexShrink: 1, maxWidth: "100%" },
input: { minWidth: 180 },
}));
@@ -0,0 +1,30 @@
import { Children, isValidElement, type ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { settingsStyles } from "@/styles/settings";
import { NestedSettingsRows } from "./row-density";
/**
* Rows that belong to the row above them, such as the rows an expanded row reveals or the details
* a switch turns on. They sit in the same card on a tinted band, laid out as nested rows.
*/
export function SettingsRowChildren({ children }: { children: ReactNode }) {
return (
<View style={styles.band}>
<NestedSettingsRows>
{Children.toArray(children).map((child, index) => (
<View key={isValidElement(child) ? child.key : index} style={settingsStyles.rowBorder}>
{child}
</View>
))}
</NestedSettingsRows>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
// The rows keep the card's rails; the tint is what groups them under the row above.
band: {
backgroundColor: theme.colors.surface0,
},
}));
@@ -0,0 +1,70 @@
import { useMemo, type ReactNode } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
import { settingsStyles } from "@/styles/settings";
import { useSettingsRowLayout } from "./row-density";
export type SettingsRowLink = Pick<ExternalLinkProps, "href" | "label" | "accessibilityLabel">;
export interface SettingsRowLabelProps {
label: string;
/** Shown beside the label, such as a badge. */
labelAccessory?: ReactNode;
/** A string is drawn as the hint line; any other node is drawn as given. */
hint?: ReactNode;
/** A page outside the app that helps with this row, drawn under the hint as "Label ↗". */
link?: SettingsRowLink;
error?: string | null;
}
/**
* The text column shared by settings rows with inline controls and collapsible content.
*/
export function SettingsRowLabel({
label,
labelAccessory,
hint,
link,
error,
}: SettingsRowLabelProps) {
const layout = useSettingsRowLayout();
const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]);
return (
<>
{labelAccessory ? (
<View style={styles.labelRow}>
<Text style={accessoryTitleStyle}>{label}</Text>
<View style={styles.accessory}>{labelAccessory}</View>
</View>
) : (
<Text style={layout.title}>{label}</Text>
)}
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
{link ? (
<View style={styles.link}>
<ExternalLink {...link} />
</View>
) : null}
{error ? (
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
{error}
</Text>
) : null}
</>
);
}
const styles = StyleSheet.create((theme) => ({
labelRow: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[2],
},
accessoryLabel: { flexShrink: 1, minWidth: 0 },
// A badge is taller than the label's line. It hangs into the row's padding instead, so the label
// and hint keep the distances of a row without one.
accessory: { marginVertical: -theme.spacing[1] },
link: { alignItems: "flex-start", marginTop: theme.spacing[1] },
}));
+17 -3
View File
@@ -1,6 +1,7 @@
import { useCallback, useMemo } from "react";
import {
Pressable,
View,
type GestureResponderEvent,
type StyleProp,
type ViewStyle,
@@ -19,7 +20,11 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import type { Theme } from "@/styles/theme";
interface SwitchProps {
value: boolean;
/**
* `null` while the value is not known yet, such as while it loads from a host. The switch's space
* stays reserved and empty, so the switch takes it when the value arrives and nothing moves.
*/
value: boolean | null;
onValueChange?: (value: boolean) => void;
disabled?: boolean;
accessibilityLabel?: string;
@@ -109,7 +114,7 @@ export function Switch({
const handlePress = useCallback(
(event: GestureResponderEvent) => {
event.stopPropagation();
if (disabled) return;
if (disabled || value === null) return;
onValueChange?.(!value);
},
[disabled, onValueChange, value],
@@ -119,7 +124,10 @@ export function Switch({
const isCompact = useIsCompactFormFactor();
const geometry = useMemo(() => switchGeometryForLayout(size, isCompact), [size, isCompact]);
const accessibilityState = useMemo(() => ({ checked: value, disabled }), [value, disabled]);
const accessibilityState = useMemo(
() => ({ checked: value === true, disabled }),
[value, disabled],
);
const pressableStyle = useMemo(
() => [
styles.switchControl,
@@ -134,6 +142,12 @@ export function Switch({
],
[disabled, geometry.hitHeight, geometry.trackHeight, style],
);
const unknownStyle = useMemo(
() => [{ width: geometry.trackWidth, minHeight: geometry.trackHeight }, style],
[geometry.trackWidth, geometry.trackHeight, style],
);
if (value === null) return <View style={unknownStyle} testID={testID} />;
return (
<Pressable
+2
View File
@@ -0,0 +1,2 @@
export { PairDeviceModal } from "./pair-device-modal";
export { WaysToConnect } from "./ways-to-connect";
@@ -1,7 +1,7 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { PairDeviceSection } from "@/desktop/components/pair-device-section";
import { PairDeviceSection } from "@/devices/pair-device-section";
export interface PairDeviceModalProps {
serverId: string;
@@ -23,7 +23,7 @@ import {
const RELAY_DOCS_URL = "https://paseo.sh/docs/security";
export const CONNECTIVITY_DOCS_URL = "https://paseo.sh/docs/connectivity";
export const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
const FLEX_ONE_STYLE = { flex: 1 } as const;
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const ThemedShieldCheck = withUnistyles(ShieldCheck);
+212
View File
@@ -0,0 +1,212 @@
import { useCallback, useMemo } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { SettingsAction, SettingsRowChildren, SettingsSwitch } from "@/components/settings";
import { useToast } from "@/contexts/toast-context";
import { useFetchQuery } from "@/data/query";
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { confirmDialog } from "@/utils/confirm-dialog";
import { copyToClipboard } from "@/utils/copy-to-clipboard";
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
const TAILSCALE_DOWNLOAD_URL = "https://tailscale.com/download";
// A product name, the same in every language.
const LABEL = "Tailscale";
type HostClient = NonNullable<ReturnType<typeof useHostRuntimeClient>>;
/**
* Turns Tailscale on or off for a host and shows the address a phone on the tailnet adds. Renders
* as a row inside a `SettingsCard`; when Tailscale is on, the address is a nested row under it.
*/
export function TailscaleRow({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const connection = useHostRuntimeSnapshot(serverId)?.connectionStatus;
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo);
const updateLink = useMemo(
() => ({ href: UPDATES_DOCS_URL, label: t("devices.tailscale.updateDocs") }),
[t],
);
// COMPAT(tailscale): added in v0.16.0, remove after 2027-05-25 once daemon floor >= v0.16.0.
if (serverInfo && serverInfo.features?.tailscale !== true) {
return (
<SettingsSwitch
label={LABEL}
hint={t("devices.tailscale.update")}
link={updateLink}
value={false}
disabled
/>
);
}
if (client && connection === "online" && serverInfo) {
return <TailscaleControl serverId={serverId} client={client} />;
}
// Without the host the row shows no value: the switch's space stays empty. A host the app has
// reached before keeps its server info, so while the app retries it still reads as disconnected.
const lost = connection === "offline" || connection === "error" || Boolean(serverInfo);
return (
<SettingsSwitch
label={LABEL}
hint={t(lost ? "workspace.terminal.hostDisconnected" : "devices.tailscale.hint")}
value={null}
/>
);
}
function TailscaleControl({ serverId, client }: { serverId: string; client: HostClient }) {
const { t } = useTranslation();
const tailscale = useTailscale(serverId, client);
const { status } = tailscale;
const installLink = useMemo(
() => ({ href: TAILSCALE_DOWNLOAD_URL, label: t("devices.tailscale.install") }),
[t],
);
return (
<>
<SettingsSwitch
label={LABEL}
hint={status ? describe(status, t) : t("devices.tailscale.hint")}
link={status?.state === "unavailable" ? installLink : undefined}
error={tailscale.error}
value={tailscale.value}
disabled={!status || status.state === "unavailable" || Boolean(status.lockedBy)}
onValueChange={tailscale.setEnabled}
/>
{tailscale.address ? <TailscaleAddress address={tailscale.address} /> : null}
</>
);
}
function TailscaleAddress({ address }: { address: string }) {
const { t } = useTranslation();
const toast = useToast();
const copy = useCallback(() => {
void copyToClipboard(address)
.then(() => toast.copied())
.catch(() => toast.error(t("common.errors.error")));
}, [address, t, toast]);
return (
<SettingsRowChildren>
<SettingsAction
label={address}
hint={t("devices.tailscale.address")}
actionLabel={t("common.actions.copy")}
onPress={copy}
testID="devices-tailscale-address"
/>
</SettingsRowChildren>
);
}
/** The line under the label for each Tailscale state, most specific first. */
function describe(status: TailscaleStatus, t: TFunction): string {
if (status.state === "unavailable") return t("devices.tailscale.unavailable");
if (status.state === "waiting") return t("devices.tailscale.waiting");
if (status.lockedBy === "launch") return t("devices.tailscale.launch");
if (status.lockedBy === "main") return t("devices.tailscale.alwaysOn");
return t("devices.tailscale.hint");
}
interface TailscaleChange {
enabled: boolean;
confirmed: boolean;
}
/**
* The host's Tailscale state and the one way to change it. While a change is in flight the switch
* already shows where it is going, so a tap answers at once; the host's answer then settles it.
* Turning Tailscale off over the connection it would cut asks first, and nothing changes on screen
* until the user confirms.
*/
function useTailscale(serverId: string, client: HostClient) {
const { t } = useTranslation();
const queryClient = useQueryClient();
const queryKey = useMemo(() => ["tailscale-status", serverId], [serverId]);
const query = useFetchQuery({
queryKey,
queryFn: async () => {
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
if (!tailscale) throw new Error("Host did not report Tailscale status");
return tailscale;
},
// Tailscale can come up after the host does; polling moves "waiting" to "on" on its own.
refetchInterval: 2_000,
staleTimeMs: 0,
dataShape: "value",
});
const change = useMutation({
mutationFn: async ({ enabled, confirmed }: TailscaleChange) => {
await queryClient.cancelQueries({ queryKey });
return client.setTailscaleEnabled(enabled, confirmed);
},
onSuccess: (result) => queryClient.setQueryData(queryKey, result.tailscale),
});
const status = query.data;
const pending = change.isPending ? change.variables.enabled : undefined;
const on = status?.state === "on" || status?.state === "waiting";
// Not known until the host first answers.
const value = pending ?? (status ? on : null);
const { mutate } = change;
const confirmTurnOff = useCallback(
() =>
confirmDialog({
title: t("devices.tailscale.confirmTitle"),
message: t("devices.tailscale.confirmMessage"),
confirmLabel: t("devices.tailscale.confirmAction"),
cancelLabel: t("common.actions.cancel"),
destructive: true,
}),
[t],
);
const turnOffConfirmed = useCallback(async () => {
if (await confirmTurnOff()) mutate({ enabled: false, confirmed: true });
}, [confirmTurnOff, mutate]);
const disconnects = status?.disconnectsCurrentConnection === true;
const setEnabled = useCallback(
(enabled: boolean) => {
if (!enabled && disconnects) {
void turnOffConfirmed();
return;
}
mutate(
{ enabled, confirmed: false },
{
// The status was stale: the host would cut this connection after all. Its answer has
// already put the row back to on, so the question is asked over what is true.
onSuccess: (result) => {
if (result.confirmationRequired) void turnOffConfirmed();
},
},
);
},
[disconnects, mutate, turnOffConfirmed],
);
let error: string | undefined;
if (change.isError) {
error = t(
change.variables.enabled ? "devices.tailscale.turnOnError" : "devices.tailscale.turnOffError",
);
} else if (query.isError && !status) {
error = t("devices.tailscale.statusError");
}
return {
status,
value,
error,
// A tap is ignored until the host answers the one before it.
setEnabled: change.isPending ? undefined : setEnabled,
address: status?.state === "on" && value ? status.address : null,
};
}
@@ -0,0 +1,51 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
import { StatusBadge } from "@/components/ui/status-badge";
import { PairDeviceModal } from "./pair-device-modal";
import { CONNECTIVITY_DOCS_URL } from "./pair-device-section";
import { TailscaleRow } from "./tailscale-row";
/**
* The ways another device can connect to a host: Relay, which pairs through a QR code in a sheet,
* and Tailscale, a switch and an address. Settings and the setup's phone step show this same block.
*/
export function WaysToConnect({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const [pairing, setPairing] = useState(false);
const openPairing = useCallback(() => setPairing(true), []);
const closePairing = useCallback(() => setPairing(false), []);
const recommended = useMemo(
() => <StatusBadge size="xs" variant="success" label={t("devices.recommended")} />,
[t],
);
const docsLink = useMemo(
() => ({
href: CONNECTIVITY_DOCS_URL,
label: t("devices.docs"),
accessibilityLabel: t("devices.docsAccessibility"),
}),
[t],
);
return (
<SettingsSection title={t("devices.waysToConnect")} link={docsLink}>
<SettingsCard>
<SettingsDetailRow
label={t("devices.relay.title")}
labelAccessory={recommended}
hint={t("devices.relay.hint")}
onPress={openPairing}
testID="devices-relay"
/>
<TailscaleRow serverId={serverId} />
</SettingsCard>
<PairDeviceModal
serverId={serverId}
visible={pairing}
onClose={closePairing}
testID="devices-relay-pairing"
/>
</SettingsSection>
);
}
+25 -8
View File
@@ -1782,12 +1782,6 @@ export const ar: TranslationResources = {
"يتيح لك تطبيق الجوال الأصلي كامل الميزات التحكم في أي كمبيوتر يعمل عليه Paseo من هاتفك",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "اختر طريقة الاتصال",
connectDocs: "الوثائق",
openConnectDocs: "افتح وثائق الاتصال",
recommended: "موصى به",
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
tailscale: { title: "Tailscale", hint: "يتطلب بعض الإعداد" },
},
},
},
@@ -1863,6 +1857,31 @@ export const ar: TranslationResources = {
hostDisconnected: "Host غير متصل",
},
},
devices: {
title: "الأجهزة",
waysToConnect: "طرق الاتصال",
docs: "الوثائق",
docsAccessibility: "افتح وثائق الاتصال",
recommended: "موصى به",
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
tailscale: {
hint: "اتصال مباشر عبر شبكة tailnet الخاصة بك، أدخل عنوانًا",
unavailable: "Tailscale لا يعمل على هذا المضيف",
install: "احصل على Tailscale",
waiting: "في انتظار بدء Tailscale على هذا المضيف",
alwaysOn: "مفعّل دائمًا، لأن هذا المضيف يقبل اتصالات Tailscale بالفعل",
launch: "يتحكم فيه الأمر الذي يشغّل هذا المضيف",
update: "حدّث هذا المضيف لاستخدام Tailscale",
updateDocs: "طريقة التحديث",
address: "على هاتف متصل بـ Tailscale، أضف مضيفًا بهذا العنوان",
statusError: "تعذّر التحقق من Tailscale",
turnOnError: "تعذّر تشغيل Tailscale",
turnOffError: "تعذّر إيقاف Tailscale",
confirmTitle: "إيقاف Tailscale؟",
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
confirmAction: "إيقاف",
},
},
pairing: {
hostPassword: {
title: "كلمة المرور لـ {{host}}",
@@ -2916,9 +2935,7 @@ export const ar: TranslationResources = {
timeout: "نفذ الوقت",
},
pairDevices: {
title: "إقران الأجهزة",
rowTitle: "إقران جهاز",
rowHint: "امسح رمز QR ضوئيًا أو انسخ رابطًا لتوصيل هاتفك بهذا المضيف",
},
skills: {
...en.settings.host.skills,
+26 -8
View File
@@ -1811,12 +1811,6 @@ export const en = {
"The fully featured native mobile app allows you to control any Paseo computer from your phone",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Choose how to connect",
connectDocs: "Docs",
openConnectDocs: "Open connectivity documentation",
recommended: "Recommended",
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
tailscale: { title: "Tailscale", hint: "Requires some setup" },
},
},
},
@@ -1892,6 +1886,32 @@ export const en = {
hostDisconnected: "Host is not connected",
},
},
devices: {
title: "Devices",
waysToConnect: "Ways to connect",
docs: "Docs",
docsAccessibility: "Open connectivity documentation",
recommended: "Recommended",
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
tailscale: {
hint: "Direct over your tailnet, enter an address",
unavailable: "Tailscale is not running on this host",
install: "Get Tailscale",
waiting: "Waiting for Tailscale to start on this host",
alwaysOn: "Always on, because this host already accepts Tailscale connections",
launch: "Controlled by the command that starts this host",
update: "Update this host to use Tailscale",
updateDocs: "How to update",
address: "On a phone with Tailscale, add a host at this address",
statusError: "Could not check Tailscale",
turnOnError: "Could not turn on Tailscale",
turnOffError: "Could not turn off Tailscale",
confirmTitle: "Turn off Tailscale?",
confirmMessage:
"This device is connected through Tailscale and will lose its connection to the host.",
confirmAction: "Turn off",
},
},
pairing: {
hostPassword: {
title: "Password for {{host}}",
@@ -3011,9 +3031,7 @@ export const en = {
timeout: "Timeout",
},
pairDevices: {
title: "Pair devices",
rowTitle: "Pair a device",
rowHint: "Scan a QR code or copy a link to connect your phone to this host",
},
skills: {
sectionTitle: "Orchestration skills",
+26 -8
View File
@@ -1830,12 +1830,6 @@ export const es: TranslationResources = {
"La app móvil nativa completa te permite controlar cualquier ordenador con Paseo desde tu teléfono",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Elige cómo conectarte",
connectDocs: "Docs",
openConnectDocs: "Abrir la documentación de conectividad",
recommended: "Recomendado",
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
tailscale: { title: "Tailscale", hint: "Requiere algo de configuración" },
},
},
},
@@ -1911,6 +1905,32 @@ export const es: TranslationResources = {
hostDisconnected: "Hostno está conectado",
},
},
devices: {
title: "Dispositivos",
waysToConnect: "Formas de conectarse",
docs: "Docs",
docsAccessibility: "Abrir la documentación de conectividad",
recommended: "Recomendado",
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
tailscale: {
hint: "Conexión directa por tu tailnet, introduce una dirección",
unavailable: "Tailscale no se está ejecutando en este host",
install: "Obtener Tailscale",
waiting: "Esperando a que Tailscale se inicie en este host",
alwaysOn: "Siempre activado, porque este host ya acepta conexiones de Tailscale",
launch: "Lo controla el comando que inicia este host",
update: "Actualiza este host para usar Tailscale",
updateDocs: "Cómo actualizar",
address: "En un teléfono con Tailscale, añade un host con esta dirección",
statusError: "No se pudo comprobar Tailscale",
turnOnError: "No se pudo activar Tailscale",
turnOffError: "No se pudo desactivar Tailscale",
confirmTitle: "¿Desactivar Tailscale?",
confirmMessage:
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
confirmAction: "Desactivar",
},
},
pairing: {
hostPassword: {
title: "Contraseña de {{host}}",
@@ -2940,9 +2960,7 @@ export const es: TranslationResources = {
timeout: "Se acabó el tiempo",
},
pairDevices: {
title: "Emparejar dispositivos",
rowTitle: "Emparejar un dispositivo",
rowHint: "Escanee un códigoQRo copie un enlace para conectar su teléfono a este host",
},
skills: {
...en.settings.host.skills,
+25 -8
View File
@@ -1828,12 +1828,6 @@ export const fr: TranslationResources = {
"L'application mobile native complète vous permet de contrôler n'importe quel ordinateur Paseo depuis votre téléphone",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Choisissez comment vous connecter",
connectDocs: "Docs",
openConnectDocs: "Ouvrir la documentation sur la connectivité",
recommended: "Recommandé",
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
tailscale: { title: "Tailscale", hint: "Demande un peu de configuration" },
},
},
},
@@ -1909,6 +1903,31 @@ export const fr: TranslationResources = {
hostDisconnected: "L’hôte n’est pas connecté",
},
},
devices: {
title: "Appareils",
waysToConnect: "Moyens de connexion",
docs: "Docs",
docsAccessibility: "Ouvrir la documentation sur la connectivité",
recommended: "Recommandé",
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
tailscale: {
hint: "Connexion directe via votre tailnet, saisissez une adresse",
unavailable: "Tailscale ne fonctionne pas sur cet hôte",
install: "Obtenir Tailscale",
waiting: "En attente du démarrage de Tailscale sur cet hôte",
alwaysOn: "Toujours activé, car cet hôte accepte déjà les connexions Tailscale",
launch: "Contrôlé par la commande qui démarre cet hôte",
update: "Mettez cet hôte à jour pour utiliser Tailscale",
updateDocs: "Comment mettre à jour",
address: "Sur un téléphone avec Tailscale, ajoutez un hôte à cette adresse",
statusError: "Impossible de vérifier Tailscale",
turnOnError: "Impossible d’activer Tailscale",
turnOffError: "Impossible de désactiver Tailscale",
confirmTitle: "Désactiver Tailscale ?",
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
confirmAction: "Désactiver",
},
},
pairing: {
hostPassword: {
title: "Mot de passe pour {{host}}",
@@ -2942,9 +2961,7 @@ export const fr: TranslationResources = {
timeout: "Délai dépassé",
},
pairDevices: {
title: "Associer des appareils",
rowTitle: "Associer un appareil",
rowHint: "Scannez un QR code ou copiez un lien pour connecter votre téléphone à cet hôte",
},
skills: {
...en.settings.host.skills,
+25 -8
View File
@@ -1802,12 +1802,6 @@ export const ja: TranslationResources = {
"フル機能のネイティブモバイルアプリで、スマートフォンからどの Paseo コンピューターでも操作できます",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "接続方法を選択",
connectDocs: "ドキュメント",
openConnectDocs: "接続のドキュメントを開く",
recommended: "おすすめ",
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
tailscale: { title: "Tailscale", hint: "少し設定が必要です" },
},
},
},
@@ -1883,6 +1877,31 @@ export const ja: TranslationResources = {
hostDisconnected: "ホストが接続されていません",
},
},
devices: {
title: "デバイス",
waysToConnect: "接続方法",
docs: "ドキュメント",
docsAccessibility: "接続のドキュメントを開く",
recommended: "おすすめ",
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
tailscale: {
hint: "tailnet 経由で直接接続、アドレスを入力",
unavailable: "このホストで Tailscale が動作していません",
install: "Tailscale を入手",
waiting: "このホストで Tailscale が起動するのを待っています",
alwaysOn: "常にオン。このホストはすでに Tailscale からの接続を受け付けています",
launch: "このホストを起動するコマンドで制御されています",
update: "Tailscale を使うにはこのホストを更新してください",
updateDocs: "更新方法",
address: "Tailscale を使うスマートフォンで、このアドレスのホストを追加してください",
statusError: "Tailscale を確認できませんでした",
turnOnError: "Tailscale をオンにできませんでした",
turnOffError: "Tailscale をオフにできませんでした",
confirmTitle: "Tailscale をオフにしますか?",
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
confirmAction: "オフにする",
},
},
pairing: {
hostPassword: {
title: "{{host}} のパスワード",
@@ -2908,9 +2927,7 @@ export const ja: TranslationResources = {
timeout: "タイムアウト",
},
pairDevices: {
title: "デバイスをペアリング",
rowTitle: "デバイスをペアリング",
rowHint: "QRコードをスキャンするかリンクをコピーしてスマートフォンをこのホストに接続",
},
skills: {
...en.settings.host.skills,
+25 -8
View File
@@ -1793,12 +1793,6 @@ export const ko: TranslationResources = {
"모든 기능을 갖춘 네이티브 모바일 앱으로 휴대폰에서 어떤 Paseo 컴퓨터든 제어할 수 있습니다",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "연결 방법 선택",
connectDocs: "문서",
openConnectDocs: "연결 문서 열기",
recommended: "권장",
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
tailscale: { title: "Tailscale", hint: "약간의 설정이 필요합니다" },
},
},
},
@@ -1874,6 +1868,31 @@ export const ko: TranslationResources = {
hostDisconnected: "호스트가 연결되어 있지 않습니다",
},
},
devices: {
title: "기기",
waysToConnect: "연결 방법",
docs: "문서",
docsAccessibility: "연결 문서 열기",
recommended: "권장",
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
tailscale: {
hint: "tailnet으로 직접 연결, 주소 입력",
unavailable: "이 호스트에서 Tailscale이 실행 중이 아닙니다",
install: "Tailscale 받기",
waiting: "이 호스트에서 Tailscale이 시작되기를 기다리는 중",
alwaysOn: "항상 켜짐. 이 호스트가 이미 Tailscale 연결을 받고 있습니다",
launch: "이 호스트를 시작하는 명령이 제어합니다",
update: "Tailscale을 사용하려면 이 호스트를 업데이트하세요",
updateDocs: "업데이트 방법",
address: "Tailscale을 사용하는 휴대전화에서 이 주소로 호스트를 추가하세요",
statusError: "Tailscale을 확인하지 못했습니다",
turnOnError: "Tailscale을 켜지 못했습니다",
turnOffError: "Tailscale을 끄지 못했습니다",
confirmTitle: "Tailscale을 끌까요?",
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
confirmAction: "끄기",
},
},
pairing: {
hostPassword: {
title: "{{host}}의 비밀번호",
@@ -2894,9 +2913,7 @@ export const ko: TranslationResources = {
timeout: "시간 초과",
},
pairDevices: {
title: "기기 페어링",
rowTitle: "기기 페어링",
rowHint: "QR 코드를 스캔하거나 링크를 복사하여 휴대폰을 이 호스트에 연결하세요",
},
skills: {
...en.settings.host.skills,
+26 -8
View File
@@ -1815,12 +1815,6 @@ export const ptBR: TranslationResources = {
"O app móvel nativo completo permite controlar qualquer computador com Paseo pelo seu celular",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Escolha como se conectar",
connectDocs: "Docs",
openConnectDocs: "Abrir documentação de conectividade",
recommended: "Recomendado",
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
tailscale: { title: "Tailscale", hint: "Requer alguma configuração" },
},
},
},
@@ -1896,6 +1890,32 @@ export const ptBR: TranslationResources = {
hostDisconnected: "Host não está conectado",
},
},
devices: {
title: "Dispositivos",
waysToConnect: "Formas de conexão",
docs: "Docs",
docsAccessibility: "Abrir documentação de conectividade",
recommended: "Recomendado",
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
tailscale: {
hint: "Conexão direta pela sua tailnet, digite um endereço",
unavailable: "O Tailscale não está em execução neste host",
install: "Baixar o Tailscale",
waiting: "Aguardando o Tailscale iniciar neste host",
alwaysOn: "Sempre ativado, porque este host já aceita conexões do Tailscale",
launch: "Controlado pelo comando que inicia este host",
update: "Atualize este host para usar o Tailscale",
updateDocs: "Como atualizar",
address: "Em um celular com Tailscale, adicione um host com este endereço",
statusError: "Não foi possível verificar o Tailscale",
turnOnError: "Não foi possível ativar o Tailscale",
turnOffError: "Não foi possível desativar o Tailscale",
confirmTitle: "Desativar o Tailscale?",
confirmMessage:
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
confirmAction: "Desativar",
},
},
pairing: {
hostPassword: {
title: "Senha de {{host}}",
@@ -2921,9 +2941,7 @@ export const ptBR: TranslationResources = {
timeout: "Timeout",
},
pairDevices: {
title: "Parear dispositivos",
rowTitle: "Parear um dispositivo",
rowHint: "Escaneie um QR code ou copie um link para conectar seu celular a este host",
},
skills: {
...en.settings.host.skills,
+25 -9
View File
@@ -1815,12 +1815,6 @@ export const ru: TranslationResources = {
"Полнофункциональное нативное мобильное приложение позволяет управлять любым компьютером с Paseo с телефона",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "Выберите способ подключения",
connectDocs: "Документация",
openConnectDocs: "Открыть документацию по подключению",
recommended: "Рекомендуется",
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
tailscale: { title: "Tailscale", hint: "Требует небольшой настройки" },
},
},
},
@@ -1896,6 +1890,31 @@ export const ru: TranslationResources = {
hostDisconnected: "Хост не подключён",
},
},
devices: {
title: "Устройства",
waysToConnect: "Способы подключения",
docs: "Документация",
docsAccessibility: "Открыть документацию по подключению",
recommended: "Рекомендуется",
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
tailscale: {
hint: "Прямое подключение через ваш tailnet, по адресу",
unavailable: "Tailscale не запущен на этом хосте",
install: "Скачать Tailscale",
waiting: "Ожидаем запуска Tailscale на этом хосте",
alwaysOn: "Всегда включено, так как хост уже принимает подключения Tailscale",
launch: "Управляется командой, которая запускает этот хост",
update: "Обновите этот хост, чтобы использовать Tailscale",
updateDocs: "Как обновить",
address: "На телефоне с Tailscale добавьте хост с этим адресом",
statusError: "Не удалось проверить Tailscale",
turnOnError: "Не удалось включить Tailscale",
turnOffError: "Не удалось выключить Tailscale",
confirmTitle: "Выключить Tailscale?",
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
confirmAction: "Выключить",
},
},
pairing: {
hostPassword: {
title: "Пароль для {{host}}",
@@ -2929,10 +2948,7 @@ export const ru: TranslationResources = {
timeout: "Время ожидания истекло",
},
pairDevices: {
title: "Подключение устройств",
rowTitle: "Подключить устройство",
rowHint:
"Отсканируйте QR-код или скопируйте ссылку, чтобы подключить телефон к этому хосту.",
},
skills: {
sectionTitle: "Навыки оркестрации",
+25 -8
View File
@@ -1764,12 +1764,6 @@ export const zhCN: TranslationResources = {
description: "功能完整的原生移动应用让你可以在手机上控制任意一台 Paseo 电脑",
appStore: "App Store",
googlePlay: "Google Play",
connectTitle: "选择连接方式",
connectDocs: "文档",
openConnectDocs: "打开连接文档",
recommended: "推荐",
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
tailscale: { title: "Tailscale", hint: "需要一些设置" },
},
},
},
@@ -1845,6 +1839,31 @@ export const zhCN: TranslationResources = {
hostDisconnected: "Host 未连接",
},
},
devices: {
title: "设备",
waysToConnect: "连接方式",
docs: "文档",
docsAccessibility: "打开连接文档",
recommended: "推荐",
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
tailscale: {
hint: "通过你的 tailnet 直连,输入地址即可",
unavailable: "此主机未运行 Tailscale",
install: "获取 Tailscale",
waiting: "正在等待此主机上的 Tailscale 启动",
alwaysOn: "始终开启,因为此主机已接受 Tailscale 连接",
launch: "由启动此主机的命令控制",
update: "更新此主机以使用 Tailscale",
updateDocs: "如何更新",
address: "在已连接 Tailscale 的手机上,用此地址添加主机",
statusError: "无法检查 Tailscale",
turnOnError: "无法开启 Tailscale",
turnOffError: "无法关闭 Tailscale",
confirmTitle: "关闭 Tailscale?",
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
confirmAction: "关闭",
},
},
pairing: {
hostPassword: {
title: "{{host}} 的密码",
@@ -2850,9 +2869,7 @@ export const zhCN: TranslationResources = {
timeout: "超时",
},
pairDevices: {
title: "配对设备",
rowTitle: "配对设备",
rowHint: "扫描二维码或复制链接,将手机连接到这个 Host",
},
skills: {
...en.settings.host.skills,
@@ -1,17 +1,11 @@
import { useCallback, useMemo, useState } from "react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { AppleIcon } from "@/components/icons/apple-icon";
import { GooglePlayIcon } from "@/components/icons/google-play-icon";
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
import { Button } from "@/components/ui/button";
import { StatusBadge } from "@/components/ui/status-badge";
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
import {
CONNECTIVITY_DOCS_URL,
TAILSCALE_DOCS_URL,
} from "@/desktop/components/pair-device-section";
import { WaysToConnect } from "@/devices";
import { ICON_SIZE } from "@/styles/theme";
import { openExternalUrl } from "@/utils/open-external-url";
@@ -26,33 +20,11 @@ function openUrl(url: string) {
void openExternalUrl(url).catch(console.error);
}
/** Get the app, then connect it: the relay pairs in a modal, Tailscale is a docs page away. */
/** Get the app, then connect it the same ways the host's Devices settings offer. */
export function PhoneStep({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const [isPairing, setIsPairing] = useState(false);
const openAppStore = useCallback(() => openUrl(APP_STORE_URL), []);
const openPlayStore = useCallback(() => openUrl(PLAY_STORE_URL), []);
const openTailscaleDocs = useCallback(() => openUrl(TAILSCALE_DOCS_URL), []);
const openPairing = useCallback(() => setIsPairing(true), []);
const closePairing = useCallback(() => setIsPairing(false), []);
const recommendedBadge = useMemo(
() => (
<StatusBadge
size="xs"
variant="success"
label={t("onboarding.setup.steps.phone.recommended")}
/>
),
[t],
);
const docsLink = useMemo(
() => ({
href: CONNECTIVITY_DOCS_URL,
label: t("onboarding.setup.steps.phone.connectDocs"),
accessibilityLabel: t("onboarding.setup.steps.phone.openConnectDocs"),
}),
[t],
);
return (
<View style={styles.container}>
@@ -64,31 +36,7 @@ export function PhoneStep({ serverId }: { serverId: string }) {
{t("onboarding.setup.steps.phone.googlePlay")}
</Button>
</View>
<SettingsSection title={t("onboarding.setup.steps.phone.connectTitle")} link={docsLink}>
<SettingsCard>
<SettingsDetailRow
label={t("onboarding.setup.steps.phone.relay.title")}
labelAccessory={recommendedBadge}
hint={t("onboarding.setup.steps.phone.relay.hint")}
onPress={openPairing}
testID="onboarding-phone-relay"
/>
<SettingsDetailRow
label={t("onboarding.setup.steps.phone.tailscale.title")}
hint={t("onboarding.setup.steps.phone.tailscale.hint")}
summary={t("onboarding.setup.steps.phone.connectDocs")}
onPress={openTailscaleDocs}
external
testID="onboarding-phone-tailscale"
/>
</SettingsCard>
</SettingsSection>
<PairDeviceModal
serverId={serverId}
visible={isPairing}
onClose={closePairing}
testID="onboarding-pair-device-card"
/>
<WaysToConnect serverId={serverId} />
</View>
);
}
@@ -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";
+4 -4
View File
@@ -100,7 +100,7 @@ import {
} from "@/i18n/locales";
import {
HostConnectionsPage,
HostPairDevicePage,
HostDevicesPage,
HostAgentsPage,
HostSettingsPage,
HostProvidersPage,
@@ -247,7 +247,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: "metadata", labelKey: "settings.hostSections.metadata", icon: Sparkles },
{ id: "voice", labelKey: "settings.hostSections.voice", icon: Mic },
@@ -267,8 +267,8 @@ function renderHostSettingsContent(
return <ProjectsScreen serverId={view.serverId} />;
case "connections":
return <HostConnectionsPage serverId={view.serverId} />;
case "pair-device":
return <HostPairDevicePage serverId={view.serverId} />;
case "devices":
return <HostDevicesPage serverId={view.serverId} />;
case "agents":
return <HostAgentsPage serverId={view.serverId} />;
case "metadata":
@@ -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 {
@@ -37,7 +36,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 {
@@ -264,19 +263,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 <HostNotFound />;
}
return (
<SettingsSection title={t("settings.host.pairDevices.title")}>
<PairDeviceRow serverId={serverId} />
</SettingsSection>
);
return <WaysToConnect serverId={serverId} />;
}
export function HostAgentsPage({ serverId }: { serverId: string }) {
@@ -1097,39 +1091,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 (
<View style={settingsStyles.card}>
<Pressable
style={settingsStyles.row}
onPress={handleOpen}
accessibilityRole="button"
testID="host-page-pair-device-row"
>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.host.pairDevices.rowTitle")}</Text>
<Text style={settingsStyles.rowHint}>{t("settings.host.pairDevices.rowHint")}</Text>
</View>
<ChevronRight size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
<PairDeviceModal
serverId={serverId}
visible={isModalOpen}
onClose={handleClose}
testID="host-page-pair-device-card"
/>
</View>
);
}
function RemoveHostSection({
host,
isLocalDaemon,
+2 -1
View File
@@ -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");
+2 -1
View File
@@ -515,7 +515,7 @@ export function isSettingsSectionSlug(value: string): value is SettingsSectionSl
export const HOST_SECTION_SLUGS = [
"projects",
"connections",
"pair-device",
"devices",
"agents",
"metadata",
"voice",
@@ -530,6 +530,7 @@ export const HOST_SECTION_SLUGS = [
export type HostSectionSlug = (typeof HOST_SECTION_SLUGS)[number];
const LEGACY_HOST_SECTION_SLUGS: Record<string, HostSectionSlug> = {
"pair-device": "devices",
orchestration: "agents",
daemon: "host",
};
+3 -1
View File
@@ -103,6 +103,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 +129,7 @@ function localStatus(home: string, instance: Awaited<ReturnType<typeof readDaemo
listen: instance?.listen ?? null,
serverId: instance?.serverId ?? undefined,
hostname: instance?.hostname ?? null,
configuredListen: config.listen,
configuredListen: config.listen.split(",", 1)[0]?.trim(),
localDaemon,
desktopManaged: instance?.desktopManaged === true,
logPath: daemonLogPath(home),
+14
View File
@@ -123,6 +123,7 @@ import type {
ProviderInstallationCheckUpdatesResponseMessage,
UsageReportEntry,
DaemonGetStatusResponse,
DaemonTailscaleSetResponse,
DaemonGetPairingOfferResponse,
DaemonConfigReloadResponse,
DiagnosticsResponse,
@@ -842,6 +843,7 @@ export interface ShutdownServerOptions {
keepTerminals?: boolean;
}
export interface DaemonStatusOptions {
includeProviders?: boolean;
requestId?: string;
timeout?: number;
}
@@ -6124,6 +6126,17 @@ export class DaemonClient {
});
}
async setTailscaleEnabled(
enabled: boolean,
confirmed = false,
): Promise<DaemonTailscaleSetResponse["payload"]> {
return this.sendCorrelatedSessionRequest({
message: { type: "daemon.tailscale.set.request", enabled, confirmed },
responseType: "daemon.tailscale.set.response",
});
}
/** The Tailscale disconnect flag describes the connection used for this request. */
async getDaemonStatus(options?: DaemonStatusOptions): Promise<DaemonStatusPayload> {
if (!this.lastServerInfoMessage) throw new DaemonConnectionError("Transport not connected");
if (this.lastServerInfoMessage?.features?.daemonStatusRpc !== true) {
@@ -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,
+40
View File
@@ -1551,9 +1551,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({
@@ -3621,6 +3629,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
SendAgentMessageRequestSchema,
WaitForFinishRequestSchema,
DaemonGetStatusRequestSchema,
DaemonTailscaleSetRequestSchema,
DaemonGetPairingOfferRequestSchema,
DaemonConfigReloadRequestSchema,
HubManagementDaemonConnectRequestSchema,
@@ -4045,6 +4054,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.
@@ -5576,6 +5586,30 @@ 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(),
// 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
@@ -5587,6 +5621,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(),
@@ -7801,6 +7837,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
SendAgentMessageResponseMessageSchema,
SetVoiceModeResponseMessageSchema,
DaemonGetStatusResponseSchema,
DaemonTailscaleSetResponseSchema,
DaemonGetPairingOfferResponseSchema,
DaemonConfigReloadResponseSchema,
HubManagementDaemonConnectResponseSchema,
@@ -8563,3 +8600,6 @@ export function parseServerInfoStatusPayload(payload: unknown): ServerInfoStatus
}
return parsed.data;
}
export type TailscaleStatus = z.infer<typeof TailscaleStatusSchema>;
export type DaemonTailscaleSetResponse = z.infer<typeof DaemonTailscaleSetResponseSchema>;
@@ -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",
@@ -68,6 +68,152 @@ 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,
getTailscaleAddress: () => tailscaleAddress,
});
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,
getTailscaleAddress: () => tailscaleAddress,
});
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.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("reload changes only the extra TCP listeners without replacing the main endpoint", async () => {
const daemon = await createTestPaseoDaemon({ relayEnabled: false });
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);
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("starts and serves health endpoint", async () => {
const daemonHandle = await createTestPaseoDaemon({
openai: { stt: { apiKey: "test-openai-api-key" }, tts: { apiKey: "test-openai-api-key" } },
+33 -63
View File
@@ -25,10 +25,15 @@ 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,
} from "./listeners.js";
export { parseListenString, formatListenTarget, type ListenTarget } from "./listeners.js";
function resolveBoundListenTarget(
listenTarget: ListenTarget,
@@ -50,60 +55,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<string>): Promise<void>;
@@ -173,6 +124,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";
@@ -269,10 +221,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";
@@ -521,6 +469,7 @@ export interface PaseoDaemon {
export interface PaseoDaemonDependencies {
builtinPlugins?: BuiltinPluginLoader;
lazyTerminalWorker?: boolean;
getTailscaleAddress?: () => string | null;
hubRelationshipRemote?: HubRelationshipRemote;
hubRelationshipClock?: HubRelationshipClock;
hubRelationshipRetryPolicy?: HubRelationshipRetryPolicy;
@@ -587,6 +536,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 ?? {};
@@ -676,6 +629,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,
};
},
@@ -730,7 +686,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));
@@ -949,6 +905,14 @@ export async function createPaseoDaemon(
});
const httpServer = createHTTPServer(app);
const listeners = createDaemonListeners({
http: httpServer,
listen: config.listen,
overridden: isListenOverridden(config),
getMain: () => boundListenTarget,
getTailscaleAddress: dependencies.getTailscaleAddress,
});
daemonConfigStore.attachListeners(listeners);
// Script proxy WebSocket upgrade handler — must be registered before the
// VoiceAssistantWebSocketServer attaches its own "upgrade" listener so that
@@ -1953,6 +1917,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;
@@ -1985,6 +1952,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({
@@ -2049,6 +2017,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<void>((resolve) => httpServer.close(() => resolve()));
@@ -2125,6 +2094,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();
}
+2 -2
View File
@@ -474,11 +474,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<typeof loadPersistedConfig>,
@@ -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<typeof createDaemonListeners>;
private lastKnownPersisted: PersistedConfig;
constructor(
@@ -567,6 +570,39 @@ export class DaemonConfigStore {
);
}
public attachListeners(listeners: ReturnType<typeof createDaemonListeners>) {
this.listeners = listeners;
}
public setTailscaleEnabled(
enabled: boolean,
localEndpoint: string | undefined,
confirmed: boolean,
) {
return this.enqueue(async () => {
const listeners = this.listeners;
if (!listeners) throw new Error("Tailscale is unavailable");
if (!enabled && !confirmed) {
const status = listeners.status(localEndpoint);
if (status.tailscale.disconnectsCurrentConnection) {
return { confirmationRequired: true, ...status };
}
}
const persisted = await loadPersistedConfigAsync(this.paseoHome, this.logger);
const listen = listeners.edit(persisted.daemon?.listen, enabled);
await savePersistedConfigAsync(
this.paseoHome,
{
...persisted,
daemon: { ...persisted.daemon, listen },
},
this.logger,
);
await listeners.apply(listen);
return { confirmationRequired: false, ...listeners.status(localEndpoint) };
});
}
public reload(): Promise<DaemonConfigReloadResult> {
return this.enqueue(() => this.reloadPersisted());
}
@@ -609,8 +645,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 +659,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),
);
@@ -0,0 +1,102 @@
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, findTailscaleAddress } from "./listeners.js";
test("retries an occupied extra listener and serves the original HTTP handler", async () => {
const blocker = createTcpServer().listen(0, "127.0.0.2");
await once(blocker, "listening");
const address = blocker.address();
if (!address || typeof address === "string") throw new Error("Expected TCP");
const extra = `127.0.0.2:${address.port}`;
const http = createServer((_req, res) => res.end("shared"));
const listeners = createExtraListeners(http, 25);
try {
await listeners.apply([extra]);
expect(listeners.status()).toEqual([{ address: extra, state: "waiting" }]);
await new Promise<void>((resolve) => blocker.close(() => resolve()));
await expect.poll(() => listeners.status()).toEqual([{ address: extra, state: "listening" }]);
expect(await (await fetch(`http://${extra}`)).text()).toBe("shared");
await listeners.apply([]);
expect(listeners.status()).toEqual([]);
await expect(fetch(`http://${extra}`)).rejects.toThrow();
} finally {
await listeners.apply([]);
blocker.close();
}
});
test("requires a Tailscale interface name or IPv6 prefix alongside the IPv4 address", () => {
function ipv4(address: string): NetworkInterfaceInfo {
return {
address,
family: "IPv4",
netmask: "255.255.255.255",
internal: false,
cidr: null,
mac: "",
};
}
expect(findTailscaleAddress(() => ({ eth0: [ipv4("100.101.102.103")] }))).toBeNull();
expect(findTailscaleAddress(() => ({ tailscale0: [ipv4("100.101.102.103")] }))).toBe(
"100.101.102.103",
);
expect(
findTailscaleAddress(() => ({
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,
},
],
})),
).toBe("100.120.121.122");
});
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 }),
getTailscaleAddress: () => "100.101.102.103",
});
expect(listeners.status().tailscale).toMatchObject({
state: "on",
address: "100.101.102.103:6767",
lockedBy: "main",
});
},
);
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 }),
getTailscaleAddress: () => null,
});
try {
await listeners.apply(listen);
expect(listeners.status()).toMatchObject({
tailscale: { ip: null, address, state: "waiting" },
extraListeners: [{ address, state: "waiting" }],
});
} finally {
await listeners.stop();
}
});
+265
View File
@@ -0,0 +1,265 @@
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]:\\/;
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 function splitListen(listen: string): [main: string, ...extras: string[]] {
const [main = "", ...extras] = listen.split(",").map((entry) => entry.trim());
for (const entry of extras) parseExtra(entry);
return [main, ...new Set(extras)];
}
function parseExtra(address: string) {
const target = parseListenString(address);
if (
target.type !== "tcp" ||
target.port < 1 ||
target.port > 65535 ||
!/^.+:\d+$/.test(address)
) {
throw new Error(`Invalid extra TCP listen address: ${address}`);
}
return target;
}
export function createExtraListeners(http: HttpServer, retryMs = 2_000) {
const active = new Map<string, ReturnType<typeof open>>();
function open(address: string) {
const { port, host } = parseExtra(address);
const sockets = new Set<Socket>();
let retry: ReturnType<typeof setTimeout> | undefined;
let stopped = false;
const server = createServer((socket) => {
sockets.add(socket);
socket.once("close", () => sockets.delete(socket));
http.emit("connection", socket);
});
function listen() {
return new Promise<void>((resolve) => {
const settled = () => {
server.off("listening", settled);
server.off("error", settled);
server.off("close", settled);
resolve();
};
server.once("listening", settled);
server.once("error", settled);
server.once("close", settled);
server.listen(port, host);
});
}
server.on("error", () => {
if (!stopped) retry = setTimeout(() => void listen(), retryMs).unref();
});
return {
ready: listen(),
state: () => (server.listening ? ("listening" as const) : ("waiting" as const)),
close() {
stopped = true;
clearTimeout(retry);
server.close();
// Let the request that removed this listener queue its response first.
setImmediate(() => {
for (const socket of sockets) socket.destroy();
});
},
};
}
return {
async apply(addresses: readonly string[]) {
const desired = new Set(addresses);
for (const [address, listener] of active) {
if (desired.has(address)) continue;
listener.close();
active.delete(address);
}
for (const address of desired) {
if (!active.has(address)) active.set(address, open(address));
}
await Promise.all(Array.from(active.values(), (listener) => listener.ready));
},
status() {
return Array.from(active, ([address, listener]) => ({ address, state: listener.state() }));
},
};
}
function isTailnetIPv4(address: string) {
const [first, second = ""] = address.split(".");
return isIPv4(address) && first === "100" && Number(second) >= 64 && Number(second) <= 127;
}
// Saved Tailscale listeners use an extra address in the Tailscale range on the main
// port. The entry can outlive the interface or its current IP.
function isTailscaleListener(
target: ReturnType<typeof parseExtra>,
port: number,
ip: string | null,
) {
return target.port === port && (target.host === ip || isTailnetIPv4(target.host));
}
export function findTailscaleAddress(readInterfaces = networkInterfaces) {
for (const [name, addresses] of Object.entries(readInterfaces())) {
if (!addresses) continue;
if (
!/^tailscale/i.test(name) &&
!addresses.some(({ address }) => address.toLowerCase().startsWith("fd7a:115c:a1e0:"))
) {
continue;
}
const v4 = addresses.find(({ address }) => isTailnetIPv4(address));
if (v4) return v4.address;
}
return null;
}
export function createDaemonListeners(options: {
http: HttpServer;
listen: string;
overridden: boolean;
getMain: () => ListenTarget | null;
getTailscaleAddress?: () => string | null;
}) {
const { http, listen, overridden, getMain, getTailscaleAddress = findTailscaleAddress } = options;
const [startupMain] = splitListen(listen);
const extras = createExtraListeners(http);
let stopped = false;
function describeTailscale() {
const main = getMain();
const ip = getTailscaleAddress();
const extraListeners = extras.status();
const configured = extraListeners.flatMap((listener) => {
const target = parseExtra(listener.address);
if (main?.type !== "tcp" || !isTailscaleListener(target, main.port, ip)) return [];
return [{ target, state: listener.state }];
});
const current = configured.find(({ target }) => target.host === ip);
const shown = current ?? configured[0];
const managedByMain =
main?.type === "tcp" && ip !== null && [ip, "0.0.0.0", "::"].includes(main.host);
let address = shown ? formatListenTarget(shown.target) : null;
if (managedByMain) address = `${ip}:${main.port}`;
let state: "on" | "off" | "waiting" | "unavailable" = ip ? "off" : "unavailable";
if (shown) state = current?.state === "listening" ? "on" : "waiting";
if (managedByMain) state = "on";
let lockedBy: "main" | "launch" | undefined;
if (managedByMain || main?.type !== "tcp") lockedBy = "main";
if (overridden) lockedBy = "launch";
return {
main,
configured,
tailscale: { ip, address, state, ...(lockedBy ? { lockedBy } : {}) },
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);
if (!stopped) await extras.apply(addresses);
return {
restartRequired: main !== startupMain,
applied: JSON.stringify(before) !== JSON.stringify(addresses),
};
},
stop() {
stopped = true;
return extras.apply([]);
},
edit(persisted: string | undefined, enabled: boolean) {
const { main, tailscale } = describeTailscale();
if (stopped || tailscale.lockedBy || main?.type !== "tcp") {
throw new Error("Tailscale listen address cannot be changed");
}
const [first, ...addresses] = splitListen(persisted ?? listen);
if (enabled) {
if (!tailscale.ip) throw new Error("Tailscale is not running");
const alreadyConfigured = addresses.some((entry) => {
const target = parseExtra(entry);
return target.host === tailscale.ip && target.port === main.port;
});
if (!alreadyConfigured) addresses.push(`${tailscale.ip}:${main.port}`);
return [first, ...addresses].join(",");
}
const remaining = addresses.filter(
(entry) => !isTailscaleListener(parseExtra(entry), main.port, tailscale.ip),
);
return [first, ...remaining].join(",");
},
};
}
+41 -17
View File
@@ -639,6 +639,7 @@ export interface SessionOptions {
serverId?: string;
daemonVersion?: string;
daemonRuntimeConfig?: DaemonRuntimeConfig;
getSourceLocalEndpoint?: (source: object) => string | undefined;
getWebSocketRuntimeMetrics?: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null;
}
@@ -898,6 +899,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<MessageReceipts, "send">;
@@ -1196,6 +1198,7 @@ export class Session {
projectRegistry: this.projectRegistry,
logger: this.sessionLogger,
});
this.getSourceLocalEndpoint = options.getSourceLocalEndpoint;
this.daemonSession = new DaemonSession({
host: {
emit: (msg) => this.emit(msg),
@@ -2743,7 +2746,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) ??
@@ -3340,7 +3343,10 @@ export class Session {
}
}
private dispatchAgentConfigMessage(msg: SessionInboundMessage): Promise<void> | undefined {
private dispatchConfigMessage(
msg: SessionInboundMessage,
source?: object,
): Promise<void> | undefined {
switch (msg.type) {
case "set_agent_mode_request":
return this.agentConfigSession.handleSetAgentModeRequest(msg);
@@ -3361,21 +3367,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({
@@ -3390,6 +3381,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<void> | undefined {
switch (msg.type) {
case "daemon.get_status.request":
return this.daemonSession.handleGetStatusRequest(
msg,
source && this.getSourceLocalEndpoint?.(source),
);
case "daemon.tailscale.set.request":
return this.daemonSession.handleSetTailscaleRequest(
msg,
source && this.getSourceLocalEndpoint?.(source),
);
case "daemon.get_pairing_offer.request":
return this.daemonSession.handleGetPairingOfferRequest(msg);
case "daemon.config.reload.request":
return this.daemonSession.handleConfigReloadRequest(msg);
case "hub.management.daemon.connect.request":
case "hub.management.daemon.get_status.request":
case "hub.management.daemon.disconnect.request":
case "hub.management.daemon.permissions.update.request":
return this.daemonSession.handleHubRelationshipRequest(msg);
case "diagnostics.request":
return this.daemonSession.handleDiagnosticsRequest(msg);
case "daemon.update.request":
return this.daemonSession.handleUpdateRequest(msg);
default:
return undefined;
}
@@ -1,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<typeof createDaemonListeners>["status"];
setTailscaleEnabled?: DaemonConfigStore["setTailscaleEnabled"];
getRelayConfig(): {
enabled: boolean;
endpoint: string;
@@ -176,8 +180,22 @@ export class DaemonSession {
}
}
async handleSetTailscaleRequest(
msg: Extract<SessionInboundMessage, { type: "daemon.tailscale.set.request" }>,
localEndpoint?: string,
): Promise<void> {
const setEnabled = this.daemonRuntimeConfig?.setTailscaleEnabled;
if (!setEnabled) throw new Error("Tailscale is unavailable");
const result = await setEnabled(msg.enabled, localEndpoint, msg.confirmed === true);
this.host.emit({
type: "daemon.tailscale.set.response",
payload: { requestId: msg.requestId, ...result },
});
}
async handleGetStatusRequest(
msg: Extract<SessionInboundMessage, { type: "daemon.get_status.request" }>,
localEndpoint?: string,
): Promise<void> {
// Read outside the degraded-status fallback below: a status that cannot say whether
// terminal cleanup finished must fail the request, not report that nothing is left.
@@ -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 } : {}),
},
});
@@ -22,6 +22,7 @@ interface TestPaseoDaemonOptions {
corsAllowedOrigins?: string[];
listen?: string;
listenPort?: number;
getTailscaleAddress?: () => string | null;
logger?: Parameters<typeof createPaseoDaemon>[1];
mcpEnabled?: boolean;
mcpDebug?: boolean;
@@ -110,6 +111,7 @@ export async function createTestPaseoDaemon(
await prepareTestDaemonConfig(options);
const logger = options.logger ?? pino({ level: "silent" });
const daemon = await createPaseoDaemon(config, logger, {
getTailscaleAddress: options.getTailscaleAddress,
builtinPlugins: options.builtinPlugins ?? new BuiltinPluginLoader(undefined, []),
lazyTerminalWorker: options.lazyTerminalWorker ?? true,
serverFeatureOverrides: {
@@ -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],
getTailscaleAddress: () => "127.0.0.2",
});
try {
await writeFile(
path.join(daemon.paseoHome, "config.json"),
JSON.stringify({ version: 1, daemon: { listen: `127.0.0.1:${daemon.port}` } }),
);
process.once("SIGTERM", async () => {
await daemon.close();
process.exit(0);
});
process.send?.({ port: daemon.port, serverId: daemon.daemon.getServerId() });
} catch (error) {
await daemon.close();
throw error;
}
@@ -579,6 +579,7 @@ export class VoiceAssistantWebSocketServer {
private readonly hostLinks = new Map<WebSocketLike, DaemonLinkEndpoint>();
private readonly pendingConnections: Map<WebSocketLike, PendingConnection> = new Map();
private readonly sessions: Map<WebSocketLike, SessionConnection> = new Map();
private readonly socketLocalEndpoints = new WeakMap<object, string>();
private readonly socketIdentities: Map<WebSocketLike, WebSocketConnectionIdentity> = new Map();
private readonly externalSessionsByKey: Map<string, ReconnectableSessionConnection> = new Map();
private readonly pluginSocketIds = new WeakMap<WebSocketLike, string>();
@@ -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 } : {}),
+13 -1
View File
@@ -74,10 +74,22 @@ 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 address or a comma-separated list such as
`127.0.0.1:6767,100.101.102.103:6767`. `PASEO_LISTEN` and `--listen` accept the same format.
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.
+12 -1
View File
@@ -72,10 +72,21 @@ 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` 设为一个地址,或用逗号分隔多个地址,例如
`127.0.0.1:6767,100.101.102.103:6767`。`PASEO_LISTEN` 和 `--listen` 也支持这个格式。
第一个地址是主监听地址。更改后请重启 daemon。运行 `paseo reload`,即可在 daemon 运行时应用额外 TCP 监听地址的更改。
daemon 会重试暂时不可用的额外地址,并在 `paseo daemon status` 中显示它们的状态。
移除额外地址会断开使用该地址的客户端连接。
如果要降级到仅支持单个监听地址的 daemon 版本,请先将配置改为单个地址。
## Agent Provider {#agent-providers}
Agent Provider,包括 Paseo 自带的一等 Provider 和你在 `agents.providers` 下添加的自定义条目,都在单独的页面中介绍。
+5 -44
View File
@@ -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.
+6 -45
View File
@@ -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. 在已连接到主机的设备上,打开 **Settings → 你的主机 → Devices**。你也可以在初始设置的手机步骤中操作。
2. 打开 **Tailscale** 并复制地址。
3. 在手机上的 Paseo 中,打开 **Settings → Add host → Direct connection**。
4. 在 **Host** 中输入 IP,在 **Port** 中输入端口号。保持 **Use SSL** 关闭,然后选择 **Connect**。
在 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`。如果命令报告主监听地址发生变化,请重启。