mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 17:55:18 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd4a72587f | ||
|
|
40b9fd4b3c | ||
|
|
79bbd80ba6 | ||
|
|
5d918a12d2 | ||
|
|
8ce42b4da7 | ||
|
|
2c639b0be0 | ||
|
|
8446b53ff0 | ||
|
|
1c7dea109a |
@@ -87,6 +87,10 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
run: npx --yes lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity
|
||||
|
||||
- name: Verify dependency signatures
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
run: npm audit signatures
|
||||
|
||||
- name: Lint
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
run: npm run lint
|
||||
|
||||
+6
-6
@@ -575,9 +575,8 @@ where the overrides apply; workspace scripts still find the binary through the r
|
||||
|
||||
## Dependency signature audit
|
||||
|
||||
The [pre-release dependency checks](release.md#pre-release-dependency-checks) include
|
||||
`npm audit signatures`. The command verifies registry signatures and, for packages published
|
||||
with provenance, fetches
|
||||
The `quality` CI job runs `npm audit signatures`. It verifies every lockfile package's registry
|
||||
signature and, for packages published with provenance, fetches
|
||||
`/-/npm/v1/attestations/<name>@<version>` from the registry. Cloudflare caches that document
|
||||
for a year. An edge that cached it in the seconds before the registry attached the publish
|
||||
attestation keeps serving a document with only the provenance bundle, and npm fails with:
|
||||
@@ -588,10 +587,11 @@ npm error <name>@<version> has attestations but no corresponding public key(s) c
|
||||
```
|
||||
|
||||
The same package's registry signature verified a moment earlier with the same keys, so the
|
||||
key list is intact. The failure names one package and depends on which Cloudflare edge serves
|
||||
the cached attestation.
|
||||
key list is intact. The failure names one package, repeats only for that package, and depends
|
||||
on the Azure region the runner landed in, because each region maps to one Cloudflare colo. A
|
||||
rerun passes only by landing elsewhere.
|
||||
|
||||
To confirm, fetch the URL from several regions and compare `content-length`, the `cf-ray` colo
|
||||
To confirm, fetch the URL from several runners and compare `content-length`, the `cf-ray` colo
|
||||
suffix, and the number of `attestations` entries (#7730 has the probe). To fix, remove or
|
||||
replace that version in the lockfile. If the dependent’s range cannot be changed, pin a clean
|
||||
version in root `overrides`. Report the URL to npm so they purge it.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -883,13 +883,6 @@ its Zod schema, and mounts the component inside the normal plugin runtime and er
|
||||
optional output `id` distinguishes several stable replacements from the same source item; its output
|
||||
index is the default.
|
||||
|
||||
Each replacement keeps a reference to the source row (`source` on the projected stream item), and
|
||||
turn logic reads a replaced reply through it. A reply split into several cards stays one reply: turn
|
||||
folding keeps every card visible, and the turn footer hangs under the last card, copies the original
|
||||
reply text once, forks at its message, and shows its duration and stats. Read the reply with
|
||||
`getAssistantReply` (`packages/app/src/types/stream.ts`) instead of checking `kind ===
|
||||
"assistant_message"`.
|
||||
|
||||
Transformers run synchronously and must be deterministic. When several transformers match, the
|
||||
first one that returns a result owns that source item. Plugin and registration ordering is stable.
|
||||
See `plugin-examples/timeline-items` for the complete contract.
|
||||
|
||||
+11
-33
@@ -17,7 +17,6 @@ A release has exactly two steps. The agent does the first, the user authorizes t
|
||||
run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag
|
||||
- push the `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` branch and confirm its `CI` and
|
||||
`Desktop Packages` runs pass (never wait on `main` CI)
|
||||
- run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
|
||||
**Go-ahead** (user says "go ahead"):
|
||||
|
||||
@@ -108,7 +107,6 @@ An explicit user instruction can select another base.
|
||||
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
|
||||
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` cancels in-progress
|
||||
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
|
||||
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
|
||||
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
|
||||
6. After go-ahead, run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta). This
|
||||
publishes to npm and pushes the `v*` tag on the already-verified commit. Because the release
|
||||
@@ -128,9 +126,7 @@ shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version
|
||||
as the next unused patch beta, `0.13.4-beta.1`, from the tested beta tag. No `version:all:*` mode
|
||||
computes that from a prerelease, so run `npm run release:check`, bump with
|
||||
`npm version 0.13.4-beta.1 --include-workspace-root --no-git-tag-version && git commit -m "chore(release): cut 0.13.4-beta.1"`,
|
||||
push the release branch for `CI` and `Desktop Packages`, and complete the
|
||||
[pre-release dependency checks](#pre-release-dependency-checks) before shipping with
|
||||
`npm run release:ship:beta`.
|
||||
push the release branch for `CI` and `Desktop Packages`, then ship with `npm run release:ship:beta`.
|
||||
Record the tested beta tag as its source so its soak still counts for the unchanged content.
|
||||
|
||||
## Release inventory
|
||||
@@ -238,7 +234,6 @@ npm run release:prep:minor
|
||||
|
||||
# 2. Push the release branch and wait for CI + Desktop Packages on this commit.
|
||||
git push -u origin HEAD
|
||||
# Complete the pre-release dependency checks on this commit.
|
||||
|
||||
# 3. After go-ahead and green release-branch checks: publish npm and push the tag.
|
||||
npm run release:ship
|
||||
@@ -274,8 +269,7 @@ npm run release:check # Typecheck, build, dry-run pack
|
||||
npm run version:all:patch
|
||||
npm run version:all:minor
|
||||
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
|
||||
# Wait for CI and Desktop Packages and complete the pre-release dependency checks.
|
||||
# After go-ahead:
|
||||
# Wait for CI and Desktop Packages on this branch to pass, then after go-ahead:
|
||||
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
|
||||
npm run release:push # Create tag vX.Y.Z on HEAD and push (triggers release workflows)
|
||||
```
|
||||
@@ -292,7 +286,6 @@ npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
|
||||
|
||||
# 2. Push the release branch and wait for CI + Desktop Packages to pass:
|
||||
git push -u origin HEAD
|
||||
# Complete the pre-release dependency checks on this commit.
|
||||
|
||||
# 3. After go-ahead:
|
||||
npm run release:ship:beta
|
||||
@@ -300,8 +293,7 @@ npm run release:ship:beta
|
||||
# Later, after soak, promote on release/vX.Y.Z:
|
||||
npm run release:prep:promote
|
||||
git push -u origin HEAD
|
||||
# Wait for CI + Desktop Packages and complete the pre-release dependency checks.
|
||||
# After go-ahead:
|
||||
# Wait for CI + Desktop Packages to pass, then after go-ahead:
|
||||
npm run release:ship
|
||||
```
|
||||
|
||||
@@ -337,21 +329,22 @@ Drafts do not appear in GitHub's releases feed. Updater clients continue to see
|
||||
|
||||
### Default behavior
|
||||
|
||||
Follow the [standard stable release procedure](#standard-release-stable). The tag push starts
|
||||
the desktop release workflow, which sets a 36-hour rollout when it publishes the release.
|
||||
`npm run release:prep:patch` or `npm run release:prep:minor` → push release branch → green checks → `npm run release:ship` → tag push → 36h ramp. No extra action needed.
|
||||
|
||||
The `rollout_hours` input on `desktop-release.yml` is **only read on `workflow_dispatch`** — tag-push runs always default to 36. To get any other rollout duration on a fresh release, use the post-publish flip below.
|
||||
|
||||
### Instant-admit release (rollout_hours=0)
|
||||
|
||||
Follow the [standard stable release procedure](#standard-release-stable). Wait for Desktop
|
||||
Release to publish, then update the manifests to admit everyone immediately.
|
||||
Tag-push runs from `npm run release:ship` always stamp 36 hours. To admit everyone immediately (hotfix, doc-only change, a release you want out fast), ship the release normally, wait for it to publish, then flip the manifests:
|
||||
|
||||
```bash
|
||||
# 1. Wait for Desktop Release to publish the GitHub Release.
|
||||
# 1. Ship the verified release branch (36h ramp from tag push).
|
||||
npm run release:ship
|
||||
|
||||
# 2. Wait for Desktop Release to publish the GitHub Release.
|
||||
gh run watch <desktop-release-run-id> --exit-status
|
||||
|
||||
# 2. Flip the published manifests to instant admit.
|
||||
# 3. Flip the published manifests to instant admit.
|
||||
gh workflow run desktop-rollout.yml \
|
||||
-f tag=v0.1.64 \
|
||||
-f rollout_hours=0
|
||||
@@ -397,8 +390,7 @@ gh workflow run desktop-release.yml \
|
||||
-f rollout_hours=6
|
||||
```
|
||||
|
||||
For a fresh release with a custom ramp, follow the [instant-admit procedure](#instant-admit-release-rollout_hours0)
|
||||
and set `rollout_hours` to your chosen duration.
|
||||
This does **not** apply to fresh releases shipped via `npm run release:ship` — tag-push runs always stamp 36. For a fresh release with a custom ramp, ship normally and then dispatch `desktop-rollout.yml` (same pattern as the instant-admit flow above, with your chosen `rollout_hours`).
|
||||
|
||||
### Releasing during an active rollout
|
||||
|
||||
@@ -867,18 +859,6 @@ Bullets within each section (Added, Changed, Fixed) follow this order:
|
||||
2. **Quality-of-life improvements** — polish, performance, smoother interactions.
|
||||
3. **Internal/infra changes last** — only include if they have a tangible user benefit (e.g. "faster startup" is user-facing even if the fix was internal).
|
||||
|
||||
## Pre-release dependency checks
|
||||
|
||||
Run these checks from the repository root on the release commit before shipping a beta or stable release.
|
||||
Use Linux x64 so the audit includes the platform-specific dependencies that the CI job checked.
|
||||
|
||||
1. Review changes to dependency versions, download URLs, and integrity hashes in `git diff <previous-release-tag> HEAD -- package-lock.json`.
|
||||
2. Install the exact dependencies from the release lockfile with `npm ci`.
|
||||
3. Run `npm audit signatures`. Investigate failures before shipping. See [Dependency signature audit](development.md#dependency-signature-audit) for help.
|
||||
|
||||
Checking signatures and reviewing the lockfile diff reduce the risk of shipping compromised dependencies.
|
||||
These checks help prevent supply-chain attacks from reaching users through Paseo.
|
||||
|
||||
## Pre-release sanity check
|
||||
|
||||
Before cutting a **stable** release, the release agent reviews the diff as a last line of defence against shipping bugs. Skip this for betas — the beta itself is the smoke test, and gating each beta on a code review defeats the point of using betas as fast release candidates.
|
||||
@@ -906,7 +886,6 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before running `release:prep:*`
|
||||
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
|
||||
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
|
||||
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
- [ ] After go-ahead, `npm run release:ship:beta` published npm and pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run
|
||||
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
|
||||
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
@@ -930,7 +909,6 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
|
||||
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
|
||||
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
|
||||
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
- [ ] After go-ahead, `npm run release:ship` published npm, updated dist-tags, and pushed the `vX.Y.Z` tag without triggering a second CI run
|
||||
- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta`
|
||||
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
closeRelayPairing,
|
||||
emptyHome,
|
||||
loadingScreen,
|
||||
openTailscaleDocsFromSetup,
|
||||
expectTailscaleSwitchDisabled,
|
||||
paseoToolsSwitch,
|
||||
pickTheme,
|
||||
projectSuggestion,
|
||||
@@ -403,12 +403,10 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
|
||||
await continueSetup(page);
|
||||
});
|
||||
|
||||
await test.step("Phone offers Tailscale docs and pairs over relay in its own modal", async () => {
|
||||
await test.step("Phone shows a disabled Tailscale switch and pairs over relay", async () => {
|
||||
await expectSetupStep(page, "Take your agents with you");
|
||||
await page.screenshot({ path: testInfo.outputPath("5-phone.png") });
|
||||
expect(await openTailscaleDocsFromSetup(page)).toBe(
|
||||
"https://paseo.sh/docs/connectivity#tailscale",
|
||||
);
|
||||
await expectTailscaleSwitchDisabled(page);
|
||||
const pairing = await openRelayPairingFromSetup(page);
|
||||
await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible();
|
||||
await enableRelayAndExpectOffer(page);
|
||||
|
||||
@@ -1,7 +1,24 @@
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
addDirectHostFromSettings,
|
||||
openSettingsHostSection,
|
||||
selectSettingsHost,
|
||||
} from "../support/helpers/settings";
|
||||
import { test } from "../support/fixtures";
|
||||
import { startTailscaleTestDaemon } from "../support/helpers/tailscale-daemon";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import {
|
||||
expectPairingOffer,
|
||||
cancelTailscaleTurnOff,
|
||||
confirmTailscaleTurnOff,
|
||||
connectThroughTailscale,
|
||||
disableTailscale,
|
||||
enableTailscale,
|
||||
expectTailscaleAddress,
|
||||
expectTailscaleRowLoadsOn,
|
||||
openSetupMobileStep,
|
||||
slowConnectionToHost,
|
||||
expectTailscaleUpdateRequired,
|
||||
expectCompletePairingQr,
|
||||
expectRelayConsent,
|
||||
openPairDeviceModal,
|
||||
@@ -37,3 +54,59 @@ test("keeps the pairing QR code inside its compact tile", async ({ page }, testI
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("asks for a host update when Tailscale controls are unavailable", async ({ page }) => {
|
||||
const daemon = await startIsolatedHostDaemon("pair-device-browser-old-host", {
|
||||
publishedVersion: "0.13.0-beta.2",
|
||||
});
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: daemon.port });
|
||||
await selectSettingsHost(page, daemon.serverId);
|
||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||
await expectTailscaleUpdateRequired(page);
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("turns Tailscale on and off from Devices, asking first over Tailscale", async ({
|
||||
page,
|
||||
baseURL,
|
||||
}, testInfo) => {
|
||||
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
|
||||
// The journey opens Devices or the setup six times, two of them over a slowed connection.
|
||||
test.setTimeout(120_000);
|
||||
if (!baseURL) throw new Error("Expected the app base URL");
|
||||
const daemon = await startTailscaleTestDaemon(baseURL);
|
||||
try {
|
||||
await preparePairingHost(page, daemon);
|
||||
await enableTailscale(page);
|
||||
await expectTailscaleAddress(page, daemon.tailscaleAddress);
|
||||
await page.screenshot({ path: testInfo.outputPath("devices.png") });
|
||||
|
||||
await test.step("While its status loads, the row never shows Tailscale off", async () => {
|
||||
const address = daemon.tailscaleAddress;
|
||||
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
|
||||
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
|
||||
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 300);
|
||||
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
|
||||
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
|
||||
restoreSpeed();
|
||||
});
|
||||
|
||||
await disableTailscale(page, daemon.tailscaleAddress);
|
||||
|
||||
await test.step("Over Tailscale, turning it off asks first and Cancel changes nothing", async () => {
|
||||
await enableTailscale(page);
|
||||
await connectThroughTailscale(page, daemon);
|
||||
await cancelTailscaleTurnOff(page, daemon.tailscaleAddress);
|
||||
});
|
||||
await test.step("Confirming turns it off and cuts this connection", async () => {
|
||||
await confirmTailscaleTurnOff(page, daemon.tailscaleAddress);
|
||||
});
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
expectChatHistoryAttachment,
|
||||
forkMostRecentAssistantTurnToNewTab,
|
||||
observeForkAttachment,
|
||||
} from "../support/helpers/assistant-fork";
|
||||
import { test } from "../support/fixtures";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import {
|
||||
ASSISTANT_TEXT,
|
||||
withTimelinePlugin,
|
||||
viewInlineThinkingExample,
|
||||
requestPluginTimeline,
|
||||
@@ -61,24 +55,3 @@ test("inline-thinking example renders a streamed thought through host UI", async
|
||||
}, info) => {
|
||||
await viewInlineThinkingExample(page, info);
|
||||
});
|
||||
|
||||
test("plugin-transformed assistant reply keeps copy, fork, and turn duration in its footer", async ({
|
||||
page,
|
||||
}, info) => {
|
||||
const forkAttachment = observeForkAttachment(page);
|
||||
await withTimelinePlugin(page, info, "assistant", async (agent) => {
|
||||
await requestPluginTimeline(agent);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
await expectWholeCompletedCard(page);
|
||||
|
||||
const footer = page.getByTestId("turn-footer").last();
|
||||
await expect(footer).toBeVisible();
|
||||
await expect(footer.getByRole("button", { name: "Copy turn" })).toBeVisible();
|
||||
await expect(footer.getByRole("button", { name: "Fork chat from here" })).toBeVisible();
|
||||
await expect(footer.getByText(/^Worked for /)).toBeVisible();
|
||||
|
||||
await forkMostRecentAssistantTurnToNewTab(page);
|
||||
await expectChatHistoryAttachment(page);
|
||||
expect(await forkAttachment.waitForText()).toContain(ASSISTANT_TEXT);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { promisify } from "node:util";
|
||||
import { once } from "node:events";
|
||||
import {
|
||||
spawn,
|
||||
execFile,
|
||||
@@ -11,6 +12,7 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import net from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { WebSocket } from "ws";
|
||||
import { withDisabledE2ESpeechEnv } from "./speech-env";
|
||||
import { killProcessTree, spawnTsx } from "./spawn-node";
|
||||
|
||||
@@ -64,12 +66,14 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
|
||||
* Resolves once this daemon answers on its port. An open TCP port is not
|
||||
* enough: the port is released before the daemon binds it, and whatever takes
|
||||
* it in between also accepts connections while the daemon exits with
|
||||
* EADDRINUSE. Only the daemon's own status reports its server id.
|
||||
* EADDRINUSE. Only the daemon's own status reports its server id. Published
|
||||
* daemons can serve status before they accept WebSocket upgrades.
|
||||
*/
|
||||
async function waitForServer(
|
||||
port: number,
|
||||
child: ChildProcess,
|
||||
identity: { serverId: string; paseoHome: string },
|
||||
published: boolean,
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + 90_000;
|
||||
let lastError: unknown = null;
|
||||
@@ -82,7 +86,10 @@ async function waitForServer(
|
||||
}
|
||||
try {
|
||||
const serverId = await readServerId(port, identity.paseoHome);
|
||||
if (serverId === identity.serverId) return;
|
||||
if (serverId === identity.serverId) {
|
||||
if (published) await checkWebSocketUpgrade(port);
|
||||
return;
|
||||
}
|
||||
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
@@ -97,6 +104,12 @@ async function waitForServer(
|
||||
);
|
||||
}
|
||||
|
||||
async function checkWebSocketUpgrade(port: number): Promise<void> {
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${port}/ws`, { handshakeTimeout: 1_000 });
|
||||
await once(socket, "open");
|
||||
socket.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the server id from the daemon's status route. The route needs a bearer
|
||||
* on a password-protected daemon; the daemon accepts the local credential it
|
||||
@@ -246,7 +259,7 @@ export async function startIsolatedHostDaemon(
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServer(port, spawned, { serverId, paseoHome });
|
||||
await waitForServer(port, spawned, { serverId, paseoHome }, Boolean(publishedPackageRoot));
|
||||
return spawned;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
|
||||
@@ -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,9 @@ 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 expectTailscaleSwitchDisabled(page: Page): Promise<void> {
|
||||
const setup = setupModal(page);
|
||||
await expect(setup.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
}
|
||||
|
||||
export interface SetupHost {
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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,7 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TurnTiming } from "@/timeline/turn-time";
|
||||
import type { TimelineItemTransform } from "@/plugins/timeline";
|
||||
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import {
|
||||
orderHeadForStreamRenderStrategy,
|
||||
@@ -580,40 +578,4 @@ describe("layoutStream", () => {
|
||||
expect(footerOwners(layout)).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["web", "android"] as const)(
|
||||
"attaches the turn footer to the final card of a plugin-split reply on %s",
|
||||
(platform) => {
|
||||
const metrics = [{ label: "Model", value: "opus" }];
|
||||
const first = { ...assistantMessage("a1", 2), turnMetrics: [{ label: "Steps", value: "1" }] };
|
||||
const latest = { ...assistantMessage("a2", 4), turnMetrics: metrics };
|
||||
const splitIntoCards: TimelineItemTransform = ({ item, sourceId }) =>
|
||||
item.type !== "assistant_message"
|
||||
? undefined
|
||||
: ["text", "card"].map((part) => ({
|
||||
type: "plugin",
|
||||
id: `${sourceId}/${part}`,
|
||||
pluginId: "genui",
|
||||
kind: `genui-${part}`,
|
||||
version: 1,
|
||||
data: {},
|
||||
}));
|
||||
const tail = projectPluginTimelineItems(
|
||||
[userMessage("u1", 1), first, userMessage("u2", 3), latest],
|
||||
splitIntoCards,
|
||||
);
|
||||
|
||||
const layout = layoutFor({
|
||||
platform,
|
||||
tail,
|
||||
timingIds: ["genui/a1/card", "genui/a2/card"],
|
||||
});
|
||||
|
||||
expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]);
|
||||
expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe(
|
||||
first.turnMetrics,
|
||||
);
|
||||
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
|
||||
import type { TurnTiming } from "@/timeline/turn-time";
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import { getAssistantMessageSpacing, getGapBetweenStreamItems } from "./spacing";
|
||||
import type { StreamFrameChildOrder, StreamStrategy } from "./strategy";
|
||||
import { continuesResponse, continuesTurn, isResponseBoundary } from "./turn-membership";
|
||||
@@ -72,9 +72,9 @@ function createTurnFooterHost(input: {
|
||||
timingByItemId: Map<string, TurnTiming>;
|
||||
}): TurnFooterHost {
|
||||
const turnMetrics =
|
||||
input.item.kind === "tool_call"
|
||||
input.item.kind === "assistant_message" || input.item.kind === "tool_call"
|
||||
? input.item.turnMetrics
|
||||
: getAssistantReply(input.item)?.turnMetrics;
|
||||
: undefined;
|
||||
return {
|
||||
itemId: input.item.id,
|
||||
items: input.items,
|
||||
@@ -109,7 +109,7 @@ function findTurnFooterSource(input: {
|
||||
if (!item || (laterItem && !continuesResponse(item, laterItem))) {
|
||||
return toolFallback;
|
||||
}
|
||||
if (getAssistantReply(item)) {
|
||||
if (item.kind === "assistant_message") {
|
||||
return { item, items, index };
|
||||
}
|
||||
laterItem = item;
|
||||
|
||||
@@ -28,11 +28,7 @@ function userMessage(id: string, text: string, seed: number): StreamItem {
|
||||
};
|
||||
}
|
||||
|
||||
function assistantMessage(
|
||||
id: string,
|
||||
text: string,
|
||||
seed: number,
|
||||
): Extract<StreamItem, { kind: "assistant_message" }> {
|
||||
function assistantMessage(id: string, text: string, seed: number): StreamItem {
|
||||
return {
|
||||
kind: "assistant_message",
|
||||
id,
|
||||
@@ -247,38 +243,4 @@ describe("layout strategy edges", () => {
|
||||
"content-then-footer",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(PLATFORMS)("copies a reply split into plugin cards once on %s", (platform) => {
|
||||
const strategy = strategyFor(platform);
|
||||
const splitReply = assistantMessage("a2", 'Summary\n\n```ui\nCard("Hi", [])\n```', 3);
|
||||
const card = (part: string): StreamItem => ({
|
||||
kind: "plugin",
|
||||
id: `genui/a2/${part}`,
|
||||
source: splitReply,
|
||||
timestamp: splitReply.timestamp,
|
||||
pluginId: "genui",
|
||||
pluginItemId: `a2/${part}`,
|
||||
itemKind: `genui-${part}`,
|
||||
version: 1,
|
||||
data: {},
|
||||
});
|
||||
const items = orderTailForStreamRenderStrategy({
|
||||
strategy,
|
||||
streamItems: [
|
||||
userMessage("u1", "prompt", 1),
|
||||
assistantMessage("a1", "Before card", 2),
|
||||
card("text"),
|
||||
card("card"),
|
||||
],
|
||||
});
|
||||
const startIndex = items.findIndex((item) => item.id === "genui/a2/card");
|
||||
|
||||
expect(
|
||||
collectAssistantResponseContentForStreamRenderStrategy({
|
||||
strategy,
|
||||
items,
|
||||
startIndex,
|
||||
}),
|
||||
).toBe(`Before card\n\n${splitReply.text}`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ComponentType, ReactElement, ReactNode, RefObject } from "react";
|
||||
import type { StyleProp, ViewStyle } from "react-native";
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import type { ReadingRowReplacements } from "./reading-anchor";
|
||||
import { continuesResponse } from "./turn-membership";
|
||||
import type { StreamHistoryBoundary, StreamRenderSegments } from "./model";
|
||||
@@ -185,7 +185,6 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate
|
||||
},
|
||||
collectAssistantResponseContent: (items, startIndex) => {
|
||||
const messages: string[] = [];
|
||||
const seenReplies = new Set<StreamItem>();
|
||||
let laterItem: StreamItem | null = null;
|
||||
for (
|
||||
let index = startIndex;
|
||||
@@ -196,11 +195,8 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate
|
||||
if (!currentItem || (laterItem && !continuesResponse(currentItem, laterItem))) {
|
||||
break;
|
||||
}
|
||||
// A transformer can split one reply into several cards; copy the reply once.
|
||||
const reply = getAssistantReply(currentItem);
|
||||
if (reply && !seenReplies.has(reply)) {
|
||||
seenReplies.add(reply);
|
||||
messages.push(reply.text);
|
||||
if (currentItem.kind === "assistant_message") {
|
||||
messages.push(currentItem.text);
|
||||
}
|
||||
laterItem = currentItem;
|
||||
}
|
||||
|
||||
@@ -112,63 +112,4 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves a fork boundary from the reply a plugin card replaced", () => {
|
||||
const reply = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
};
|
||||
const card: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/1",
|
||||
source: reply,
|
||||
timelineCursor: reply.timelineCursor,
|
||||
timestamp: reply.timestamp,
|
||||
pluginId: "genui",
|
||||
pluginItemId: "assistant-1/1",
|
||||
itemKind: "genui-block",
|
||||
version: 1,
|
||||
data: {},
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveAssistantTurnForkBoundary({
|
||||
items: [userMessage("user-1", 1), card],
|
||||
startIndex: 1,
|
||||
supportsTimelineCursor: true,
|
||||
}),
|
||||
).toEqual({
|
||||
boundaryCursor: { epoch: "timeline-1", seq: 42 },
|
||||
boundaryMessageId: "msg-assistant-1",
|
||||
});
|
||||
expect(
|
||||
resolveAssistantTurnForkBoundary({
|
||||
items: [userMessage("user-1", 1), card],
|
||||
startIndex: 1,
|
||||
supportsTimelineCursor: false,
|
||||
}),
|
||||
).toEqual({ boundaryMessageId: "msg-assistant-1" });
|
||||
});
|
||||
|
||||
it("ignores plugin cards that did not replace a reply", () => {
|
||||
const appended: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "plugin/card-1",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timestamp: timestamp(2),
|
||||
pluginId: "plugin",
|
||||
pluginItemId: "card-1",
|
||||
itemKind: "card",
|
||||
version: 1,
|
||||
data: {},
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveAssistantTurnForkBoundary({
|
||||
items: [userMessage("user-1", 1), appended],
|
||||
startIndex: 1,
|
||||
supportsTimelineCursor: true,
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
|
||||
import type { StreamItem, TimelinePosition } from "@/types/stream";
|
||||
|
||||
export type AssistantTurnForkBoundary =
|
||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
||||
@@ -9,15 +9,15 @@ export function resolveAssistantTurnForkBoundary(input: {
|
||||
startIndex: number;
|
||||
supportsTimelineCursor: boolean;
|
||||
}): AssistantTurnForkBoundary | undefined {
|
||||
const reply = getAssistantReply(input.items[input.startIndex]);
|
||||
if (!reply) {
|
||||
const item = input.items[input.startIndex];
|
||||
if (item?.kind !== "assistant_message") {
|
||||
return undefined;
|
||||
}
|
||||
if (input.supportsTimelineCursor && reply.timelineCursor) {
|
||||
if (input.supportsTimelineCursor && item.timelineCursor) {
|
||||
return {
|
||||
boundaryCursor: reply.timelineCursor,
|
||||
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
|
||||
boundaryCursor: item.timelineCursor,
|
||||
...(item.messageId ? { boundaryMessageId: item.messageId } : {}),
|
||||
};
|
||||
}
|
||||
return reply.messageId ? { boundaryMessageId: reply.messageId } : undefined;
|
||||
return item.messageId ? { boundaryMessageId: item.messageId } : undefined;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ function pluginReply(sourceId: string, part = "0"): StreamItem {
|
||||
return {
|
||||
kind: "plugin",
|
||||
id: `math/${sourceId}/${part}`,
|
||||
source: reply(sourceId),
|
||||
sourceId,
|
||||
sourceKind: "assistant_message",
|
||||
timestamp: at,
|
||||
pluginId: "math",
|
||||
pluginItemId: `${sourceId}/${part}`,
|
||||
@@ -98,10 +99,10 @@ describe("collapseTurns", () => {
|
||||
expect(result.hostIdByFoldedMessageId.get("intermediate")).toBe("prompt");
|
||||
});
|
||||
|
||||
it.each([undefined, thought("card"), shell("card")])(
|
||||
"does not treat a plugin row replacing %o as a reply",
|
||||
(source) => {
|
||||
const card = { ...pluginReply("card"), source };
|
||||
it.each([undefined, "thought", "tool_call"] as const)(
|
||||
"does not treat a plugin row with source kind %s as a reply",
|
||||
(sourceKind) => {
|
||||
const card = { ...pluginReply("card"), sourceKind };
|
||||
const items = [user("prompt"), shell("call"), card];
|
||||
expect(collapse(items).tail).toEqual(items);
|
||||
expect(collapse(items).summaryRowsByHostId.size).toBe(0);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { isTurnBoundary, isTurnTrigger } from "../turn-membership";
|
||||
import {
|
||||
getStreamItemMessageId,
|
||||
getAssistantReply,
|
||||
type StreamItem,
|
||||
type ThoughtItem,
|
||||
type TimelinePosition,
|
||||
@@ -104,15 +103,22 @@ function staysVisibleWhenCollapsed(item: StreamItem): boolean {
|
||||
return isTurnTrigger(item) || item.kind === "compaction";
|
||||
}
|
||||
|
||||
function isAssistantReply(item: StreamItem): boolean {
|
||||
return (
|
||||
item.kind === "assistant_message" ||
|
||||
(item.kind === "plugin" && item.sourceKind === "assistant_message")
|
||||
);
|
||||
}
|
||||
|
||||
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
|
||||
for (let index = end - 1; index >= start; index -= 1) {
|
||||
const item = tail[index]!;
|
||||
if (!getAssistantReply(item)) continue;
|
||||
if (!isAssistantReply(item)) continue;
|
||||
const messageId = getStreamItemMessageId(item);
|
||||
// A transformer can split one reply into several cards; keep the whole reply visible.
|
||||
while (index > start) {
|
||||
const previous = tail[index - 1]!;
|
||||
if (!getAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break;
|
||||
if (!isAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break;
|
||||
index -= 1;
|
||||
}
|
||||
return index;
|
||||
@@ -150,7 +156,7 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse {
|
||||
}
|
||||
const folded = tail.slice(runStart, replyIndex);
|
||||
const tools = summarizeTurn(folded, input.getGroupedCalls);
|
||||
if (!hasWork(tools) && !folded.some((item) => getAssistantReply(item))) {
|
||||
if (!hasWork(tools) && !folded.some(isAssistantReply)) {
|
||||
output.push(...tail.slice(runStart, runEnd));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -150,44 +150,3 @@ describe("turn stats", () => {
|
||||
expect(host.getBoundingClientRect().height).toBe(without);
|
||||
});
|
||||
});
|
||||
|
||||
const projectedReply: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "genui/reply/1",
|
||||
source: {
|
||||
kind: "assistant_message",
|
||||
id: "reply",
|
||||
messageId: "provider-reply-1",
|
||||
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
},
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
pluginId: "genui",
|
||||
pluginItemId: "reply/1",
|
||||
itemKind: "genui-block",
|
||||
version: 1,
|
||||
data: {},
|
||||
};
|
||||
|
||||
it("renders copy, fork, and duration for a plugin-projected assistant reply", () => {
|
||||
const onFork = vi.fn();
|
||||
|
||||
act(() =>
|
||||
root.render(
|
||||
<CompletedTurnFooterRow
|
||||
strategy={createNativeStreamStrategy()}
|
||||
items={[projectedReply]}
|
||||
timing={COMPLETED_TIMING}
|
||||
startIndex={0}
|
||||
supportsTimelineCursor={true}
|
||||
onForkAssistantTurn={onFork}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
|
||||
expect(host.querySelector('[aria-label="Copy turn"]')).not.toBeNull();
|
||||
expect(host.querySelector('[aria-label="Fork chat from here"]')).not.toBeNull();
|
||||
expect(host.textContent).toContain("Worked for 26s");
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import { View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { SPACING, type Theme } from "@/styles/theme";
|
||||
import type { TurnTiming } from "@/timeline/turn-time";
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import {
|
||||
collectAssistantResponseContentForStreamRenderStrategy,
|
||||
type StreamStrategy,
|
||||
@@ -208,7 +208,7 @@ function CompletedTurnFooter({
|
||||
return (
|
||||
<View style={stylesheet.turnFooterSlot}>
|
||||
<AssistantTurnFooter
|
||||
getContent={getAssistantReply(items[startIndex]) ? getContent : undefined}
|
||||
getContent={items[startIndex]?.kind === "assistant_message" ? getContent : undefined}
|
||||
completedAt={timing?.completedAt}
|
||||
durationMs={timing?.durationMs}
|
||||
onFork={boundary && onForkAssistantTurn ? handleFork : undefined}
|
||||
|
||||
@@ -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,7 +25,10 @@ import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { ControlSizeProvider } from "@/components/ui/control-size";
|
||||
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
|
||||
import { useSettingsRowLayout } from "./row-density";
|
||||
import { SettingsRowTitle } from "./row-label";
|
||||
export { SettingsRowChildren } from "./row-children";
|
||||
export { SettingsGroup } from "./headings/settings-group";
|
||||
export { SettingsSection } from "./headings/settings-section";
|
||||
export { SettingsCollapsibleRow } from "./collapsible-row";
|
||||
@@ -36,11 +39,16 @@ export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
|
||||
export { SettingsInfoTip } from "./headings/settings-info-tip";
|
||||
export { MenuSettingsRows } from "./row-density";
|
||||
|
||||
/** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */
|
||||
/**
|
||||
* What app screens can add to a plugin-facing row: an accessory beside the label, such as an info
|
||||
* tip, an icon before the label, and a link to a page outside the app under the hint.
|
||||
*/
|
||||
interface AppRowExtras {
|
||||
labelAccessory?: ReactNode;
|
||||
/** An icon before the label, such as the thing the row is about. */
|
||||
leading?: ReactNode;
|
||||
/** A page outside the app that helps with this row, drawn under the hint as "Label ↗". */
|
||||
link?: Pick<ExternalLinkProps, "href" | "label" | "accessibilityLabel">;
|
||||
}
|
||||
|
||||
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
|
||||
@@ -67,6 +75,7 @@ export function SettingsRow({
|
||||
leading,
|
||||
labelAccessory,
|
||||
hint,
|
||||
link,
|
||||
error,
|
||||
children,
|
||||
testID,
|
||||
@@ -74,20 +83,17 @@ export function SettingsRow({
|
||||
const compact = useIsCompactFormFactor();
|
||||
const layout = useSettingsRowLayout();
|
||||
const rowStyle = useMemo(() => [layout.row, compact && styles.compactRow], [compact, layout]);
|
||||
const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]);
|
||||
return (
|
||||
<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>
|
||||
)}
|
||||
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
||||
{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}
|
||||
@@ -103,7 +109,15 @@ export function SettingsRow({
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsSwitch({ value, onValueChange, disabled, ...row }: SettingsSwitchProps) {
|
||||
/** A switch row. App screens may pass `null` while the value is not known yet; see `Switch`. */
|
||||
export function SettingsSwitch({
|
||||
value,
|
||||
onValueChange,
|
||||
disabled,
|
||||
...row
|
||||
}: Omit<SettingsSwitchProps, "onValueChange" | "value"> &
|
||||
Partial<Pick<SettingsSwitchProps, "onValueChange">> &
|
||||
AppRowExtras & { value: boolean | null }) {
|
||||
return (
|
||||
<SettingsRow {...row}>
|
||||
<Switch
|
||||
@@ -204,7 +218,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 +240,7 @@ 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 },
|
||||
link: { alignItems: "flex-start", marginTop: theme.spacing[1] },
|
||||
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,
|
||||
},
|
||||
}));
|
||||
@@ -11,6 +11,7 @@ import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
|
||||
import { SettingsRowTitle } from "./row-label";
|
||||
|
||||
const ThemedChevron = withUnistyles(ChevronRight);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
@@ -114,9 +115,8 @@ export function SettingsRowHeader({
|
||||
</View>
|
||||
) : null}
|
||||
<View style={[settingsStyles.rowContent, styles.passThrough]}>
|
||||
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<Text style={layout.title}>{label}</Text>
|
||||
{labelAccessory}
|
||||
<View {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
||||
</View>
|
||||
{hintStatus ? (
|
||||
<RowHintLine hint={hint} status={hintStatus} hintStyle={layout.hint} />
|
||||
@@ -256,7 +256,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
labelRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
|
||||
summary: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { useSettingsRowLayout } from "./row-density";
|
||||
|
||||
/**
|
||||
* A row's label line: the label, and beside it an accessory such as a badge or an info tip. Rows
|
||||
* with inline controls and rows that lead somewhere both draw it, so their labels and hints keep
|
||||
* the same distances whether or not a row carries an accessory.
|
||||
*/
|
||||
export function SettingsRowTitle({ label, accessory }: { label: string; accessory?: ReactNode }) {
|
||||
const layout = useSettingsRowLayout();
|
||||
const titleStyle = useMemo(() => [layout.title, styles.title], [layout]);
|
||||
if (!accessory) return <Text style={layout.title}>{label}</Text>;
|
||||
return (
|
||||
<View style={styles.line}>
|
||||
<Text style={titleStyle}>{label}</Text>
|
||||
<View style={styles.accessory}>{accessory}</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
line: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
title: { flexShrink: 1, minWidth: 0 },
|
||||
// An accessory is taller than the label's line. It hangs into the row's padding instead, so the
|
||||
// label and hint keep the distances of a row without one.
|
||||
accessory: { marginVertical: -theme.spacing[1] },
|
||||
}));
|
||||
@@ -1,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
|
||||
|
||||
@@ -11,13 +11,8 @@ import { i18n } from "@/i18n/i18next";
|
||||
|
||||
const DESKTOP_SETTINGS_QUERY_KEY = ["desktop-settings"] as const;
|
||||
|
||||
export type DesktopUpdateMode = "automatic" | "notify" | "off";
|
||||
|
||||
export interface DesktopSettings {
|
||||
releaseChannel: ReleaseChannel;
|
||||
updates: {
|
||||
mode: DesktopUpdateMode;
|
||||
};
|
||||
notifications: {
|
||||
playSound: boolean;
|
||||
};
|
||||
@@ -29,16 +24,12 @@ export interface DesktopSettings {
|
||||
|
||||
export interface DesktopSettingsPatch {
|
||||
releaseChannel?: ReleaseChannel;
|
||||
updates?: Partial<DesktopSettings["updates"]>;
|
||||
notifications?: Partial<DesktopSettings["notifications"]>;
|
||||
daemon?: Partial<DesktopSettings["daemon"]>;
|
||||
}
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
@@ -158,24 +149,13 @@ export async function migrateLegacyDesktopSettings(input: {
|
||||
await invokeDesktopCommand("migrate_legacy_desktop_settings", input);
|
||||
}
|
||||
|
||||
function parseUpdateMode(value: unknown): DesktopUpdateMode {
|
||||
if (value === "automatic" || value === "notify" || value === "off") {
|
||||
return value;
|
||||
}
|
||||
return DEFAULT_DESKTOP_SETTINGS.updates.mode;
|
||||
}
|
||||
|
||||
function parseDesktopSettings(raw: unknown): DesktopSettings {
|
||||
const record = isRecord(raw) ? raw : {};
|
||||
const updates = isRecord(record.updates) ? record.updates : {};
|
||||
const notifications = isRecord(record.notifications) ? record.notifications : {};
|
||||
const daemon = isRecord(record.daemon) ? record.daemon : {};
|
||||
|
||||
return {
|
||||
releaseChannel: record.releaseChannel === "beta" ? "beta" : "stable",
|
||||
updates: {
|
||||
mode: parseUpdateMode(updates.mode),
|
||||
},
|
||||
notifications: {
|
||||
playSound:
|
||||
typeof notifications.playSound === "boolean"
|
||||
@@ -201,10 +181,6 @@ function mergeDesktopSettings(
|
||||
): DesktopSettings {
|
||||
return {
|
||||
releaseChannel: updates.releaseChannel ?? current.releaseChannel,
|
||||
updates: {
|
||||
...current.updates,
|
||||
...updates.updates,
|
||||
},
|
||||
notifications: {
|
||||
...current.notifications,
|
||||
...updates.notifications,
|
||||
@@ -219,7 +195,6 @@ function mergeDesktopSettings(
|
||||
function normalizePatch(updates: DesktopSettingsPatch): Record<string, unknown> {
|
||||
return {
|
||||
...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}),
|
||||
...(updates.updates ? { updates: updates.updates } : {}),
|
||||
...(updates.notifications ? { notifications: updates.notifications } : {}),
|
||||
...(updates.daemon ? { daemon: updates.daemon } : {}),
|
||||
};
|
||||
|
||||
@@ -128,43 +128,6 @@ describe("desktop app updater — check", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reports 'available' when an update is available to download without auto-downloading", async () => {
|
||||
const { updater, port } = createUpdater({ now: () => 42 });
|
||||
port.nextCheckResult(
|
||||
buildFakeCheckResult({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.3",
|
||||
}),
|
||||
);
|
||||
|
||||
await updater.checkForUpdates({ releaseChannel: "stable" });
|
||||
|
||||
expect(updater.getSnapshot()).toMatchObject({
|
||||
status: "available",
|
||||
availableUpdate: { latestVersion: "1.2.3", readyToInstall: false, downloading: false },
|
||||
lastCheckedAt: 42,
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks download progress updates and clears them once install completes", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
port.nextInstallResult(buildFakeInstallResult({ installed: true }));
|
||||
|
||||
updater.setDownloadProgress({
|
||||
version: "1.2.3",
|
||||
percent: 42.4,
|
||||
transferred: 42,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
expect(updater.getSnapshot().downloadProgress?.percent).toBe(42.4);
|
||||
|
||||
await updater.installUpdate({ releaseChannel: "stable" });
|
||||
expect(updater.getSnapshot().downloadProgress).toBeNull();
|
||||
});
|
||||
|
||||
it("reports 'up-to-date' when the check resolves with no update", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
port.nextCheckResult(buildFakeCheckResult({ hasUpdate: false, readyToInstall: false }));
|
||||
@@ -377,55 +340,6 @@ describe("desktop app updater — install", () => {
|
||||
expect(updater.getSnapshot().status).toBe("up-to-date");
|
||||
});
|
||||
|
||||
it("moves to 'error' instead of 'up-to-date' when the install returns an errorMessage", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
port.nextInstallResult(
|
||||
buildFakeInstallResult({
|
||||
installed: false,
|
||||
message: "Update failed: ECONNRESET",
|
||||
errorMessage: "ECONNRESET",
|
||||
}),
|
||||
);
|
||||
|
||||
await updater.installUpdate({ releaseChannel: "stable" });
|
||||
|
||||
expect(updater.getSnapshot()).toMatchObject({
|
||||
status: "error",
|
||||
errorMessage: "ECONNRESET",
|
||||
downloadProgress: null,
|
||||
isInstalling: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores duplicate install requests and silent checks while an install is in progress", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
let resolveInstall!: (result: ReturnType<typeof buildFakeInstallResult>) => void;
|
||||
port.installDesktopAppUpdate = async (input) => {
|
||||
port.recordedInstalls.push(input);
|
||||
return new Promise((resolve) => {
|
||||
resolveInstall = resolve;
|
||||
});
|
||||
};
|
||||
|
||||
const firstInstall = updater.installUpdate({ releaseChannel: "stable" });
|
||||
const secondInstall = await updater.installUpdate({ releaseChannel: "stable" });
|
||||
const silentCheck = await updater.checkForUpdates({
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
silent: true,
|
||||
});
|
||||
|
||||
expect(secondInstall).toBeNull();
|
||||
expect(silentCheck).toBeNull();
|
||||
expect(port.recordedInstalls).toHaveLength(1);
|
||||
expect(port.recordedChecks).toHaveLength(0);
|
||||
expect(updater.getSnapshot().status).toBe("installing");
|
||||
|
||||
resolveInstall(buildFakeInstallResult({ installed: true }));
|
||||
await firstInstall;
|
||||
expect(updater.getSnapshot().status).toBe("installed");
|
||||
});
|
||||
|
||||
it("reports the install error and moves to 'error' when the install throws", async () => {
|
||||
const { updater, port, reportedInstallErrors } = createUpdater();
|
||||
const error = new Error("install failed");
|
||||
@@ -548,47 +462,6 @@ describe("formatStatusText", () => {
|
||||
).toBe("Restart now");
|
||||
});
|
||||
|
||||
it("formats download-available and live download progress status text", () => {
|
||||
expect(
|
||||
formatStatusText({
|
||||
status: "available",
|
||||
availableUpdate: buildFakeCheckResult({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.3",
|
||||
}),
|
||||
installMessage: null,
|
||||
lastCheckedAt: 42,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
}),
|
||||
).toBe("Update available: v1.2.3. Last checked at time-42.");
|
||||
|
||||
expect(
|
||||
formatStatusText({
|
||||
status: "installing",
|
||||
availableUpdate: buildFakeCheckResult({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.3",
|
||||
}),
|
||||
downloadProgress: {
|
||||
version: "1.2.3",
|
||||
percent: 64.6,
|
||||
transferred: 65,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
},
|
||||
installMessage: null,
|
||||
lastCheckedAt: null,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
}),
|
||||
).toBe("Downloading v1.2.3... 65%");
|
||||
});
|
||||
|
||||
it("uses the active app language for local status wrappers", async () => {
|
||||
await i18n.changeLanguage("zh-CN");
|
||||
try {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DesktopAppUpdateCheckResult,
|
||||
DesktopAppUpdateCheckIntent,
|
||||
DesktopAppUpdateDownloadProgress,
|
||||
DesktopAppUpdateInstallResult,
|
||||
DesktopReleaseChannel,
|
||||
} from "@/desktop/updates/desktop-updates";
|
||||
@@ -22,7 +21,6 @@ export const PENDING_RECHECK_MS = 10_000;
|
||||
export interface DesktopAppUpdaterSnapshot {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
@@ -55,7 +53,6 @@ export interface DesktopAppUpdaterDeps {
|
||||
export interface DesktopAppUpdater {
|
||||
getSnapshot(): DesktopAppUpdaterSnapshot;
|
||||
subscribe(listener: () => void): () => void;
|
||||
setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void;
|
||||
checkForUpdates(options?: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
intent?: DesktopAppUpdateCheckIntent;
|
||||
@@ -69,7 +66,6 @@ export interface DesktopAppUpdater {
|
||||
interface InternalState {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
@@ -80,7 +76,6 @@ interface InternalState {
|
||||
const INITIAL_STATE: InternalState = {
|
||||
status: "idle",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
errorMessage: null,
|
||||
installMessage: null,
|
||||
lastCheckedAt: null,
|
||||
@@ -92,7 +87,6 @@ function buildSnapshot(state: InternalState): DesktopAppUpdaterSnapshot {
|
||||
return {
|
||||
status: state.status,
|
||||
availableUpdate: state.availableUpdate,
|
||||
downloadProgress: state.downloadProgress,
|
||||
errorMessage: state.errorMessage,
|
||||
installMessage: state.installMessage,
|
||||
lastCheckedAt: state.lastCheckedAt,
|
||||
@@ -108,113 +102,9 @@ function getErrorMessage(error: unknown): string {
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function formatInstallingStatusText(input: {
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
}): string {
|
||||
const { availableUpdate, downloadProgress, formatVersion } = input;
|
||||
if (downloadProgress == null) {
|
||||
return i18n.t("desktop.updates.status.installing");
|
||||
}
|
||||
const percent = Math.round(downloadProgress.percent);
|
||||
const version = downloadProgress.version ?? availableUpdate?.latestVersion;
|
||||
if (version) {
|
||||
return i18n.t("desktop.updates.status.downloadingVersionProgress", {
|
||||
version: formatVersion(version),
|
||||
percent,
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.downloadingProgress", { percent });
|
||||
}
|
||||
|
||||
function formatPendingStatusText(input: {
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
lastCheckedAt: number | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
formatLastCheckedAt: (timestamp: number) => string;
|
||||
}): string {
|
||||
const { availableUpdate, downloadProgress, lastCheckedAt, formatVersion, formatLastCheckedAt } =
|
||||
input;
|
||||
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
|
||||
if (availableUpdate?.latestVersion) {
|
||||
const version = formatVersion(availableUpdate.latestVersion);
|
||||
if (downloadProgress != null) {
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.pendingWithVersionProgressAndLastChecked"
|
||||
: "desktop.updates.status.pendingWithVersionProgress",
|
||||
{ version, percent: Math.round(downloadProgress.percent), time },
|
||||
);
|
||||
}
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.pendingWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.pendingWithVersion",
|
||||
{ version, time },
|
||||
);
|
||||
}
|
||||
if (time !== undefined) {
|
||||
return i18n.t("desktop.updates.status.pendingWithLastChecked", { time });
|
||||
}
|
||||
return i18n.t("desktop.updates.status.pending");
|
||||
}
|
||||
|
||||
function formatAvailableStatusText(input: {
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
lastCheckedAt: number | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
formatLastCheckedAt: (timestamp: number) => string;
|
||||
}): string {
|
||||
const { availableUpdate, lastCheckedAt, formatVersion, formatLastCheckedAt } = input;
|
||||
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
|
||||
const isDownloadRequired =
|
||||
availableUpdate?.hasUpdate === true && availableUpdate.readyToInstall === false;
|
||||
if (availableUpdate?.latestVersion) {
|
||||
const version = formatVersion(availableUpdate.latestVersion);
|
||||
if (isDownloadRequired) {
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.downloadAvailableWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.downloadAvailableWithVersion",
|
||||
{ version, time },
|
||||
);
|
||||
}
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.availableWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.availableWithVersion",
|
||||
{ version, time },
|
||||
);
|
||||
}
|
||||
if (isDownloadRequired) {
|
||||
return time !== undefined
|
||||
? i18n.t("desktop.updates.status.downloadAvailableWithLastChecked", { time })
|
||||
: i18n.t("desktop.updates.status.downloadAvailable");
|
||||
}
|
||||
return time !== undefined
|
||||
? i18n.t("desktop.updates.status.availableWithLastChecked", { time })
|
||||
: i18n.t("desktop.updates.status.available");
|
||||
}
|
||||
|
||||
function resolveCheckOutcome(result: DesktopAppUpdateCheckResult): {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
} {
|
||||
if (result.readyToInstall || (result.hasUpdate && !result.downloading)) {
|
||||
return { status: "available", availableUpdate: result };
|
||||
}
|
||||
if (result.hasUpdate) {
|
||||
return { status: "pending", availableUpdate: result };
|
||||
}
|
||||
return { status: "up-to-date", availableUpdate: null };
|
||||
}
|
||||
|
||||
export function formatStatusText(input: {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
@@ -223,45 +113,79 @@ export function formatStatusText(input: {
|
||||
const {
|
||||
status,
|
||||
availableUpdate,
|
||||
downloadProgress = null,
|
||||
installMessage,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
} = input;
|
||||
|
||||
if (status === "checking") return i18n.t("desktop.updates.status.checking");
|
||||
if (status === "checking") {
|
||||
return i18n.t("desktop.updates.status.checking");
|
||||
}
|
||||
|
||||
if (status === "installing") {
|
||||
return formatInstallingStatusText({ availableUpdate, downloadProgress, formatVersion });
|
||||
return i18n.t("desktop.updates.status.installing");
|
||||
}
|
||||
|
||||
if (status === "up-to-date") {
|
||||
return lastCheckedAt != null
|
||||
? i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
})
|
||||
: i18n.t("desktop.updates.status.upToDate");
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.upToDate");
|
||||
}
|
||||
|
||||
if (status === "pending") {
|
||||
return formatPendingStatusText({
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
});
|
||||
if (availableUpdate?.latestVersion) {
|
||||
return i18n.t(
|
||||
lastCheckedAt != null
|
||||
? "desktop.updates.status.pendingWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.pendingWithVersion",
|
||||
{
|
||||
version: formatVersion(availableUpdate.latestVersion),
|
||||
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.pendingWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.pending");
|
||||
}
|
||||
|
||||
if (status === "available") {
|
||||
return formatAvailableStatusText({
|
||||
availableUpdate,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
});
|
||||
if (availableUpdate?.latestVersion) {
|
||||
return i18n.t(
|
||||
lastCheckedAt != null
|
||||
? "desktop.updates.status.availableWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.availableWithVersion",
|
||||
{
|
||||
version: formatVersion(availableUpdate.latestVersion),
|
||||
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.availableWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.available");
|
||||
}
|
||||
|
||||
if (status === "installed") {
|
||||
return installMessage ?? i18n.t("desktop.updates.status.installed");
|
||||
}
|
||||
if (status === "error") return i18n.t("desktop.updates.status.failed");
|
||||
|
||||
if (status === "error") {
|
||||
return i18n.t("desktop.updates.status.failed");
|
||||
}
|
||||
|
||||
return i18n.t("desktop.updates.status.idle");
|
||||
}
|
||||
|
||||
@@ -278,16 +202,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
}
|
||||
}
|
||||
|
||||
function setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void {
|
||||
if (progress === null && state.downloadProgress === null) {
|
||||
return;
|
||||
}
|
||||
commit({
|
||||
...state,
|
||||
downloadProgress: progress,
|
||||
});
|
||||
}
|
||||
|
||||
async function checkForUpdates(options?: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
intent?: DesktopAppUpdateCheckIntent;
|
||||
@@ -297,7 +211,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
return null;
|
||||
}
|
||||
const { releaseChannel, intent = "manual", silent = false } = options;
|
||||
if (silent && (state.status === "checking" || state.isInstalling)) {
|
||||
if (silent && state.status === "checking") {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -327,7 +241,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
...state,
|
||||
status: "error",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
errorMessage: result.errorMessage,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
@@ -335,13 +248,24 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
return result;
|
||||
}
|
||||
|
||||
const outcome = resolveCheckOutcome(result);
|
||||
let nextStatus: DesktopAppUpdateStatus;
|
||||
let nextAvailable: DesktopAppUpdateCheckResult | null;
|
||||
|
||||
if (result.readyToInstall) {
|
||||
nextStatus = "available";
|
||||
nextAvailable = result;
|
||||
} else if (result.hasUpdate) {
|
||||
nextStatus = "pending";
|
||||
nextAvailable = result;
|
||||
} else {
|
||||
nextStatus = "up-to-date";
|
||||
nextAvailable = null;
|
||||
}
|
||||
|
||||
commit({
|
||||
...state,
|
||||
status: outcome.status,
|
||||
availableUpdate: outcome.availableUpdate,
|
||||
downloadProgress: outcome.status === "pending" ? state.downloadProgress : null,
|
||||
status: nextStatus,
|
||||
availableUpdate: nextAvailable,
|
||||
errorMessage: null,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
@@ -360,7 +284,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: message,
|
||||
lastCheckedAt: intent === "manual" ? deps.now() : state.lastCheckedAt,
|
||||
});
|
||||
@@ -372,10 +295,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
async function installUpdate(options: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
}): Promise<DesktopAppUpdateInstallResult | null> {
|
||||
if (state.isInstalling) {
|
||||
return null;
|
||||
}
|
||||
|
||||
commit({
|
||||
...state,
|
||||
status: "installing",
|
||||
@@ -388,23 +307,10 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
releaseChannel: options.releaseChannel,
|
||||
});
|
||||
const nextLastCheckedAt = deps.now();
|
||||
if (!result.installed && result.errorMessage) {
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: result.errorMessage,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
isInstalling: false,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
commit({
|
||||
...state,
|
||||
status: result.installed ? "installed" : "up-to-date",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
installMessage: result.message,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
isInstalling: false,
|
||||
@@ -420,7 +326,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: message,
|
||||
isInstalling: false,
|
||||
});
|
||||
@@ -436,7 +341,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
setDownloadProgress,
|
||||
checkForUpdates,
|
||||
installUpdate,
|
||||
};
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
import { listenToDesktopEvent, type DesktopEventUnlisten } from "@/desktop/electron/events";
|
||||
import { invokeDesktopCommand } from "@/desktop/electron/invoke";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export interface DesktopAppUpdateDownloadProgress {
|
||||
version: string | null;
|
||||
percent: number;
|
||||
transferred: number;
|
||||
total: number;
|
||||
bytesPerSecond: number;
|
||||
}
|
||||
|
||||
export interface DesktopAppUpdateCheckResult {
|
||||
hasUpdate: boolean;
|
||||
readyToInstall: boolean;
|
||||
downloading: boolean;
|
||||
currentVersion: string | null;
|
||||
latestVersion: string | null;
|
||||
body: string | null;
|
||||
@@ -27,7 +17,6 @@ export interface DesktopAppUpdateInstallResult {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
message: string;
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
||||
export interface DesktopRuntimeInfo {
|
||||
@@ -126,13 +115,9 @@ export async function checkDesktopAppUpdate({
|
||||
throw new Error("Unexpected response while checking desktop updates.");
|
||||
}
|
||||
|
||||
const hasUpdate = result.hasUpdate === true;
|
||||
const readyToInstall = result.readyToInstall === true;
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading:
|
||||
typeof result.downloading === "boolean" ? result.downloading : hasUpdate && !readyToInstall,
|
||||
hasUpdate: result.hasUpdate === true,
|
||||
readyToInstall: result.readyToInstall === true,
|
||||
currentVersion: toStringOrNull(result.currentVersion),
|
||||
latestVersion: toStringOrNull(result.latestVersion),
|
||||
body: toStringOrNull(result.body),
|
||||
@@ -141,36 +126,6 @@ export async function checkDesktopAppUpdate({
|
||||
};
|
||||
}
|
||||
|
||||
export function parseDesktopAppUpdateDownloadProgress(
|
||||
raw: unknown,
|
||||
): DesktopAppUpdateDownloadProgress | null {
|
||||
if (!isRecord(raw)) {
|
||||
return null;
|
||||
}
|
||||
const percent = toNumberOr(Number.NaN, raw.percent);
|
||||
if (!Number.isFinite(percent)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
version: toStringOrNull(raw.version),
|
||||
percent: Math.max(0, Math.min(100, percent)),
|
||||
transferred: toNumberOr(0, raw.transferred),
|
||||
total: toNumberOr(0, raw.total),
|
||||
bytesPerSecond: toNumberOr(0, raw.bytesPerSecond),
|
||||
};
|
||||
}
|
||||
|
||||
export async function subscribeDesktopAppUpdateDownloadProgress(
|
||||
handler: (progress: DesktopAppUpdateDownloadProgress | null) => void,
|
||||
): Promise<DesktopEventUnlisten> {
|
||||
if (!shouldShowDesktopUpdateSection()) {
|
||||
return () => {};
|
||||
}
|
||||
return listenToDesktopEvent<unknown>("app-update-download-progress", (payload) => {
|
||||
handler(payload === null ? null : parseDesktopAppUpdateDownloadProgress(payload));
|
||||
});
|
||||
}
|
||||
|
||||
export async function installDesktopAppUpdate({
|
||||
releaseChannel,
|
||||
}: {
|
||||
@@ -181,12 +136,10 @@ export async function installDesktopAppUpdate({
|
||||
throw new Error("Unexpected response while installing desktop update.");
|
||||
}
|
||||
|
||||
const errorMessage = toStringOrNull(result.errorMessage);
|
||||
return {
|
||||
installed: result.installed === true,
|
||||
version: toStringOrNull(result.version),
|
||||
message: toStringOrNull(result.message) ?? i18n.t("desktop.updates.status.installed"),
|
||||
...(errorMessage ? { errorMessage } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -76,50 +76,6 @@ describe("resolveUpdateCalloutDescriptor", () => {
|
||||
expect(descriptor?.dismissalKey).toBe("desktop-update:installing:1.2.3");
|
||||
});
|
||||
|
||||
it("labels the callout as Download when the update has not been downloaded yet", () => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor(
|
||||
input({ availableUpdate: { latestVersion: "1.2.3", readyToInstall: false } }),
|
||||
);
|
||||
|
||||
expect(descriptor?.title).toBe("Update available");
|
||||
expect(descriptor?.body).toEqual({
|
||||
kind: "available",
|
||||
versionLabel: "v1.2.3",
|
||||
readyToInstall: false,
|
||||
});
|
||||
expect(descriptor?.actions).toEqual([
|
||||
{ role: "changelog", label: "What's new" },
|
||||
{ role: "install", label: "Download", variant: "primary", disabled: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows download progress while downloading an update", () => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor(
|
||||
input({
|
||||
status: "installing",
|
||||
isInstalling: true,
|
||||
downloadProgress: {
|
||||
version: "1.2.3",
|
||||
percent: 42.2,
|
||||
transferred: 42,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(descriptor?.title).toBe("Downloading update");
|
||||
expect(descriptor?.body).toEqual({
|
||||
kind: "downloading",
|
||||
versionLabel: "v1.2.3",
|
||||
percent: 42,
|
||||
});
|
||||
expect(descriptor?.actions).toEqual([
|
||||
{ role: "changelog", label: "What's new" },
|
||||
{ role: "install", label: "Downloading...", variant: "primary", disabled: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows a retry action and surfaces the error message on error", () => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor(
|
||||
input({ status: "error", errorMessage: "Download failed", availableUpdate: null }),
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import type { DesktopAppUpdateStatus } from "@/desktop/updates/use-desktop-app-updater";
|
||||
import type { DesktopAppUpdateDownloadProgress } from "@/desktop/updates/desktop-updates";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export type UpdateCalloutBody =
|
||||
| { kind: "available"; versionLabel: string | null; readyToInstall?: boolean }
|
||||
| { kind: "downloading"; versionLabel: string | null; percent: number }
|
||||
| { kind: "available"; versionLabel: string | null }
|
||||
| { kind: "installing" }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
@@ -33,8 +31,7 @@ export interface ResolveUpdateCalloutInput {
|
||||
isDesktopApp: boolean;
|
||||
status: DesktopAppUpdateStatus;
|
||||
isInstalling: boolean;
|
||||
availableUpdate: { latestVersion?: string | null; readyToInstall?: boolean } | null;
|
||||
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
|
||||
availableUpdate: { latestVersion?: string | null } | null;
|
||||
errorMessage: string | null;
|
||||
}
|
||||
|
||||
@@ -43,59 +40,6 @@ function formatVersionLabel(latestVersion: string | null | undefined): string |
|
||||
return `v${latestVersion.replace(/^v/i, "")}`;
|
||||
}
|
||||
|
||||
function resolveCalloutPresentation(input: {
|
||||
isError: boolean;
|
||||
isInstalling: boolean;
|
||||
readyToInstall: boolean;
|
||||
latestVersion: string | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null | undefined;
|
||||
errorMessage: string | null;
|
||||
}): { title: string; body: UpdateCalloutBody } {
|
||||
if (input.isInstalling && input.downloadProgress != null) {
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.downloadingTitle"),
|
||||
body: {
|
||||
kind: "downloading",
|
||||
versionLabel: formatVersionLabel(input.latestVersion),
|
||||
percent: Math.round(input.downloadProgress.percent),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (input.isInstalling) {
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.installingTitle"),
|
||||
body: { kind: "installing" },
|
||||
};
|
||||
}
|
||||
if (input.isError) {
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.failedTitle"),
|
||||
body: {
|
||||
kind: "error",
|
||||
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
|
||||
},
|
||||
};
|
||||
}
|
||||
const versionLabel = formatVersionLabel(input.latestVersion);
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.availableTitle"),
|
||||
body: input.readyToInstall
|
||||
? { kind: "available", versionLabel }
|
||||
: { kind: "available", versionLabel, readyToInstall: false },
|
||||
};
|
||||
}
|
||||
|
||||
function resolveInstallActionLabel(input: {
|
||||
isDownloading: boolean;
|
||||
isInstalling: boolean;
|
||||
readyToInstall: boolean;
|
||||
}): string {
|
||||
if (input.isDownloading) return i18n.t("desktop.updates.callout.downloadingAction");
|
||||
if (input.isInstalling) return i18n.t("desktop.updates.callout.installingAction");
|
||||
if (input.readyToInstall) return i18n.t("desktop.updates.callout.installAndRestart");
|
||||
return i18n.t("desktop.updates.callout.downloadAndRestart");
|
||||
}
|
||||
|
||||
export function resolveUpdateCalloutDescriptor(
|
||||
input: ResolveUpdateCalloutInput,
|
||||
): UpdateCalloutDescriptor | null {
|
||||
@@ -106,22 +50,26 @@ export function resolveUpdateCalloutDescriptor(
|
||||
|
||||
const isError = input.status === "error";
|
||||
const isInstalling = input.isInstalling;
|
||||
const isDownloading = isInstalling && input.downloadProgress != null;
|
||||
const isAvailable = !isInstalling && !isError;
|
||||
const readyToInstall = input.availableUpdate?.readyToInstall !== false;
|
||||
|
||||
const latestVersion =
|
||||
input.availableUpdate?.latestVersion ?? input.downloadProgress?.version ?? null;
|
||||
const latestVersion = input.availableUpdate?.latestVersion ?? null;
|
||||
const dismissalKey = `desktop-update:${input.status}:${latestVersion ?? "unknown"}`;
|
||||
|
||||
const { title, body } = resolveCalloutPresentation({
|
||||
isError,
|
||||
isInstalling,
|
||||
readyToInstall,
|
||||
latestVersion,
|
||||
downloadProgress: input.downloadProgress,
|
||||
errorMessage: input.errorMessage,
|
||||
});
|
||||
let title: string;
|
||||
let body: UpdateCalloutBody;
|
||||
if (isInstalling) {
|
||||
title = i18n.t("desktop.updates.callout.installingTitle");
|
||||
body = { kind: "installing" };
|
||||
} else if (isError) {
|
||||
title = i18n.t("desktop.updates.callout.failedTitle");
|
||||
body = {
|
||||
kind: "error",
|
||||
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
|
||||
};
|
||||
} else {
|
||||
title = i18n.t("desktop.updates.callout.availableTitle");
|
||||
body = { kind: "available", versionLabel: formatVersionLabel(latestVersion) };
|
||||
}
|
||||
|
||||
const actions: UpdateCalloutActionDescriptor[] = [
|
||||
{ role: "changelog", label: i18n.t("desktop.updates.callout.whatsNew") },
|
||||
@@ -131,7 +79,9 @@ export function resolveUpdateCalloutDescriptor(
|
||||
} else {
|
||||
actions.push({
|
||||
role: "install",
|
||||
label: resolveInstallActionLabel({ isDownloading, isInstalling, readyToInstall }),
|
||||
label: isInstalling
|
||||
? i18n.t("desktop.updates.callout.installingAction")
|
||||
: i18n.t("desktop.updates.callout.installAndRestart"),
|
||||
variant: "primary",
|
||||
disabled: isInstalling,
|
||||
});
|
||||
|
||||
@@ -34,12 +34,9 @@ type InstallOutcome =
|
||||
function buildCheckResult(
|
||||
overrides: Partial<DesktopAppUpdateCheckResult> = {},
|
||||
): DesktopAppUpdateCheckResult {
|
||||
const hasUpdate = overrides.hasUpdate ?? false;
|
||||
const readyToInstall = overrides.readyToInstall ?? false;
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading: overrides.downloading ?? (hasUpdate && !readyToInstall),
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
currentVersion: null,
|
||||
latestVersion: null,
|
||||
body: null,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Gift } from "lucide-react-native";
|
||||
import { type ReactNode, useEffect, useMemo, useRef } from "react";
|
||||
import { View } from "react-native";
|
||||
import { type ReactNode, useEffect, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { useUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
type SidebarCalloutAction,
|
||||
SidebarCalloutDescriptionText,
|
||||
@@ -20,24 +19,9 @@ import { openChangelog } from "@/changelog";
|
||||
const CHECK_INTERVAL_MS = 30 * 60 * 1000;
|
||||
|
||||
function renderBody(body: UpdateCalloutBody, t: ReturnType<typeof useTranslation>["t"]): ReactNode {
|
||||
if (body.kind === "downloading") {
|
||||
return (
|
||||
<UpdateDownloadingDescription
|
||||
versionLabel={body.versionLabel ?? undefined}
|
||||
percent={body.percent}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (body.kind === "installing") return t("desktop.updates.callout.installingDescription");
|
||||
if (body.kind === "error") return body.message;
|
||||
return (
|
||||
<UpdateAvailableDescription
|
||||
versionLabel={body.versionLabel ?? undefined}
|
||||
readyToInstall={body.readyToInstall !== false}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
return <UpdateAvailableDescription versionLabel={body.versionLabel ?? undefined} t={t} />;
|
||||
}
|
||||
|
||||
function materializeActions(
|
||||
@@ -58,11 +42,8 @@ export function UpdateCalloutSource() {
|
||||
const { theme } = useUnistyles();
|
||||
const {
|
||||
isDesktopApp,
|
||||
updateMode,
|
||||
isLoadingSettings,
|
||||
status,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
checkForUpdates,
|
||||
installUpdate,
|
||||
@@ -77,7 +58,7 @@ export function UpdateCalloutSource() {
|
||||
void checkForUpdates();
|
||||
});
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp || isLoadingSettings || updateMode === "off") return;
|
||||
if (!isDesktopApp) return;
|
||||
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
|
||||
@@ -90,7 +71,7 @@ export function UpdateCalloutSource() {
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
};
|
||||
}, [isDesktopApp, isLoadingSettings, updateMode, checkForUpdates]);
|
||||
}, [isDesktopApp, checkForUpdates]);
|
||||
|
||||
useEffect(() => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor({
|
||||
@@ -98,7 +79,6 @@ export function UpdateCalloutSource() {
|
||||
status,
|
||||
isInstalling,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
});
|
||||
if (!descriptor) return;
|
||||
@@ -123,7 +103,6 @@ export function UpdateCalloutSource() {
|
||||
}, [
|
||||
availableUpdate,
|
||||
callouts,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
install,
|
||||
isDesktopApp,
|
||||
@@ -138,94 +117,23 @@ export function UpdateCalloutSource() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatAvailableSummary(
|
||||
t: ReturnType<typeof useTranslation>["t"],
|
||||
versionLabel: string | undefined,
|
||||
readyToInstall: boolean,
|
||||
): string {
|
||||
if (readyToInstall) {
|
||||
return versionLabel
|
||||
? t("desktop.updates.callout.versionReady", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionReady");
|
||||
}
|
||||
return versionLabel
|
||||
? t("desktop.updates.callout.versionAvailable", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionAvailable");
|
||||
}
|
||||
|
||||
function UpdateAvailableDescription({
|
||||
versionLabel,
|
||||
readyToInstall,
|
||||
t,
|
||||
}: {
|
||||
versionLabel?: string;
|
||||
readyToInstall: boolean;
|
||||
t: ReturnType<typeof useTranslation>["t"];
|
||||
}) {
|
||||
const summary = formatAvailableSummary(t, versionLabel, readyToInstall);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SidebarCalloutDescriptionText>{summary}</SidebarCalloutDescriptionText>
|
||||
<SidebarCalloutDescriptionText>
|
||||
{versionLabel
|
||||
? t("desktop.updates.callout.versionReady", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionReady")}
|
||||
</SidebarCalloutDescriptionText>
|
||||
<SidebarCalloutDescriptionText>
|
||||
{t("desktop.updates.callout.restartWarning")}
|
||||
</SidebarCalloutDescriptionText>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function UpdateDownloadingDescription({
|
||||
versionLabel,
|
||||
percent,
|
||||
t,
|
||||
}: {
|
||||
versionLabel?: string;
|
||||
percent: number;
|
||||
t: ReturnType<typeof useTranslation>["t"];
|
||||
}) {
|
||||
const clampedPercent = Math.max(0, Math.min(100, percent));
|
||||
const accessibilityValue = useMemo(
|
||||
() => ({ min: 0, max: 100, now: clampedPercent }),
|
||||
[clampedPercent],
|
||||
);
|
||||
const progressFillStyle = useMemo(
|
||||
() => [styles.progressFill, { width: `${clampedPercent}%` as const }],
|
||||
[clampedPercent],
|
||||
);
|
||||
return (
|
||||
<View style={styles.progressContainer}>
|
||||
<SidebarCalloutDescriptionText>
|
||||
{versionLabel
|
||||
? t("desktop.updates.callout.downloadingVersionDescription", {
|
||||
version: versionLabel,
|
||||
percent: clampedPercent,
|
||||
})
|
||||
: t("desktop.updates.callout.downloadingDescription", { percent: clampedPercent })}
|
||||
</SidebarCalloutDescriptionText>
|
||||
<View
|
||||
style={styles.progressTrack}
|
||||
accessibilityRole="progressbar"
|
||||
accessibilityValue={accessibilityValue}
|
||||
>
|
||||
<View style={progressFillStyle} />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
progressContainer: {
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
progressTrack: {
|
||||
height: 4,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.surface3,
|
||||
overflow: "hidden",
|
||||
},
|
||||
progressFill: {
|
||||
height: "100%",
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,94 +1,30 @@
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
|
||||
import {
|
||||
checkDesktopAppUpdate,
|
||||
formatVersionWithPrefix,
|
||||
installDesktopAppUpdate,
|
||||
shouldShowDesktopUpdateSection,
|
||||
subscribeDesktopAppUpdateDownloadProgress,
|
||||
type DesktopAppUpdateCheckResult,
|
||||
type DesktopAppUpdateCheckIntent,
|
||||
type DesktopAppUpdateDownloadProgress,
|
||||
type DesktopAppUpdateInstallResult,
|
||||
} from "@/desktop/updates/desktop-updates";
|
||||
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopIpcErrorReporter } from "@/desktop/hooks/desktop-ipc-error";
|
||||
import {
|
||||
PENDING_RECHECK_MS,
|
||||
createDesktopAppUpdater,
|
||||
formatStatusText,
|
||||
type DesktopAppUpdater,
|
||||
type DesktopAppUpdaterErrorReport,
|
||||
type DesktopAppUpdateStatus,
|
||||
} from "@/desktop/updates/desktop-app-updater";
|
||||
import { formatMessageTimestamp } from "@/utils/time";
|
||||
|
||||
export type { DesktopAppUpdateStatus };
|
||||
|
||||
let activeInstallErrorReporter: ((report: DesktopAppUpdaterErrorReport) => void) | null = null;
|
||||
let sharedDesktopAppUpdater: DesktopAppUpdater | null = null;
|
||||
let progressSubscriptionCount = 0;
|
||||
let progressUnsubscribe: (() => void) | null = null;
|
||||
|
||||
function getSharedDesktopAppUpdater(): DesktopAppUpdater {
|
||||
if (!sharedDesktopAppUpdater) {
|
||||
sharedDesktopAppUpdater = createDesktopAppUpdater({
|
||||
port: {
|
||||
checkDesktopAppUpdate,
|
||||
installDesktopAppUpdate,
|
||||
},
|
||||
now: () => Date.now(),
|
||||
reportInstallError: (report) => {
|
||||
activeInstallErrorReporter?.(report);
|
||||
},
|
||||
});
|
||||
}
|
||||
return sharedDesktopAppUpdater;
|
||||
}
|
||||
|
||||
function retainDownloadProgressSubscription(updater: DesktopAppUpdater): () => void {
|
||||
progressSubscriptionCount += 1;
|
||||
if (progressSubscriptionCount === 1) {
|
||||
let active = true;
|
||||
const teardown = () => {
|
||||
active = false;
|
||||
};
|
||||
progressUnsubscribe = teardown;
|
||||
void subscribeDesktopAppUpdateDownloadProgress((progress) => {
|
||||
if (active) {
|
||||
updater.setDownloadProgress(progress);
|
||||
}
|
||||
})
|
||||
.then((cleanup) => {
|
||||
if (active) {
|
||||
progressUnsubscribe = () => {
|
||||
active = false;
|
||||
cleanup();
|
||||
};
|
||||
} else {
|
||||
cleanup();
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
return () => {
|
||||
progressSubscriptionCount = Math.max(0, progressSubscriptionCount - 1);
|
||||
if (progressSubscriptionCount === 0) {
|
||||
progressUnsubscribe?.();
|
||||
progressUnsubscribe = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export interface UseDesktopAppUpdaterReturn {
|
||||
isDesktopApp: boolean;
|
||||
updateMode: DesktopUpdateMode;
|
||||
isLoadingSettings: boolean;
|
||||
status: DesktopAppUpdateStatus;
|
||||
statusText: string;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
isChecking: boolean;
|
||||
@@ -102,15 +38,22 @@ export interface UseDesktopAppUpdaterReturn {
|
||||
|
||||
export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
const isDesktopApp = shouldShowDesktopUpdateSection();
|
||||
const { settings: desktopSettings, isLoading: isLoadingSettings } = useDesktopSettings();
|
||||
const { settings: desktopSettings } = useDesktopSettings();
|
||||
const releaseChannel = desktopSettings.releaseChannel;
|
||||
const updateMode = desktopSettings.updates.mode;
|
||||
const reportError = useDesktopIpcErrorReporter();
|
||||
const updater = getSharedDesktopAppUpdater();
|
||||
|
||||
useEffect(() => {
|
||||
activeInstallErrorReporter = reportError;
|
||||
}, [reportError]);
|
||||
const updater = useMemo(
|
||||
() =>
|
||||
createDesktopAppUpdater({
|
||||
port: {
|
||||
checkDesktopAppUpdate,
|
||||
installDesktopAppUpdate,
|
||||
},
|
||||
now: () => Date.now(),
|
||||
reportInstallError: reportError,
|
||||
}),
|
||||
[reportError],
|
||||
);
|
||||
|
||||
const snapshot = useSyncExternalStore(
|
||||
updater.subscribe,
|
||||
@@ -141,20 +84,13 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp) {
|
||||
return undefined;
|
||||
}
|
||||
return retainDownloadProgressSubscription(updater);
|
||||
}, [isDesktopApp, updater]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp || isLoadingSettings || updateMode === "off") {
|
||||
return;
|
||||
}
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
}, [checkForUpdates, isDesktopApp, isLoadingSettings, updateMode]);
|
||||
}, [checkForUpdates, isDesktopApp]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp || snapshot.status !== "pending" || updateMode === "off") {
|
||||
if (!isDesktopApp || snapshot.status !== "pending") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -165,24 +101,20 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
return () => {
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [checkForUpdates, isDesktopApp, snapshot.status, updateMode]);
|
||||
}, [checkForUpdates, isDesktopApp, snapshot.status]);
|
||||
|
||||
return {
|
||||
isDesktopApp,
|
||||
updateMode,
|
||||
isLoadingSettings,
|
||||
status: snapshot.status,
|
||||
statusText: formatStatusText({
|
||||
status: snapshot.status,
|
||||
availableUpdate: snapshot.availableUpdate,
|
||||
downloadProgress: snapshot.downloadProgress,
|
||||
installMessage: snapshot.installMessage,
|
||||
lastCheckedAt: snapshot.lastCheckedAt,
|
||||
formatVersion: formatVersionWithPrefix,
|
||||
formatLastCheckedAt: (timestamp) => formatMessageTimestamp(new Date(timestamp)),
|
||||
}),
|
||||
availableUpdate: snapshot.availableUpdate,
|
||||
downloadProgress: snapshot.downloadProgress,
|
||||
errorMessage: snapshot.errorMessage,
|
||||
lastCheckedAt: snapshot.lastCheckedAt,
|
||||
isChecking: snapshot.isChecking,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export { PairDeviceModal } from "./pair-device-modal";
|
||||
export { WaysToConnect } from "./ways-to-connect";
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { PairDeviceSection } from "@/desktop/components/pair-device-section";
|
||||
import { PairDeviceSection } from "@/devices/pair-device-section";
|
||||
|
||||
export interface PairDeviceModalProps {
|
||||
serverId: string;
|
||||
+1
-1
@@ -23,7 +23,7 @@ import {
|
||||
|
||||
const RELAY_DOCS_URL = "https://paseo.sh/docs/security";
|
||||
export const CONNECTIVITY_DOCS_URL = "https://paseo.sh/docs/connectivity";
|
||||
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);
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { describeTailscale } from "./tailscale-hint";
|
||||
|
||||
// Statuses as the host reports them; see `createDaemonListeners` in the server's listeners.ts.
|
||||
const off: TailscaleStatus = { ip: "100.101.102.103", address: null, state: "off" };
|
||||
|
||||
describe("the Tailscale row's hint", () => {
|
||||
it("says why Tailscale stays off when the host listens on a socket", () => {
|
||||
const socketHint = "Off, because this host listens on a local socket";
|
||||
expect(describeTailscale({ ...off, lockedBy: "main", mainIsSocket: true }, i18n.t)).toBe(
|
||||
socketHint,
|
||||
);
|
||||
expect(describeTailscale({ ...off, lockedBy: "launch", mainIsSocket: true }, i18n.t)).toBe(
|
||||
socketHint,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the hint of every other state", () => {
|
||||
const hint = (status: TailscaleStatus) => describeTailscale(status, i18n.t);
|
||||
expect(hint(off)).toBe("Direct over your tailnet, enter an address");
|
||||
expect(hint({ ip: null, address: null, state: "unavailable", lockedBy: "launch" })).toBe(
|
||||
"Tailscale is not running on this host",
|
||||
);
|
||||
expect(hint({ ...off, state: "waiting", address: "100.101.102.103:6767" })).toBe(
|
||||
"Waiting for Tailscale to start on this host",
|
||||
);
|
||||
expect(hint({ ...off, state: "on", address: "100.101.102.103:6767", lockedBy: "main" })).toBe(
|
||||
"Always on, because this host already accepts Tailscale connections",
|
||||
);
|
||||
expect(hint({ ...off, lockedBy: "launch" })).toBe(
|
||||
"Controlled by the command that starts this host",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
/** The line under the Tailscale label for each state the host reports, most specific first. */
|
||||
export function describeTailscale(status: TailscaleStatus, t: TFunction): string {
|
||||
if (status.state === "unavailable") return t("devices.tailscale.unavailable");
|
||||
if (status.state === "waiting") return t("devices.tailscale.waiting");
|
||||
// A socket is why Tailscale cannot be on, even when the launch command also fixes the address.
|
||||
if (status.mainIsSocket) return t("devices.tailscale.socket");
|
||||
if (status.lockedBy === "launch") return t("devices.tailscale.launch");
|
||||
if (status.lockedBy === "main") return t("devices.tailscale.alwaysOn");
|
||||
return t("devices.tailscale.hint");
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SettingsAction, SettingsRowChildren, SettingsSwitch } from "@/components/settings";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { copyToClipboard } from "@/utils/copy-to-clipboard";
|
||||
import { describeTailscale } from "./tailscale-hint";
|
||||
|
||||
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
||||
const TAILSCALE_DOWNLOAD_URL = "https://tailscale.com/download";
|
||||
// A product name, the same in every language.
|
||||
const LABEL = "Tailscale";
|
||||
|
||||
type HostClient = NonNullable<ReturnType<typeof useHostRuntimeClient>>;
|
||||
|
||||
/**
|
||||
* Turns Tailscale on or off for a host and shows the address a phone on the tailnet adds. Renders
|
||||
* as a row inside a `SettingsCard`; when Tailscale is on, the address is a nested row under it.
|
||||
*/
|
||||
export function TailscaleRow({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const connection = useHostRuntimeSnapshot(serverId)?.connectionStatus;
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo);
|
||||
const updateLink = useMemo(
|
||||
() => ({ href: UPDATES_DOCS_URL, label: t("devices.tailscale.updateDocs") }),
|
||||
[t],
|
||||
);
|
||||
// COMPAT(tailscale): added in v0.16.0, remove after 2027-05-25 once daemon floor >= v0.16.0.
|
||||
if (serverInfo && serverInfo.features?.tailscale !== true) {
|
||||
return (
|
||||
<SettingsSwitch
|
||||
label={LABEL}
|
||||
hint={t("devices.tailscale.update")}
|
||||
link={updateLink}
|
||||
value={false}
|
||||
disabled
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (client && connection === "online" && serverInfo) {
|
||||
return <TailscaleControl serverId={serverId} client={client} />;
|
||||
}
|
||||
// Without the host the row shows no value: the switch's space stays empty. A host the app has
|
||||
// reached before keeps its server info, so while the app retries it still reads as disconnected.
|
||||
const lost = connection === "offline" || connection === "error" || Boolean(serverInfo);
|
||||
return (
|
||||
<SettingsSwitch
|
||||
label={LABEL}
|
||||
hint={t(lost ? "workspace.terminal.hostDisconnected" : "devices.tailscale.hint")}
|
||||
value={null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TailscaleControl({ serverId, client }: { serverId: string; client: HostClient }) {
|
||||
const { t } = useTranslation();
|
||||
const tailscale = useTailscale(serverId, client);
|
||||
const { status } = tailscale;
|
||||
const installLink = useMemo(
|
||||
() => ({ href: TAILSCALE_DOWNLOAD_URL, label: t("devices.tailscale.install") }),
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsSwitch
|
||||
label={LABEL}
|
||||
hint={status ? describeTailscale(status, t) : t("devices.tailscale.hint")}
|
||||
link={status?.state === "unavailable" ? installLink : undefined}
|
||||
error={tailscale.error}
|
||||
value={tailscale.value}
|
||||
disabled={!status || status.state === "unavailable" || Boolean(status.lockedBy)}
|
||||
onValueChange={tailscale.setEnabled}
|
||||
/>
|
||||
{tailscale.address ? <TailscaleAddress address={tailscale.address} /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function TailscaleAddress({ address }: { address: string }) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const copy = useCallback(() => {
|
||||
void copyToClipboard(address)
|
||||
.then(() => toast.copied())
|
||||
.catch(() => toast.error(t("common.errors.error")));
|
||||
}, [address, t, toast]);
|
||||
return (
|
||||
<SettingsRowChildren>
|
||||
<SettingsAction
|
||||
label={address}
|
||||
hint={t("devices.tailscale.address")}
|
||||
actionLabel={t("common.actions.copy")}
|
||||
onPress={copy}
|
||||
testID="devices-tailscale-address"
|
||||
/>
|
||||
</SettingsRowChildren>
|
||||
);
|
||||
}
|
||||
|
||||
interface TailscaleChange {
|
||||
enabled: boolean;
|
||||
confirmed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The host's Tailscale state and the one way to change it. While a change is in flight the switch
|
||||
* already shows where it is going, so a tap answers at once; the host's answer then settles it.
|
||||
* Turning Tailscale off over the connection it would cut asks first, and nothing changes on screen
|
||||
* until the user confirms.
|
||||
*/
|
||||
function useTailscale(serverId: string, client: HostClient) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const queryKey = useMemo(() => ["tailscale-status", serverId], [serverId]);
|
||||
|
||||
const query = useFetchQuery({
|
||||
queryKey,
|
||||
queryFn: async () => {
|
||||
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
|
||||
if (!tailscale) throw new Error("Host did not report Tailscale status");
|
||||
return tailscale;
|
||||
},
|
||||
// Tailscale can come up after the host does; polling moves "waiting" to "on" on its own.
|
||||
refetchInterval: 2_000,
|
||||
staleTimeMs: 0,
|
||||
dataShape: "value",
|
||||
});
|
||||
|
||||
const change = useMutation({
|
||||
mutationFn: async ({ enabled, confirmed }: TailscaleChange) => {
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
return client.setTailscaleEnabled(enabled, confirmed);
|
||||
},
|
||||
onSuccess: (result) => queryClient.setQueryData(queryKey, result.tailscale),
|
||||
});
|
||||
|
||||
const status = query.data;
|
||||
const pending = change.isPending ? change.variables.enabled : undefined;
|
||||
const on = status?.state === "on" || status?.state === "waiting";
|
||||
// Not known until the host first answers.
|
||||
const value = pending ?? (status ? on : null);
|
||||
|
||||
const { mutate } = change;
|
||||
const confirmTurnOff = useCallback(
|
||||
() =>
|
||||
confirmDialog({
|
||||
title: t("devices.tailscale.confirmTitle"),
|
||||
message: t("devices.tailscale.confirmMessage"),
|
||||
confirmLabel: t("devices.tailscale.confirmAction"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
destructive: true,
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
const turnOffConfirmed = useCallback(async () => {
|
||||
if (await confirmTurnOff()) mutate({ enabled: false, confirmed: true });
|
||||
}, [confirmTurnOff, mutate]);
|
||||
const disconnects = status?.disconnectsCurrentConnection === true;
|
||||
const setEnabled = useCallback(
|
||||
(enabled: boolean) => {
|
||||
if (!enabled && disconnects) {
|
||||
void turnOffConfirmed();
|
||||
return;
|
||||
}
|
||||
mutate(
|
||||
{ enabled, confirmed: false },
|
||||
{
|
||||
// The status was stale: the host would cut this connection after all. Its answer has
|
||||
// already put the row back to on, so the question is asked over what is true.
|
||||
onSuccess: (result) => {
|
||||
if (result.confirmationRequired) void turnOffConfirmed();
|
||||
},
|
||||
},
|
||||
);
|
||||
},
|
||||
[disconnects, mutate, turnOffConfirmed],
|
||||
);
|
||||
|
||||
let error: string | undefined;
|
||||
if (change.isError) {
|
||||
error = t(
|
||||
change.variables.enabled ? "devices.tailscale.turnOnError" : "devices.tailscale.turnOffError",
|
||||
);
|
||||
} else if (query.isError && !status) {
|
||||
error = t("devices.tailscale.statusError");
|
||||
}
|
||||
|
||||
return {
|
||||
status,
|
||||
value,
|
||||
error,
|
||||
// A tap is ignored until the host answers the one before it.
|
||||
setEnabled: change.isPending ? undefined : setEnabled,
|
||||
address: status?.state === "on" && value ? status.address : null,
|
||||
};
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -32,9 +32,6 @@ export interface FakeDesktopBridge extends DesktopSettingsBridge {
|
||||
|
||||
const DEFAULT_DESKTOP: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
|
||||
@@ -656,7 +656,6 @@ describe("loadSettingsFromStorage", () => {
|
||||
isElectron: true,
|
||||
settings: {
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true },
|
||||
},
|
||||
|
||||
@@ -1541,8 +1541,6 @@ export const ar: TranslationResources = {
|
||||
status: {
|
||||
checking: "جارٍ التحقق من وجود تحديثات للتطبيق...",
|
||||
installing: "جارٍ تثبيت تحديث التطبيق...",
|
||||
downloadingVersionProgress: "جارٍ تنزيل {{version}}... {{percent}}%",
|
||||
downloadingProgress: "جارٍ تنزيل تحديث التطبيق... {{percent}}%",
|
||||
upToDate: "التطبيق محدث.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "سنخبرك عندما يصبح التحديث جاهزًا.",
|
||||
@@ -1550,14 +1548,6 @@ export const ar: TranslationResources = {
|
||||
pendingWithVersion: "تم العثور على تحديث: {{version}}. جارٍ التنزيل...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... آخر فحص في {{time}}.",
|
||||
pendingWithVersionProgress: "تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}% آخر فحص في {{time}}.",
|
||||
downloadAvailableWithVersion: "التحديث متاح: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"التحديث متاح: {{version}}. آخر فحص في {{time}}.",
|
||||
downloadAvailable: "يتوفر تحديث للتطبيق.",
|
||||
downloadAvailableWithLastChecked: "يتوفر تحديث للتطبيق. آخر فحص في {{time}}.",
|
||||
availableWithVersion: "التحديث جاهز:{{version}}",
|
||||
availableWithVersionAndLastChecked: "التحديث جاهز:{{version}}. آخر فحص في {{time}}.",
|
||||
available: "تحديث التطبيق جاهز للتثبيت.",
|
||||
@@ -1568,21 +1558,14 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
installError: "غير قادر على تثبيت تحديث تطبيق سطح المكتب.",
|
||||
callout: {
|
||||
downloadingTitle: "جارٍ تنزيل التحديث",
|
||||
installingTitle: "تثبيت التحديث",
|
||||
failedTitle: "فشل التحديث",
|
||||
availableTitle: "التحديث متاح",
|
||||
genericError: "حدث خطأ ما.",
|
||||
whatsNew: "ما هو الجديد",
|
||||
downloadingAction: "جارٍ التنزيل...",
|
||||
installingAction: "جارٍ التثبيت...",
|
||||
downloadAndRestart: "تنزيل",
|
||||
installAndRestart: "التثبيت وإعادة التشغيل",
|
||||
downloadingVersionDescription: "جارٍ تنزيل {{version}}... {{percent}}%",
|
||||
downloadingDescription: "جارٍ تنزيل التحديث... {{percent}}%",
|
||||
installingDescription: "التثبيت وإعادة التشغيل...",
|
||||
versionAvailable: "{{version}} متاح للتنزيل.",
|
||||
newVersionAvailable: "يتوفر إصدار جديد للتنزيل.",
|
||||
versionReady: "{{version}}جاهز للتثبيت.",
|
||||
newVersionReady: "إصدار جديد جاهز للتثبيت.",
|
||||
restartWarning: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.",
|
||||
@@ -1799,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: "يتطلب بعض الإعداد" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1880,6 +1857,32 @@ export const ar: TranslationResources = {
|
||||
hostDisconnected: "Host غير متصل",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "الأجهزة",
|
||||
waysToConnect: "طرق الاتصال",
|
||||
docs: "الوثائق",
|
||||
docsAccessibility: "افتح وثائق الاتصال",
|
||||
recommended: "موصى به",
|
||||
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
|
||||
tailscale: {
|
||||
hint: "اتصال مباشر عبر شبكة tailnet الخاصة بك، أدخل عنوانًا",
|
||||
unavailable: "Tailscale لا يعمل على هذا المضيف",
|
||||
install: "احصل على Tailscale",
|
||||
waiting: "في انتظار بدء Tailscale على هذا المضيف",
|
||||
alwaysOn: "مفعّل دائمًا، لأن هذا المضيف يقبل اتصالات Tailscale بالفعل",
|
||||
socket: "متوقف، لأن هذا المضيف يستمع على مقبس محلي",
|
||||
launch: "يتحكم فيه الأمر الذي يشغّل هذا المضيف",
|
||||
update: "حدّث هذا المضيف لاستخدام Tailscale",
|
||||
updateDocs: "طريقة التحديث",
|
||||
address: "على هاتف متصل بـ Tailscale، أضف مضيفًا بهذا العنوان",
|
||||
statusError: "تعذّر التحقق من Tailscale",
|
||||
turnOnError: "تعذّر تشغيل Tailscale",
|
||||
turnOffError: "تعذّر إيقاف Tailscale",
|
||||
confirmTitle: "إيقاف Tailscale؟",
|
||||
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
|
||||
confirmAction: "إيقاف",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "كلمة المرور لـ {{host}}",
|
||||
@@ -2660,28 +2663,9 @@ export const ar: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "التحديثات التلقائية",
|
||||
options: {
|
||||
automatic: "تلقائي",
|
||||
notify: "إشعار",
|
||||
off: "إيقاف",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "التحقق من التحديثات وتنزيلها في الخلفية",
|
||||
notify: "التحقق من التحديثات وتنزيلها فقط عند اختيارك",
|
||||
off: "عدم التحقق تلقائيًا. يتم التحقق فقط عند النقر على فحص",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "تحديثات التطبيق",
|
||||
readyToInstall: "جاهز للتثبيت:{{version}}",
|
||||
downloadTitle: "تنزيل تحديث سطح المكتب",
|
||||
downloadMessage: "سيؤدي هذا إلى تنزيل تحديث Paseo وتثبيته على هذا الكمبيوتر",
|
||||
downloadConfirm: "تنزيل وتثبيت",
|
||||
download: "تنزيل",
|
||||
downloadTo: "تنزيل {{version}}",
|
||||
downloading: "جارٍ التنزيل...",
|
||||
installTitle: "تثبيت تحديث سطح المكتب",
|
||||
installMessage: "يؤدي هذا إلى تحديث Paseo على هذا الكمبيوتر",
|
||||
installConfirm: "تثبيت التحديث",
|
||||
@@ -2952,9 +2936,7 @@ export const ar: TranslationResources = {
|
||||
timeout: "نفذ الوقت",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "إقران الأجهزة",
|
||||
rowTitle: "إقران جهاز",
|
||||
rowHint: "امسح رمز QR ضوئيًا أو انسخ رابطًا لتوصيل هاتفك بهذا المضيف",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1568,8 +1568,6 @@ export const en = {
|
||||
status: {
|
||||
checking: "Checking for app updates...",
|
||||
installing: "Installing app update...",
|
||||
downloadingVersionProgress: "Downloading {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Downloading app update... {{percent}}%",
|
||||
upToDate: "App is up to date.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "We'll let you know when the update is ready.",
|
||||
@@ -1578,14 +1576,6 @@ export const en = {
|
||||
pendingWithVersion: "Update found: {{version}}. Downloading...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Update found: {{version}}. Downloading... Last checked at {{time}}.",
|
||||
pendingWithVersionProgress: "Update found: {{version}}. Downloading... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Update found: {{version}}. Downloading... {{percent}}% Last checked at {{time}}.",
|
||||
downloadAvailableWithVersion: "Update available: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Update available: {{version}}. Last checked at {{time}}.",
|
||||
downloadAvailable: "An app update is available.",
|
||||
downloadAvailableWithLastChecked: "An app update is available. Last checked at {{time}}.",
|
||||
availableWithVersion: "Update ready: {{version}}",
|
||||
availableWithVersionAndLastChecked: "Update ready: {{version}}. Last checked at {{time}}.",
|
||||
available: "An app update is ready to install.",
|
||||
@@ -1596,21 +1586,14 @@ export const en = {
|
||||
},
|
||||
installError: "Unable to install the desktop app update.",
|
||||
callout: {
|
||||
downloadingTitle: "Downloading update",
|
||||
installingTitle: "Installing update",
|
||||
failedTitle: "Update failed",
|
||||
availableTitle: "Update available",
|
||||
genericError: "Something went wrong.",
|
||||
whatsNew: "What's new",
|
||||
downloadingAction: "Downloading...",
|
||||
installingAction: "Installing...",
|
||||
downloadAndRestart: "Download",
|
||||
installAndRestart: "Install & restart",
|
||||
downloadingVersionDescription: "Downloading {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Downloading update... {{percent}}%",
|
||||
installingDescription: "Installing and restarting...",
|
||||
versionAvailable: "{{version}} is available to download.",
|
||||
newVersionAvailable: "A new version is available to download.",
|
||||
versionReady: "{{version}} is ready to install.",
|
||||
newVersionReady: "A new version is ready to install.",
|
||||
restartWarning: "Upgrading the app will stop running agents and close terminal sessions.",
|
||||
@@ -1828,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" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1909,6 +1886,33 @@ export const en = {
|
||||
hostDisconnected: "Host is not connected",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Devices",
|
||||
waysToConnect: "Ways to connect",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Open connectivity documentation",
|
||||
recommended: "Recommended",
|
||||
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
|
||||
tailscale: {
|
||||
hint: "Direct over your tailnet, enter an address",
|
||||
unavailable: "Tailscale is not running on this host",
|
||||
install: "Get Tailscale",
|
||||
waiting: "Waiting for Tailscale to start on this host",
|
||||
alwaysOn: "Always on, because this host already accepts Tailscale connections",
|
||||
socket: "Off, because this host listens on a local socket",
|
||||
launch: "Controlled by the command that starts this host",
|
||||
update: "Update this host to use Tailscale",
|
||||
updateDocs: "How to update",
|
||||
address: "On a phone with Tailscale, add a host at this address",
|
||||
statusError: "Could not check Tailscale",
|
||||
turnOnError: "Could not turn on Tailscale",
|
||||
turnOffError: "Could not turn off Tailscale",
|
||||
confirmTitle: "Turn off Tailscale?",
|
||||
confirmMessage:
|
||||
"This device is connected through Tailscale and will lose its connection to the host.",
|
||||
confirmAction: "Turn off",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Password for {{host}}",
|
||||
@@ -2756,28 +2760,9 @@ export const en = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Automatic updates",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notify",
|
||||
off: "Off",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Check and download updates in the background",
|
||||
notify: "Check for updates, but only download when you choose",
|
||||
off: "Never check automatically. Only check when you click Check",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "App updates",
|
||||
readyToInstall: "Ready to install: {{version}}",
|
||||
downloadTitle: "Download desktop update",
|
||||
downloadMessage: "This downloads and installs the Paseo update on this computer",
|
||||
downloadConfirm: "Download & install",
|
||||
download: "Download",
|
||||
downloadTo: "Download {{version}}",
|
||||
downloading: "Downloading...",
|
||||
installTitle: "Install desktop update",
|
||||
installMessage: "This updates Paseo on this computer",
|
||||
installConfirm: "Install update",
|
||||
@@ -3047,9 +3032,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",
|
||||
|
||||
@@ -1578,8 +1578,6 @@ export const es: TranslationResources = {
|
||||
status: {
|
||||
checking: "Buscando actualizaciones de la aplicación...",
|
||||
installing: "Instalando actualización de la aplicación...",
|
||||
downloadingVersionProgress: "Descargando {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Descargando actualización de la aplicación... {{percent}}%",
|
||||
upToDate: "La aplicación está actualizada.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "Le avisaremos cuando la actualización esté lista.",
|
||||
@@ -1588,16 +1586,6 @@ export const es: TranslationResources = {
|
||||
pendingWithVersion: "Actualización encontrada: {{version}}. Descargando...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Actualización encontrada: {{version}}. Descargando... Última comprobación a las {{time}}.",
|
||||
pendingWithVersionProgress:
|
||||
"Actualización encontrada: {{version}}. Descargando... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Actualización encontrada: {{version}}. Descargando... {{percent}}% Última comprobación a las {{time}}.",
|
||||
downloadAvailableWithVersion: "Actualización disponible: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Actualización disponible: {{version}}. Última comprobación a las {{time}}.",
|
||||
downloadAvailable: "Hay una actualización de la aplicación disponible.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Hay una actualización de la aplicación disponible. Última comprobación a las {{time}}.",
|
||||
availableWithVersion: "Actualización lista:{{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Actualización lista:{{version}}. Última comprobación a las {{time}}.",
|
||||
@@ -1610,21 +1598,14 @@ export const es: TranslationResources = {
|
||||
},
|
||||
installError: "No se puede instalar la actualización de la aplicación de escritorio.",
|
||||
callout: {
|
||||
downloadingTitle: "Descargando actualización",
|
||||
installingTitle: "Instalando actualización",
|
||||
failedTitle: "La actualización falló",
|
||||
availableTitle: "Actualización disponible",
|
||||
genericError: "Algo salió mal.",
|
||||
whatsNew: "Qué hay de nuevo",
|
||||
downloadingAction: "Descargando...",
|
||||
installingAction: "Instalando...",
|
||||
downloadAndRestart: "Descargar",
|
||||
installAndRestart: "Instalar y reiniciar",
|
||||
downloadingVersionDescription: "Descargando {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Descargando actualización... {{percent}}%",
|
||||
installingDescription: "Instalando y reiniciando...",
|
||||
versionAvailable: "{{version}} está disponible para descargar.",
|
||||
newVersionAvailable: "Una nueva versión está disponible para descargar.",
|
||||
versionReady: "{{version}}está listo para instalar.",
|
||||
newVersionReady: "Una nueva versión está lista para instalar.",
|
||||
restartWarning:
|
||||
@@ -1849,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" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1930,6 +1905,33 @@ export const es: TranslationResources = {
|
||||
hostDisconnected: "Hostno está conectado",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Dispositivos",
|
||||
waysToConnect: "Formas de conectarse",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Abrir la documentación de conectividad",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
|
||||
tailscale: {
|
||||
hint: "Conexión directa por tu tailnet, introduce una dirección",
|
||||
unavailable: "Tailscale no se está ejecutando en este host",
|
||||
install: "Obtener Tailscale",
|
||||
waiting: "Esperando a que Tailscale se inicie en este host",
|
||||
alwaysOn: "Siempre activado, porque este host ya acepta conexiones de Tailscale",
|
||||
socket: "Desactivado, porque este host escucha en un socket local",
|
||||
launch: "Lo controla el comando que inicia este host",
|
||||
update: "Actualiza este host para usar Tailscale",
|
||||
updateDocs: "Cómo actualizar",
|
||||
address: "En un teléfono con Tailscale, añade un host con esta dirección",
|
||||
statusError: "No se pudo comprobar Tailscale",
|
||||
turnOnError: "No se pudo activar Tailscale",
|
||||
turnOffError: "No se pudo desactivar Tailscale",
|
||||
confirmTitle: "¿Desactivar Tailscale?",
|
||||
confirmMessage:
|
||||
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
|
||||
confirmAction: "Desactivar",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Contraseña de {{host}}",
|
||||
@@ -2683,28 +2685,9 @@ export const es: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Actualizaciones automáticas",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notificar",
|
||||
off: "Desactivado",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Buscar y descargar actualizaciones en segundo plano",
|
||||
notify: "Buscar actualizaciones, pero descargar solo cuando lo elijas",
|
||||
off: "No buscar automáticamente. Solo buscar al hacer clic en Comprobar",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Actualizaciones de aplicaciones",
|
||||
readyToInstall: "Listo para instalar:{{version}}",
|
||||
downloadTitle: "Descargar actualización de escritorio",
|
||||
downloadMessage: "Esto descarga e instala la actualización de Paseo en esta computadora.",
|
||||
downloadConfirm: "Descargar e instalar",
|
||||
download: "Descargar",
|
||||
downloadTo: "Descargar {{version}}",
|
||||
downloading: "Descargando...",
|
||||
installTitle: "Instalar actualización de escritorio",
|
||||
installMessage: "Esto actualizaPaseoen esta computadora.",
|
||||
installConfirm: "Instalar actualización",
|
||||
@@ -2978,9 +2961,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,
|
||||
|
||||
@@ -1571,8 +1571,6 @@ export const fr: TranslationResources = {
|
||||
status: {
|
||||
checking: "Recherche de mises à jour de l’application…",
|
||||
installing: "Installation de la mise à jour de l’application…",
|
||||
downloadingVersionProgress: "Téléchargement de {{version}}… {{percent}} %",
|
||||
downloadingProgress: "Téléchargement de la mise à jour… {{percent}} %",
|
||||
upToDate: "L’application est à jour.",
|
||||
upToDateWithLastChecked: "À jour. Dernière vérification à {{time}}.",
|
||||
pending: "Nous vous préviendrons quand la mise à jour sera prête.",
|
||||
@@ -1581,16 +1579,6 @@ export const fr: TranslationResources = {
|
||||
pendingWithVersion: "Mise à jour trouvée : {{version}}. Téléchargement…",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Mise à jour trouvée : {{version}}. Téléchargement… Dernière vérification à {{time}}.",
|
||||
pendingWithVersionProgress:
|
||||
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} %",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} % Dernière vérification à {{time}}.",
|
||||
downloadAvailableWithVersion: "Mise à jour disponible : {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Mise à jour disponible : {{version}}. Dernière vérification à {{time}}.",
|
||||
downloadAvailable: "Une mise à jour de l’application est disponible.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Une mise à jour de l’application est disponible. Dernière vérification à {{time}}.",
|
||||
availableWithVersion: "Mise à jour prête : {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Mise à jour prête : {{version}}. Dernière vérification à {{time}}.",
|
||||
@@ -1603,21 +1591,14 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
installError: "Impossible d’installer la mise à jour de l’application de bureau.",
|
||||
callout: {
|
||||
downloadingTitle: "Téléchargement de la mise à jour",
|
||||
installingTitle: "Installation de la mise à jour",
|
||||
failedTitle: "Échec de la mise à jour",
|
||||
availableTitle: "Mise à jour disponible",
|
||||
genericError: "Une erreur s’est produite.",
|
||||
whatsNew: "Nouveautés",
|
||||
downloadingAction: "Téléchargement…",
|
||||
installingAction: "Installation…",
|
||||
downloadAndRestart: "Télécharger",
|
||||
installAndRestart: "Installer et redémarrer",
|
||||
downloadingVersionDescription: "Téléchargement de {{version}}… {{percent}} %",
|
||||
downloadingDescription: "Téléchargement de la mise à jour… {{percent}} %",
|
||||
installingDescription: "Installation et redémarrage…",
|
||||
versionAvailable: "La version {{version}} est disponible au téléchargement.",
|
||||
newVersionAvailable: "Une nouvelle version est disponible au téléchargement.",
|
||||
versionReady: "La version {{version}} est prête à être installée.",
|
||||
newVersionReady: "Une nouvelle version est prête à être installée.",
|
||||
restartWarning:
|
||||
@@ -1847,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" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1928,6 +1903,32 @@ export const fr: TranslationResources = {
|
||||
hostDisconnected: "L’hôte n’est pas connecté",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Appareils",
|
||||
waysToConnect: "Moyens de connexion",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Ouvrir la documentation sur la connectivité",
|
||||
recommended: "Recommandé",
|
||||
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
|
||||
tailscale: {
|
||||
hint: "Connexion directe via votre tailnet, saisissez une adresse",
|
||||
unavailable: "Tailscale ne fonctionne pas sur cet hôte",
|
||||
install: "Obtenir Tailscale",
|
||||
waiting: "En attente du démarrage de Tailscale sur cet hôte",
|
||||
alwaysOn: "Toujours activé, car cet hôte accepte déjà les connexions Tailscale",
|
||||
socket: "Désactivé, car cet hôte écoute sur un socket local",
|
||||
launch: "Contrôlé par la commande qui démarre cet hôte",
|
||||
update: "Mettez cet hôte à jour pour utiliser Tailscale",
|
||||
updateDocs: "Comment mettre à jour",
|
||||
address: "Sur un téléphone avec Tailscale, ajoutez un hôte à cette adresse",
|
||||
statusError: "Impossible de vérifier Tailscale",
|
||||
turnOnError: "Impossible d’activer Tailscale",
|
||||
turnOffError: "Impossible de désactiver Tailscale",
|
||||
confirmTitle: "Désactiver Tailscale ?",
|
||||
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
|
||||
confirmAction: "Désactiver",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Mot de passe pour {{host}}",
|
||||
@@ -2683,28 +2684,9 @@ export const fr: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Bêta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Mises à jour automatiques",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notifier",
|
||||
off: "Désactivé",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Vérifier et télécharger les mises à jour en arrière-plan",
|
||||
notify: "Vérifier les mises à jour, mais ne télécharger que lorsque vous choisissez",
|
||||
off: "Ne jamais vérifier automatiquement. Vérifier uniquement sur clic sur Vérifier",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Mises à jour de l’application",
|
||||
readyToInstall: "Prête à installer : {{version}}",
|
||||
downloadTitle: "Télécharger la mise à jour de l’app de bureau",
|
||||
downloadMessage: "La mise à jour de Paseo sera téléchargée et installée sur cet ordinateur",
|
||||
downloadConfirm: "Télécharger et installer",
|
||||
download: "Télécharger",
|
||||
downloadTo: "Télécharger {{version}}",
|
||||
downloading: "Téléchargement…",
|
||||
installTitle: "Installer la mise à jour de l’app de bureau",
|
||||
installMessage: "Paseo sera mis à jour sur cet ordinateur",
|
||||
installConfirm: "Installer la mise à jour",
|
||||
@@ -2980,9 +2962,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,
|
||||
|
||||
@@ -1556,8 +1556,6 @@ export const ja: TranslationResources = {
|
||||
status: {
|
||||
checking: "アプリの更新を確認中...",
|
||||
installing: "アプリの更新をインストール中...",
|
||||
downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%",
|
||||
downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%",
|
||||
upToDate: "アプリは最新です。",
|
||||
upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。",
|
||||
pending: "更新の準備ができたらお知らせします。",
|
||||
@@ -1565,15 +1563,6 @@ export const ja: TranslationResources = {
|
||||
pendingWithVersion: "更新が見つかりました: {{version}}。ダウンロード中...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"更新が見つかりました: {{version}}。ダウンロード中... 最終確認: {{time}}。",
|
||||
pendingWithVersionProgress:
|
||||
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}% 最終確認: {{time}}。",
|
||||
downloadAvailableWithVersion: "利用可能な更新: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"利用可能な更新: {{version}}。最終確認: {{time}}。",
|
||||
downloadAvailable: "アプリの更新が利用可能です。",
|
||||
downloadAvailableWithLastChecked: "アプリの更新が利用可能です。最終確認: {{time}}。",
|
||||
availableWithVersion: "更新の準備ができました: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"更新の準備ができました: {{version}}。最終確認: {{time}}。",
|
||||
@@ -1585,21 +1574,14 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
installError: "デスクトップアプリの更新をインストールできません。",
|
||||
callout: {
|
||||
downloadingTitle: "更新をダウンロード中",
|
||||
installingTitle: "更新をインストール中",
|
||||
failedTitle: "更新に失敗しました",
|
||||
availableTitle: "更新が利用可能",
|
||||
genericError: "問題が発生しました。",
|
||||
whatsNew: "新機能",
|
||||
downloadingAction: "ダウンロード中...",
|
||||
installingAction: "インストール中...",
|
||||
downloadAndRestart: "ダウンロード",
|
||||
installAndRestart: "インストールして再起動",
|
||||
downloadingVersionDescription: "{{version}} をダウンロード中... {{percent}}%",
|
||||
downloadingDescription: "更新をダウンロード中... {{percent}}%",
|
||||
installingDescription: "インストールして再起動中...",
|
||||
versionAvailable: "{{version}} をダウンロードできます。",
|
||||
newVersionAvailable: "新しいバージョンをダウンロードできます。",
|
||||
versionReady: "{{version}}のインストール準備ができました。",
|
||||
newVersionReady: "新しいバージョンのインストール準備ができました。",
|
||||
restartWarning:
|
||||
@@ -1820,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: "少し設定が必要です" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1901,6 +1877,32 @@ export const ja: TranslationResources = {
|
||||
hostDisconnected: "ホストが接続されていません",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "デバイス",
|
||||
waysToConnect: "接続方法",
|
||||
docs: "ドキュメント",
|
||||
docsAccessibility: "接続のドキュメントを開く",
|
||||
recommended: "おすすめ",
|
||||
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
|
||||
tailscale: {
|
||||
hint: "tailnet 経由で直接接続、アドレスを入力",
|
||||
unavailable: "このホストで Tailscale が動作していません",
|
||||
install: "Tailscale を入手",
|
||||
waiting: "このホストで Tailscale が起動するのを待っています",
|
||||
alwaysOn: "常にオン。このホストはすでに Tailscale からの接続を受け付けています",
|
||||
socket: "オフ。このホストはローカルソケットで待ち受けています",
|
||||
launch: "このホストを起動するコマンドで制御されています",
|
||||
update: "Tailscale を使うにはこのホストを更新してください",
|
||||
updateDocs: "更新方法",
|
||||
address: "Tailscale を使うスマートフォンで、このアドレスのホストを追加してください",
|
||||
statusError: "Tailscale を確認できませんでした",
|
||||
turnOnError: "Tailscale をオンにできませんでした",
|
||||
turnOffError: "Tailscale をオフにできませんでした",
|
||||
confirmTitle: "Tailscale をオフにしますか?",
|
||||
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
|
||||
confirmAction: "オフにする",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} のパスワード",
|
||||
@@ -2649,28 +2651,9 @@ export const ja: TranslationResources = {
|
||||
stable: "安定版",
|
||||
beta: "ベータ",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "自動更新",
|
||||
options: {
|
||||
automatic: "自動",
|
||||
notify: "通知のみ",
|
||||
off: "オフ",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "バックグラウンドで更新を確認してダウンロードします",
|
||||
notify: "更新を確認しますが、選択したときだけダウンロードします",
|
||||
off: "自動で更新を確認しません。「確認」をクリックしたときだけ確認します",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "アプリの更新",
|
||||
readyToInstall: "インストール準備完了: {{version}}",
|
||||
downloadTitle: "デスクトップの更新をダウンロード",
|
||||
downloadMessage: "このコンピューターにPaseoの更新をダウンロードしてインストールします",
|
||||
downloadConfirm: "ダウンロードしてインストール",
|
||||
download: "ダウンロード",
|
||||
downloadTo: "{{version}}をダウンロード",
|
||||
downloading: "ダウンロード中...",
|
||||
installTitle: "デスクトップの更新をインストール",
|
||||
installMessage: "このコンピューターのPaseoを更新します",
|
||||
installConfirm: "更新をインストール",
|
||||
@@ -2945,9 +2928,7 @@ export const ja: TranslationResources = {
|
||||
timeout: "タイムアウト",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "デバイスをペアリング",
|
||||
rowTitle: "デバイスをペアリング",
|
||||
rowHint: "QRコードをスキャンするかリンクをコピーしてスマートフォンをこのホストに接続",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1547,8 +1547,6 @@ export const ko: TranslationResources = {
|
||||
status: {
|
||||
checking: "앱 업데이트 확인 중...",
|
||||
installing: "앱 업데이트 설치 중...",
|
||||
downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%",
|
||||
downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%",
|
||||
upToDate: "앱이 최신 상태입니다.",
|
||||
upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.",
|
||||
pending: "업데이트가 준비되면 알려드리겠습니다.",
|
||||
@@ -1557,15 +1555,6 @@ export const ko: TranslationResources = {
|
||||
pendingWithVersion: "업데이트 발견: {{version}}. 다운로드 중...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"업데이트 발견: {{version}}. 다운로드 중... {{time}}에서 마지막으로 확인했습니다.",
|
||||
pendingWithVersionProgress: "업데이트 발견: {{version}}. 다운로드 중... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"업데이트 발견: {{version}}. 다운로드 중... {{percent}}% {{time}}에서 마지막으로 확인했습니다.",
|
||||
downloadAvailableWithVersion: "사용 가능한 업데이트: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"사용 가능한 업데이트: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
|
||||
downloadAvailable: "사용 가능한 앱 업데이트가 있습니다.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"사용 가능한 앱 업데이트가 있습니다. {{time}}에서 마지막으로 확인했습니다.",
|
||||
availableWithVersion: "업데이트 준비됨: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"업데이트 준비됨: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
|
||||
@@ -1578,21 +1567,14 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
installError: "데스크톱 앱 업데이트를 설치할 수 없습니다.",
|
||||
callout: {
|
||||
downloadingTitle: "업데이트 다운로드 중",
|
||||
installingTitle: "업데이트 설치 중",
|
||||
failedTitle: "업데이트 실패",
|
||||
availableTitle: "업데이트 사용 가능",
|
||||
genericError: "문제가 발생했습니다.",
|
||||
whatsNew: "새로운 기능",
|
||||
downloadingAction: "다운로드 중...",
|
||||
installingAction: "설치 중...",
|
||||
downloadAndRestart: "다운로드",
|
||||
installAndRestart: "설치 후 재시작",
|
||||
downloadingVersionDescription: "{{version}} 다운로드 중... {{percent}}%",
|
||||
downloadingDescription: "업데이트 다운로드 중... {{percent}}%",
|
||||
installingDescription: "설치 후 재시작 중...",
|
||||
versionAvailable: "{{version}} 버전을 다운로드할 수 있습니다.",
|
||||
newVersionAvailable: "새 버전을 다운로드할 수 있습니다.",
|
||||
versionReady: "{{version}} 설치가 준비되었습니다.",
|
||||
newVersionReady: "새 버전 설치가 준비되었습니다.",
|
||||
restartWarning: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.",
|
||||
@@ -1811,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: "약간의 설정이 필요합니다" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1892,6 +1868,32 @@ export const ko: TranslationResources = {
|
||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "기기",
|
||||
waysToConnect: "연결 방법",
|
||||
docs: "문서",
|
||||
docsAccessibility: "연결 문서 열기",
|
||||
recommended: "권장",
|
||||
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
||||
tailscale: {
|
||||
hint: "tailnet으로 직접 연결, 주소 입력",
|
||||
unavailable: "이 호스트에서 Tailscale이 실행 중이 아닙니다",
|
||||
install: "Tailscale 받기",
|
||||
waiting: "이 호스트에서 Tailscale이 시작되기를 기다리는 중",
|
||||
alwaysOn: "항상 켜짐. 이 호스트가 이미 Tailscale 연결을 받고 있습니다",
|
||||
socket: "꺼짐. 이 호스트가 로컬 소켓에서 수신 대기 중입니다",
|
||||
launch: "이 호스트를 시작하는 명령이 제어합니다",
|
||||
update: "Tailscale을 사용하려면 이 호스트를 업데이트하세요",
|
||||
updateDocs: "업데이트 방법",
|
||||
address: "Tailscale을 사용하는 휴대전화에서 이 주소로 호스트를 추가하세요",
|
||||
statusError: "Tailscale을 확인하지 못했습니다",
|
||||
turnOnError: "Tailscale을 켜지 못했습니다",
|
||||
turnOffError: "Tailscale을 끄지 못했습니다",
|
||||
confirmTitle: "Tailscale을 끌까요?",
|
||||
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
|
||||
confirmAction: "끄기",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}}의 비밀번호",
|
||||
@@ -2639,28 +2641,9 @@ export const ko: TranslationResources = {
|
||||
stable: "안정",
|
||||
beta: "베타",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "자동 업데이트",
|
||||
options: {
|
||||
automatic: "자동",
|
||||
notify: "알림만",
|
||||
off: "끄기",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "백그라운드에서 업데이트를 확인하고 다운로드합니다",
|
||||
notify: "업데이트를 확인하지만 선택할 때만 다운로드합니다",
|
||||
off: "자동으로 확인하지 않습니다. 확인 버튼을 누를 때만 확인합니다",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "앱 업데이트",
|
||||
readyToInstall: "설치 준비됨: {{version}}",
|
||||
downloadTitle: "데스크톱 업데이트 다운로드",
|
||||
downloadMessage: "이 컴퓨터에 Paseo 업데이트를 다운로드하고 설치합니다",
|
||||
downloadConfirm: "다운로드 및 설치",
|
||||
download: "다운로드",
|
||||
downloadTo: "{{version}} 다운로드",
|
||||
downloading: "다운로드 중...",
|
||||
installTitle: "데스크톱 업데이트 설치",
|
||||
installMessage: "이 컴퓨터의 Paseo를 업데이트합니다",
|
||||
installConfirm: "업데이트 설치",
|
||||
@@ -2931,9 +2914,7 @@ export const ko: TranslationResources = {
|
||||
timeout: "시간 초과",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "기기 페어링",
|
||||
rowTitle: "기기 페어링",
|
||||
rowHint: "QR 코드를 스캔하거나 링크를 복사하여 휴대폰을 이 호스트에 연결하세요",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1568,8 +1568,6 @@ export const ptBR: TranslationResources = {
|
||||
status: {
|
||||
checking: "Verificando atualizações do app...",
|
||||
installing: "Instalando atualização do app...",
|
||||
downloadingVersionProgress: "Baixando {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Baixando atualização do app... {{percent}}%",
|
||||
upToDate: "O app está atualizado.",
|
||||
upToDateWithLastChecked: "Atualizado. Última verificação às {{time}}.",
|
||||
pending: "Avisaremos quando a atualização estiver pronta.",
|
||||
@@ -1578,15 +1576,6 @@ export const ptBR: TranslationResources = {
|
||||
pendingWithVersion: "Atualização encontrada: {{version}}. Baixando...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Atualização encontrada: {{version}}. Baixando... Última verificação às {{time}}.",
|
||||
pendingWithVersionProgress: "Atualização encontrada: {{version}}. Baixando... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Atualização encontrada: {{version}}. Baixando... {{percent}}% Última verificação às {{time}}.",
|
||||
downloadAvailableWithVersion: "Atualização disponível: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Atualização disponível: {{version}}. Última verificação às {{time}}.",
|
||||
downloadAvailable: "Há uma atualização do app disponível.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Há uma atualização do app disponível. Última verificação às {{time}}.",
|
||||
availableWithVersion: "Atualização pronta: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Atualização pronta: {{version}}. Última verificação às {{time}}.",
|
||||
@@ -1599,21 +1588,14 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
installError: "Não foi possível instalar a atualização do app desktop.",
|
||||
callout: {
|
||||
downloadingTitle: "Baixando atualização",
|
||||
installingTitle: "Instalando atualização",
|
||||
failedTitle: "Falha na atualização",
|
||||
availableTitle: "Atualização disponível",
|
||||
genericError: "Algo deu errado.",
|
||||
whatsNew: "Novidades",
|
||||
downloadingAction: "Baixando...",
|
||||
installingAction: "Instalando...",
|
||||
downloadAndRestart: "Baixar",
|
||||
installAndRestart: "Instalar e reiniciar",
|
||||
downloadingVersionDescription: "Baixando {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Baixando atualização... {{percent}}%",
|
||||
installingDescription: "Instalando e reiniciando...",
|
||||
versionAvailable: "{{version}} está disponível para download.",
|
||||
newVersionAvailable: "Uma nova versão está disponível para download.",
|
||||
versionReady: "{{version}} está pronta para instalar.",
|
||||
newVersionReady: "Uma nova versão está pronta para instalar.",
|
||||
restartWarning:
|
||||
@@ -1833,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" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1914,6 +1890,33 @@ export const ptBR: TranslationResources = {
|
||||
hostDisconnected: "Host não está conectado",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Dispositivos",
|
||||
waysToConnect: "Formas de conexão",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Abrir documentação de conectividade",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
|
||||
tailscale: {
|
||||
hint: "Conexão direta pela sua tailnet, digite um endereço",
|
||||
unavailable: "O Tailscale não está em execução neste host",
|
||||
install: "Baixar o Tailscale",
|
||||
waiting: "Aguardando o Tailscale iniciar neste host",
|
||||
alwaysOn: "Sempre ativado, porque este host já aceita conexões do Tailscale",
|
||||
socket: "Desativado, porque este host escuta em um socket local",
|
||||
launch: "Controlado pelo comando que inicia este host",
|
||||
update: "Atualize este host para usar o Tailscale",
|
||||
updateDocs: "Como atualizar",
|
||||
address: "Em um celular com Tailscale, adicione um host com este endereço",
|
||||
statusError: "Não foi possível verificar o Tailscale",
|
||||
turnOnError: "Não foi possível ativar o Tailscale",
|
||||
turnOffError: "Não foi possível desativar o Tailscale",
|
||||
confirmTitle: "Desativar o Tailscale?",
|
||||
confirmMessage:
|
||||
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
|
||||
confirmAction: "Desativar",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Senha de {{host}}",
|
||||
@@ -2664,28 +2667,9 @@ export const ptBR: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Atualizações automáticas",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notificar",
|
||||
off: "Desativado",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Verificar e baixar atualizações em segundo plano",
|
||||
notify: "Verificar atualizações, mas baixar apenas quando você escolher",
|
||||
off: "Nunca verificar automaticamente. Verificar apenas ao clicar em Verificar",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Atualizações do app",
|
||||
readyToInstall: "Pronta para instalar: {{version}}",
|
||||
downloadTitle: "Baixar atualização desktop",
|
||||
downloadMessage: "Isso baixa e instala a atualização do Paseo neste computador",
|
||||
downloadConfirm: "Baixar e instalar",
|
||||
download: "Baixar",
|
||||
downloadTo: "Baixar {{version}}",
|
||||
downloading: "Baixando...",
|
||||
installTitle: "Instalar atualização desktop",
|
||||
installMessage: "Isso atualiza o Paseo neste computador",
|
||||
installConfirm: "Instalar atualização",
|
||||
@@ -2958,9 +2942,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,
|
||||
|
||||
@@ -1562,8 +1562,6 @@ export const ru: TranslationResources = {
|
||||
status: {
|
||||
checking: "Проверка обновлений приложения...",
|
||||
installing: "Установка обновления приложения...",
|
||||
downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Загрузка обновления приложения... {{percent}}%",
|
||||
upToDate: "Установлена последняя версия приложения.",
|
||||
upToDateWithLastChecked:
|
||||
"Установлена последняя версия приложения. Последняя проверка: {{time}}.",
|
||||
@@ -1573,15 +1571,6 @@ export const ru: TranslationResources = {
|
||||
pendingWithVersion: "Найдено обновление: {{version}}. Загрузка...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Найдено обновление: {{version}}. Загрузка... Последняя проверка в {{time}}.",
|
||||
pendingWithVersionProgress: "Найдено обновление: {{version}}. Загрузка... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Найдено обновление: {{version}}. Загрузка... {{percent}}% Последняя проверка в {{time}}.",
|
||||
downloadAvailableWithVersion: "Доступно обновление: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Доступно обновление: {{version}}. Последняя проверка: {{time}}.",
|
||||
downloadAvailable: "Доступно обновление приложения.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Доступно обновление приложения. Последняя проверка: {{time}}.",
|
||||
availableWithVersion: "Обновление готово: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Обновление готово: {{version}}. Последняя проверка: {{time}}.",
|
||||
@@ -1594,21 +1583,14 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
installError: "Не удалось установить обновление настольного приложения.",
|
||||
callout: {
|
||||
downloadingTitle: "Загрузка обновления",
|
||||
installingTitle: "Установка обновления",
|
||||
failedTitle: "Обновление не выполнено",
|
||||
availableTitle: "Доступно обновление",
|
||||
genericError: "Что-то пошло не так.",
|
||||
whatsNew: "Что нового",
|
||||
downloadingAction: "Загрузка...",
|
||||
installingAction: "Установка...",
|
||||
downloadAndRestart: "Скачать",
|
||||
installAndRestart: "Установить и перезапустить",
|
||||
downloadingVersionDescription: "Загрузка {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Загрузка обновления... {{percent}}%",
|
||||
installingDescription: "Установка и перезапуск...",
|
||||
versionAvailable: "Версия {{version}} доступна для загрузки.",
|
||||
newVersionAvailable: "Новая версия доступна для загрузки.",
|
||||
versionReady: "Версия {{version}} готова к установке.",
|
||||
newVersionReady: "Новая версия готова к установке.",
|
||||
restartWarning:
|
||||
@@ -1833,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: "Требует небольшой настройки" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1914,6 +1890,32 @@ export const ru: TranslationResources = {
|
||||
hostDisconnected: "Хост не подключён",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Устройства",
|
||||
waysToConnect: "Способы подключения",
|
||||
docs: "Документация",
|
||||
docsAccessibility: "Открыть документацию по подключению",
|
||||
recommended: "Рекомендуется",
|
||||
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
|
||||
tailscale: {
|
||||
hint: "Прямое подключение через ваш tailnet, по адресу",
|
||||
unavailable: "Tailscale не запущен на этом хосте",
|
||||
install: "Скачать Tailscale",
|
||||
waiting: "Ожидаем запуска Tailscale на этом хосте",
|
||||
alwaysOn: "Всегда включено, так как хост уже принимает подключения Tailscale",
|
||||
socket: "Выключено, так как хост слушает локальный сокет",
|
||||
launch: "Управляется командой, которая запускает этот хост",
|
||||
update: "Обновите этот хост, чтобы использовать Tailscale",
|
||||
updateDocs: "Как обновить",
|
||||
address: "На телефоне с Tailscale добавьте хост с этим адресом",
|
||||
statusError: "Не удалось проверить Tailscale",
|
||||
turnOnError: "Не удалось включить Tailscale",
|
||||
turnOffError: "Не удалось выключить Tailscale",
|
||||
confirmTitle: "Выключить Tailscale?",
|
||||
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
|
||||
confirmAction: "Выключить",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Пароль для {{host}}",
|
||||
@@ -2671,28 +2673,9 @@ export const ru: TranslationResources = {
|
||||
stable: "Стабильный",
|
||||
beta: "Бета",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Автообновления",
|
||||
options: {
|
||||
automatic: "Авто",
|
||||
notify: "Уведомлять",
|
||||
off: "Выкл.",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Проверять и загружать обновления в фоновом режиме",
|
||||
notify: "Проверять обновления, но загружать только по вашему выбору",
|
||||
off: "Не проверять автоматически. Проверять только по нажатию кнопки Проверить",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Обновления приложения",
|
||||
readyToInstall: "Версия {{version}} готова к установке",
|
||||
downloadTitle: "Загрузить обновление настольного приложения",
|
||||
downloadMessage: "Это загрузит и установит обновление Paseo на этом компьютере.",
|
||||
downloadConfirm: "Загрузить и установить",
|
||||
download: "Загрузить",
|
||||
downloadTo: "Загрузить {{version}}",
|
||||
downloading: "Загрузка...",
|
||||
installTitle: "Установить обновление настольного приложения",
|
||||
installMessage: "Это обновит Paseo на этом компьютере.",
|
||||
installConfirm: "Установить обновление",
|
||||
@@ -2966,10 +2949,7 @@ export const ru: TranslationResources = {
|
||||
timeout: "Время ожидания истекло",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Подключение устройств",
|
||||
rowTitle: "Подключить устройство",
|
||||
rowHint:
|
||||
"Отсканируйте QR-код или скопируйте ссылку, чтобы подключить телефон к этому хосту.",
|
||||
},
|
||||
skills: {
|
||||
sectionTitle: "Навыки оркестрации",
|
||||
|
||||
@@ -1528,8 +1528,6 @@ export const zhCN: TranslationResources = {
|
||||
status: {
|
||||
checking: "正在检查 app 更新...",
|
||||
installing: "正在安装 app 更新...",
|
||||
downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%",
|
||||
downloadingProgress: "正在下载 app 更新... {{percent}}%",
|
||||
upToDate: "App 已是最新版本。",
|
||||
upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。",
|
||||
pending: "更新准备好后会通知你。",
|
||||
@@ -1537,14 +1535,6 @@ export const zhCN: TranslationResources = {
|
||||
pendingWithVersion: "发现更新:{{version}}。正在下载...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"发现更新:{{version}}。正在下载... 上次检查时间:{{time}}。",
|
||||
pendingWithVersionProgress: "发现更新:{{version}}。正在下载... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"发现更新:{{version}}。正在下载... {{percent}}% 上次检查时间:{{time}}。",
|
||||
downloadAvailableWithVersion: "有可用更新:{{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"有可用更新:{{version}}。上次检查时间:{{time}}。",
|
||||
downloadAvailable: "有 app 更新可用。",
|
||||
downloadAvailableWithLastChecked: "有 app 更新可用。上次检查时间:{{time}}。",
|
||||
availableWithVersion: "更新已就绪:{{version}}",
|
||||
availableWithVersionAndLastChecked: "更新已就绪:{{version}}。上次检查时间:{{time}}。",
|
||||
available: "有 app 更新可安装。",
|
||||
@@ -1555,21 +1545,14 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
installError: "无法安装 desktop app 更新。",
|
||||
callout: {
|
||||
downloadingTitle: "正在下载更新",
|
||||
installingTitle: "正在安装更新",
|
||||
failedTitle: "更新失败",
|
||||
availableTitle: "有可用更新",
|
||||
genericError: "出了点问题。",
|
||||
whatsNew: "更新内容",
|
||||
downloadingAction: "正在下载...",
|
||||
installingAction: "正在安装...",
|
||||
downloadAndRestart: "下载",
|
||||
installAndRestart: "安装并重启",
|
||||
downloadingVersionDescription: "正在下载 {{version}}... {{percent}}%",
|
||||
downloadingDescription: "正在下载更新... {{percent}}%",
|
||||
installingDescription: "正在安装并重启...",
|
||||
versionAvailable: "{{version}} 可供下载。",
|
||||
newVersionAvailable: "有新版本可供下载。",
|
||||
versionReady: "{{version}} 已准备好安装。",
|
||||
newVersionReady: "新版本已准备好安装。",
|
||||
restartWarning: "升级 app 会停止正在运行的 agents,并关闭 terminal 会话。",
|
||||
@@ -1781,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: "需要一些设置" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1862,6 +1839,32 @@ export const zhCN: TranslationResources = {
|
||||
hostDisconnected: "Host 未连接",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "设备",
|
||||
waysToConnect: "连接方式",
|
||||
docs: "文档",
|
||||
docsAccessibility: "打开连接文档",
|
||||
recommended: "推荐",
|
||||
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
|
||||
tailscale: {
|
||||
hint: "通过你的 tailnet 直连,输入地址即可",
|
||||
unavailable: "此主机未运行 Tailscale",
|
||||
install: "获取 Tailscale",
|
||||
waiting: "正在等待此主机上的 Tailscale 启动",
|
||||
alwaysOn: "始终开启,因为此主机已接受 Tailscale 连接",
|
||||
socket: "已关闭,因为此主机监听的是本地套接字",
|
||||
launch: "由启动此主机的命令控制",
|
||||
update: "更新此主机以使用 Tailscale",
|
||||
updateDocs: "如何更新",
|
||||
address: "在已连接 Tailscale 的手机上,用此地址添加主机",
|
||||
statusError: "无法检查 Tailscale",
|
||||
turnOnError: "无法开启 Tailscale",
|
||||
turnOffError: "无法关闭 Tailscale",
|
||||
confirmTitle: "关闭 Tailscale?",
|
||||
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
|
||||
confirmAction: "关闭",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} 的密码",
|
||||
@@ -2597,28 +2600,9 @@ export const zhCN: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "自动更新",
|
||||
options: {
|
||||
automatic: "自动",
|
||||
notify: "仅通知",
|
||||
off: "关闭",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "在后台检查并下载更新",
|
||||
notify: "检查更新,但仅在你选择时才下载",
|
||||
off: "从不自动检查,仅在点击检查时检查更新",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "应用更新",
|
||||
readyToInstall: "可安装:{{version}}",
|
||||
downloadTitle: "下载桌面版更新",
|
||||
downloadMessage: "这会在此电脑上下载并安装 Paseo 更新",
|
||||
downloadConfirm: "下载并安装",
|
||||
download: "下载",
|
||||
downloadTo: "下载 {{version}}",
|
||||
downloading: "正在下载...",
|
||||
installTitle: "安装桌面版更新",
|
||||
installMessage: "这会更新此电脑上的 Paseo",
|
||||
installConfirm: "安装更新",
|
||||
@@ -2886,9 +2870,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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -98,7 +98,8 @@ describe("plugin timeline projection", () => {
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "inline-thinking/thought-1/0",
|
||||
source: { kind: "thought", id: "thought-1" },
|
||||
sourceId: "thought-1",
|
||||
sourceKind: "thought",
|
||||
data: { text: "First", phase: "streaming" },
|
||||
},
|
||||
]);
|
||||
@@ -191,54 +192,4 @@ describe("plugin timeline projection", () => {
|
||||
]);
|
||||
expect(filtered).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps the replaced reply on every card it was split into", () => {
|
||||
const source: StreamItem = {
|
||||
kind: "assistant_message",
|
||||
id: "assistant-1",
|
||||
messageId: "provider-msg-1",
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
turnId: "turn-1",
|
||||
text: 'Summary\n\n```ui\nCard("Hi", [])\n```',
|
||||
timestamp: new Date("2026-01-01T00:00:02.000Z"),
|
||||
};
|
||||
const split: TimelineItemTransform = ({ sourceId }) => [
|
||||
{
|
||||
type: "plugin",
|
||||
id: `${sourceId}/text`,
|
||||
pluginId: "genui",
|
||||
kind: "genui-text",
|
||||
version: 1,
|
||||
data: { part: "text" },
|
||||
},
|
||||
{
|
||||
type: "plugin",
|
||||
id: `${sourceId}/card`,
|
||||
pluginId: "genui",
|
||||
kind: "genui-block",
|
||||
version: 1,
|
||||
data: { part: "card" },
|
||||
},
|
||||
];
|
||||
const projected = projectPluginTimelineItems([source], split);
|
||||
|
||||
expect(projected).toMatchObject([
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/text",
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
turnId: "turn-1",
|
||||
},
|
||||
{
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/card",
|
||||
timelineCursor: { epoch: "e1", seq: 7 },
|
||||
turnId: "turn-1",
|
||||
},
|
||||
]);
|
||||
expect(projected.map((item) => item.kind === "plugin" && item.source)).toEqual([
|
||||
source,
|
||||
source,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -95,7 +95,8 @@ function transformSourceItem(
|
||||
const projected: PluginTimelineStreamItem = {
|
||||
kind: "plugin",
|
||||
id: `${pluginItem.pluginId}/${pluginItem.id}`,
|
||||
source: item,
|
||||
sourceId: item.id,
|
||||
sourceKind: item.kind,
|
||||
timestamp: item.timestamp,
|
||||
pluginId: pluginItem.pluginId,
|
||||
pluginItemId: pluginItem.id,
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -83,7 +83,6 @@ import { DesktopNotificationsSection } from "@/desktop/components/desktop-notifi
|
||||
import { BrowserDataSection } from "@/desktop/browser/settings/browser-data-section";
|
||||
import { IntegrationsSection } from "@/desktop/components/integrations-section";
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopAppUpdater } from "@/desktop/updates/use-desktop-app-updater";
|
||||
import { formatVersionWithPrefix } from "@/desktop/updates/desktop-updates";
|
||||
import { resolveAppVersion } from "@/utils/app-version";
|
||||
@@ -101,7 +100,7 @@ import {
|
||||
} from "@/i18n/locales";
|
||||
import {
|
||||
HostConnectionsPage,
|
||||
HostPairDevicePage,
|
||||
HostDevicesPage,
|
||||
HostAgentsPage,
|
||||
HostSettingsPage,
|
||||
HostProvidersPage,
|
||||
@@ -248,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 },
|
||||
@@ -268,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":
|
||||
@@ -610,92 +609,25 @@ function HostVersionRow({
|
||||
|
||||
function getUpdateButtonLabel(
|
||||
t: TFunction,
|
||||
input: {
|
||||
isInstalling: boolean;
|
||||
isDownloading: boolean;
|
||||
isActionable: boolean;
|
||||
readyToInstall: boolean;
|
||||
latestVersion: string | null | undefined;
|
||||
},
|
||||
isInstalling: boolean,
|
||||
latestVersion: string | null | undefined,
|
||||
): string {
|
||||
if (input.isInstalling) {
|
||||
return input.isDownloading
|
||||
? t("settings.about.updates.downloading")
|
||||
: t("settings.about.updates.installing");
|
||||
}
|
||||
if (input.isActionable && !input.readyToInstall) {
|
||||
if (input.latestVersion) {
|
||||
return t("settings.about.updates.downloadTo", {
|
||||
version: formatVersionWithPrefix(input.latestVersion),
|
||||
});
|
||||
}
|
||||
return t("settings.about.updates.download");
|
||||
}
|
||||
if (input.latestVersion) {
|
||||
if (isInstalling) return t("settings.about.updates.installing");
|
||||
if (latestVersion) {
|
||||
return t("settings.about.updates.updateTo", {
|
||||
version: formatVersionWithPrefix(input.latestVersion),
|
||||
version: formatVersionWithPrefix(latestVersion),
|
||||
});
|
||||
}
|
||||
return t("settings.about.updates.update");
|
||||
}
|
||||
|
||||
function getUpdateModeDescription(t: TFunction, mode: DesktopUpdateMode): string {
|
||||
if (mode === "off") return t("settings.about.autoUpdate.descriptions.off");
|
||||
if (mode === "notify") return t("settings.about.autoUpdate.descriptions.notify");
|
||||
return t("settings.about.autoUpdate.descriptions.automatic");
|
||||
}
|
||||
|
||||
function getUpdateConfirmDialogCopy(t: TFunction, isUpdateReady: boolean) {
|
||||
if (isUpdateReady) {
|
||||
return {
|
||||
title: t("settings.about.updates.installTitle"),
|
||||
message: t("settings.about.updates.installMessage"),
|
||||
confirmLabel: t("settings.about.updates.installConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: t("settings.about.updates.downloadTitle"),
|
||||
message: t("settings.about.updates.downloadMessage"),
|
||||
confirmLabel: t("settings.about.updates.downloadConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
};
|
||||
}
|
||||
|
||||
function DesktopUpdateProgressBar({ percent }: { percent: number }) {
|
||||
const accessibilityValue = useMemo(() => ({ min: 0, max: 100, now: percent }), [percent]);
|
||||
const fillStyle = useMemo(
|
||||
() => [styles.aboutUpdateProgressFill, { width: `${percent}%` as const }],
|
||||
[percent],
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
style={styles.aboutUpdateProgressTrack}
|
||||
accessibilityRole="progressbar"
|
||||
accessibilityValue={accessibilityValue}
|
||||
testID="settings-about-update-progress"
|
||||
>
|
||||
<View style={fillStyle} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopAppUpdateRow() {
|
||||
const { t } = useTranslation();
|
||||
const { settings, updateSettings } = useSettings();
|
||||
const {
|
||||
settings: desktopSettings,
|
||||
isLoading: isLoadingDesktopSettings,
|
||||
updateSettings: updateDesktopSettings,
|
||||
} = useDesktopSettings();
|
||||
const updateMode = desktopSettings.updates.mode;
|
||||
const {
|
||||
isDesktopApp,
|
||||
status,
|
||||
statusText,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
isChecking,
|
||||
isInstalling,
|
||||
@@ -705,12 +637,12 @@ function DesktopAppUpdateRow() {
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!isDesktopApp || isLoadingDesktopSettings || updateMode === "off") {
|
||||
if (!isDesktopApp) {
|
||||
return undefined;
|
||||
}
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
return undefined;
|
||||
}, [checkForUpdates, isDesktopApp, isLoadingDesktopSettings, updateMode]),
|
||||
}, [checkForUpdates, isDesktopApp]),
|
||||
);
|
||||
|
||||
const handleCheckForUpdates = useCallback(() => {
|
||||
@@ -734,36 +666,17 @@ function DesktopAppUpdateRow() {
|
||||
[t],
|
||||
);
|
||||
|
||||
const handleUpdateModeChange = useCallback(
|
||||
(mode: DesktopUpdateMode) => {
|
||||
void updateDesktopSettings({ updates: { mode } });
|
||||
},
|
||||
[updateDesktopSettings],
|
||||
);
|
||||
const updateModeOptions = useMemo(
|
||||
() => [
|
||||
{ value: "automatic" as const, label: t("settings.about.autoUpdate.options.automatic") },
|
||||
{ value: "notify" as const, label: t("settings.about.autoUpdate.options.notify") },
|
||||
{ value: "off" as const, label: t("settings.about.autoUpdate.options.off") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const isUpdateReady = availableUpdate?.readyToInstall === true;
|
||||
const isUpdateActionable = status === "available" && availableUpdate?.hasUpdate === true;
|
||||
const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null;
|
||||
const actionableVersion = isUpdateActionable ? availableUpdate?.latestVersion : null;
|
||||
const downloadPercent =
|
||||
(isInstalling || status === "pending") && downloadProgress
|
||||
? Math.max(0, Math.min(100, Math.round(downloadProgress.percent)))
|
||||
: null;
|
||||
|
||||
const handleInstallUpdate = useCallback(() => {
|
||||
if (!isDesktopApp) {
|
||||
return;
|
||||
}
|
||||
|
||||
void confirmDialog(getUpdateConfirmDialogCopy(t, isUpdateReady))
|
||||
void confirmDialog({
|
||||
title: t("settings.about.updates.installTitle"),
|
||||
message: t("settings.about.updates.installMessage"),
|
||||
confirmLabel: t("settings.about.updates.installConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
})
|
||||
.then((confirmed) => {
|
||||
if (!confirmed) {
|
||||
return;
|
||||
@@ -778,7 +691,10 @@ function DesktopAppUpdateRow() {
|
||||
t("settings.about.updates.alertMessage"),
|
||||
);
|
||||
});
|
||||
}, [installUpdate, isDesktopApp, isUpdateReady, t]);
|
||||
}, [installUpdate, isDesktopApp, t]);
|
||||
|
||||
const isUpdateReady = availableUpdate?.readyToInstall === true;
|
||||
const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null;
|
||||
|
||||
if (!isDesktopApp) {
|
||||
return null;
|
||||
@@ -799,18 +715,6 @@ function DesktopAppUpdateRow() {
|
||||
options={releaseChannelOptions}
|
||||
/>
|
||||
</View>
|
||||
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{t("settings.about.autoUpdate.label")}</Text>
|
||||
<Text style={settingsStyles.rowHint}>{getUpdateModeDescription(t, updateMode)}</Text>
|
||||
</View>
|
||||
<SegmentedControl
|
||||
value={updateMode}
|
||||
onValueChange={handleUpdateModeChange}
|
||||
options={updateModeOptions}
|
||||
testID="settings-about-update-mode"
|
||||
/>
|
||||
</View>
|
||||
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{t("settings.about.updates.label")}</Text>
|
||||
@@ -822,7 +726,6 @@ function DesktopAppUpdateRow() {
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
{downloadPercent !== null ? <DesktopUpdateProgressBar percent={downloadPercent} /> : null}
|
||||
{errorMessage ? <Text style={styles.aboutErrorText}>{errorMessage}</Text> : null}
|
||||
</View>
|
||||
<View style={styles.aboutUpdateActions}>
|
||||
@@ -836,15 +739,9 @@ function DesktopAppUpdateRow() {
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={handleInstallUpdate}
|
||||
disabled={isChecking || isInstalling || !isUpdateActionable}
|
||||
disabled={isChecking || isInstalling || !isUpdateReady}
|
||||
>
|
||||
{getUpdateButtonLabel(t, {
|
||||
isInstalling,
|
||||
isDownloading: isInstalling && downloadProgress != null,
|
||||
isActionable: isUpdateActionable,
|
||||
readyToInstall: isUpdateReady,
|
||||
latestVersion: actionableVersion,
|
||||
})}
|
||||
{getUpdateButtonLabel(t, isInstalling, readyUpdateVersion)}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
@@ -1609,19 +1506,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
aboutUpdateProgressTrack: {
|
||||
marginTop: theme.spacing[2],
|
||||
height: 4,
|
||||
maxWidth: 260,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.surface3,
|
||||
overflow: "hidden",
|
||||
},
|
||||
aboutUpdateProgressFill: {
|
||||
height: "100%",
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
placeholder: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -247,37 +247,3 @@ it("times a heartbeat that ends with tools and no assistant text", () => {
|
||||
});
|
||||
assert.equal(timing.byItemId.get("last")?.durationMs, 5000);
|
||||
});
|
||||
|
||||
it("times a reply that a plugin split into cards", () => {
|
||||
const userAt = new Date("2026-05-15T00:00:00.000Z");
|
||||
const replyAt = new Date("2026-05-15T00:00:06.000Z");
|
||||
const reply: StreamItem = {
|
||||
kind: "assistant_message",
|
||||
id: "a1",
|
||||
text: "Intro",
|
||||
timestamp: replyAt,
|
||||
};
|
||||
const card = (part: string): StreamItem => ({
|
||||
kind: "plugin",
|
||||
id: `genui/a1/${part}`,
|
||||
source: reply,
|
||||
timestamp: replyAt,
|
||||
pluginId: "genui",
|
||||
pluginItemId: `a1/${part}`,
|
||||
itemKind: `genui-${part}`,
|
||||
version: 1,
|
||||
data: {},
|
||||
});
|
||||
|
||||
const timing = deriveStreamTurnTiming({
|
||||
isTurnActive: false,
|
||||
activeTurnStartedAt: null,
|
||||
tail: [user("u1", userAt), card("text"), card("card")],
|
||||
head: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(timing.byItemId.get("genui/a1/card"), {
|
||||
completedAt: replyAt,
|
||||
durationMs: 6000,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import { startsNewTurn, isTurnTrigger } from "@/agent-stream/turn-membership";
|
||||
|
||||
export interface TurnTiming {
|
||||
@@ -70,7 +70,7 @@ function walkTurns(
|
||||
assistantIds = [];
|
||||
}
|
||||
lastItemAt = item.timestamp;
|
||||
if (getAssistantReply(item)) {
|
||||
if (item.kind === "assistant_message") {
|
||||
assistantIds.push(item.id);
|
||||
}
|
||||
previousItem = item;
|
||||
|
||||
@@ -783,7 +783,7 @@ export type AgentToolCallItem = ToolCallItem & {
|
||||
|
||||
/** Find and scrolling address a plugin row by the source it replaces. */
|
||||
export function getStreamItemMessageId(item: StreamItem): string {
|
||||
if (item.kind === "plugin") return item.source?.id ?? item.id;
|
||||
if (item.kind === "plugin") return item.sourceId ?? item.id;
|
||||
return item.id;
|
||||
}
|
||||
|
||||
@@ -791,15 +791,6 @@ export function isAgentToolCallItem(item: StreamItem): item is AgentToolCallItem
|
||||
return item.kind === "tool_call" && item.payload.source === "agent";
|
||||
}
|
||||
|
||||
/** The assistant reply a row shows: the row itself, or the reply a timeline plugin replaced. */
|
||||
export function getAssistantReply(
|
||||
item: StreamItem | null | undefined,
|
||||
): AssistantMessageItem | null {
|
||||
if (item?.kind === "assistant_message") return item;
|
||||
if (item?.kind === "plugin" && item.source?.kind === "assistant_message") return item.source;
|
||||
return null;
|
||||
}
|
||||
|
||||
type NotificationLevel = "info" | "warning" | "error";
|
||||
|
||||
export interface NotificationItem {
|
||||
@@ -827,12 +818,10 @@ export interface CompactionItem {
|
||||
export interface PluginTimelineStreamItem {
|
||||
kind: "plugin";
|
||||
id: string;
|
||||
/**
|
||||
* The row a timeline transformer replaced; set only by projection. Turn folding, timing, and the
|
||||
* turn footer read the replaced row through it, so a transformed reply keeps its copy, fork,
|
||||
* duration, and stats.
|
||||
*/
|
||||
source?: StreamItem;
|
||||
/** The id of the stream item a timeline transformer replaced; set only by projection. */
|
||||
sourceId?: string;
|
||||
/** The original row kind, retained by projection for turn folding. */
|
||||
sourceKind?: StreamItem["kind"];
|
||||
timelineCursor?: TimelinePosition;
|
||||
turnId?: string;
|
||||
timestamp: Date;
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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",
|
||||
};
|
||||
|
||||
@@ -6,7 +6,11 @@ import {
|
||||
isSameDaemonInstance,
|
||||
DaemonInstanceError,
|
||||
} from "@getpaseo/server/daemon-control";
|
||||
import { readPersistedConfig, resolveConfigFromPersisted } from "@getpaseo/server/configuration";
|
||||
import {
|
||||
readPersistedConfig,
|
||||
resolveConfigFromPersisted,
|
||||
getMainListenAddress,
|
||||
} from "@getpaseo/server/configuration";
|
||||
import { connectToDaemon, buildDaemonConnectionCommandError } from "../../utils/client.js";
|
||||
import { withOutput, toCommandError, type CommandOptions } from "../../output/index.js";
|
||||
import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js";
|
||||
@@ -103,6 +107,8 @@ async function probeDaemonStatus(
|
||||
daemonNode: status.nodePath,
|
||||
providers: status.providers,
|
||||
relay: status.relay,
|
||||
tailscale: status.tailscale,
|
||||
extraListeners: status.extraListeners,
|
||||
...(status.terminalsUnavailable ? { terminals: status.terminalsUnavailable } : {}),
|
||||
};
|
||||
}
|
||||
@@ -127,7 +133,7 @@ function localStatus(home: string, instance: Awaited<ReturnType<typeof readDaemo
|
||||
listen: instance?.listen ?? null,
|
||||
serverId: instance?.serverId ?? undefined,
|
||||
hostname: instance?.hostname ?? null,
|
||||
configuredListen: config.listen,
|
||||
configuredListen: getMainListenAddress(config.listen),
|
||||
localDaemon,
|
||||
desktopManaged: instance?.desktopManaged === true,
|
||||
logPath: daemonLogPath(home),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -23,7 +23,7 @@ const SETTINGS_DESTINATIONS = [
|
||||
"Overview",
|
||||
"Projects",
|
||||
"Connections",
|
||||
"Pair device",
|
||||
"Devices",
|
||||
"Agents",
|
||||
"Metadata",
|
||||
"Workspaces",
|
||||
|
||||
@@ -55,12 +55,9 @@ export async function loadRealDaemonState(): Promise<RealDaemonState> {
|
||||
|
||||
export interface DesktopRuntimeConfig {
|
||||
serverId: string;
|
||||
updateMode?: "automatic" | "notify" | "off";
|
||||
updateAvailable?: boolean;
|
||||
latestVersion?: string;
|
||||
updateReadyToInstall?: boolean;
|
||||
updateDownloading?: boolean;
|
||||
downloadProgressSteps?: number[];
|
||||
manualUpdateBypassesRollout?: boolean;
|
||||
slowInstall?: boolean;
|
||||
/** Initial PID reported by desktop_daemon_status. Defaults to null. */
|
||||
@@ -113,7 +110,6 @@ declare global {
|
||||
interface Window {
|
||||
__capturedDialogCall: ConfirmDialogCall | undefined;
|
||||
__capturedDialogOpenCalls: Array<Record<string, unknown> | undefined>;
|
||||
__capturedUpdateChecks?: Array<{ intent: unknown; releaseChannel: unknown }>;
|
||||
__recordDesktopEditorOpen?: (input: DesktopEditorOpenRecord) => Promise<void>;
|
||||
__desktopDaemonStartRequested?: boolean;
|
||||
}
|
||||
@@ -144,22 +140,11 @@ export async function installDesktopRuntime(
|
||||
await page.addInitScript((cfg) => {
|
||||
// Mutable state shared across IPC calls within this page
|
||||
let manageDaemon = cfg.manageBuiltInDaemon ?? false;
|
||||
let updateMode = cfg.updateMode ?? "automatic";
|
||||
let daemonRunning = true;
|
||||
let currentPid: number | null = cfg.daemonPid ?? null;
|
||||
let ownedByDesktop = cfg.ownedByDesktop ?? false;
|
||||
let manualUpdateAdmitted = false;
|
||||
const eventListeners = new Map<string, Set<(payload: unknown) => void>>();
|
||||
window.__desktopDaemonStartRequested = false;
|
||||
window.__capturedUpdateChecks = [];
|
||||
|
||||
function emitDesktopEvent(event: string, payload: unknown) {
|
||||
const listeners = eventListeners.get(event);
|
||||
if (!listeners) return;
|
||||
for (const listener of listeners) {
|
||||
listener(payload);
|
||||
}
|
||||
}
|
||||
|
||||
function buildDaemonStatus() {
|
||||
return {
|
||||
@@ -197,15 +182,10 @@ export async function installDesktopRuntime(
|
||||
}
|
||||
}
|
||||
|
||||
function buildAppUpdateCheckResult(
|
||||
hasUpdate: boolean,
|
||||
readyToInstall: boolean,
|
||||
downloading = hasUpdate && !readyToInstall,
|
||||
) {
|
||||
function buildAppUpdateCheckResult(hasUpdate: boolean, readyToInstall: boolean) {
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading,
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: hasUpdate ? (cfg.latestVersion ?? "1.2.3") : null,
|
||||
body: null,
|
||||
@@ -214,78 +194,19 @@ export async function installDesktopRuntime(
|
||||
}
|
||||
|
||||
function checkAppUpdate(intent: unknown) {
|
||||
if (intent === "automatic" && updateMode === "off") {
|
||||
return buildAppUpdateCheckResult(false, false, false);
|
||||
}
|
||||
if (!cfg.manualUpdateBypassesRollout) {
|
||||
const hasUpdate = cfg.updateAvailable === true;
|
||||
const readyToInstall =
|
||||
hasUpdate && (cfg.updateReadyToInstall ?? updateMode === "automatic");
|
||||
const downloading =
|
||||
cfg.updateDownloading ?? (hasUpdate && !readyToInstall && updateMode === "automatic");
|
||||
return buildAppUpdateCheckResult(hasUpdate, readyToInstall, downloading);
|
||||
return buildAppUpdateCheckResult(
|
||||
cfg.updateAvailable === true,
|
||||
cfg.updateAvailable === true && (cfg.updateReadyToInstall ?? true),
|
||||
);
|
||||
}
|
||||
|
||||
if (intent === "manual") {
|
||||
manualUpdateAdmitted = true;
|
||||
return buildAppUpdateCheckResult(true, false, updateMode === "automatic");
|
||||
return buildAppUpdateCheckResult(true, false);
|
||||
}
|
||||
|
||||
return buildAppUpdateCheckResult(manualUpdateAdmitted, manualUpdateAdmitted, false);
|
||||
}
|
||||
|
||||
async function installAppUpdate() {
|
||||
if (cfg.downloadProgressSteps?.length) {
|
||||
for (const percent of cfg.downloadProgressSteps) {
|
||||
emitDesktopEvent("app-update-download-progress", {
|
||||
version: cfg.latestVersion ?? "1.2.3",
|
||||
percent,
|
||||
transferred: percent * 1_000_000,
|
||||
total: 100_000_000,
|
||||
bytesPerSecond: 5_000_000,
|
||||
});
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 600));
|
||||
}
|
||||
}
|
||||
if (cfg.slowInstall) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 3000));
|
||||
}
|
||||
emitDesktopEvent("app-update-download-progress", null);
|
||||
return {
|
||||
installed: true,
|
||||
version: cfg.latestVersion ?? "1.2.3",
|
||||
message: "App update installed. Restart required.",
|
||||
};
|
||||
}
|
||||
|
||||
function buildDesktopSettings() {
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
updates: { mode: updateMode },
|
||||
daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true },
|
||||
};
|
||||
}
|
||||
|
||||
function patchDesktopSettings(args?: Record<string, unknown>) {
|
||||
const updates = args?.updates;
|
||||
if (
|
||||
updates !== null &&
|
||||
typeof updates === "object" &&
|
||||
"mode" in updates &&
|
||||
(updates.mode === "automatic" || updates.mode === "notify" || updates.mode === "off")
|
||||
) {
|
||||
updateMode = updates.mode;
|
||||
}
|
||||
const daemon = args?.daemon;
|
||||
if (
|
||||
daemon !== null &&
|
||||
typeof daemon === "object" &&
|
||||
"manageBuiltInDaemon" in daemon &&
|
||||
typeof daemon.manageBuiltInDaemon === "boolean"
|
||||
) {
|
||||
manageDaemon = daemon.manageBuiltInDaemon;
|
||||
}
|
||||
return buildDesktopSettings();
|
||||
return buildAppUpdateCheckResult(manualUpdateAdmitted, manualUpdateAdmitted);
|
||||
}
|
||||
|
||||
const desktopBridge: {
|
||||
@@ -296,9 +217,7 @@ export async function installDesktopRuntime(
|
||||
open: (options?: Record<string, unknown>) => Promise<string | string[] | null>;
|
||||
};
|
||||
getPendingOpenProject: () => Promise<string | null>;
|
||||
events: {
|
||||
on: (event: string, handler: (payload: unknown) => void) => Promise<() => void>;
|
||||
};
|
||||
events: { on: () => Promise<() => void> };
|
||||
editor?: {
|
||||
listTargets: () => Promise<DesktopEditorTargetConfig[]>;
|
||||
openTarget: (input: DesktopEditorOpenRecord) => Promise<void>;
|
||||
@@ -307,15 +226,18 @@ export async function installDesktopRuntime(
|
||||
platform: "darwin",
|
||||
invoke: async (command: string, args?: Record<string, unknown>) => {
|
||||
if (command === "check_app_update") {
|
||||
window.__capturedUpdateChecks?.push({
|
||||
intent: args?.intent,
|
||||
releaseChannel: args?.releaseChannel,
|
||||
});
|
||||
return checkAppUpdate(args?.intent);
|
||||
}
|
||||
|
||||
if (command === "install_app_update") {
|
||||
return installAppUpdate();
|
||||
if (cfg.slowInstall) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 3000));
|
||||
}
|
||||
return {
|
||||
installed: true,
|
||||
version: cfg.latestVersion ?? "1.2.3",
|
||||
message: "App update installed. Restart required.",
|
||||
};
|
||||
}
|
||||
|
||||
if (command === "desktop_daemon_status") {
|
||||
@@ -328,11 +250,26 @@ export async function installDesktopRuntime(
|
||||
|
||||
if (command === "get_desktop_settings") {
|
||||
await waitForDesktopSettingsResponse();
|
||||
return buildDesktopSettings();
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true },
|
||||
};
|
||||
}
|
||||
|
||||
if (command === "patch_desktop_settings") {
|
||||
return patchDesktopSettings(args);
|
||||
const daemon = args?.daemon;
|
||||
if (
|
||||
daemon !== null &&
|
||||
typeof daemon === "object" &&
|
||||
"manageBuiltInDaemon" in daemon &&
|
||||
typeof daemon.manageBuiltInDaemon === "boolean"
|
||||
) {
|
||||
manageDaemon = daemon.manageBuiltInDaemon;
|
||||
}
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true },
|
||||
};
|
||||
}
|
||||
|
||||
if (command === "stop_desktop_daemon") {
|
||||
@@ -362,19 +299,7 @@ export async function installDesktopRuntime(
|
||||
},
|
||||
},
|
||||
getPendingOpenProject: async () => null,
|
||||
events: {
|
||||
on: async (event: string, handler: (payload: unknown) => void) => {
|
||||
let listeners = eventListeners.get(event);
|
||||
if (!listeners) {
|
||||
listeners = new Set();
|
||||
eventListeners.set(event, listeners);
|
||||
}
|
||||
listeners.add(handler);
|
||||
return () => {
|
||||
listeners?.delete(handler);
|
||||
};
|
||||
},
|
||||
},
|
||||
events: { on: async () => () => undefined },
|
||||
};
|
||||
|
||||
if (cfg.editorTargets) {
|
||||
|
||||
@@ -91,74 +91,6 @@ test.describe("Desktop updates", () => {
|
||||
await expectPendingUpdateCheckResult(page, "1.2.3");
|
||||
await expectReadyUpdateCheckResult(page, "1.2.3");
|
||||
});
|
||||
|
||||
test("off mode skips automatic update checks until Check is clicked", async ({ page }) => {
|
||||
await installDesktopRuntime(page, {
|
||||
serverId: getServerId(),
|
||||
updateMode: "off",
|
||||
updateAvailable: true,
|
||||
latestVersion: "1.2.3",
|
||||
});
|
||||
await gotoAppShell(page);
|
||||
await openDesktopAboutSettings(page);
|
||||
|
||||
await expect(
|
||||
page.getByText("Never check automatically. Only check when you click Check"),
|
||||
).toBeVisible();
|
||||
await expect(page.getByTestId("update-callout")).toHaveCount(0);
|
||||
const automaticChecks = await page.evaluate(() => window.__capturedUpdateChecks ?? []);
|
||||
expect(automaticChecks).toEqual([]);
|
||||
|
||||
await clickCheckForUpdates(page);
|
||||
await expect(page.getByText(/Update available: v1\.2\.3/)).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Download v1.2.3" })).toBeEnabled();
|
||||
});
|
||||
|
||||
test("notify mode shows Download and live download progress", async ({ page }) => {
|
||||
await installDesktopRuntime(page, {
|
||||
serverId: getServerId(),
|
||||
updateMode: "notify",
|
||||
updateAvailable: true,
|
||||
latestVersion: "1.2.3",
|
||||
downloadProgressSteps: [42, 78],
|
||||
slowInstall: true,
|
||||
});
|
||||
await gotoAppShell(page);
|
||||
|
||||
const callout = page.getByTestId("update-callout");
|
||||
await expect(callout).toBeVisible({ timeout: 15_000 });
|
||||
await expect(callout).toContainText("v1.2.3 is available to download.");
|
||||
await page.getByRole("button", { name: "Download", exact: true }).click();
|
||||
await expect(callout).toContainText("Downloading v1.2.3... 42%");
|
||||
await expect(callout.getByRole("progressbar")).toBeVisible();
|
||||
});
|
||||
|
||||
test("starting download in About updates the sidebar callout and disables its action", async ({
|
||||
page,
|
||||
}) => {
|
||||
await installDesktopRuntime(page, {
|
||||
serverId: getServerId(),
|
||||
updateMode: "notify",
|
||||
updateAvailable: true,
|
||||
latestVersion: "1.2.3",
|
||||
downloadProgressSteps: [55],
|
||||
slowInstall: true,
|
||||
confirmShouldAccept: true,
|
||||
});
|
||||
await gotoAppShell(page);
|
||||
await expect(page.getByTestId("update-callout")).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
await openDesktopAboutSettings(page);
|
||||
await page.getByRole("button", { name: "Download v1.2.3" }).click();
|
||||
await expect(
|
||||
page.getByTestId("settings-detail-scroll-body").getByText("Downloading v1.2.3... 55%"),
|
||||
).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Back" }).click();
|
||||
const callout = page.getByTestId("update-callout");
|
||||
await expect(callout).toContainText("Downloading v1.2.3... 55%");
|
||||
await expect(callout.getByRole("button", { name: "Downloading..." })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Desktop daemon management", () => {
|
||||
|
||||
@@ -14,22 +14,13 @@ import {
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
paseoHome: "",
|
||||
settingsError: null as Error | null,
|
||||
settings: {
|
||||
releaseChannel: "stable" as "stable" | "beta",
|
||||
updates: {
|
||||
mode: "automatic" as "automatic" | "notify" | "off",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
releaseChannel: "stable",
|
||||
daemon: {
|
||||
manageBuiltInDaemon: true,
|
||||
keepRunningAfterQuit: true,
|
||||
},
|
||||
},
|
||||
checkForAppUpdate: vi.fn(),
|
||||
downloadAndInstallUpdate: vi.fn(),
|
||||
runExternalCliJsonCommand: vi.fn(),
|
||||
runExternalCliTextCommand: vi.fn(),
|
||||
createNodeEntrypointInvocation: vi.fn(() => ({
|
||||
@@ -50,8 +41,6 @@ vi.mock("electron", () => ({
|
||||
getVersion: vi.fn(() => "1.2.3"),
|
||||
isPackaged: true,
|
||||
},
|
||||
autoUpdater: undefined,
|
||||
BrowserWindow: { getAllWindows: vi.fn(() => []) },
|
||||
ipcMain: { handle: vi.fn() },
|
||||
powerMonitor: { getSystemIdleTime: vi.fn(() => 0) },
|
||||
}));
|
||||
@@ -76,12 +65,7 @@ vi.mock("@getpaseo/server/daemon-control", async (importOriginal) => ({
|
||||
|
||||
vi.mock("../settings/desktop-settings-electron.js", () => ({
|
||||
getDesktopSettingsStore: () => ({
|
||||
get: async () => {
|
||||
if (mocks.settingsError) {
|
||||
throw mocks.settingsError;
|
||||
}
|
||||
return mocks.settings;
|
||||
},
|
||||
get: async () => mocks.settings,
|
||||
patch: vi.fn(),
|
||||
migrateLegacyRendererSettings: vi.fn(),
|
||||
}),
|
||||
@@ -95,12 +79,6 @@ vi.mock("./runtime-paths.js", () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../features/auto-updater.js", async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
checkForAppUpdate: mocks.checkForAppUpdate,
|
||||
downloadAndInstallUpdate: mocks.downloadAndInstallUpdate,
|
||||
}));
|
||||
|
||||
vi.mock("./cli/external.js", async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
runExternalCliJsonCommand: mocks.runExternalCliJsonCommand,
|
||||
@@ -115,8 +93,6 @@ describe("daemon-manager commands", () => {
|
||||
mocks.paseoHome = path.join(fixtureRoot, "home");
|
||||
mocks.appLogPath = path.join(fixtureRoot, "main.log");
|
||||
mocks.settings = DEFAULT_DESKTOP_SETTINGS;
|
||||
mocks.checkForAppUpdate.mockReset();
|
||||
mocks.downloadAndInstallUpdate.mockReset();
|
||||
mocks.runExternalCliJsonCommand.mockReset();
|
||||
mocks.runExternalCliTextCommand.mockReset();
|
||||
mocks.createNodeEntrypointInvocation.mockReset();
|
||||
@@ -206,54 +182,6 @@ describe("daemon-manager commands", () => {
|
||||
writeFileSync(lockPath, JSON.stringify({ ...lock, desktopManaged: false }));
|
||||
expect(await handler({ listen: "localhost:6799" })).toBeNull();
|
||||
});
|
||||
|
||||
it("delegates update checks to checkForAppUpdate even when desktop-settings.json cannot be read", async () => {
|
||||
const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
mocks.checkForAppUpdate.mockResolvedValue({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
date: null,
|
||||
errorMessage: null,
|
||||
});
|
||||
mocks.downloadAndInstallUpdate.mockResolvedValue({
|
||||
installed: true,
|
||||
version: "1.2.4",
|
||||
message: "Update downloaded.",
|
||||
});
|
||||
|
||||
mocks.settingsError = new SyntaxError("Unexpected token } in JSON");
|
||||
try {
|
||||
await createDaemonCommandHandlers().check_app_update({
|
||||
intent: "manual",
|
||||
releaseChannel: "beta",
|
||||
});
|
||||
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "beta",
|
||||
intent: "manual",
|
||||
});
|
||||
|
||||
await createDaemonCommandHandlers().check_app_update({ intent: "automatic" });
|
||||
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
|
||||
await createDaemonCommandHandlers().install_app_update({});
|
||||
expect(mocks.downloadAndInstallUpdate).toHaveBeenLastCalledWith(
|
||||
{ currentVersion: "1.2.3", releaseChannel: "stable" },
|
||||
expect.any(Function),
|
||||
);
|
||||
} finally {
|
||||
mocks.settingsError = null;
|
||||
consoleWarn.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("desktop stops and terminals", () => {
|
||||
|
||||
@@ -481,17 +481,7 @@ async function getLocalDaemonVersion(): Promise<{ version: string | null; error:
|
||||
async function resolveRequestedReleaseChannel(
|
||||
args: Record<string, unknown> | undefined,
|
||||
): Promise<AppReleaseChannel> {
|
||||
const explicit = parseReleaseChannel(args);
|
||||
if (explicit) return explicit;
|
||||
try {
|
||||
return (await getDesktopSettingsStore().get()).releaseChannel;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"[auto-updater] Failed to read release channel from desktop settings, defaulting to stable:",
|
||||
error,
|
||||
);
|
||||
return "stable";
|
||||
}
|
||||
return parseReleaseChannel(args) ?? (await getDesktopSettingsStore().get()).releaseChannel;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -551,12 +541,10 @@ export function createDaemonCommandHandlers(): Record<string, DesktopCommandHand
|
||||
},
|
||||
check_app_update: async (args) => {
|
||||
const currentVersion = resolveDesktopAppVersion();
|
||||
const releaseChannel = await resolveRequestedReleaseChannel(args);
|
||||
const intent = parseAppUpdateCheckIntent(args);
|
||||
return checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent,
|
||||
releaseChannel: await resolveRequestedReleaseChannel(args),
|
||||
intent: parseAppUpdateCheckIntent(args),
|
||||
});
|
||||
},
|
||||
install_app_update: async (args) => {
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { DesktopUpdateMode } from "../settings/desktop-settings";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createAppUpdateService,
|
||||
type AppUpdateDownloadProgress,
|
||||
type AppUpdateInstallRequest,
|
||||
type AppUpdateRuntime,
|
||||
type AppUpdateRuntimeConfiguration,
|
||||
type RuntimeDownloadProgressInfo,
|
||||
type RuntimeUpdateCheckResult,
|
||||
type RuntimeUpdateInfo,
|
||||
} from "./app-update-service";
|
||||
|
||||
@@ -30,8 +26,6 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
|
||||
resolve(): void;
|
||||
reject(error: Error): void;
|
||||
} | null = null;
|
||||
lastAutoDownload: boolean | null = null;
|
||||
nextQuitAndInstallResult: { started: boolean; errorMessage?: string } | null = null;
|
||||
checkCount = 0;
|
||||
downloadCallCount = 0;
|
||||
requestedDownloadVersions: string[] = [];
|
||||
@@ -41,18 +35,9 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
|
||||
|
||||
configure(input: AppUpdateRuntimeConfiguration): void {
|
||||
this.configuration = input;
|
||||
this.lastAutoDownload = input.autoDownload;
|
||||
this.gate = input.shouldAdmitUpdate;
|
||||
}
|
||||
|
||||
setAutoDownload(enabled: boolean): void {
|
||||
this.lastAutoDownload = enabled;
|
||||
}
|
||||
|
||||
emitDownloadProgress(progress: RuntimeDownloadProgressInfo): void {
|
||||
this.configuration?.onDownloadProgress(progress);
|
||||
}
|
||||
|
||||
nextCheck(result: { isUpdateAvailable: boolean; updateInfo: RuntimeUpdateInfo } | null): void {
|
||||
this.checks.push(result);
|
||||
}
|
||||
@@ -158,36 +143,21 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest) {
|
||||
if (this.nextQuitAndInstallResult) {
|
||||
const outcome = this.nextQuitAndInstallResult;
|
||||
this.nextQuitAndInstallResult = null;
|
||||
return outcome;
|
||||
}
|
||||
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void {
|
||||
if (this.downloadedUpdate) {
|
||||
this.installedVersions.push(this.downloadedUpdate.version);
|
||||
this.installModes.push({ targetVersion, isSilent, isForceRunAfter });
|
||||
}
|
||||
return { started: true };
|
||||
}
|
||||
}
|
||||
|
||||
function createService(input?: {
|
||||
now?: () => number;
|
||||
bucket?: () => Promise<number>;
|
||||
updateMode?: () => DesktopUpdateMode | Promise<DesktopUpdateMode>;
|
||||
reportSettingsError?: (error: unknown) => void;
|
||||
onDownloadProgress?: (progress: AppUpdateDownloadProgress | null) => void;
|
||||
}) {
|
||||
function createService(input?: { now?: () => number; bucket?: () => Promise<number> }) {
|
||||
const runtime = new FakeAppUpdateRuntime();
|
||||
const service = createAppUpdateService({
|
||||
runtime,
|
||||
isPackaged: () => true,
|
||||
now: input?.now ?? (() => Date.parse("2026-04-28T12:00:00.000Z")),
|
||||
bucket: input?.bucket ?? (async () => 0.99),
|
||||
updateMode: input?.updateMode,
|
||||
reportSettingsError: input?.reportSettingsError,
|
||||
onDownloadProgress: input?.onDownloadProgress,
|
||||
});
|
||||
return { runtime, service };
|
||||
}
|
||||
@@ -212,7 +182,6 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -234,7 +203,6 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
@@ -363,7 +331,6 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.5",
|
||||
body: null,
|
||||
@@ -394,7 +361,6 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.5",
|
||||
body: null,
|
||||
@@ -603,7 +569,6 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -625,7 +590,6 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -656,7 +620,6 @@ describe("app update service", () => {
|
||||
expect(retryResult).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -686,7 +649,6 @@ describe("app update service", () => {
|
||||
expect(automaticResult).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -729,7 +691,6 @@ describe("app update service", () => {
|
||||
expect(automaticResult).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -760,7 +721,6 @@ describe("app update service", () => {
|
||||
expect(failedPreparation).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
@@ -779,7 +739,6 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.5",
|
||||
body: null,
|
||||
@@ -843,7 +802,6 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.5",
|
||||
body: null,
|
||||
@@ -876,7 +834,6 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: true,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
@@ -884,422 +841,4 @@ describe("app update service", () => {
|
||||
errorMessage: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an available update without downloading when autoDownload is false", async () => {
|
||||
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
onDownloadProgress: (progress) => progressEvents.push(progress),
|
||||
});
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
|
||||
const result = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: false,
|
||||
});
|
||||
|
||||
expect(runtime.lastAutoDownload).toBe(false);
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
date: "2026-04-28T00:00:00.000Z",
|
||||
errorMessage: null,
|
||||
});
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const activeDownload = runtime.beginUpdateDownload(rolledOutUpdate);
|
||||
const installPending = service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
await Promise.resolve();
|
||||
runtime.emitDownloadProgress({
|
||||
percent: 45,
|
||||
transferred: 45,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
activeDownload.resolve();
|
||||
const installResult = await installPending;
|
||||
|
||||
expect(installResult.installed).toBe(true);
|
||||
expect(progressEvents).toContainEqual({
|
||||
version: "1.2.4",
|
||||
percent: 45,
|
||||
transferred: 45,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
expect(progressEvents[progressEvents.length - 1]).toBeNull();
|
||||
});
|
||||
|
||||
it("allows retrying the same version after a transient download failure in notify/off mode", async () => {
|
||||
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
onDownloadProgress: (progress) => progressEvents.push(progress),
|
||||
});
|
||||
|
||||
// 1. Discover v1.2.4 without auto-downloading.
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const discovered = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "manual",
|
||||
autoDownload: false,
|
||||
});
|
||||
expect(discovered).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.4",
|
||||
});
|
||||
|
||||
// 2. First explicit download fails transiently mid-transfer.
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const failingDownload = runtime.beginUpdateDownload(rolledOutUpdate);
|
||||
const failedInstallPromise = service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(runtime.downloadCallCount).toBe(1);
|
||||
runtime.emitDownloadProgress({
|
||||
percent: 37,
|
||||
transferred: 37,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
failingDownload.reject(new Error("ECONNRESET"));
|
||||
const failedInstall = await failedInstallPromise;
|
||||
|
||||
expect(failedInstall).toMatchObject({
|
||||
installed: false,
|
||||
errorMessage: "ECONNRESET",
|
||||
});
|
||||
expect(progressEvents[progressEvents.length - 1]).toBeNull();
|
||||
|
||||
// 3. User retries manual Check for the SAME version (v1.2.4) — must not be stranded on stale error!
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const retryCheck = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "manual",
|
||||
autoDownload: false,
|
||||
});
|
||||
expect(retryCheck).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.4",
|
||||
errorMessage: null,
|
||||
});
|
||||
|
||||
// 4. Second explicit download succeeds and installs cleanly.
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const retryInstall = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
expect(retryInstall.installed).toBe(true);
|
||||
expect(runtime.installedVersions).toEqual(["1.2.4"]);
|
||||
});
|
||||
|
||||
it("downloads and installs a newer release if one ships after notify discovery", async () => {
|
||||
const { runtime, service } = createService({ bucket: async () => 0 });
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: false,
|
||||
});
|
||||
|
||||
const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" };
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate });
|
||||
const result = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
|
||||
expect(result.installed).toBe(true);
|
||||
expect(runtime.installedVersions).toEqual(["1.2.5"]);
|
||||
});
|
||||
|
||||
it("reuses an already-downloaded update when installing manually after switching to notify/off", async () => {
|
||||
const { runtime, service } = createService({ bucket: async () => 0 });
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
runtime.finishUpdateDownload(rolledOutUpdate);
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const result = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
|
||||
expect(result.installed).toBe(true);
|
||||
expect(runtime.downloadCallCount).toBe(0);
|
||||
expect(runtime.installedVersions).toEqual(["1.2.4"]);
|
||||
});
|
||||
|
||||
it("transitions cleanly from notify discovery to automatic background download", async () => {
|
||||
const { runtime, service } = createService({ bucket: async () => 0 });
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const notifyCheck = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: false,
|
||||
});
|
||||
expect(notifyCheck).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
});
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const autoCheck = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
expect(runtime.lastAutoDownload).toBe(true);
|
||||
expect(autoCheck).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("clamps NaN and out-of-range download progress values safely", async () => {
|
||||
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
onDownloadProgress: (progress) => progressEvents.push(progress),
|
||||
});
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
|
||||
runtime.emitDownloadProgress({
|
||||
percent: Number.NaN,
|
||||
transferred: Number.NaN,
|
||||
total: Number.POSITIVE_INFINITY,
|
||||
bytesPerSecond: Number.NaN,
|
||||
});
|
||||
runtime.emitDownloadProgress({
|
||||
percent: 140,
|
||||
transferred: 200,
|
||||
total: 100,
|
||||
bytesPerSecond: 50,
|
||||
});
|
||||
|
||||
expect(progressEvents).toContainEqual({
|
||||
version: "1.2.4",
|
||||
percent: 0,
|
||||
transferred: 0,
|
||||
total: 0,
|
||||
bytesPerSecond: 0,
|
||||
});
|
||||
expect(progressEvents).toContainEqual({
|
||||
version: "1.2.4",
|
||||
percent: 100,
|
||||
transferred: 200,
|
||||
total: 100,
|
||||
bytesPerSecond: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("applies updated updateMode after rollout bucket lookup before authorizing download", async () => {
|
||||
let mode: DesktopUpdateMode = "automatic";
|
||||
let resolveBucket!: (value: number) => void;
|
||||
const { runtime, service } = createService({
|
||||
bucket: () =>
|
||||
new Promise<number>((resolve) => {
|
||||
resolveBucket = resolve;
|
||||
}),
|
||||
updateMode: async () => mode,
|
||||
});
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const check = service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(resolveBucket).toBeDefined();
|
||||
});
|
||||
mode = "notify";
|
||||
resolveBucket(0);
|
||||
const result = await check;
|
||||
|
||||
expect(runtime.lastAutoDownload).toBe(false);
|
||||
expect(result).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.4",
|
||||
});
|
||||
});
|
||||
|
||||
it("skips a queued automatic check after Off is saved while an earlier check is in flight", async () => {
|
||||
let mode: DesktopUpdateMode = "automatic";
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
updateMode: async () => mode,
|
||||
});
|
||||
const firstCheck = runtime.deferNextCheck();
|
||||
|
||||
const firstPending = service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
const queuedPending = service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(runtime.checkCount).toBe(1);
|
||||
});
|
||||
mode = "off";
|
||||
firstCheck.resolve({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
|
||||
const [firstResult, queuedResult] = await Promise.all([firstPending, queuedPending]);
|
||||
expect(runtime.checkCount).toBe(1);
|
||||
expect(firstResult.hasUpdate).toBe(false);
|
||||
expect(queuedResult.hasUpdate).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to automatic mode when reading updateMode fails so updates are never stranded", async () => {
|
||||
const settingsErrors: unknown[] = [];
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
updateMode: async () => {
|
||||
throw new SyntaxError("Unexpected token } in JSON");
|
||||
},
|
||||
reportSettingsError: (error) => settingsErrors.push(error),
|
||||
});
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const autoResult = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
expect(autoResult).toMatchObject({
|
||||
hasUpdate: true,
|
||||
downloading: true,
|
||||
latestVersion: "1.2.4",
|
||||
errorMessage: null,
|
||||
});
|
||||
|
||||
runtime.finishUpdateDownload(rolledOutUpdate);
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const installedOnQuit = await service.installUpdateOnQuit({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
expect(installedOnQuit).toBe(true);
|
||||
expect(settingsErrors.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("skips installUpdateOnQuit when updateMode is notify or off", async () => {
|
||||
let mode: DesktopUpdateMode = "automatic";
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
updateMode: async () => mode,
|
||||
});
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
runtime.finishUpdateDownload(rolledOutUpdate);
|
||||
|
||||
mode = "notify";
|
||||
expect(
|
||||
await service.installUpdateOnQuit({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
mode = "off";
|
||||
expect(
|
||||
await service.installUpdateOnQuit({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(runtime.installedVersions).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports installer launch failures instead of success on both cached and downloaded paths", async () => {
|
||||
const { runtime, service } = createService({ bucket: async () => 0 });
|
||||
|
||||
// Path 1: already downloaded, installer fails to launch
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
runtime.finishUpdateDownload(rolledOutUpdate);
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
runtime.nextQuitAndInstallResult = {
|
||||
started: false,
|
||||
errorMessage: "EROFS: read-only file system",
|
||||
};
|
||||
const cachedFailure = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
expect(cachedFailure).toMatchObject({
|
||||
installed: false,
|
||||
errorMessage: "EROFS: read-only file system",
|
||||
});
|
||||
|
||||
// Path 2: fresh download, installer fails to launch
|
||||
const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" };
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate });
|
||||
runtime.nextQuitAndInstallResult = {
|
||||
started: false,
|
||||
errorMessage: "Neither dpkg nor apt command found",
|
||||
};
|
||||
const freshFailure = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
expect(freshFailure).toMatchObject({
|
||||
installed: false,
|
||||
errorMessage: "Neither dpkg nor apt command found",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { DesktopUpdateMode } from "../settings/desktop-settings.js";
|
||||
import {
|
||||
rolloutManifestSchema,
|
||||
shouldAdmitAppUpdate,
|
||||
@@ -6,18 +5,9 @@ import {
|
||||
type AppUpdateCheckIntent,
|
||||
} from "./app-update-rollout.js";
|
||||
|
||||
export interface AppUpdateDownloadProgress {
|
||||
version: string | null;
|
||||
percent: number;
|
||||
transferred: number;
|
||||
total: number;
|
||||
bytesPerSecond: number;
|
||||
}
|
||||
|
||||
export interface AppUpdateCheckResult {
|
||||
hasUpdate: boolean;
|
||||
readyToInstall: boolean;
|
||||
downloading: boolean;
|
||||
currentVersion: string;
|
||||
latestVersion: string;
|
||||
body: string | null;
|
||||
@@ -29,7 +19,6 @@ export interface AppUpdateInstallResult {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
message: string;
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
||||
export interface RuntimeUpdateInfo {
|
||||
@@ -39,13 +28,6 @@ export interface RuntimeUpdateInfo {
|
||||
rolloutHours?: unknown;
|
||||
}
|
||||
|
||||
export interface RuntimeDownloadProgressInfo {
|
||||
percent: number;
|
||||
transferred: number;
|
||||
total: number;
|
||||
bytesPerSecond: number;
|
||||
}
|
||||
|
||||
export interface RuntimeUpdateCheckResult {
|
||||
isUpdateAvailable: boolean;
|
||||
updateInfo: RuntimeUpdateInfo;
|
||||
@@ -53,10 +35,8 @@ export interface RuntimeUpdateCheckResult {
|
||||
|
||||
export interface AppUpdateRuntimeConfiguration {
|
||||
releaseChannel: AppReleaseChannel;
|
||||
autoDownload: boolean;
|
||||
shouldAdmitUpdate(info: RuntimeUpdateInfo): boolean | Promise<boolean>;
|
||||
onUpdateAvailable(info: RuntimeUpdateInfo): void;
|
||||
onDownloadProgress(progress: RuntimeDownloadProgressInfo): void;
|
||||
onUpdateDownloaded(info: RuntimeUpdateInfo): void;
|
||||
onError(error: unknown): void;
|
||||
}
|
||||
@@ -67,19 +47,11 @@ export interface AppUpdateInstallRequest {
|
||||
isForceRunAfter: boolean;
|
||||
}
|
||||
|
||||
export interface AppUpdateInstallLaunchResult {
|
||||
started: boolean;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
export interface AppUpdateRuntime {
|
||||
configure(input: AppUpdateRuntimeConfiguration): void;
|
||||
setAutoDownload?(enabled: boolean): void;
|
||||
checkForUpdates(): Promise<RuntimeUpdateCheckResult | null>;
|
||||
downloadUpdate(targetVersion: string): Promise<unknown>;
|
||||
quitAndInstall(
|
||||
input: AppUpdateInstallRequest,
|
||||
): Promise<AppUpdateInstallLaunchResult> | AppUpdateInstallLaunchResult;
|
||||
quitAndInstall(input: AppUpdateInstallRequest): void;
|
||||
}
|
||||
|
||||
export interface AppUpdateService {
|
||||
@@ -87,7 +59,6 @@ export interface AppUpdateService {
|
||||
currentVersion: string;
|
||||
releaseChannel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
autoDownload?: boolean;
|
||||
}): Promise<AppUpdateCheckResult>;
|
||||
downloadAndInstallUpdate(
|
||||
input: {
|
||||
@@ -108,9 +79,6 @@ export interface AppUpdateServiceDeps {
|
||||
isPackaged(): boolean;
|
||||
now(): number;
|
||||
bucket(): Promise<number>;
|
||||
updateMode?: () => DesktopUpdateMode | Promise<DesktopUpdateMode>;
|
||||
onDownloadProgress?(progress: AppUpdateDownloadProgress | null): void;
|
||||
reportSettingsError?(error: unknown): void;
|
||||
reportCheckError?(error: unknown): void;
|
||||
reportRuntimeError?(error: unknown): void;
|
||||
reportInstallError?(message: string): void;
|
||||
@@ -120,23 +88,14 @@ function buildCheckResult(input: {
|
||||
currentVersion: string;
|
||||
hasUpdate: boolean;
|
||||
readyToInstall: boolean;
|
||||
downloading?: boolean;
|
||||
info?: RuntimeUpdateInfo | null;
|
||||
errorMessage?: string | null;
|
||||
}): AppUpdateCheckResult {
|
||||
const {
|
||||
currentVersion,
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading = false,
|
||||
info,
|
||||
errorMessage = null,
|
||||
} = input;
|
||||
const { currentVersion, hasUpdate, readyToInstall, info, errorMessage = null } = input;
|
||||
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading,
|
||||
currentVersion,
|
||||
latestVersion: info?.version ?? currentVersion,
|
||||
body: typeof info?.releaseNotes === "string" ? info.releaseNotes : null,
|
||||
@@ -158,14 +117,11 @@ async function performQuitAndInstall(
|
||||
},
|
||||
): Promise<void> {
|
||||
if (onBeforeQuit) await onBeforeQuit();
|
||||
const launch = await runtime.quitAndInstall({
|
||||
runtime.quitAndInstall({
|
||||
targetVersion,
|
||||
isSilent: !restart,
|
||||
isForceRunAfter: restart,
|
||||
});
|
||||
if (!launch.started) {
|
||||
throw new Error(launch.errorMessage ?? "Failed to launch update installer.");
|
||||
}
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown): string {
|
||||
@@ -189,7 +145,6 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
let configuredReleaseChannel: AppReleaseChannel | null = null;
|
||||
let preparationError: { version: string; message: string } | null = null;
|
||||
let preparingUpdateVersion: string | null = null;
|
||||
let currentAutoDownload = true;
|
||||
let checkQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
function isReadyToInstallVersion(version: string): boolean {
|
||||
@@ -201,7 +156,6 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
downloadedUpdateVersion = null;
|
||||
preparationError = null;
|
||||
preparingUpdateVersion = null;
|
||||
deps.onDownloadProgress?.(null);
|
||||
}
|
||||
|
||||
function buildPreviouslyAdmittedUpdateResult(
|
||||
@@ -213,89 +167,42 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
return null;
|
||||
}
|
||||
|
||||
const readyToInstall = isReadyToInstallVersion(info.version);
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: true,
|
||||
readyToInstall,
|
||||
downloading: !readyToInstall && preparingUpdateVersion === info.version,
|
||||
readyToInstall: isReadyToInstallVersion(info.version),
|
||||
info,
|
||||
errorMessage: preparationError?.version === info.version ? preparationError.message : null,
|
||||
});
|
||||
}
|
||||
|
||||
async function resolveUpdateMode(): Promise<DesktopUpdateMode> {
|
||||
if (!deps.updateMode) {
|
||||
return "automatic";
|
||||
}
|
||||
try {
|
||||
return await deps.updateMode();
|
||||
} catch (error) {
|
||||
deps.reportSettingsError?.(error);
|
||||
return "automatic";
|
||||
}
|
||||
}
|
||||
|
||||
function resolveAutoDownload(mode: DesktopUpdateMode, override: boolean | undefined): boolean {
|
||||
return override ?? mode === "automatic";
|
||||
}
|
||||
|
||||
function configureRuntime(
|
||||
releaseChannel: AppReleaseChannel,
|
||||
intent: AppUpdateCheckIntent,
|
||||
initialAutoDownload: boolean,
|
||||
autoDownloadOverride: boolean | undefined,
|
||||
): void {
|
||||
function configureRuntime(releaseChannel: AppReleaseChannel, intent: AppUpdateCheckIntent): void {
|
||||
if (configuredReleaseChannel !== releaseChannel) {
|
||||
clearUpdateState();
|
||||
configuredReleaseChannel = releaseChannel;
|
||||
}
|
||||
currentAutoDownload = initialAutoDownload;
|
||||
|
||||
deps.runtime.configure({
|
||||
releaseChannel,
|
||||
autoDownload: initialAutoDownload,
|
||||
shouldAdmitUpdate: async (info) => {
|
||||
const parsed = rolloutManifestSchema.parse(info);
|
||||
const bucket = await deps.bucket();
|
||||
const liveMode = await resolveUpdateMode();
|
||||
if (intent === "automatic" && liveMode === "off") {
|
||||
return false;
|
||||
}
|
||||
const admitted = shouldAdmitAppUpdate({
|
||||
return shouldAdmitAppUpdate({
|
||||
channel: releaseChannel,
|
||||
intent,
|
||||
rolloutHours: parsed.rolloutHours,
|
||||
releaseDate: parsed.releaseDate,
|
||||
now: deps.now(),
|
||||
bucket,
|
||||
bucket: await deps.bucket(),
|
||||
});
|
||||
if (admitted) {
|
||||
currentAutoDownload = resolveAutoDownload(liveMode, autoDownloadOverride);
|
||||
deps.runtime.setAutoDownload?.(currentAutoDownload);
|
||||
}
|
||||
return admitted;
|
||||
},
|
||||
onUpdateAvailable(info) {
|
||||
const alreadyReady = downloadedUpdateVersion === info.version;
|
||||
cachedUpdateInfo = info;
|
||||
downloadedUpdateVersion = alreadyReady ? info.version : null;
|
||||
if (!alreadyReady && currentAutoDownload && preparingUpdateVersion === null) {
|
||||
if (!alreadyReady && preparingUpdateVersion === null) {
|
||||
preparingUpdateVersion = info.version;
|
||||
}
|
||||
},
|
||||
onDownloadProgress(progress) {
|
||||
const percent = Number.isFinite(progress.percent)
|
||||
? Math.max(0, Math.min(100, progress.percent))
|
||||
: 0;
|
||||
deps.onDownloadProgress?.({
|
||||
version: preparingUpdateVersion ?? cachedUpdateInfo?.version ?? null,
|
||||
percent,
|
||||
transferred: Number.isFinite(progress.transferred) ? progress.transferred : 0,
|
||||
total: Number.isFinite(progress.total) ? progress.total : 0,
|
||||
bytesPerSecond: Number.isFinite(progress.bytesPerSecond) ? progress.bytesPerSecond : 0,
|
||||
});
|
||||
},
|
||||
onUpdateDownloaded(info) {
|
||||
// A superseded download can finish after a newer manifest check. Keep
|
||||
// the validated manifest as the install target in that case.
|
||||
@@ -307,7 +214,6 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
if (preparationError?.version === info.version) {
|
||||
preparationError = null;
|
||||
}
|
||||
deps.onDownloadProgress?.(null);
|
||||
},
|
||||
onError(error) {
|
||||
if (preparingUpdateVersion) {
|
||||
@@ -317,7 +223,6 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
};
|
||||
preparingUpdateVersion = null;
|
||||
}
|
||||
deps.onDownloadProgress?.(null);
|
||||
deps.reportRuntimeError?.(error);
|
||||
},
|
||||
});
|
||||
@@ -332,58 +237,14 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
return result;
|
||||
}
|
||||
|
||||
function resolveAvailableUpdateResult(
|
||||
currentVersion: string,
|
||||
info: RuntimeUpdateInfo,
|
||||
): AppUpdateCheckResult {
|
||||
const latestVersion = info.version;
|
||||
if (latestVersion === currentVersion) {
|
||||
clearUpdateState();
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
|
||||
cachedUpdateInfo = info;
|
||||
const readyToInstall = isReadyToInstallVersion(latestVersion);
|
||||
const errorMessage =
|
||||
preparationError?.version === latestVersion ? preparationError.message : null;
|
||||
if (!errorMessage) {
|
||||
preparationError = null;
|
||||
}
|
||||
if (
|
||||
!readyToInstall &&
|
||||
!errorMessage &&
|
||||
currentAutoDownload &&
|
||||
preparingUpdateVersion === null
|
||||
) {
|
||||
preparingUpdateVersion = latestVersion;
|
||||
}
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: true,
|
||||
readyToInstall,
|
||||
downloading:
|
||||
!readyToInstall &&
|
||||
!errorMessage &&
|
||||
(currentAutoDownload || preparingUpdateVersion === latestVersion),
|
||||
info,
|
||||
errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
async function checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent,
|
||||
autoDownload,
|
||||
}: {
|
||||
currentVersion: string;
|
||||
releaseChannel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
autoDownload?: boolean;
|
||||
}): Promise<AppUpdateCheckResult> {
|
||||
if (!deps.isPackaged()) {
|
||||
return buildCheckResult({
|
||||
@@ -394,33 +255,10 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
}
|
||||
|
||||
return runCheckExclusively(async () => {
|
||||
const mode = deps.updateMode ? await resolveUpdateMode() : "automatic";
|
||||
if (intent === "automatic" && mode === "off") {
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
if (intent === "manual") {
|
||||
preparationError = null;
|
||||
}
|
||||
configureRuntime(
|
||||
releaseChannel,
|
||||
intent,
|
||||
resolveAutoDownload(mode, autoDownload),
|
||||
autoDownload,
|
||||
);
|
||||
configureRuntime(releaseChannel, intent);
|
||||
|
||||
try {
|
||||
const result = await deps.runtime.checkForUpdates();
|
||||
if (intent === "automatic" && deps.updateMode && (await resolveUpdateMode()) === "off") {
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
if (!result || !result.updateInfo) {
|
||||
clearUpdateState();
|
||||
return buildCheckResult({
|
||||
@@ -447,7 +285,32 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
});
|
||||
}
|
||||
|
||||
return resolveAvailableUpdateResult(currentVersion, result.updateInfo);
|
||||
const info = result.updateInfo;
|
||||
const latestVersion = info.version;
|
||||
const hasUpdate = latestVersion !== currentVersion;
|
||||
|
||||
if (hasUpdate) {
|
||||
cachedUpdateInfo = info;
|
||||
const errorMessage =
|
||||
preparationError?.version === latestVersion ? preparationError.message : null;
|
||||
if (!errorMessage) {
|
||||
preparationError = null;
|
||||
}
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: true,
|
||||
readyToInstall: isReadyToInstallVersion(latestVersion),
|
||||
info,
|
||||
errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
clearUpdateState();
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
} catch (error) {
|
||||
deps.reportCheckError?.(error);
|
||||
return buildCheckResult({
|
||||
@@ -482,39 +345,18 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent: "manual",
|
||||
autoDownload: false,
|
||||
});
|
||||
if (!check.hasUpdate) {
|
||||
return {
|
||||
installed: false,
|
||||
version: currentVersion,
|
||||
message: check.errorMessage ?? "No update available.",
|
||||
...(check.errorMessage ? { errorMessage: check.errorMessage } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return installCachedUpdate(currentVersion, { onBeforeQuit, restart: true });
|
||||
}
|
||||
|
||||
function clearPreparingVersion(version: string): void {
|
||||
if (preparingUpdateVersion === version) {
|
||||
preparingUpdateVersion = null;
|
||||
}
|
||||
deps.onDownloadProgress?.(null);
|
||||
}
|
||||
|
||||
function shouldRetryStaleDownloadError(
|
||||
attemptedVersion: string,
|
||||
readyVersion: string,
|
||||
signal?: AbortSignal,
|
||||
): boolean {
|
||||
return (
|
||||
attemptedVersion !== readyVersion &&
|
||||
cachedUpdateInfo?.version === readyVersion &&
|
||||
!signal?.aborted
|
||||
);
|
||||
}
|
||||
|
||||
async function ensureUpdateDownloaded(
|
||||
readyVersion: string,
|
||||
signal?: AbortSignal,
|
||||
@@ -525,14 +367,14 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
|
||||
const attemptedVersion: string = preparingUpdateVersion ?? readyVersion;
|
||||
preparingUpdateVersion ??= readyVersion;
|
||||
if (preparationError?.version === attemptedVersion) {
|
||||
preparationError = null;
|
||||
}
|
||||
try {
|
||||
await deps.runtime.downloadUpdate(attemptedVersion);
|
||||
} catch (error) {
|
||||
clearPreparingVersion(attemptedVersion);
|
||||
if (shouldRetryStaleDownloadError(attemptedVersion, readyVersion, signal)) {
|
||||
if (
|
||||
attemptedVersion !== readyVersion &&
|
||||
cachedUpdateInfo?.version === readyVersion &&
|
||||
!signal?.aborted
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
@@ -543,9 +385,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
// validated release instead of treating the stale artifact as ready.
|
||||
if (attemptedVersion === readyVersion && !isReadyToInstallVersion(readyVersion)) {
|
||||
downloadedUpdateVersion = readyVersion;
|
||||
clearPreparingVersion(readyVersion);
|
||||
} else if (preparingUpdateVersion === attemptedVersion) {
|
||||
clearPreparingVersion(attemptedVersion);
|
||||
preparingUpdateVersion = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -577,19 +417,30 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
return buildDeferredInstallResult(currentVersion);
|
||||
}
|
||||
|
||||
if (isReadyToInstallVersion(readyVersion)) {
|
||||
await performQuitAndInstall(deps.runtime, {
|
||||
targetVersion: readyVersion,
|
||||
onBeforeQuit,
|
||||
restart,
|
||||
});
|
||||
return {
|
||||
installed: true,
|
||||
version: readyVersion,
|
||||
message: "Update downloaded. The app will restart shortly.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
if (!isReadyToInstallVersion(readyVersion)) {
|
||||
const preparation = await ensureUpdateDownloaded(readyVersion, signal);
|
||||
if (preparation === "aborted") {
|
||||
return buildDeferredInstallResult(currentVersion);
|
||||
}
|
||||
if (preparation === "superseded") {
|
||||
return {
|
||||
installed: false,
|
||||
version: currentVersion,
|
||||
message: "A newer update was found and will be installed later.",
|
||||
};
|
||||
}
|
||||
const preparation = await ensureUpdateDownloaded(readyVersion, signal);
|
||||
if (preparation === "aborted") {
|
||||
return buildDeferredInstallResult(currentVersion);
|
||||
}
|
||||
if (preparation === "superseded") {
|
||||
return {
|
||||
installed: false,
|
||||
version: currentVersion,
|
||||
message: "A newer update was found and will be installed later.",
|
||||
};
|
||||
}
|
||||
await performQuitAndInstall(deps.runtime, {
|
||||
targetVersion: readyVersion,
|
||||
@@ -603,14 +454,12 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
message: "Update downloaded. The app will restart shortly.",
|
||||
};
|
||||
} catch (error) {
|
||||
deps.onDownloadProgress?.(null);
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
deps.reportInstallError?.(message);
|
||||
return {
|
||||
installed: false,
|
||||
version: currentVersion,
|
||||
message: `Update failed: ${message}`,
|
||||
errorMessage: message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -627,9 +476,6 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
if (!deps.isPackaged() || !downloadedUpdateVersion) {
|
||||
return false;
|
||||
}
|
||||
if ((await resolveUpdateMode()) !== "automatic") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const check = await checkForAppUpdate({
|
||||
currentVersion,
|
||||
|
||||
@@ -1,26 +1,14 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { UUID } from "builder-util-runtime";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { autoUpdaterMock, getAllWindowsMock, desktopSettingsMock } = vi.hoisted(() => {
|
||||
const handlers = new Map<string, Set<(value: unknown) => void>>();
|
||||
const { autoUpdaterMock } = vi.hoisted(() => {
|
||||
const handlers = new Map<string, (value: unknown) => void>();
|
||||
return {
|
||||
getAllWindowsMock: vi.fn<() => unknown[]>(() => []),
|
||||
desktopSettingsMock: {
|
||||
mode: "automatic" as "automatic" | "notify" | "off",
|
||||
error: null as Error | null,
|
||||
},
|
||||
autoUpdaterMock: {
|
||||
handlers: {
|
||||
get: (event: string) => (value: unknown) => {
|
||||
for (const listener of handlers.get(event) ?? []) {
|
||||
listener(value);
|
||||
}
|
||||
},
|
||||
},
|
||||
handlers,
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
error: vi.fn((message: unknown) => console.error(message)),
|
||||
@@ -30,15 +18,7 @@ const { autoUpdaterMock, getAllWindowsMock, desktopSettingsMock } = vi.hoisted((
|
||||
checkForUpdates: vi.fn(),
|
||||
downloadUpdate: vi.fn(),
|
||||
on: vi.fn((event: string, handler: (value: unknown) => void) => {
|
||||
let set = handlers.get(event);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
handlers.set(event, set);
|
||||
}
|
||||
set.add(handler);
|
||||
}),
|
||||
removeListener: vi.fn((event: string, handler: (value: unknown) => void) => {
|
||||
handlers.get(event)?.delete(handler);
|
||||
handlers.set(event, handler);
|
||||
}),
|
||||
quitAndInstall: vi.fn(),
|
||||
},
|
||||
@@ -50,26 +30,6 @@ vi.mock("electron", () => ({
|
||||
getPath: vi.fn(),
|
||||
isPackaged: true,
|
||||
},
|
||||
autoUpdater: undefined,
|
||||
BrowserWindow: {
|
||||
getAllWindows: getAllWindowsMock,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../settings/desktop-settings-electron.js", () => ({
|
||||
getDesktopSettingsStore: () => ({
|
||||
get: async () => {
|
||||
if (desktopSettingsMock.error) {
|
||||
throw desktopSettingsMock.error;
|
||||
}
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
updates: { mode: desktopSettingsMock.mode },
|
||||
notifications: { playSound: true },
|
||||
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
|
||||
};
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("electron-updater", () => ({
|
||||
@@ -80,10 +40,8 @@ import {
|
||||
bucketFromStagingUserId,
|
||||
checkForAppUpdate,
|
||||
createAppUpdateLifecycleLogger,
|
||||
downloadAndInstallUpdate,
|
||||
resolveStagingUserId,
|
||||
rolloutManifestSchema,
|
||||
runElectronQuitAndInstall,
|
||||
shouldAdmitToRollout,
|
||||
shouldInstallAppUpdateOnQuit,
|
||||
} from "./auto-updater";
|
||||
@@ -109,7 +67,6 @@ describe("checkForAppUpdate", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -140,248 +97,6 @@ describe("checkForAppUpdate", () => {
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("configures electron-updater autoDownload from checkForAppUpdate options", async () => {
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.5" },
|
||||
});
|
||||
|
||||
const result = await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: false,
|
||||
});
|
||||
|
||||
expect((autoUpdaterMock as unknown as { autoDownload?: boolean }).autoDownload).toBe(false);
|
||||
expect(result).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.5",
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards download-progress to window progress bars and renderer events", async () => {
|
||||
const setProgressBar = vi.fn();
|
||||
const send = vi.fn();
|
||||
getAllWindowsMock.mockReturnValue([
|
||||
{ isDestroyed: () => false, setProgressBar, webContents: { send } },
|
||||
]);
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.6" },
|
||||
});
|
||||
|
||||
await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
autoUpdaterMock.handlers.get("download-progress")?.({
|
||||
percent: 42,
|
||||
transferred: 420,
|
||||
total: 1000,
|
||||
bytesPerSecond: 100,
|
||||
});
|
||||
|
||||
expect(setProgressBar).toHaveBeenCalledWith(0.42);
|
||||
expect(send).toHaveBeenCalledWith("paseo:event:app-update-download-progress", {
|
||||
version: "1.2.6",
|
||||
percent: 42,
|
||||
transferred: 420,
|
||||
total: 1000,
|
||||
bytesPerSecond: 100,
|
||||
});
|
||||
|
||||
autoUpdaterMock.handlers.get("update-downloaded")?.({ version: "1.2.6" });
|
||||
expect(setProgressBar).toHaveBeenLastCalledWith(-1);
|
||||
expect(send).toHaveBeenLastCalledWith("paseo:event:app-update-download-progress", null);
|
||||
getAllWindowsMock.mockReturnValue([]);
|
||||
});
|
||||
|
||||
it("gates automatic checks and autoDownload from desktop settings and falls back to automatic on read failure", async () => {
|
||||
const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
try {
|
||||
autoUpdaterMock.checkForUpdates.mockClear();
|
||||
desktopSettingsMock.mode = "off";
|
||||
const offAuto = await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
expect(offAuto.hasUpdate).toBe(false);
|
||||
expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled();
|
||||
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.9" },
|
||||
});
|
||||
const offManual = await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "manual",
|
||||
});
|
||||
expect(offManual).toMatchObject({
|
||||
hasUpdate: true,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.9",
|
||||
});
|
||||
|
||||
desktopSettingsMock.mode = "automatic";
|
||||
desktopSettingsMock.error = new SyntaxError("Unexpected token } in JSON");
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.10" },
|
||||
});
|
||||
const fallbackResult = await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
expect(fallbackResult).toMatchObject({
|
||||
hasUpdate: true,
|
||||
downloading: true,
|
||||
latestVersion: "1.2.10",
|
||||
});
|
||||
expect(consoleWarn).toHaveBeenCalled();
|
||||
autoUpdaterMock.handlers.get("update-downloaded")?.({ version: "1.2.10" });
|
||||
} finally {
|
||||
desktopSettingsMock.mode = "automatic";
|
||||
desktopSettingsMock.error = null;
|
||||
consoleWarn.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not fail update events when setProgressBar throws", async () => {
|
||||
const send = vi.fn();
|
||||
getAllWindowsMock.mockReturnValue([
|
||||
{
|
||||
isDestroyed: () => false,
|
||||
setProgressBar: () => {
|
||||
throw new Error("unsupported desktop environment");
|
||||
},
|
||||
webContents: { send },
|
||||
},
|
||||
]);
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.7" },
|
||||
});
|
||||
|
||||
await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
expect(() => {
|
||||
autoUpdaterMock.handlers.get("download-progress")?.({
|
||||
percent: 50,
|
||||
transferred: 50,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
}).not.toThrow();
|
||||
expect(send).toHaveBeenCalledWith(
|
||||
"paseo:event:app-update-download-progress",
|
||||
expect.objectContaining({ version: "1.2.7", percent: 50 }),
|
||||
);
|
||||
getAllWindowsMock.mockReturnValue([]);
|
||||
});
|
||||
|
||||
it("reports a failure when quitAndInstall emits an installer error and returns normally", async () => {
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.8" },
|
||||
});
|
||||
autoUpdaterMock.downloadUpdate.mockResolvedValueOnce(undefined);
|
||||
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
|
||||
autoUpdaterMock.handlers.get("error")?.(new Error("EROFS: read-only file system"));
|
||||
});
|
||||
|
||||
const result = await downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
installed: false,
|
||||
errorMessage: "EROFS: read-only file system",
|
||||
});
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("waits on macOS explicit installs until Squirrel reports an error or signals quit, while returning immediately on quit-time handoff", async () => {
|
||||
const updater = Object.assign(new EventEmitter(), {
|
||||
quitAndInstall: vi.fn(),
|
||||
});
|
||||
const nativeUpdater = new EventEmitter();
|
||||
|
||||
const failedInstall = runElectronQuitAndInstall({
|
||||
platform: "darwin",
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent: false,
|
||||
isForceRunAfter: true,
|
||||
});
|
||||
expect(
|
||||
await Promise.race([failedInstall.then(() => "settled"), Promise.resolve("pending")]),
|
||||
).toBe("pending");
|
||||
|
||||
nativeUpdater.emit("error", new Error("Code signature invalid"));
|
||||
await expect(failedInstall).resolves.toEqual({
|
||||
started: false,
|
||||
errorMessage: "Code signature invalid",
|
||||
});
|
||||
expect(updater.listenerCount("error")).toBe(0);
|
||||
expect(nativeUpdater.listenerCount("error")).toBe(0);
|
||||
expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0);
|
||||
|
||||
const restartInstall = runElectronQuitAndInstall({
|
||||
platform: "darwin",
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent: false,
|
||||
isForceRunAfter: true,
|
||||
});
|
||||
nativeUpdater.emit("before-quit-for-update");
|
||||
await expect(restartInstall).resolves.toEqual({ started: true });
|
||||
|
||||
// Quit-time install (isForceRunAfter: false) returns immediately so
|
||||
// quit-lifecycle owns its separate handoff deadline.
|
||||
await expect(
|
||||
runElectronQuitAndInstall({
|
||||
platform: "darwin",
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent: true,
|
||||
isForceRunAfter: false,
|
||||
}),
|
||||
).resolves.toEqual({ started: true });
|
||||
expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0);
|
||||
|
||||
// Explicit install times out cleanly instead of hanging forever if Squirrel never emits.
|
||||
await expect(
|
||||
runElectronQuitAndInstall({
|
||||
platform: "darwin",
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent: false,
|
||||
isForceRunAfter: true,
|
||||
timeoutMs: 10,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
started: false,
|
||||
errorMessage: "Timed out waiting for the update installer to start.",
|
||||
});
|
||||
expect(updater.listenerCount("error")).toBe(0);
|
||||
expect(nativeUpdater.listenerCount("error")).toBe(0);
|
||||
expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0);
|
||||
});
|
||||
|
||||
it("logs the update handoff with current and selected target versions", () => {
|
||||
const info = vi.fn();
|
||||
const lifecycleLog = createAppUpdateLifecycleLogger({ info });
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { app, autoUpdater as electronAutoUpdater, BrowserWindow } from "electron";
|
||||
import { app } from "electron";
|
||||
import { UUID } from "builder-util-runtime";
|
||||
import log from "electron-log/main";
|
||||
import { autoUpdater } from "electron-updater";
|
||||
import { getDesktopSettingsStore } from "../settings/desktop-settings-electron.js";
|
||||
import {
|
||||
createAppUpdateService,
|
||||
type AppUpdateCheckResult,
|
||||
type AppUpdateDownloadProgress,
|
||||
type AppUpdateInstallLaunchResult,
|
||||
type AppUpdateInstallRequest,
|
||||
type AppUpdateInstallResult,
|
||||
type AppUpdateRuntime,
|
||||
type AppUpdateRuntimeConfiguration,
|
||||
type RuntimeDownloadProgressInfo,
|
||||
type RuntimeUpdateCheckResult,
|
||||
type RuntimeUpdateInfo,
|
||||
} from "./app-update-service.js";
|
||||
@@ -34,7 +30,6 @@ export {
|
||||
type AppReleaseChannel,
|
||||
type AppUpdateCheckIntent,
|
||||
type AppUpdateCheckResult,
|
||||
type AppUpdateDownloadProgress,
|
||||
type AppUpdateInstallResult,
|
||||
};
|
||||
|
||||
@@ -145,143 +140,11 @@ export function shouldInstallAppUpdateOnQuit(input: {
|
||||
return !(input.platform === "linux" && input.isAppImage);
|
||||
}
|
||||
|
||||
const APP_UPDATE_DOWNLOAD_PROGRESS_EVENT = "paseo:event:app-update-download-progress";
|
||||
|
||||
function resolveProgressBarValue(progress: AppUpdateDownloadProgress | null): number {
|
||||
if (progress === null) return -1;
|
||||
if (!Number.isFinite(progress.percent)) return 0;
|
||||
return Math.max(0, Math.min(1, progress.percent / 100));
|
||||
}
|
||||
|
||||
function broadcastDownloadProgress(progress: AppUpdateDownloadProgress | null): void {
|
||||
const normalizedBar = resolveProgressBarValue(progress);
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
if (win.isDestroyed()) continue;
|
||||
try {
|
||||
win.setProgressBar(normalizedBar);
|
||||
} catch {
|
||||
// Progress bar support is optional across desktop environments.
|
||||
}
|
||||
try {
|
||||
win.webContents.send(APP_UPDATE_DOWNLOAD_PROGRESS_EVENT, progress);
|
||||
} catch {
|
||||
// Window may be tearing down during quitAndInstall.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const MACOS_INSTALL_HANDOFF_TIMEOUT_MS = 2 * 60 * 1000;
|
||||
|
||||
export interface QuitAndInstallEventSource {
|
||||
on(event: string, listener: (...args: unknown[]) => void): unknown;
|
||||
removeListener?(event: string, listener: (...args: unknown[]) => void): unknown;
|
||||
}
|
||||
|
||||
function formatLaunchError(error: unknown): string {
|
||||
return error instanceof Error && typeof error.message === "string"
|
||||
? error.message
|
||||
: String(error);
|
||||
}
|
||||
|
||||
export function runElectronQuitAndInstall({
|
||||
platform,
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
timeoutMs = MACOS_INSTALL_HANDOFF_TIMEOUT_MS,
|
||||
}: {
|
||||
platform: NodeJS.Platform;
|
||||
updater: QuitAndInstallEventSource & {
|
||||
quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void;
|
||||
};
|
||||
nativeUpdater?: QuitAndInstallEventSource;
|
||||
isSilent: boolean;
|
||||
isForceRunAfter: boolean;
|
||||
timeoutMs?: number;
|
||||
}): Promise<AppUpdateInstallLaunchResult> {
|
||||
// Only await macOS Squirrel preparation for explicit Download / Restart Now
|
||||
// installs (isForceRunAfter === true). Quit-time installs (isForceRunAfter === false)
|
||||
// return immediately so quit-lifecycle owns its separate handoff deadline.
|
||||
if (platform !== "darwin" || !isForceRunAfter || typeof nativeUpdater?.on !== "function") {
|
||||
let launchError: unknown = null;
|
||||
const captureLaunchError = (error: unknown) => {
|
||||
launchError ??= error;
|
||||
};
|
||||
updater.on("error", captureLaunchError);
|
||||
try {
|
||||
updater.quitAndInstall(isSilent, isForceRunAfter);
|
||||
} catch (error) {
|
||||
launchError ??= error;
|
||||
} finally {
|
||||
updater.removeListener?.("error", captureLaunchError);
|
||||
}
|
||||
if (launchError !== null) {
|
||||
return Promise.resolve({ started: false, errorMessage: formatLaunchError(launchError) });
|
||||
}
|
||||
return Promise.resolve({ started: true });
|
||||
}
|
||||
|
||||
// With autoInstallOnAppQuit disabled, electron-updater's MacUpdater starts
|
||||
// native Squirrel preparation asynchronously inside quitAndInstall(). Keep
|
||||
// the explicit install promise pending until Squirrel hands off to quit, fails,
|
||||
// or hits the safety timeout.
|
||||
return new Promise<AppUpdateInstallLaunchResult>((resolve) => {
|
||||
let settled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
updater.removeListener?.("error", handleError);
|
||||
nativeUpdater.removeListener?.("error", handleError);
|
||||
nativeUpdater.removeListener?.("update-not-available", handleNotAvailable);
|
||||
nativeUpdater.removeListener?.("before-quit-for-update", handleQuitStarted);
|
||||
};
|
||||
const finish = (result: AppUpdateInstallLaunchResult) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
cleanup();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
const handleError = (error: unknown) => {
|
||||
finish({ started: false, errorMessage: formatLaunchError(error) });
|
||||
};
|
||||
const handleNotAvailable = () => {
|
||||
finish({ started: false, errorMessage: "Update could not be prepared for installation." });
|
||||
};
|
||||
const handleQuitStarted = () => {
|
||||
finish({ started: true });
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
finish({
|
||||
started: false,
|
||||
errorMessage: "Timed out waiting for the update installer to start.",
|
||||
});
|
||||
}, timeoutMs);
|
||||
|
||||
updater.on("error", handleError);
|
||||
nativeUpdater.on("error", handleError);
|
||||
nativeUpdater.on("update-not-available", handleNotAvailable);
|
||||
nativeUpdater.on("before-quit-for-update", handleQuitStarted);
|
||||
|
||||
try {
|
||||
updater.quitAndInstall(isSilent, isForceRunAfter);
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
private configured = false;
|
||||
private configuration: AppUpdateRuntimeConfiguration | null = null;
|
||||
|
||||
configure(input: AppUpdateRuntimeConfiguration): void {
|
||||
this.configuration = input;
|
||||
autoUpdater.autoDownload = input.autoDownload;
|
||||
autoUpdater.autoDownload = true;
|
||||
autoUpdater.autoRunAppAfterInstall = true;
|
||||
// Paseo revalidates the current manifest before explicitly installing on quit.
|
||||
// Electron's built-in handler would install an older download without checking
|
||||
@@ -292,7 +155,7 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
autoUpdater.allowDowngrade = false;
|
||||
autoUpdater.isUserWithinRollout = async (info) => {
|
||||
try {
|
||||
return await (this.configuration?.shouldAdmitUpdate(info as RuntimeUpdateInfo) ?? true);
|
||||
return await input.shouldAdmitUpdate(info as RuntimeUpdateInfo);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
@@ -316,26 +179,19 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
autoUpdater.on("update-available", (info) => {
|
||||
const updateInfo = info as RuntimeUpdateInfo;
|
||||
updateLifecycleLog.updateAvailable(updateInfo.version);
|
||||
this.configuration?.onUpdateAvailable(updateInfo);
|
||||
});
|
||||
autoUpdater.on("download-progress", (progress) => {
|
||||
this.configuration?.onDownloadProgress(progress as RuntimeDownloadProgressInfo);
|
||||
input.onUpdateAvailable(updateInfo);
|
||||
});
|
||||
autoUpdater.on("update-downloaded", (info) => {
|
||||
const updateInfo = info as RuntimeUpdateInfo;
|
||||
updateLifecycleLog.updateDownloaded(updateInfo.version);
|
||||
this.configuration?.onUpdateDownloaded(updateInfo);
|
||||
input.onUpdateDownloaded(updateInfo);
|
||||
});
|
||||
autoUpdater.on("error", (error) => {
|
||||
if (isUpdateChannelNotPublished(error)) return;
|
||||
this.configuration?.onError(error);
|
||||
input.onError(error);
|
||||
});
|
||||
}
|
||||
|
||||
setAutoDownload(enabled: boolean): void {
|
||||
autoUpdater.autoDownload = enabled;
|
||||
}
|
||||
|
||||
async checkForUpdates(): Promise<RuntimeUpdateCheckResult | null> {
|
||||
try {
|
||||
const result = await autoUpdater.checkForUpdates();
|
||||
@@ -355,25 +211,14 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
return autoUpdater.downloadUpdate();
|
||||
}
|
||||
|
||||
quitAndInstall({
|
||||
targetVersion,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
}: AppUpdateInstallRequest): Promise<AppUpdateInstallLaunchResult> {
|
||||
broadcastDownloadProgress(null);
|
||||
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void {
|
||||
autoUpdater.autoRunAppAfterInstall = isForceRunAfter;
|
||||
updateLifecycleLog.quitAndInstallRequested({
|
||||
targetVersion,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
});
|
||||
return runElectronQuitAndInstall({
|
||||
platform: process.platform,
|
||||
updater: autoUpdater,
|
||||
nativeUpdater: electronAutoUpdater,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
});
|
||||
autoUpdater.quitAndInstall(isSilent, isForceRunAfter);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,14 +227,6 @@ const appUpdateService = createAppUpdateService({
|
||||
isPackaged: () => app.isPackaged,
|
||||
now: () => Date.now(),
|
||||
bucket: async () => bucketFromStagingUserId(await getStagingUserId()),
|
||||
updateMode: async () => (await getDesktopSettingsStore().get()).updates.mode,
|
||||
onDownloadProgress: broadcastDownloadProgress,
|
||||
reportSettingsError: (error) => {
|
||||
console.warn(
|
||||
"[auto-updater] Failed to read desktop update mode, defaulting to automatic:",
|
||||
error,
|
||||
);
|
||||
},
|
||||
reportCheckError: (error) => {
|
||||
console.error("[auto-updater] Failed to check for updates:", error);
|
||||
},
|
||||
@@ -409,19 +246,16 @@ export async function checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent,
|
||||
autoDownload,
|
||||
}: {
|
||||
currentVersion: string;
|
||||
releaseChannel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
autoDownload?: boolean;
|
||||
}): Promise<AppUpdateCheckResult> {
|
||||
updateLifecycleLog.checkStarted({ currentVersion, releaseChannel, intent });
|
||||
const result = await appUpdateService.checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent,
|
||||
autoDownload,
|
||||
});
|
||||
updateLifecycleLog.checkCompleted({
|
||||
currentVersion,
|
||||
|
||||
@@ -1058,18 +1058,10 @@ const quitLifecycle = createQuitLifecycle({
|
||||
showShutdownFeedback: showDaemonShutdownDialog,
|
||||
}),
|
||||
installAppUpdateOnQuit: async (signal) => {
|
||||
let releaseChannel: "stable" | "beta" = "stable";
|
||||
try {
|
||||
releaseChannel = (await getDesktopSettingsStore().get()).releaseChannel;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
"[auto-updater] Failed to read desktop settings on quit, defaulting to stable:",
|
||||
error,
|
||||
);
|
||||
}
|
||||
const settings = await getDesktopSettingsStore().get();
|
||||
return installAppUpdateOnQuit({
|
||||
currentVersion: app.getVersion(),
|
||||
releaseChannel,
|
||||
releaseChannel: settings.releaseChannel,
|
||||
signal,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -81,7 +81,6 @@ describe("desktop-settings", () => {
|
||||
|
||||
expect(settings).toEqual({
|
||||
releaseChannel: "stable",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: true,
|
||||
@@ -98,14 +97,12 @@ describe("desktop-settings", () => {
|
||||
await store.get();
|
||||
const next = await store.patch({
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "notify" },
|
||||
daemon: { keepRunningAfterQuit: false },
|
||||
});
|
||||
const files = await readdir(userDataPath);
|
||||
|
||||
expect(next).toEqual({
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "notify" },
|
||||
notifications: { playSound: true },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: true,
|
||||
@@ -115,65 +112,6 @@ describe("desktop-settings", () => {
|
||||
expect(files).toEqual(["desktop-settings.json"]);
|
||||
});
|
||||
|
||||
it("defaults updates.mode to automatic and persists explicit choices across restarts", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
await writeFile(
|
||||
settingsFilePath(userDataPath),
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
settings: {
|
||||
releaseChannel: "stable",
|
||||
updates: { mode: "invalid" },
|
||||
},
|
||||
migrations: {
|
||||
legacyRendererSettingsImported: true,
|
||||
daemonStopOnQuitDefaultApplied: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const defaulted = await createDesktopSettingsStore({ userDataPath }).get();
|
||||
expect(defaulted.updates.mode).toBe("automatic");
|
||||
|
||||
await createDesktopSettingsStore({ userDataPath }).patch({ updates: { mode: "off" } });
|
||||
const persisted = await createDesktopSettingsStore({ userDataPath }).get();
|
||||
expect(persisted.updates.mode).toBe("off");
|
||||
});
|
||||
|
||||
it("serializes overlapping patches so neither update mode nor release channel is lost", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
const store = createDesktopSettingsStore({ userDataPath });
|
||||
|
||||
const [offResult, betaResult] = await Promise.all([
|
||||
store.patch({ updates: { mode: "off" } }),
|
||||
store.patch({ releaseChannel: "beta" }),
|
||||
]);
|
||||
|
||||
expect(offResult.updates.mode).toBe("off");
|
||||
expect(betaResult.updates.mode).toBe("off");
|
||||
expect(betaResult.releaseChannel).toBe("beta");
|
||||
|
||||
const reloaded = await createDesktopSettingsStore({ userDataPath }).get();
|
||||
expect(reloaded.updates.mode).toBe("off");
|
||||
expect(reloaded.releaseChannel).toBe("beta");
|
||||
});
|
||||
|
||||
it("waits for an in-flight patch before resolving get() from cache", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
const store = createDesktopSettingsStore({ userDataPath });
|
||||
|
||||
await store.patch({ updates: { mode: "off" } });
|
||||
const patchPromise = store.patch({ updates: { mode: "automatic" } });
|
||||
const readDuringPatch = store.get();
|
||||
|
||||
const [patched, read] = await Promise.all([patchPromise, readDuringPatch]);
|
||||
expect(patched.updates.mode).toBe("automatic");
|
||||
expect(read.updates.mode).toBe("automatic");
|
||||
});
|
||||
|
||||
it("defaults notification sounds on for existing settings documents", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
@@ -332,7 +270,6 @@ describe("desktop-settings", () => {
|
||||
|
||||
expect(migrated).toEqual({
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: false,
|
||||
@@ -378,7 +315,6 @@ describe("desktop-settings", () => {
|
||||
expect(persisted.settings.releaseChannel).toBe("beta");
|
||||
expect(next).toEqual({
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: false },
|
||||
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: false },
|
||||
});
|
||||
|
||||
@@ -6,13 +6,8 @@ import { z } from "zod";
|
||||
|
||||
import type { AppReleaseChannel } from "../features/auto-updater.js";
|
||||
|
||||
export type DesktopUpdateMode = "automatic" | "notify" | "off";
|
||||
|
||||
export interface DesktopSettings {
|
||||
releaseChannel: AppReleaseChannel;
|
||||
updates: {
|
||||
mode: DesktopUpdateMode;
|
||||
};
|
||||
notifications: {
|
||||
playSound: boolean;
|
||||
};
|
||||
@@ -24,7 +19,6 @@ export interface DesktopSettings {
|
||||
|
||||
interface DesktopSettingsPatch {
|
||||
releaseChannel?: AppReleaseChannel;
|
||||
updates?: Partial<DesktopSettings["updates"]>;
|
||||
notifications?: Partial<DesktopSettings["notifications"]>;
|
||||
daemon?: Partial<DesktopSettings["daemon"]>;
|
||||
}
|
||||
@@ -37,9 +31,6 @@ export interface DesktopSettingsStore {
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
@@ -52,13 +43,6 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
const DESKTOP_SETTINGS_FILENAME = "desktop-settings.json";
|
||||
|
||||
const ReleaseChannelSchema = z.enum(["stable", "beta"]);
|
||||
const UpdateModeSchema = z.enum(["automatic", "notify", "off"]);
|
||||
|
||||
const UpdatesSchema = z
|
||||
.looseObject({
|
||||
mode: UpdateModeSchema.catch(DEFAULT_DESKTOP_SETTINGS.updates.mode),
|
||||
})
|
||||
.catch(() => ({ ...DEFAULT_DESKTOP_SETTINGS.updates }));
|
||||
|
||||
const NotificationsSchema = z
|
||||
.looseObject({
|
||||
@@ -76,7 +60,6 @@ const DaemonSchema = z
|
||||
const DesktopSettingsSchema = z
|
||||
.looseObject({
|
||||
releaseChannel: ReleaseChannelSchema.catch(DEFAULT_DESKTOP_SETTINGS.releaseChannel),
|
||||
updates: UpdatesSchema,
|
||||
notifications: NotificationsSchema,
|
||||
daemon: DaemonSchema,
|
||||
})
|
||||
@@ -112,11 +95,6 @@ function coerceReleaseChannel(value: unknown): AppReleaseChannel | null {
|
||||
return result.success ? result.data : null;
|
||||
}
|
||||
|
||||
function coerceUpdateMode(value: unknown): DesktopUpdateMode | null {
|
||||
const result = UpdateModeSchema.safeParse(value);
|
||||
return result.success ? result.data : null;
|
||||
}
|
||||
|
||||
function coerceBoolean(value: unknown): boolean | null {
|
||||
return typeof value === "boolean" ? value : null;
|
||||
}
|
||||
@@ -128,7 +106,6 @@ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
||||
function buildDefaultSettings(): StoredDesktopSettings {
|
||||
return {
|
||||
releaseChannel: DEFAULT_DESKTOP_SETTINGS.releaseChannel,
|
||||
updates: { ...DEFAULT_DESKTOP_SETTINGS.updates },
|
||||
notifications: { ...DEFAULT_DESKTOP_SETTINGS.notifications },
|
||||
daemon: { ...DEFAULT_DESKTOP_SETTINGS.daemon },
|
||||
};
|
||||
@@ -148,7 +125,6 @@ function buildDefaultDocument(): PersistedDesktopSettingsDocument {
|
||||
function toDesktopSettings(stored: StoredDesktopSettings): DesktopSettings {
|
||||
return {
|
||||
releaseChannel: stored.releaseChannel,
|
||||
updates: { mode: stored.updates.mode },
|
||||
notifications: { playSound: stored.notifications.playSound },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: stored.daemon.manageBuiltInDaemon,
|
||||
@@ -168,13 +144,6 @@ function coerceDesktopSettingsPatch(input: unknown): DesktopSettingsPatch {
|
||||
patch.releaseChannel = releaseChannel;
|
||||
}
|
||||
|
||||
if (isRecord(input.updates)) {
|
||||
const mode = coerceUpdateMode(input.updates.mode);
|
||||
if (mode) {
|
||||
patch.updates = { mode };
|
||||
}
|
||||
}
|
||||
|
||||
if (isRecord(input.notifications)) {
|
||||
const playSound = coerceBoolean(input.notifications.playSound);
|
||||
if (playSound !== null) {
|
||||
@@ -228,7 +197,6 @@ function mergeDesktopSettings(
|
||||
return {
|
||||
...current,
|
||||
releaseChannel: patch.releaseChannel ?? current.releaseChannel,
|
||||
updates: { ...current.updates, ...patch.updates },
|
||||
notifications: { ...current.notifications, ...patch.notifications },
|
||||
daemon: { ...current.daemon, ...patch.daemon },
|
||||
};
|
||||
@@ -264,26 +232,22 @@ export function createDesktopSettingsStore({
|
||||
}): DesktopSettingsStore {
|
||||
const filePath = path.join(userDataPath, DESKTOP_SETTINGS_FILENAME);
|
||||
let cachedDocument: PersistedDesktopSettingsDocument | null = null;
|
||||
let operationQueue: Promise<void> = Promise.resolve();
|
||||
let persistQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
function enqueueOperation<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = operationQueue.then(operation, operation);
|
||||
operationQueue = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
async function persistDocument(document: PersistedDesktopSettingsDocument): Promise<void> {
|
||||
const write = async () => {
|
||||
await mkdir(userDataPath, { recursive: true });
|
||||
const tempFilePath = `${filePath}.tmp.${process.pid}.${randomUUID()}`;
|
||||
await writeFile(tempFilePath, `${JSON.stringify(document, null, 2)}\n`, "utf8");
|
||||
await rename(tempFilePath, filePath);
|
||||
cachedDocument = document;
|
||||
};
|
||||
const queued = persistQueue.then(write, write);
|
||||
persistQueue = queued.catch(() => undefined);
|
||||
await queued;
|
||||
}
|
||||
|
||||
async function writeDocument(document: PersistedDesktopSettingsDocument): Promise<void> {
|
||||
await mkdir(userDataPath, { recursive: true });
|
||||
const tempFilePath = `${filePath}.tmp.${process.pid}.${randomUUID()}`;
|
||||
await writeFile(tempFilePath, `${JSON.stringify(document, null, 2)}\n`, "utf8");
|
||||
await rename(tempFilePath, filePath);
|
||||
cachedDocument = document;
|
||||
}
|
||||
|
||||
async function loadDocumentUnlocked(): Promise<PersistedDesktopSettingsDocument> {
|
||||
async function loadDocument(): Promise<PersistedDesktopSettingsDocument> {
|
||||
if (cachedDocument) {
|
||||
return cachedDocument;
|
||||
}
|
||||
@@ -296,7 +260,7 @@ export function createDesktopSettingsStore({
|
||||
throw error;
|
||||
}
|
||||
const document = buildDefaultDocument();
|
||||
await writeDocument(document);
|
||||
await persistDocument(document);
|
||||
return document;
|
||||
}
|
||||
const document = coerceDocument(JSON.parse(raw));
|
||||
@@ -304,67 +268,58 @@ export function createDesktopSettingsStore({
|
||||
return document;
|
||||
}
|
||||
|
||||
async function initializeLegacyRendererMigrationUnlocked(): Promise<PersistedDesktopSettingsDocument> {
|
||||
async function initializeLegacyRendererMigration(): Promise<PersistedDesktopSettingsDocument> {
|
||||
try {
|
||||
return await loadDocumentUnlocked();
|
||||
return await loadDocument();
|
||||
} catch {
|
||||
const document = buildDefaultDocument();
|
||||
await writeDocument(document);
|
||||
await persistDocument(document);
|
||||
return document;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async get(): Promise<DesktopSettings> {
|
||||
const document = await enqueueOperation(async () => {
|
||||
if (cachedDocument) {
|
||||
return cachedDocument;
|
||||
}
|
||||
return loadDocumentUnlocked();
|
||||
});
|
||||
const document = await loadDocument();
|
||||
return toDesktopSettings(document.settings);
|
||||
},
|
||||
|
||||
async patch(patch: unknown): Promise<DesktopSettings> {
|
||||
return enqueueOperation(async () => {
|
||||
const current = await loadDocumentUnlocked();
|
||||
const coercedPatch = coerceDesktopSettingsPatch(patch);
|
||||
const next = mergeDesktopSettings(current.settings, coercedPatch);
|
||||
await writeDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported:
|
||||
current.migrations.legacyRendererSettingsImported ||
|
||||
hasLegacyRendererOwnedPatch(coercedPatch),
|
||||
},
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
const current = await loadDocument();
|
||||
const coercedPatch = coerceDesktopSettingsPatch(patch);
|
||||
const next = mergeDesktopSettings(current.settings, coercedPatch);
|
||||
await persistDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported:
|
||||
current.migrations.legacyRendererSettingsImported ||
|
||||
hasLegacyRendererOwnedPatch(coercedPatch),
|
||||
},
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
},
|
||||
|
||||
async migrateLegacyRendererSettings(legacySettings: unknown): Promise<DesktopSettings> {
|
||||
return enqueueOperation(async () => {
|
||||
const current = await initializeLegacyRendererMigrationUnlocked();
|
||||
if (current.migrations.legacyRendererSettingsImported) {
|
||||
return toDesktopSettings(current.settings);
|
||||
}
|
||||
const current = await initializeLegacyRendererMigration();
|
||||
if (current.migrations.legacyRendererSettingsImported) {
|
||||
return toDesktopSettings(current.settings);
|
||||
}
|
||||
|
||||
const next = mergeDesktopSettings(
|
||||
current.settings,
|
||||
pickDesktopSettingsFromLegacyRendererSettings(legacySettings),
|
||||
);
|
||||
await writeDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported: true,
|
||||
},
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
const next = mergeDesktopSettings(
|
||||
current.settings,
|
||||
pickDesktopSettingsFromLegacyRendererSettings(legacySettings),
|
||||
);
|
||||
await persistDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported: true,
|
||||
},
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,32 @@ export const GetDaemonConfigResponseMessageSchema = z.object({
|
||||
.passthrough(),
|
||||
});
|
||||
|
||||
const TailscaleStatusSchema = z.object({
|
||||
ip: z.string().nullable(),
|
||||
address: z.string().nullable(),
|
||||
state: z.enum(["unavailable", "off", "waiting", "on"]),
|
||||
lockedBy: z.enum(["main", "launch"]).optional(),
|
||||
// COMPAT(tailscale): keep lockedBy "main" for older clients when the main listener is a socket.
|
||||
mainIsSocket: z.literal(true).optional(),
|
||||
// Whether turning off Tailscale would disconnect the source of this request.
|
||||
disconnectsCurrentConnection: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const ExtraListenerStatusSchema = z.object({
|
||||
address: z.string(),
|
||||
state: z.enum(["waiting", "listening"]),
|
||||
});
|
||||
|
||||
export const DaemonTailscaleSetResponseSchema = z.object({
|
||||
type: z.literal("daemon.tailscale.set.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
confirmationRequired: z.boolean(),
|
||||
tailscale: TailscaleStatusSchema,
|
||||
extraListeners: z.array(ExtraListenerStatusSchema),
|
||||
}),
|
||||
});
|
||||
|
||||
export const DaemonGetStatusResponseSchema = z.object({
|
||||
type: z.literal("daemon.get_status.response"),
|
||||
payload: z
|
||||
@@ -5587,6 +5623,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 +7839,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
SendAgentMessageResponseMessageSchema,
|
||||
SetVoiceModeResponseMessageSchema,
|
||||
DaemonGetStatusResponseSchema,
|
||||
DaemonTailscaleSetResponseSchema,
|
||||
DaemonGetPairingOfferResponseSchema,
|
||||
DaemonConfigReloadResponseSchema,
|
||||
HubManagementDaemonConnectResponseSchema,
|
||||
@@ -8563,3 +8602,6 @@ export function parseServerInfoStatusPayload(payload: unknown): ServerInfoStatus
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
export type TailscaleStatus = z.infer<typeof TailscaleStatusSchema>;
|
||||
export type DaemonTailscaleSetResponse = z.infer<typeof DaemonTailscaleSetResponseSchema>;
|
||||
|
||||
@@ -1470,31 +1470,6 @@ describe("Codex app-server provider", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["thread/start", "thread/resume"] as const)(
|
||||
"%s appends plugin instructions to the developer instructions configured in Codex",
|
||||
async (method) => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"config/read": () => ({ config: { developer_instructions: "Configured role" } }),
|
||||
});
|
||||
const provider = createProviderWithFakeAppServer(appServer);
|
||||
const config = { pluginAppendSystemPrompt: ["Plugin instructions"] };
|
||||
const session =
|
||||
method === "thread/start"
|
||||
? await provider.createSession(createConfig(config))
|
||||
: await provider.resumeSession({ sessionId: "saved-thread" }, config);
|
||||
try {
|
||||
await session.startTurn("hello");
|
||||
await appServer.waitForTurnStart();
|
||||
expect(
|
||||
appServer.requests().find((request) => request.method === method)?.params,
|
||||
).toMatchObject({ developerInstructions: "Configured role\n\nPlugin instructions" });
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("reopen injects current instructions once, including an explicit empty snapshot", async () => {
|
||||
const handlers = {
|
||||
initialize: () => ({ userAgent: "codex/0.165.0" }),
|
||||
|
||||
@@ -57,7 +57,7 @@ import path from "node:path";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { z } from "zod";
|
||||
import { renderPromptAttachmentAsText } from "../prompt-attachments.js";
|
||||
import { composeAgentSystemPrompt, composeSystemPromptParts } from "../system-prompt.js";
|
||||
import { composeAgentSystemPrompt } from "../system-prompt.js";
|
||||
import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js";
|
||||
import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js";
|
||||
import {
|
||||
@@ -3797,7 +3797,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
private resolvedWorkspaceWrite: NonNullable<
|
||||
CodexProviderOptions["sandbox_workspace_write"]
|
||||
> | null = null;
|
||||
private configuredDeveloperInstructions: string | undefined;
|
||||
private resolvedSandboxPolicy: Record<string, unknown> | null = null;
|
||||
private currentThreadId: string | null = null;
|
||||
// Codex writes a new thread's rollout at its first turn. Until then the thread exists only
|
||||
@@ -4063,7 +4062,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
this.speedModels =
|
||||
CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? [];
|
||||
this.normalizeSpeed();
|
||||
await this.loadResolvedConfig();
|
||||
await this.loadResolvedWorkspaceWrite();
|
||||
await this.loadCollaborationModes();
|
||||
await this.loadSkills();
|
||||
|
||||
@@ -4094,7 +4093,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
private async loadResolvedConfig(): Promise<void> {
|
||||
private async loadResolvedWorkspaceWrite(): Promise<void> {
|
||||
if (!this.client) return;
|
||||
try {
|
||||
const response = toObjectRecord(
|
||||
@@ -4102,25 +4101,11 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
);
|
||||
const config = toObjectRecord(response?.config);
|
||||
this.resolvedWorkspaceWrite = readSandboxWorkspaceWrite(config?.sandbox_workspace_write);
|
||||
this.configuredDeveloperInstructions =
|
||||
typeof config?.developer_instructions === "string"
|
||||
? config.developer_instructions
|
||||
: undefined;
|
||||
} catch (error) {
|
||||
this.logger.debug({ error }, "Failed to read resolved Codex config");
|
||||
this.logger.debug({ error }, "Failed to read resolved Codex workspace-write config");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Codex uses a thread's developerInstructions in place of the developer_instructions in its
|
||||
* config, so Paseo's instructions carry the configured ones ahead of them.
|
||||
*/
|
||||
private threadDeveloperInstructions(): string | undefined {
|
||||
const paseoInstructions = composeAgentSystemPrompt(this.config);
|
||||
if (!paseoInstructions) return undefined;
|
||||
return composeSystemPromptParts(this.configuredDeveloperInstructions, paseoInstructions);
|
||||
}
|
||||
|
||||
private rememberResolvedSandboxPolicy(response: unknown): void {
|
||||
const sandbox = toObjectRecord(toObjectRecord(response)?.sandbox);
|
||||
this.resolvedSandboxPolicy = sandbox ?? null;
|
||||
@@ -4576,7 +4561,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
// the unnamespaced key emitted by earlier Paseo versions.
|
||||
params.modelProvider = this.deps.customCodexConfig.model_provider;
|
||||
}
|
||||
const developerInstructions = this.threadDeveloperInstructions();
|
||||
const developerInstructions = composeAgentSystemPrompt(this.config);
|
||||
if (developerInstructions) {
|
||||
params.developerInstructions = developerInstructions;
|
||||
}
|
||||
@@ -5541,7 +5526,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
model: this.config.model ?? null,
|
||||
serviceTier: this.serviceTier,
|
||||
config: this.buildCodexInnerConfig(),
|
||||
developerInstructions: this.threadDeveloperInstructions(),
|
||||
developerInstructions: composeAgentSystemPrompt(this.config),
|
||||
userMessageTurns: this.codexUserMessageTurns(),
|
||||
threadRollbackAvailable: this.threadRollbackAvailable,
|
||||
setThreadId: async (threadId) => {
|
||||
@@ -6097,7 +6082,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
const approvalPolicy = this.hasWorkflowModeOverride ? preset.approvalPolicy : undefined;
|
||||
const sandbox = this.hasWorkflowModeOverride ? preset.sandbox : undefined;
|
||||
const innerConfig = this.buildCodexInnerConfig();
|
||||
const developerInstructions = this.threadDeveloperInstructions();
|
||||
const developerInstructions = composeAgentSystemPrompt(this.config);
|
||||
const params: Record<string, unknown> = {
|
||||
model,
|
||||
cwd: this.config.cwd ?? null,
|
||||
|
||||
@@ -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,302 @@ describe("paseo daemon bootstrap", () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test("switches Tailscale live and requires confirmation from the extra listener", async () => {
|
||||
let tailscaleAddress: string | null = null;
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
relayEnabled: false,
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: tailscaleAddress ? [tailscaleAddress] : [],
|
||||
otherAddresses: new Set(),
|
||||
}),
|
||||
});
|
||||
const local = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const address = `127.0.0.2:${daemon.port}`;
|
||||
const remote = new DaemonClient({ url: `ws://${address}/ws` });
|
||||
|
||||
try {
|
||||
const configPath = path.join(daemon.paseoHome, "config.json");
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: 1, daemon: { listen: daemon.config.listen } }),
|
||||
);
|
||||
await local.connect();
|
||||
expect(local.getLastServerInfoMessage()?.features?.tailscale).toBe(true);
|
||||
const initial = await local.getDaemonStatus();
|
||||
expect(initial.tailscale?.state).toBe("unavailable");
|
||||
|
||||
tailscaleAddress = "127.0.0.2";
|
||||
expect((await local.getDaemonStatus()).tailscale?.state).toBe("off");
|
||||
expect(await local.setTailscaleEnabled(true)).toMatchObject({
|
||||
tailscale: { address, state: "on" },
|
||||
extraListeners: [{ address, state: "listening" }],
|
||||
});
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).daemon.listen).toBe(
|
||||
`${daemon.config.listen},${address}`,
|
||||
);
|
||||
|
||||
await remote.connect();
|
||||
expect(remote.getLastServerInfoMessage()?.serverId).toBe(initial.serverId);
|
||||
const [mainStatus, tailscaleStatus] = await Promise.all([
|
||||
local.getDaemonStatus({ includeProviders: false }),
|
||||
remote.getDaemonStatus({ includeProviders: false }),
|
||||
]);
|
||||
expect([mainStatus.tailscale, tailscaleStatus.tailscale]).toMatchObject([
|
||||
{ address, state: "on", disconnectsCurrentConnection: false },
|
||||
{ address, state: "on", disconnectsCurrentConnection: true },
|
||||
]);
|
||||
expect(await remote.setTailscaleEnabled(false)).toMatchObject({
|
||||
confirmationRequired: true,
|
||||
tailscale: tailscaleStatus.tailscale,
|
||||
});
|
||||
expect(await local.setTailscaleEnabled(true)).toMatchObject({
|
||||
confirmationRequired: false,
|
||||
tailscale: mainStatus.tailscale,
|
||||
});
|
||||
expect(await remote.setTailscaleEnabled(false, true)).toMatchObject({
|
||||
confirmationRequired: false,
|
||||
tailscale: { state: "off", disconnectsCurrentConnection: false },
|
||||
});
|
||||
await expect.poll(() => remote.isConnected).toBe(false);
|
||||
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).daemon.listen).toBe(
|
||||
daemon.config.listen,
|
||||
);
|
||||
expect(await local.getDaemonStatus()).toMatchObject({
|
||||
pid: initial.pid,
|
||||
listen: initial.listen,
|
||||
tailscale: { state: "off" },
|
||||
extraListeners: [],
|
||||
});
|
||||
} finally {
|
||||
await Promise.all([remote.close(), local.close()]);
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ condition: "the interface goes away", nextAddress: null, nextState: "unavailable" },
|
||||
{ condition: "the interface gets a new IP", nextAddress: "100.127.255.253", nextState: "off" },
|
||||
])(
|
||||
"turns off a saved Tailscale listener after $condition",
|
||||
async ({ nextAddress, nextState }) => {
|
||||
let tailscaleAddress: string | null = "100.127.255.254";
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
relayEnabled: false,
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: tailscaleAddress ? [tailscaleAddress] : [],
|
||||
otherAddresses: new Set(),
|
||||
}),
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const configPath = path.join(daemon.paseoHome, "config.json");
|
||||
const originalAddress = `100.127.255.254:${daemon.port}`;
|
||||
const unrelatedAddress = `127.0.0.3:${daemon.port}`;
|
||||
const originalListen = `${daemon.config.listen},${unrelatedAddress}`;
|
||||
const readListen = async () => JSON.parse(await readFile(configPath, "utf8")).daemon.listen;
|
||||
|
||||
try {
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: 1, daemon: { listen: originalListen } }),
|
||||
);
|
||||
await client.connect();
|
||||
await client.reloadDaemonConfig();
|
||||
await client.setTailscaleEnabled(true);
|
||||
expect(await readListen()).toBe(`${originalListen},${originalAddress}`);
|
||||
|
||||
tailscaleAddress = nextAddress;
|
||||
expect((await client.getDaemonStatus()).tailscale).toMatchObject({
|
||||
address: originalAddress,
|
||||
state: "waiting",
|
||||
});
|
||||
expect(await client.setTailscaleEnabled(false)).toMatchObject({
|
||||
tailscale: { address: null, state: nextState },
|
||||
extraListeners: [{ address: unrelatedAddress }],
|
||||
});
|
||||
expect(await readListen()).toBe(originalListen);
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("keeps Tailscale on its original port across a main port change", async () => {
|
||||
const tailscaleIp = "127.0.0.2";
|
||||
const carrierNatIp = "100.127.255.254";
|
||||
const dependencies = {
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: [tailscaleIp],
|
||||
otherAddresses: new Set([carrierNatIp]),
|
||||
}),
|
||||
};
|
||||
const original = await createTestPaseoDaemon({ ...dependencies, cleanup: false });
|
||||
const oldAddress = `${tailscaleIp}:${original.port}`;
|
||||
const first = new DaemonClient({ url: `ws://127.0.0.1:${original.port}/ws` });
|
||||
const configPath = path.join(original.paseoHome, "config.json");
|
||||
const persist = (listen: string) =>
|
||||
writeFile(configPath, JSON.stringify({ version: 1, daemon: { listen } }));
|
||||
const readListen = async () => JSON.parse(await readFile(configPath, "utf8")).daemon.listen;
|
||||
let restarted: Awaited<ReturnType<typeof createPaseoDaemon>> | undefined;
|
||||
let local: DaemonClient | undefined;
|
||||
let remote: DaemonClient | undefined;
|
||||
try {
|
||||
await first.connect();
|
||||
await first.setTailscaleEnabled(true);
|
||||
const [, savedExtra] = (await readListen()).split(",");
|
||||
expect(savedExtra).toBe(oldAddress);
|
||||
|
||||
const newPort = await findFreePort();
|
||||
const newMain = `127.0.0.1:${newPort}`;
|
||||
await persist(`${newMain},${savedExtra}`);
|
||||
await first.close();
|
||||
await original.close();
|
||||
restarted = await createPaseoDaemon(
|
||||
{ ...original.config, listen: loadConfig(original.paseoHome, { env: {} }).listen },
|
||||
pino({ level: "silent" }),
|
||||
{
|
||||
...dependencies,
|
||||
builtinPlugins: new BuiltinPluginLoader(undefined, []),
|
||||
lazyTerminalWorker: true,
|
||||
},
|
||||
);
|
||||
await restarted.start();
|
||||
|
||||
local = new DaemonClient({ url: `ws://${newMain}/ws` });
|
||||
remote = new DaemonClient({ url: `ws://${oldAddress}/ws` });
|
||||
await Promise.all([local.connect(), remote.connect()]);
|
||||
expect((await local.getDaemonStatus()).tailscale).toMatchObject({
|
||||
state: "on",
|
||||
address: oldAddress,
|
||||
});
|
||||
expect(await local.setTailscaleEnabled(true)).toMatchObject({
|
||||
extraListeners: [{ address: oldAddress, state: "listening" }],
|
||||
});
|
||||
expect(await readListen()).toBe(`${newMain},${oldAddress}`);
|
||||
|
||||
const anotherTailscale = `${tailscaleIp}:${newPort}`;
|
||||
const carrierNat = `${carrierNatIp}:${original.port}`;
|
||||
await persist(`${newMain},${oldAddress},${carrierNat},${anotherTailscale}`);
|
||||
await local.reloadDaemonConfig();
|
||||
expect((await fetch(`http://${anotherTailscale}/api/health`)).ok).toBe(true);
|
||||
expect((await local.getDaemonStatus()).tailscale?.address).toBe(oldAddress);
|
||||
expect(await remote.setTailscaleEnabled(false)).toMatchObject({
|
||||
confirmationRequired: true,
|
||||
tailscale: { state: "on", address: oldAddress },
|
||||
});
|
||||
expect(await remote.setTailscaleEnabled(false, true)).toMatchObject({
|
||||
confirmationRequired: false,
|
||||
tailscale: { state: "off" },
|
||||
extraListeners: [{ address: carrierNat }],
|
||||
});
|
||||
await expect.poll(() => remote.isConnected).toBe(false);
|
||||
await expect(fetch(`http://${anotherTailscale}/api/health`)).rejects.toThrow();
|
||||
expect(await readListen()).toBe(`${newMain},${carrierNat}`);
|
||||
} finally {
|
||||
await Promise.all([first.close(), local?.close(), remote?.close()]);
|
||||
if (restarted) await restarted.stop();
|
||||
else await original.close();
|
||||
await Promise.all([
|
||||
rm(path.dirname(original.paseoHome), { recursive: true, force: true }),
|
||||
rm(original.staticDir, { recursive: true, force: true }),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
test("reload changes only the extra TCP listeners without replacing the main endpoint", async () => {
|
||||
const daemon = await createTestPaseoDaemon({ relayEnabled: false, hostnames: [] });
|
||||
const local = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const address = `127.0.0.2:${daemon.port}`;
|
||||
const configPath = path.join(daemon.paseoHome, "config.json");
|
||||
try {
|
||||
await local.connect();
|
||||
const persist = (listen: string) =>
|
||||
writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: 1, daemon: { listen, relay: { enabled: false } } }),
|
||||
);
|
||||
await persist(`${daemon.config.listen},${address}`);
|
||||
expect(await local.reloadDaemonConfig()).toMatchObject({
|
||||
appliedPaths: expect.arrayContaining(["daemon.listen"]),
|
||||
restartRequiredPaths: [],
|
||||
});
|
||||
expect((await fetch(`http://${address}/api/health`)).ok).toBe(true);
|
||||
const rejectedHost = await new Promise<number | undefined>((resolve, reject) => {
|
||||
const request = http.get(
|
||||
`http://${address}/api/health`,
|
||||
{ headers: { host: "unlisted.example.test" } },
|
||||
(response) => {
|
||||
response.resume();
|
||||
resolve(response.statusCode);
|
||||
},
|
||||
);
|
||||
request.on("error", reject);
|
||||
});
|
||||
expect(rejectedHost).toBe(403);
|
||||
|
||||
await persist("127.0.0.3:0");
|
||||
expect(await local.reloadDaemonConfig()).toMatchObject({
|
||||
appliedPaths: expect.arrayContaining(["daemon.listen"]),
|
||||
restartRequiredPaths: ["daemon.listen"],
|
||||
});
|
||||
expect((await local.getDaemonStatus()).listen).toBe(`127.0.0.1:${daemon.port}`);
|
||||
await expect(fetch(`http://${address}/api/health`)).rejects.toThrow();
|
||||
} finally {
|
||||
await local.close();
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("switching Tailscale preserves unrelated live listeners and pending listen edits", async () => {
|
||||
const carrierNatIp = "100.127.255.254";
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
relayEnabled: false,
|
||||
getTailscaleNetwork: () => ({
|
||||
addresses: ["127.0.0.2"],
|
||||
otherAddresses: new Set([carrierNatIp]),
|
||||
}),
|
||||
});
|
||||
const tailscale = `127.0.0.2:${daemon.port}`;
|
||||
const live = `127.0.0.3:${daemon.port}`;
|
||||
const pending = `127.0.0.4:${daemon.port}`;
|
||||
const carrierNat = `${carrierNatIp}:${daemon.port}`;
|
||||
const local = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const other = new DaemonClient({ url: `ws://${live}/ws` });
|
||||
const configPath = path.join(daemon.paseoHome, "config.json");
|
||||
const persist = (listen: string) =>
|
||||
writeFile(configPath, JSON.stringify({ version: 1, daemon: { listen } }));
|
||||
try {
|
||||
await local.connect();
|
||||
await persist(`${daemon.config.listen},${live},${carrierNat}`);
|
||||
await local.reloadDaemonConfig();
|
||||
await other.connect();
|
||||
|
||||
// Leave another addition and removal pending in config.json across both toggles.
|
||||
await persist(`${daemon.config.listen},${carrierNat},${pending}`);
|
||||
expect(await local.setTailscaleEnabled(true)).toMatchObject({
|
||||
extraListeners: [{ address: live }, { address: carrierNat }, { address: tailscale }],
|
||||
});
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).daemon.listen).toBe(
|
||||
`${daemon.config.listen},${carrierNat},${pending},${tailscale}`,
|
||||
);
|
||||
|
||||
expect(await other.setTailscaleEnabled(false)).toMatchObject({
|
||||
confirmationRequired: false,
|
||||
extraListeners: [{ address: live }, { address: carrierNat }],
|
||||
});
|
||||
expect((await other.getDaemonStatus({ includeProviders: false })).tailscale?.state).toBe(
|
||||
"off",
|
||||
);
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).daemon.listen).toBe(
|
||||
`${daemon.config.listen},${carrierNat},${pending}`,
|
||||
);
|
||||
} finally {
|
||||
await Promise.all([other.close(), local.close()]);
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("starts and serves health endpoint", async () => {
|
||||
const daemonHandle = await createTestPaseoDaemon({
|
||||
openai: { stt: { apiKey: "test-openai-api-key" }, tts: { apiKey: "test-openai-api-key" } },
|
||||
@@ -930,6 +1226,47 @@ export default function contribute(plugin: unknown) {
|
||||
});
|
||||
});
|
||||
|
||||
test.skipIf(isPlatform("win32"))(
|
||||
"keeps network listeners closed when a socket daemon reloads a staged TCP main address",
|
||||
async () => {
|
||||
const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-socket-listen-"));
|
||||
const socketPath = path.join(paseoHome, "daemon.sock");
|
||||
const configPath = path.join(paseoHome, "config.json");
|
||||
const persist = (listen: string) =>
|
||||
writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: 1, daemon: { listen, relay: { enabled: false } } }),
|
||||
);
|
||||
await persist(socketPath);
|
||||
const config = loadConfig(paseoHome, { env: {} });
|
||||
config.agentClients = createTestAgentClients();
|
||||
const daemon = await createPaseoDaemon(config, pino({ level: "silent" }), {
|
||||
builtinPlugins: new BuiltinPluginLoader(undefined, []),
|
||||
lazyTerminalWorker: true,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws+unix://${socketPath}:/ws` });
|
||||
try {
|
||||
await daemon.start();
|
||||
await client.connect();
|
||||
const extra = `127.0.0.1:${await findFreePort()}`;
|
||||
await persist(`127.0.0.1:6767,${extra}`);
|
||||
expect(await client.reloadDaemonConfig()).toMatchObject({
|
||||
appliedPaths: [],
|
||||
restartRequiredPaths: ["daemon.listen"],
|
||||
});
|
||||
expect(await client.getDaemonStatus({ includeProviders: false })).toMatchObject({
|
||||
listen: socketPath,
|
||||
extraListeners: [],
|
||||
});
|
||||
await expect(fetch(`http://${extra}/api/health`)).rejects.toThrow();
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.stop();
|
||||
await rm(paseoHome, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// POSIX-only: Unix socket listen paths are invalid Windows listen targets.
|
||||
test.skipIf(isPlatform("win32"))(
|
||||
"generates a relay pairing offer for unix socket listeners",
|
||||
@@ -937,7 +1274,7 @@ export default function contribute(plugin: unknown) {
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-socket-relay-"));
|
||||
const paseoHome = path.join(paseoHomeRoot, ".paseo");
|
||||
const staticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-static-"));
|
||||
const socketPath = path.join(paseoHomeRoot, "run", "paseo.sock");
|
||||
const socketPath = path.join(paseoHomeRoot, "run", "paseo.sock,127.0.0.1:12345");
|
||||
await mkdir(path.dirname(socketPath), { recursive: true });
|
||||
await mkdir(paseoHome, { recursive: true });
|
||||
const logger = pino({ level: "silent" });
|
||||
@@ -967,6 +1304,7 @@ export default function contribute(plugin: unknown) {
|
||||
|
||||
try {
|
||||
await daemon.start();
|
||||
expect(daemon.getListenTarget()).toEqual({ type: "socket", path: socketPath });
|
||||
const pairing = await generateLocalPairingOffer({
|
||||
paseoHome,
|
||||
relayEnabled: true,
|
||||
|
||||
@@ -25,10 +25,16 @@ import type { Logger } from "pino";
|
||||
import { z } from "zod";
|
||||
import { createBranchChangeRouteHandler } from "./script-route-branch-handler.js";
|
||||
|
||||
export type ListenTarget =
|
||||
| { type: "tcp"; host: string; port: number }
|
||||
| { type: "socket"; path: string }
|
||||
| { type: "pipe"; path: string };
|
||||
import {
|
||||
createDaemonListeners,
|
||||
parseListenString,
|
||||
formatListenTarget,
|
||||
formatHostForHttpUrl,
|
||||
splitListen,
|
||||
type ListenTarget,
|
||||
type TailscaleNetwork,
|
||||
} from "./listeners.js";
|
||||
export { parseListenString, formatListenTarget, type ListenTarget } from "./listeners.js";
|
||||
|
||||
function resolveBoundListenTarget(
|
||||
listenTarget: ListenTarget,
|
||||
@@ -50,60 +56,6 @@ function resolveBoundListenTarget(
|
||||
};
|
||||
}
|
||||
|
||||
// Matches a Windows drive-letter path like C:\ or D:\
|
||||
const WINDOWS_DRIVE_RE = /^[A-Za-z]:\\/;
|
||||
|
||||
export function parseListenString(listen: string): ListenTarget {
|
||||
// 1. Windows named pipes: \\.\pipe\... or pipe://...
|
||||
if (listen.startsWith("\\\\.\\pipe\\") || listen.startsWith("pipe://")) {
|
||||
return {
|
||||
type: "pipe",
|
||||
path: listen.startsWith("pipe://") ? listen.slice("pipe://".length) : listen,
|
||||
};
|
||||
}
|
||||
// 2. Explicit unix:// prefix
|
||||
if (listen.startsWith("unix://")) {
|
||||
return { type: "socket", path: listen.slice(7) };
|
||||
}
|
||||
// 3. Reject Windows absolute drive paths — they are not Unix sockets
|
||||
if (WINDOWS_DRIVE_RE.test(listen)) {
|
||||
throw new Error(`Invalid listen string (Windows path is not a valid listen target): ${listen}`);
|
||||
}
|
||||
// 4. POSIX absolute path (/ or ~) — Unix socket
|
||||
if (listen.startsWith("/") || listen.startsWith("~")) {
|
||||
return { type: "socket", path: listen };
|
||||
}
|
||||
// 5. Pure numeric — TCP port on 127.0.0.1
|
||||
const trimmed = listen.trim();
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const port = parseInt(trimmed, 10);
|
||||
return { type: "tcp", host: "127.0.0.1", port };
|
||||
}
|
||||
// 6. host:port — TCP
|
||||
if (listen.includes(":")) {
|
||||
const lastColonIdx = listen.lastIndexOf(":");
|
||||
const host = listen.slice(0, lastColonIdx);
|
||||
const portStr = listen.slice(lastColonIdx + 1);
|
||||
const parsedPort = parseInt(portStr, 10);
|
||||
if (!Number.isFinite(parsedPort)) {
|
||||
throw new Error(`Invalid port in listen string: ${listen}`);
|
||||
}
|
||||
const cleanHost = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
||||
return { type: "tcp", host: cleanHost || "127.0.0.1", port: parsedPort };
|
||||
}
|
||||
throw new Error(`Invalid listen string: ${listen}`);
|
||||
}
|
||||
|
||||
export function formatListenTarget(listenTarget: ListenTarget | null): string | null {
|
||||
if (!listenTarget) {
|
||||
return null;
|
||||
}
|
||||
if (listenTarget.type === "tcp") {
|
||||
return `${formatHostForHttpUrl(listenTarget.host)}:${listenTarget.port}`;
|
||||
}
|
||||
return listenTarget.path;
|
||||
}
|
||||
|
||||
export async function fanOutReconciledWorkspaceUpdates(input: {
|
||||
sessions: Iterable<{
|
||||
syncWorkspaceGitObserversForExternalWorkspaceIds(workspaceIds: Iterable<string>): Promise<void>;
|
||||
@@ -173,6 +125,7 @@ import { DaemonConfigStore, type MutableDaemonConfig } from "./daemon-config-sto
|
||||
import { createOrchestrationSkills } from "./orchestration-skills/index.js";
|
||||
import {
|
||||
resolveReloadableConfig,
|
||||
resolveListenAddress,
|
||||
type ResolvedDaemonSettings,
|
||||
type CliConfigOverrides,
|
||||
} from "./config.js";
|
||||
@@ -269,10 +222,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 +470,7 @@ export interface PaseoDaemon {
|
||||
export interface PaseoDaemonDependencies {
|
||||
builtinPlugins?: BuiltinPluginLoader;
|
||||
lazyTerminalWorker?: boolean;
|
||||
getTailscaleNetwork?: () => TailscaleNetwork;
|
||||
hubRelationshipRemote?: HubRelationshipRemote;
|
||||
hubRelationshipClock?: HubRelationshipClock;
|
||||
hubRelationshipRetryPolicy?: HubRelationshipRetryPolicy;
|
||||
@@ -587,6 +537,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 +630,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 +687,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));
|
||||
@@ -798,17 +755,17 @@ export async function createPaseoDaemon(
|
||||
app.use(serviceProxy.middleware());
|
||||
|
||||
// Host allowlist / DNS rebinding protection (vite-like semantics).
|
||||
// For non-TCP (unix sockets), skip host validation.
|
||||
if (listenTarget.type === "tcp") {
|
||||
app.use((req, res, next) => {
|
||||
// Validate the accepted connection so extra TCP listeners also enforce the allowlist.
|
||||
app.use((req, res, next) => {
|
||||
if (req.socket.localPort !== undefined) {
|
||||
const hostHeader = typeof req.headers.host === "string" ? req.headers.host : undefined;
|
||||
if (!isHostnameAllowed(hostHeader, configuredHostnames)) {
|
||||
res.status(403).json({ error: "Invalid Host header" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
}
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
// CORS - allow same-origin + configured origins
|
||||
const fixedAllowedOrigins = [
|
||||
@@ -949,6 +906,14 @@ export async function createPaseoDaemon(
|
||||
});
|
||||
|
||||
const httpServer = createHTTPServer(app);
|
||||
const listeners = createDaemonListeners({
|
||||
http: httpServer,
|
||||
listen: config.listen,
|
||||
overridden: isListenOverridden(config),
|
||||
getMain: () => boundListenTarget,
|
||||
getTailscaleNetwork: dependencies.getTailscaleNetwork,
|
||||
});
|
||||
daemonConfigStore.attachListeners(listeners);
|
||||
|
||||
// Script proxy WebSocket upgrade handler — must be registered before the
|
||||
// VoiceAssistantWebSocketServer attaches its own "upgrade" listener so that
|
||||
@@ -1953,6 +1918,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 +1953,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 +2018,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 +2095,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();
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ export {
|
||||
editPersistedConfig,
|
||||
type PersistedConfig,
|
||||
} from "./persisted-config.js";
|
||||
export { getMainListenAddress } from "./listeners.js";
|
||||
|
||||
const DEFAULT_PORT = 6767;
|
||||
const DEFAULT_RELAY_ENDPOINT = "relay.paseo.sh:443";
|
||||
@@ -474,11 +475,11 @@ function resolveTrustedProxiesConfig(
|
||||
}
|
||||
|
||||
// PASEO_LISTEN can be:
|
||||
// - host:port (TCP)
|
||||
// - host:port (TCP), with optional comma-separated extra TCP listeners
|
||||
// - /path/to/socket (Unix socket)
|
||||
// - unix:///path/to/socket (Unix socket)
|
||||
// Default is TCP at 127.0.0.1:6767
|
||||
function resolveListenAddress(
|
||||
export function resolveListenAddress(
|
||||
env: NodeJS.ProcessEnv,
|
||||
cli: CliConfigOverrides | undefined,
|
||||
persisted: ReturnType<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,41 @@ export class DaemonConfigStore {
|
||||
);
|
||||
}
|
||||
|
||||
public attachListeners(listeners: ReturnType<typeof createDaemonListeners>) {
|
||||
this.listeners = listeners;
|
||||
}
|
||||
|
||||
public setTailscaleEnabled(
|
||||
enabled: boolean,
|
||||
localEndpoint: string | undefined,
|
||||
confirmed: boolean,
|
||||
) {
|
||||
return this.enqueue(async () => {
|
||||
const listeners = this.listeners;
|
||||
if (!listeners) throw new Error("Tailscale is unavailable");
|
||||
const persisted = await loadPersistedConfigAsync(this.paseoHome, this.logger);
|
||||
const change = listeners.prepareTailscaleChange(
|
||||
persisted.daemon?.listen,
|
||||
enabled,
|
||||
localEndpoint,
|
||||
confirmed,
|
||||
);
|
||||
if (change.confirmationRequired) {
|
||||
return { confirmationRequired: true, ...listeners.status(localEndpoint) };
|
||||
}
|
||||
await savePersistedConfigAsync(
|
||||
this.paseoHome,
|
||||
{
|
||||
...persisted,
|
||||
daemon: { ...persisted.daemon, listen: change.listen },
|
||||
},
|
||||
this.logger,
|
||||
);
|
||||
await change.apply();
|
||||
return { confirmationRequired: false, ...listeners.status(localEndpoint) };
|
||||
});
|
||||
}
|
||||
|
||||
public reload(): Promise<DaemonConfigReloadResult> {
|
||||
return this.enqueue(() => this.reloadPersisted());
|
||||
}
|
||||
@@ -609,8 +647,11 @@ export class DaemonConfigStore {
|
||||
)
|
||||
);
|
||||
});
|
||||
const listenChange = await this.listeners?.apply(resolved.listen ?? persisted.daemon?.listen);
|
||||
if (listenChange?.applied) appliedPaths.push("daemon.listen");
|
||||
const restartRequiredPaths = compactOwnedPaths(
|
||||
diffPaths(this.startupPersisted, persisted).filter((path) => {
|
||||
if (path === "daemon.listen" && listenChange) return false;
|
||||
if (path === "$schema" || path === "version") return false;
|
||||
if (RELOADABLE_PATHS.some((owner) => pathBelongsTo(path, owner))) return false;
|
||||
if (this.speechOwner && SPEECH_PERSISTED_PATHS.some((owner) => pathBelongsTo(path, owner)))
|
||||
@@ -620,6 +661,11 @@ export class DaemonConfigStore {
|
||||
[],
|
||||
);
|
||||
|
||||
if (listenChange?.restartRequired) {
|
||||
restartRequiredPaths.push("daemon.listen");
|
||||
restartRequiredPaths.sort();
|
||||
}
|
||||
|
||||
const removedProviders = Object.keys(this.current.providers).filter(
|
||||
(provider) => !(provider in desired.providers),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { createServer } from "node:http";
|
||||
import { createServer as createTcpServer } from "node:net";
|
||||
import { once } from "node:events";
|
||||
import { expect, test } from "vitest";
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
import {
|
||||
createDaemonListeners,
|
||||
createExtraListeners,
|
||||
inspectTailscaleNetwork,
|
||||
splitListen,
|
||||
} from "./listeners.js";
|
||||
|
||||
test.each([
|
||||
"/tmp/paseo,qa.sock",
|
||||
"unix:///tmp/paseo,127.0.0.1:12345",
|
||||
String.raw`\\.\pipe\paseo,qa`,
|
||||
String.raw`pipe://\\.\pipe\paseo,qa`,
|
||||
])("preserves the legacy socket or pipe path %s", (listen) => {
|
||||
expect(splitListen(listen)).toEqual([listen]);
|
||||
});
|
||||
|
||||
test("retries an occupied extra listener and serves the original HTTP handler", async () => {
|
||||
const blocker = createTcpServer().listen(0, "127.0.0.2");
|
||||
await once(blocker, "listening");
|
||||
const address = blocker.address();
|
||||
if (!address || typeof address === "string") throw new Error("Expected TCP");
|
||||
const extra = `127.0.0.2:${address.port}`;
|
||||
const http = createServer((_req, res) => res.end("shared"));
|
||||
const listeners = createExtraListeners(http, 25);
|
||||
try {
|
||||
await listeners.apply([extra]);
|
||||
expect(listeners.status()).toEqual([{ address: extra, state: "waiting" }]);
|
||||
await new Promise<void>((resolve) => blocker.close(() => resolve()));
|
||||
await expect.poll(() => listeners.status()).toEqual([{ address: extra, state: "listening" }]);
|
||||
expect(await (await fetch(`http://${extra}`)).text()).toBe("shared");
|
||||
await listeners.apply([]);
|
||||
expect(listeners.status()).toEqual([]);
|
||||
await expect(fetch(`http://${extra}`)).rejects.toThrow();
|
||||
} finally {
|
||||
await listeners.apply([]);
|
||||
blocker.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("requires a Tailscale interface name or IPv6 prefix alongside the IPv4 address", () => {
|
||||
function ipv4(address: string): NetworkInterfaceInfo {
|
||||
return {
|
||||
address,
|
||||
family: "IPv4",
|
||||
netmask: "255.255.255.255",
|
||||
internal: false,
|
||||
cidr: null,
|
||||
mac: "",
|
||||
};
|
||||
}
|
||||
expect(inspectTailscaleNetwork(() => ({ eth0: [ipv4("100.101.102.103")] }))).toEqual({
|
||||
addresses: [],
|
||||
otherAddresses: new Set(["100.101.102.103"]),
|
||||
});
|
||||
expect(inspectTailscaleNetwork(() => ({ tailscale0: [ipv4("100.101.102.103")] }))).toEqual({
|
||||
addresses: ["100.101.102.103"],
|
||||
otherAddresses: new Set(),
|
||||
});
|
||||
expect(
|
||||
inspectTailscaleNetwork(() => ({
|
||||
eth0: [ipv4("100.101.102.103")],
|
||||
utun4: [
|
||||
ipv4("100.120.121.122"),
|
||||
{
|
||||
address: "fd7a:115c:a1e0::123",
|
||||
family: "IPv6",
|
||||
netmask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||
cidr: null,
|
||||
internal: false,
|
||||
mac: "",
|
||||
scopeid: 0,
|
||||
},
|
||||
],
|
||||
})),
|
||||
).toEqual({ addresses: ["100.120.121.122"], otherAddresses: new Set(["100.101.102.103"]) });
|
||||
});
|
||||
|
||||
test.each(["100.101.102.103", "0.0.0.0"])(
|
||||
"recognizes Tailscale through main listener %s",
|
||||
(host) => {
|
||||
const listeners = createDaemonListeners({
|
||||
http: createServer(),
|
||||
listen: `${host}:6767`,
|
||||
overridden: false,
|
||||
getMain: () => ({ type: "tcp", host, port: 6767 }),
|
||||
getTailscaleNetwork: () => ({ addresses: ["100.101.102.103"], otherAddresses: new Set() }),
|
||||
});
|
||||
expect(listeners.status().tailscale).toMatchObject({
|
||||
state: "on",
|
||||
address: "100.101.102.103:6767",
|
||||
lockedBy: "main",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
{ type: "socket", path: "/tmp/paseo.sock" },
|
||||
{ type: "pipe", path: String.raw`\\.\pipe\paseo` },
|
||||
] as const)("reports a $type main listener separately from TCP", (main) => {
|
||||
const listeners = createDaemonListeners({
|
||||
http: createServer(),
|
||||
listen: main.path,
|
||||
overridden: false,
|
||||
getMain: () => main,
|
||||
getTailscaleNetwork: () => ({ addresses: ["100.101.102.103"], otherAddresses: new Set() }),
|
||||
});
|
||||
expect(listeners.status().tailscale).toMatchObject({
|
||||
state: "off",
|
||||
address: null,
|
||||
lockedBy: "main",
|
||||
mainIsSocket: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("shows the saved Tailscale listener waiting when the host has no Tailscale interface yet", async () => {
|
||||
const address = "100.127.255.254:6767";
|
||||
const listen = `127.0.0.1:6767,${address}`;
|
||||
const listeners = createDaemonListeners({
|
||||
http: createServer(),
|
||||
listen,
|
||||
overridden: false,
|
||||
getMain: () => ({ type: "tcp", host: "127.0.0.1", port: 6767 }),
|
||||
getTailscaleNetwork: () => ({ addresses: [], otherAddresses: new Set() }),
|
||||
});
|
||||
try {
|
||||
await listeners.apply(listen);
|
||||
expect(listeners.status()).toMatchObject({
|
||||
tailscale: { ip: null, address, state: "waiting" },
|
||||
extraListeners: [{ address, state: "waiting" }],
|
||||
});
|
||||
const change = listeners.prepareTailscaleChange(listen, false, undefined, false);
|
||||
expect(change).toMatchObject({ confirmationRequired: false, listen: "127.0.0.1:6767" });
|
||||
if (change.confirmationRequired) throw new Error("Unexpected confirmation");
|
||||
await change.apply();
|
||||
expect(listeners.status()).toMatchObject({
|
||||
tailscale: { ip: null, address: null, state: "unavailable" },
|
||||
extraListeners: [],
|
||||
});
|
||||
} finally {
|
||||
await listeners.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not count an extra listener on a non-Tailscale interface in the shared range", async () => {
|
||||
const address = "100.127.255.254";
|
||||
const endpoint = `${address}:6767`;
|
||||
const listen = `127.0.0.1:6767,${endpoint}`;
|
||||
const listeners = createDaemonListeners({
|
||||
http: createServer(),
|
||||
listen,
|
||||
overridden: false,
|
||||
getMain: () => ({ type: "tcp", host: "127.0.0.1", port: 6767 }),
|
||||
getTailscaleNetwork: () => ({ addresses: [], otherAddresses: new Set([address]) }),
|
||||
});
|
||||
try {
|
||||
await listeners.apply(listen);
|
||||
expect(listeners.status(endpoint)).toMatchObject({
|
||||
tailscale: {
|
||||
ip: null,
|
||||
address: null,
|
||||
state: "unavailable",
|
||||
disconnectsCurrentConnection: false,
|
||||
},
|
||||
extraListeners: [{ address: endpoint }],
|
||||
});
|
||||
} finally {
|
||||
await listeners.stop();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,337 @@
|
||||
import type { Server as HttpServer } from "node:http";
|
||||
import { createServer, isIPv4, type Socket } from "node:net";
|
||||
import { networkInterfaces } from "node:os";
|
||||
|
||||
export function formatHostForHttpUrl(host: string): string {
|
||||
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
}
|
||||
|
||||
export type ListenTarget =
|
||||
| { type: "tcp"; host: string; port: number }
|
||||
| { type: "socket"; path: string }
|
||||
| { type: "pipe"; path: string };
|
||||
|
||||
// Matches a Windows drive-letter path like C:\ or D:\
|
||||
const WINDOWS_DRIVE_RE = /^[A-Za-z]:\\/;
|
||||
|
||||
function parseSocketTarget(listen: string): ListenTarget | undefined {
|
||||
// Windows named pipes: \\.\pipe\... or pipe://...
|
||||
if (listen.startsWith("\\\\.\\pipe\\") || listen.startsWith("pipe://")) {
|
||||
return {
|
||||
type: "pipe",
|
||||
path: listen.startsWith("pipe://") ? listen.slice("pipe://".length) : listen,
|
||||
};
|
||||
}
|
||||
// Explicit unix:// prefix
|
||||
if (listen.startsWith("unix://")) {
|
||||
return { type: "socket", path: listen.slice(7) };
|
||||
}
|
||||
// POSIX absolute path (/ or ~) — Unix socket
|
||||
if (listen.startsWith("/") || listen.startsWith("~")) {
|
||||
return { type: "socket", path: listen };
|
||||
}
|
||||
}
|
||||
|
||||
export function parseListenString(listen: string): ListenTarget {
|
||||
const socket = parseSocketTarget(listen);
|
||||
if (socket) return socket;
|
||||
if (WINDOWS_DRIVE_RE.test(listen)) {
|
||||
throw new Error(`Invalid listen string (Windows path is not a valid listen target): ${listen}`);
|
||||
}
|
||||
// Pure numeric — TCP port on 127.0.0.1
|
||||
const trimmed = listen.trim();
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const port = parseInt(trimmed, 10);
|
||||
return { type: "tcp", host: "127.0.0.1", port };
|
||||
}
|
||||
// host:port — TCP
|
||||
if (listen.includes(":")) {
|
||||
const lastColonIdx = listen.lastIndexOf(":");
|
||||
const host = listen.slice(0, lastColonIdx);
|
||||
const portStr = listen.slice(lastColonIdx + 1);
|
||||
const parsedPort = parseInt(portStr, 10);
|
||||
if (!Number.isFinite(parsedPort)) {
|
||||
throw new Error(`Invalid port in listen string: ${listen}`);
|
||||
}
|
||||
const cleanHost = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
||||
return { type: "tcp", host: cleanHost || "127.0.0.1", port: parsedPort };
|
||||
}
|
||||
throw new Error(`Invalid listen string: ${listen}`);
|
||||
}
|
||||
|
||||
export function formatListenTarget(listenTarget: ListenTarget | null): string | null {
|
||||
if (!listenTarget) {
|
||||
return null;
|
||||
}
|
||||
if (listenTarget.type === "tcp") {
|
||||
return `${formatHostForHttpUrl(listenTarget.host)}:${listenTarget.port}`;
|
||||
}
|
||||
return listenTarget.path;
|
||||
}
|
||||
|
||||
export function splitListen(listen: string): [main: string, ...extras: string[]] {
|
||||
if (parseSocketTarget(listen)) return [listen];
|
||||
const [main = "", ...extras] = listen.split(",").map((entry) => entry.trim());
|
||||
for (const entry of extras) parseExtra(entry);
|
||||
return [main, ...new Set(extras)];
|
||||
}
|
||||
|
||||
export function getMainListenAddress(listen: string): string {
|
||||
return parseSocketTarget(listen) ? listen : listen.split(",", 1)[0].trim();
|
||||
}
|
||||
|
||||
function parseExtra(address: string) {
|
||||
const target = parseListenString(address);
|
||||
if (
|
||||
target.type !== "tcp" ||
|
||||
target.port < 1 ||
|
||||
target.port > 65535 ||
|
||||
!/^.+:\d+$/.test(address)
|
||||
) {
|
||||
throw new Error(`Invalid extra TCP listen address: ${address}`);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
export function createExtraListeners(http: HttpServer, retryMs = 2_000) {
|
||||
const active = new Map<string, ReturnType<typeof open>>();
|
||||
function open(address: string) {
|
||||
const { port, host } = parseExtra(address);
|
||||
const sockets = new Set<Socket>();
|
||||
let retry: ReturnType<typeof setTimeout> | undefined;
|
||||
let stopped = false;
|
||||
const server = createServer((socket) => {
|
||||
sockets.add(socket);
|
||||
socket.once("close", () => sockets.delete(socket));
|
||||
http.emit("connection", socket);
|
||||
});
|
||||
function listen() {
|
||||
return new Promise<void>((resolve) => {
|
||||
const settled = () => {
|
||||
server.off("listening", settled);
|
||||
server.off("error", settled);
|
||||
server.off("close", settled);
|
||||
resolve();
|
||||
};
|
||||
server.once("listening", settled);
|
||||
server.once("error", settled);
|
||||
server.once("close", settled);
|
||||
server.listen(port, host);
|
||||
});
|
||||
}
|
||||
server.on("error", () => {
|
||||
if (!stopped) retry = setTimeout(() => void listen(), retryMs).unref();
|
||||
});
|
||||
return {
|
||||
ready: listen(),
|
||||
state: () => (server.listening ? ("listening" as const) : ("waiting" as const)),
|
||||
close() {
|
||||
stopped = true;
|
||||
clearTimeout(retry);
|
||||
server.close();
|
||||
// Let the request that removed this listener queue its response first.
|
||||
setImmediate(() => {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
async apply(addresses: readonly string[]) {
|
||||
const desired = new Set(addresses);
|
||||
for (const [address, listener] of active) {
|
||||
if (desired.has(address)) continue;
|
||||
listener.close();
|
||||
active.delete(address);
|
||||
}
|
||||
for (const address of desired) {
|
||||
if (!active.has(address)) active.set(address, open(address));
|
||||
}
|
||||
await Promise.all(Array.from(active.values(), (listener) => listener.ready));
|
||||
},
|
||||
status() {
|
||||
return Array.from(active, ([address, listener]) => ({ address, state: listener.state() }));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function isTailnetIPv4(address: string) {
|
||||
const [first, second = ""] = address.split(".");
|
||||
return isIPv4(address) && first === "100" && Number(second) >= 64 && Number(second) <= 127;
|
||||
}
|
||||
|
||||
export interface TailscaleNetwork {
|
||||
addresses: readonly string[];
|
||||
otherAddresses: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
// A saved address can outlive its interface. An address assigned to a different
|
||||
// interface belongs to that interface even when it is in the shared IPv4 range.
|
||||
function isTailscaleListener(target: ReturnType<typeof parseExtra>, network: TailscaleNetwork) {
|
||||
return (
|
||||
!network.otherAddresses.has(target.host) &&
|
||||
(network.addresses.includes(target.host) || isTailnetIPv4(target.host))
|
||||
);
|
||||
}
|
||||
|
||||
export function inspectTailscaleNetwork(readInterfaces = networkInterfaces): TailscaleNetwork {
|
||||
const tailscaleAddresses: string[] = [];
|
||||
const otherAddresses = new Set<string>();
|
||||
for (const [name, addresses] of Object.entries(readInterfaces())) {
|
||||
if (!addresses) continue;
|
||||
const isTailscale =
|
||||
/^tailscale/i.test(name) ||
|
||||
addresses.some(({ address }) => address.toLowerCase().startsWith("fd7a:115c:a1e0:"));
|
||||
for (const { address } of addresses) {
|
||||
if (!isTailnetIPv4(address)) continue;
|
||||
if (isTailscale) tailscaleAddresses.push(address);
|
||||
else otherAddresses.add(address);
|
||||
}
|
||||
}
|
||||
return {
|
||||
addresses: tailscaleAddresses.filter((address) => !otherAddresses.has(address)),
|
||||
otherAddresses,
|
||||
};
|
||||
}
|
||||
|
||||
function mainTailscaleEndpoint(main: ListenTarget | null, addresses: readonly string[]) {
|
||||
if (main?.type !== "tcp") return null;
|
||||
if (addresses.includes(main.host)) return `${main.host}:${main.port}`;
|
||||
const [ip] = addresses;
|
||||
return ip && ["0.0.0.0", "::"].includes(main.host) ? `${ip}:${main.port}` : null;
|
||||
}
|
||||
|
||||
export function createDaemonListeners(options: {
|
||||
http: HttpServer;
|
||||
listen: string;
|
||||
overridden: boolean;
|
||||
getMain: () => ListenTarget | null;
|
||||
getTailscaleNetwork?: () => TailscaleNetwork;
|
||||
}) {
|
||||
const {
|
||||
http,
|
||||
listen,
|
||||
overridden,
|
||||
getMain,
|
||||
getTailscaleNetwork = inspectTailscaleNetwork,
|
||||
} = options;
|
||||
const [startupMain] = splitListen(listen);
|
||||
const extras = createExtraListeners(http);
|
||||
let stopped = false;
|
||||
|
||||
async function applyLive(addresses: readonly string[]) {
|
||||
if (!stopped) await extras.apply(addresses);
|
||||
}
|
||||
|
||||
function describeTailscale() {
|
||||
const main = getMain();
|
||||
const network = getTailscaleNetwork();
|
||||
const ip = network.addresses[0] ?? null;
|
||||
const extraListeners = extras.status();
|
||||
const configured = extraListeners.flatMap((listener) => {
|
||||
const target = parseExtra(listener.address);
|
||||
if (main?.type !== "tcp" || !isTailscaleListener(target, network)) return [];
|
||||
return [{ ...listener, target }];
|
||||
});
|
||||
const current = configured.find(
|
||||
({ state, target }) => state === "listening" && network.addresses.includes(target.host),
|
||||
);
|
||||
const shown = current ?? configured[0];
|
||||
const mainEndpoint = mainTailscaleEndpoint(main, network.addresses);
|
||||
const address = mainEndpoint ?? (shown ? formatListenTarget(shown.target) : null);
|
||||
let state: "on" | "off" | "waiting" | "unavailable" = ip ? "off" : "unavailable";
|
||||
if (shown) state = current ? "on" : "waiting";
|
||||
if (mainEndpoint) state = "on";
|
||||
|
||||
let lockedBy: "main" | "launch" | undefined;
|
||||
if (mainEndpoint || main?.type !== "tcp") lockedBy = "main";
|
||||
if (overridden) lockedBy = "launch";
|
||||
return {
|
||||
main,
|
||||
network,
|
||||
configured,
|
||||
tailscale: {
|
||||
ip,
|
||||
address,
|
||||
state,
|
||||
...(lockedBy ? { lockedBy } : {}),
|
||||
...(main && main.type !== "tcp" ? { mainIsSocket: true as const } : {}),
|
||||
},
|
||||
extraListeners,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status(localEndpoint?: string) {
|
||||
const { tailscale, configured, extraListeners } = describeTailscale();
|
||||
const disconnectsCurrentConnection =
|
||||
!tailscale.lockedBy &&
|
||||
configured.some(({ target }) => formatListenTarget(target) === localEndpoint);
|
||||
return {
|
||||
tailscale: { ...tailscale, disconnectsCurrentConnection },
|
||||
extraListeners,
|
||||
};
|
||||
},
|
||||
async apply(persisted: string | undefined) {
|
||||
const [main, ...addresses] = splitListen(overridden ? listen : (persisted ?? listen));
|
||||
const before = extras.status().map(({ address }) => address);
|
||||
const applicable = getMain()?.type === "tcp" ? addresses : [];
|
||||
await applyLive(applicable);
|
||||
return {
|
||||
restartRequired: main !== startupMain,
|
||||
applied: JSON.stringify(before) !== JSON.stringify(applicable),
|
||||
};
|
||||
},
|
||||
stop() {
|
||||
stopped = true;
|
||||
return extras.apply([]);
|
||||
},
|
||||
prepareTailscaleChange(
|
||||
persisted: string | undefined,
|
||||
enabled: boolean,
|
||||
localEndpoint: string | undefined,
|
||||
confirmed: boolean,
|
||||
) {
|
||||
const { main, network, tailscale, configured, extraListeners } = describeTailscale();
|
||||
if (stopped || tailscale.lockedBy || main?.type !== "tcp") {
|
||||
throw new Error("Tailscale listen address cannot be changed");
|
||||
}
|
||||
const [first, ...saved] = splitListen(persisted ?? listen);
|
||||
const live = extraListeners.map(({ address }) => address);
|
||||
if (enabled) {
|
||||
if (configured.length) {
|
||||
return {
|
||||
confirmationRequired: false as const,
|
||||
listen: persisted ?? listen,
|
||||
apply: () => Promise.resolve(),
|
||||
};
|
||||
}
|
||||
if (!tailscale.ip) throw new Error("Tailscale is not running");
|
||||
if (parseSocketTarget(first)) throw new Error("The configured main listener is a socket");
|
||||
const address = `${tailscale.ip}:${main.port}`;
|
||||
const add = (addresses: string[]) =>
|
||||
addresses.some((entry) => formatListenTarget(parseExtra(entry)) === address)
|
||||
? addresses
|
||||
: [...addresses, address];
|
||||
return {
|
||||
confirmationRequired: false as const,
|
||||
listen: [first, ...add(saved)].join(","),
|
||||
apply: () => applyLive(add(live)),
|
||||
};
|
||||
}
|
||||
if (
|
||||
!confirmed &&
|
||||
configured.some(({ target }) => formatListenTarget(target) === localEndpoint)
|
||||
) {
|
||||
return { confirmationRequired: true as const };
|
||||
}
|
||||
const removed = new Set(configured.map(({ address }) => address));
|
||||
const remaining = saved.filter((entry) => !isTailscaleListener(parseExtra(entry), network));
|
||||
return {
|
||||
confirmationRequired: false as const,
|
||||
listen: [first, ...remaining].join(","),
|
||||
apply: () => applyLive(live.filter((address) => !removed.has(address))),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -639,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 } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -14,14 +14,17 @@ import type { AgentClient, AgentProvider } from "../agent/agent-sdk-types.js";
|
||||
import { createTestAgentClients } from "./fake-agent-client.js";
|
||||
import type { PushNotificationSender } from "../push/index.js";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import type { TailscaleNetwork } from "../listeners.js";
|
||||
|
||||
interface TestPaseoDaemonOptions {
|
||||
daemonVersion?: string;
|
||||
desktopManaged?: boolean;
|
||||
downloadTokenTtlMs?: number;
|
||||
corsAllowedOrigins?: string[];
|
||||
hostnames?: PaseoDaemonConfig["hostnames"];
|
||||
listen?: string;
|
||||
listenPort?: number;
|
||||
getTailscaleNetwork?: () => TailscaleNetwork;
|
||||
logger?: Parameters<typeof createPaseoDaemon>[1];
|
||||
mcpEnabled?: boolean;
|
||||
mcpDebug?: boolean;
|
||||
@@ -110,6 +113,7 @@ export async function createTestPaseoDaemon(
|
||||
await prepareTestDaemonConfig(options);
|
||||
const logger = options.logger ?? pino({ level: "silent" });
|
||||
const daemon = await createPaseoDaemon(config, logger, {
|
||||
getTailscaleNetwork: options.getTailscaleNetwork,
|
||||
builtinPlugins: options.builtinPlugins ?? new BuiltinPluginLoader(undefined, []),
|
||||
lazyTerminalWorker: options.lazyTerminalWorker ?? true,
|
||||
serverFeatureOverrides: {
|
||||
@@ -195,7 +199,7 @@ async function prepareTestDaemonConfig(
|
||||
daemonVersion: options.daemonVersion,
|
||||
desktopManaged: options.desktopManaged,
|
||||
corsAllowedOrigins: options.corsAllowedOrigins ?? [],
|
||||
hostnames: true,
|
||||
hostnames: options.hostnames ?? true,
|
||||
mcpEnabled: options.mcpEnabled ?? true,
|
||||
staticDir,
|
||||
mcpDebug: options.mcpDebug ?? false,
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createTestPaseoDaemon } from "./paseo-daemon.js";
|
||||
|
||||
const [, , origin] = process.argv;
|
||||
if (!origin) throw new Error("Expected the app origin");
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
corsAllowedOrigins: [origin],
|
||||
getTailscaleNetwork: () => ({ addresses: ["127.0.0.2"], otherAddresses: new Set() }),
|
||||
});
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(daemon.paseoHome, "config.json"),
|
||||
JSON.stringify({ version: 1, daemon: { listen: `127.0.0.1:${daemon.port}` } }),
|
||||
);
|
||||
process.once("SIGTERM", async () => {
|
||||
await daemon.close();
|
||||
process.exit(0);
|
||||
});
|
||||
process.send?.({ port: daemon.port, serverId: daemon.daemon.getServerId() });
|
||||
} catch (error) {
|
||||
await daemon.close();
|
||||
throw error;
|
||||
}
|
||||
@@ -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 } : {}),
|
||||
|
||||
@@ -74,10 +74,23 @@ Runtime-safe settings include relay enablement, MCP settings, browser tools, hos
|
||||
|
||||
New homes keep relay disabled when you remove `daemon.relay.enabled`. A daemon whose config already omitted this field when it started keeps the legacy relay-enabled behavior for compatibility. Set `daemon.relay.enabled` explicitly when editing an older config.
|
||||
|
||||
Idle runtime cleanup, listen addresses, authentication, relay endpoints and TLS, worktree allocation, service-proxy addresses, the bundled web UI, logging, speech, voice, credentials, and local model settings require a restart. Reload applies other valid edits in the same file before reporting those paths.
|
||||
Idle runtime cleanup, the main listen address, authentication, relay endpoints and TLS, worktree allocation, service-proxy addresses, the bundled web UI, logging, speech, voice, credentials, and local model settings require a restart. Reload applies other valid edits in the same file before reporting those paths.
|
||||
|
||||
Deployment environment variables and legacy supervisor flags remain authoritative. Reload reports a changed file setting under `overrideControlledPaths` when a launch override prevents it from taking effect. This includes startup settings such as listen addresses, passwords, relay endpoints and TLS, service-proxy and web UI settings, logging, speech, and voice configuration. List settings such as hostnames and CORS origins still append across sources, so values from `config.json` continue to apply. Stop and relaunch the deployment without the override to make the file value authoritative.
|
||||
|
||||
## Listen addresses
|
||||
|
||||
Set `daemon.listen` to one TCP address or a comma-separated list of TCP addresses, such as
|
||||
`127.0.0.1:6767,100.101.102.103:6767`. A Unix socket or named pipe path is always one address, even
|
||||
if it contains a comma. `PASEO_LISTEN` and `--listen` accept the same forms.
|
||||
|
||||
The first address is the main listener. Restart after changing it. Run `paseo reload` to
|
||||
apply changes to extra TCP listeners while the daemon is running. The daemon retries
|
||||
extra addresses that are unavailable and reports their state in `paseo daemon status`.
|
||||
Removing an extra address disconnects clients using it.
|
||||
|
||||
Use a single address before downgrading to a daemon version that predates listen lists.
|
||||
|
||||
## Agent providers
|
||||
|
||||
Agent providers, both the first-class ones Paseo ships with and custom entries you add under `agents.providers`, are documented on their own page.
|
||||
|
||||
@@ -72,10 +72,22 @@ paseo daemon restart
|
||||
|
||||
当你删除 `daemon.relay.enabled` 时,新的主目录会保持中继关闭。如果 daemon 启动时其配置就已经省略了这个字段,它会为了兼容而保持旧版的中继开启行为。编辑较旧的配置时,请显式设置 `daemon.relay.enabled`。
|
||||
|
||||
空闲运行时清理、监听地址、身份验证、中继端点和 TLS、worktree 分配、服务代理地址、内置的 Web UI、日志、语音合成与识别、语音、凭据以及本地模型设置都需要重启。重新加载会先应用同一文件中的其他有效编辑,再报告这些路径。
|
||||
空闲运行时清理、主监听地址、身份验证、中继端点和 TLS、worktree 分配、服务代理地址、内置的 Web UI、日志、语音合成与识别、语音、凭据以及本地模型设置都需要重启。重新加载会先应用同一文件中的其他有效编辑,再报告这些路径。
|
||||
|
||||
部署环境变量和旧版进程管理器参数仍然具有最终决定权。当某个启动覆盖项阻止了文件中已更改的设置生效时,重新加载会在 `overrideControlledPaths` 下报告它。这包括启动设置,例如监听地址、密码、中继端点和 TLS、服务代理和 Web UI 设置、日志、语音合成与识别以及语音配置。主机名和 CORS 来源等列表设置仍然在各个来源之间追加,因此 `config.json` 中的值继续生效。要让文件中的值具有决定权,请停止该部署并在不带覆盖项的情况下重新启动。
|
||||
|
||||
## 监听地址 {#listen-addresses}
|
||||
|
||||
将 `daemon.listen` 设为一个 TCP 地址,或用逗号分隔多个 TCP 地址,例如
|
||||
`127.0.0.1:6767,100.101.102.103:6767`。Unix 套接字或命名管道的路径即使包含逗号,也始终是一个地址。
|
||||
`PASEO_LISTEN` 和 `--listen` 支持相同的格式。
|
||||
|
||||
第一个地址是主监听地址。更改后请重启 daemon。运行 `paseo reload`,即可在 daemon 运行时应用额外 TCP 监听地址的更改。
|
||||
daemon 会重试暂时不可用的额外地址,并在 `paseo daemon status` 中显示它们的状态。
|
||||
移除额外地址会断开使用该地址的客户端连接。
|
||||
|
||||
如果要降级到仅支持单个监听地址的 daemon 版本,请先将配置改为单个地址。
|
||||
|
||||
## Agent Provider {#agent-providers}
|
||||
|
||||
Agent Provider,包括 Paseo 自带的一等 Provider 和你在 `agents.providers` 下添加的自定义条目,都在单独的页面中介绍。
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user