mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 10:15:46 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1435b688d0 | ||
|
|
be6b5eb169 | ||
|
|
c0903be174 | ||
|
|
5238bfb641 | ||
|
|
90c8446fb8 | ||
|
|
717e75d032 | ||
|
|
62cdc2f2cf | ||
|
|
eaef730f1e | ||
|
|
f0bf09efee | ||
|
|
ad068bd21d | ||
|
|
25666d9172 | ||
|
|
6c237aabf1 | ||
|
|
22baf9e344 |
@@ -342,6 +342,8 @@ jobs:
|
||||
run: |
|
||||
npm run test:unit --workspace=@getpaseo/server -- \
|
||||
src/server/file-observer \
|
||||
src/server/workspace-reconciliation-observation.test.ts \
|
||||
src/utils/checkout-git-identity.test.ts \
|
||||
src/server/workspace-git-service.observation.test.ts \
|
||||
src/server/workspace-git-service.observation.integration.test.ts \
|
||||
--bail=1
|
||||
|
||||
@@ -38,9 +38,9 @@ on:
|
||||
- "true"
|
||||
- "false"
|
||||
rollout_hours:
|
||||
description: "Linear rollout duration in hours. Use 0 for instant rollout."
|
||||
description: "Rollout duration in hours: a 5% canary hold, then a ramp to 100%. Use 0 to admit everyone at once."
|
||||
required: false
|
||||
default: "36"
|
||||
default: "18"
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
@@ -51,7 +51,7 @@ env:
|
||||
SOURCE_TAG: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref_name }}
|
||||
CHECKOUT_REF: ${{ github.event_name == 'workflow_dispatch' && (github.event.inputs.checkout_ref || github.ref_name) || github.ref_name }}
|
||||
SHOULD_PUBLISH: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.publish != 'false' }}
|
||||
ROLLOUT_HOURS: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.rollout_hours || '36' }}
|
||||
ROLLOUT_HOURS: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.rollout_hours || '18' }}
|
||||
DESKTOP_PACKAGE_PATH: "packages/desktop"
|
||||
|
||||
jobs:
|
||||
|
||||
+13
-1
@@ -183,7 +183,7 @@ caller, child, and host into one watch.
|
||||
|
||||
Bootstrap restores these watches after repairing stale running records to `closed` and before opening
|
||||
ingress. Reading a closed child's result does not load its provider. A finish notification reports that
|
||||
the child's run has settled; the parent decides whether its task is complete. A child chosen for restart
|
||||
the child has settled (see below); the parent decides whether its task is complete. A child chosen for restart
|
||||
recovery is observed only after its resume was sent, so the parent never hears that it was closed
|
||||
in between. Archived or deleted parents suppress delivery;
|
||||
parent-owned creation watches also stop
|
||||
@@ -196,6 +196,18 @@ outstanding intent. A crash after successful dispatch but before removal commits
|
||||
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
|
||||
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
|
||||
A turn end is not always a settled child. When the child ends its turn with work that will start its
|
||||
next turn by itself, the caller gets one `message` notice ("ended its turn but is still working") and
|
||||
the subscription keeps following the child. That work is a running turn, queued messages, a pending
|
||||
provider wake-up (`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and
|
||||
one-shot wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats,
|
||||
recurring crons, change-request watches, and other daemon background items never count: they are
|
||||
external triggers, not work the caller is waiting for. While following, turn ends and work changes stay
|
||||
silent until nothing is pending, which sends `finished` and removes the subscription. `followingSince`
|
||||
is stored before the notice is sent, so restarts resume following without repeating it, and following
|
||||
ends after 24 hours with an "is still working" notice. Remote children and providers without the probe
|
||||
report their first turn end as `finished`.
|
||||
|
||||
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
|
||||
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
|
||||
A watched child that closes before its finish event also notifies the caller so delegated work cannot disappear silently during archive or workspace teardown.
|
||||
|
||||
@@ -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.
|
||||
|
||||
+4
-1
@@ -225,7 +225,10 @@ aborts the shared refresh signal at the deadline, and when it stops. Shutdown wa
|
||||
probes to settle before it shuts down provider clients, so a probe cannot start provider work,
|
||||
such as an OpenCode server, after its client has cleaned up. Providers name active catalog operations and
|
||||
finish subprocess, server, or session cleanup before rejecting. Timeout errors list the operations
|
||||
that were still active when the deadline expired.
|
||||
that were still active when the deadline expired. A plugin provider's connection is shared with its
|
||||
running sessions, so the bridge cannot close it at the deadline; it sends `request.cancel` for the
|
||||
abandoned request instead, and the provider stops that request's work
|
||||
([provider guide](../public-docs/plugins/providers.md#stop-a-request-paseo-cancels)).
|
||||
|
||||
Catalogue results stay cached by identity until a refresh or a change to that provider's configuration.
|
||||
Providers change their model lists on the server without a CLI update, so the daemon refreshes
|
||||
|
||||
+93
-31
@@ -48,7 +48,7 @@ the shipped source.
|
||||
The user decides when the changes on `main` warrant a release and how much risk it takes:
|
||||
|
||||
1. **Direct stable release** for a low-risk batch of polish and bug fixes. Stable desktop updates
|
||||
already ramp over 36 hours (see [Staged rollout](#staged-rollout-stable-channel)), and store
|
||||
start with a 5% canary and ramp over 18 hours (see [Staged rollout](#staged-rollout-stable-channel)), and store
|
||||
review often takes about a day, with no guaranteed timing.
|
||||
2. **Beta flow**, the default for changes that need testing. Release candidates on the `beta`
|
||||
channel. Each beta folds into the series' single changelog entry, publishes npm only on the
|
||||
@@ -324,11 +324,33 @@ Use the beta path when you need to:
|
||||
|
||||
## Staged rollout (stable channel)
|
||||
|
||||
Stable desktop releases go out via a linear time-based rollout for automatic update checks: 0% admitted when the updater manifests appear, 100% admitted 36 hours later, linear ramp in between. Manual checks bypass the rollout so a user can install immediately when they click **Check**. Beta releases bypass the rollout entirely — beta users always receive updates immediately.
|
||||
A stable desktop release reaches automatic updates in stages, so a bad release reaches few installs before you stop it. Each install decides locally from two fields in the release manifests, `releaseDate` and `rolloutHours`. No server tracks installs.
|
||||
|
||||
The rollout is driven by a `rolloutHours` field stamped into the GitHub Release manifests (`latest-mac.yml`, `latest-linux.yml`, `latest.yml`) by the `finalize-rollout` job in `desktop-release.yml`.
|
||||
| Stage | Rule |
|
||||
| -------------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| Canary | For the first 8 hours, 5% of installs are admitted. |
|
||||
| Ramp | From 8 hours to `rolloutHours` (18 by default), admission rises in a straight line from 5% to 100%. |
|
||||
| Check interval | An install asks GitHub for the latest release at most once every 6 hours. |
|
||||
| Cooldown | After an install updates, it skips paced releases for 72 hours. |
|
||||
| Staged update | An install that holds a downloaded update keeps it and does not download the paced release that follows. |
|
||||
|
||||
Desktop release builds now publish in two phases:
|
||||
A paced release is a stable release with `rolloutHours` above 0. When `rolloutHours` is under 16, the canary hold is half of `rolloutHours`.
|
||||
|
||||
Every release places each install at a new position in the rollout, so the canary group changes with each release. With one or two releases per day, an install updates at most once every 72 hours and skips the releases in between.
|
||||
|
||||
These paths skip the stages:
|
||||
|
||||
- A manual check (**Check**) always asks GitHub and always offers the latest release.
|
||||
- A release with `rolloutHours: 0` is an emergency release. Every install takes it at its next check, during a cooldown too, and it replaces a staged update.
|
||||
- The beta channel has no stages. A beta install takes each release at its next check.
|
||||
|
||||
The **Notify** update mode follows the same stages and prompts instead of downloading. **Off** makes no automatic requests.
|
||||
|
||||
`packages/desktop/src/features/app-update-rollout.ts` owns the curve. `app-update-pacing.ts` owns the check interval and the cooldown, and `app-update-service.ts` owns the staged update.
|
||||
|
||||
### How a release is published
|
||||
|
||||
The `finalize-rollout` job in `desktop-release.yml` stamps `releaseDate` and `rolloutHours` into the GitHub Release manifests (`latest-mac.yml`, `latest-linux.yml`, `latest.yml`). Desktop release builds publish in two phases:
|
||||
|
||||
- The GitHub Release stays a draft while platform build jobs upload the installers/packages (`.dmg`, `.zip`, `.exe`, `.AppImage`, etc.).
|
||||
- The final job merges and stamps every channel manifest, uploads them with the final `releaseDate` and `rolloutHours`, then publishes the GitHub Release.
|
||||
@@ -338,20 +360,20 @@ 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.
|
||||
the desktop release workflow, which sets an 18-hour rollout when it publishes the release.
|
||||
|
||||
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.
|
||||
The `rollout_hours` input on `desktop-release.yml` is read only on `workflow_dispatch`. Tag-push runs always use 18. To get any other rollout duration on a fresh release, use the post-publish flip below.
|
||||
|
||||
### Instant-admit release (rollout_hours=0)
|
||||
### Emergency 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.
|
||||
Release to publish, then update the manifests to admit everyone at once.
|
||||
|
||||
```bash
|
||||
# 1. 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.
|
||||
# 2. Flip the published manifests to an emergency release.
|
||||
gh workflow run desktop-rollout.yml \
|
||||
-f tag=v0.1.64 \
|
||||
-f rollout_hours=0
|
||||
@@ -359,23 +381,13 @@ gh workflow run desktop-rollout.yml \
|
||||
|
||||
Dispatch only after `finalize-rollout` has published the release. Until then the release is a draft, and a draft has no tag: `desktop-rollout.yml` looks the release up by tag and fails with `release not found`. The concurrency group `desktop-rollout-<tag>` that the two workflows share orders them only once both are queued; it does not hold an early dispatch until the draft is published.
|
||||
|
||||
The first public manifests carry `rolloutHours=36` for the minutes between publish and the flip. The renderer polls every 30 minutes, so active stable users pick up the new manifest on their next check.
|
||||
The first public manifests carry `rolloutHours=18` for the minutes between publish and the flip. An install sees the flip at its next check, which is up to 6 hours after its previous one. In automatic mode it then downloads the release and installs it when the app quits.
|
||||
|
||||
### Adjusting an already-published release
|
||||
|
||||
To change the rollout duration on a release that's already shipped — e.g. flip a hotfix to instant admit, or slow a release down — use the dedicated `desktop-rollout.yml` workflow. It edits the manifests in place on the GitHub release without rebuilding anything. It only rewrites `rolloutHours`; `releaseDate` is preserved, so the rollout clock keeps ticking from the original publish time.
|
||||
To change the rollout duration on a release that already shipped, use the `desktop-rollout.yml` workflow. It edits the manifests in place on the GitHub release without rebuilding anything. It rewrites only `rolloutHours`. `releaseDate` is preserved, so the rollout clock keeps running from the original publish time.
|
||||
|
||||
**Hotfix (instant admit) on an already-shipped release:**
|
||||
|
||||
```bash
|
||||
gh workflow run desktop-rollout.yml \
|
||||
-f tag=v0.1.42 \
|
||||
-f rollout_hours=0
|
||||
```
|
||||
|
||||
`rollout_hours=0` admits 100% of stable users on their next update check (within ~30 min for active clients).
|
||||
|
||||
**Slow a rollout down** (e.g. extend total duration to 72h since the original release):
|
||||
To slow a rollout down, for example to 72 hours since the original release:
|
||||
|
||||
```bash
|
||||
gh workflow run desktop-rollout.yml \
|
||||
@@ -383,13 +395,59 @@ gh workflow run desktop-rollout.yml \
|
||||
-f rollout_hours=72
|
||||
```
|
||||
|
||||
`rollout_hours` is **total duration since the original release date**, not "extend by N more hours from now." If `v0.1.42` was published 2h ago and you set `rollout_hours=72`, the ramp finishes 70h from now.
|
||||
`rollout_hours` is the total duration since the original release date. If `v0.1.42` was published 2 hours ago and you set `rollout_hours=72`, the ramp finishes 70 hours from now.
|
||||
|
||||
A longer rollout does not stop a release. The canary group still updates. To stop a release, [halt it](#halt-a-release).
|
||||
|
||||
The dispatch is idempotent and shares the `desktop-rollout-<tag>` concurrency group with `desktop-release.yml`'s `finalize-rollout` job, so it serializes safely against an in-flight tag-push pipeline targeting the same release.
|
||||
|
||||
### Halt a release
|
||||
|
||||
Stable installs and the download page follow the release that GitHub marks as latest. To stop a release, mark the last good release as latest:
|
||||
|
||||
```bash
|
||||
# v0.1.41 is the last good release.
|
||||
gh release edit v0.1.41 --latest
|
||||
|
||||
# Prints v0.1.41 when the halt is in effect.
|
||||
gh api repos/getpaseo/paseo/releases/latest --jq .tag_name
|
||||
```
|
||||
|
||||
The halt applies to every stable install from its next check, including installs older than the staged rollout:
|
||||
|
||||
- An install that has not downloaded the halted release no longer sees it.
|
||||
- An install that downloaded it asks GitHub again before it installs at quit, and drops the download.
|
||||
- An install that already runs the halted release stays on it, because the app never downgrades. [Ship a fix](#fix-a-bad-release).
|
||||
|
||||
A halt does not reach the beta channel. Beta installs read the release list by date and still take the halted release.
|
||||
|
||||
To resume a halted release, run `gh release edit v0.1.42 --latest` with its tag.
|
||||
|
||||
### Fix a bad release
|
||||
|
||||
1. [Halt](#halt-a-release) the bad release.
|
||||
2. Ship the fix as the next patch with the [standard stable release procedure](#standard-release-stable).
|
||||
3. After Desktop Release publishes the fix, make sure that GitHub marks it as latest:
|
||||
|
||||
```bash
|
||||
gh api repos/getpaseo/paseo/releases/latest --jq .tag_name
|
||||
```
|
||||
|
||||
If the command prints another tag, run `gh release edit <fix-tag> --latest`.
|
||||
|
||||
4. Flip the fix to an [emergency release](#emergency-release-rollout_hours0):
|
||||
|
||||
```bash
|
||||
gh workflow run desktop-rollout.yml \
|
||||
-f tag=<fix-tag> \
|
||||
-f rollout_hours=0
|
||||
```
|
||||
|
||||
Do not leave the fix as a paced release. The installs that took the bad release are in their 72-hour cooldown and skip a paced release. An install that holds the bad release as a staged update, and did not check during the halt, keeps it when a paced release follows. An emergency release reaches both.
|
||||
|
||||
### Custom ramp on a manually-dispatched build
|
||||
|
||||
`desktop-release.yml` accepts `rollout_hours` only on `workflow_dispatch`, which is the path used to **rebuild an existing tag** (retry a failed release, force a rebuild on a different ref). When you go that route, you can stamp a non-default ramp directly:
|
||||
`desktop-release.yml` accepts `rollout_hours` only on `workflow_dispatch`, which is the path used to rebuild an existing tag (retry a failed release, force a rebuild on a different ref). On that path, you can stamp a different ramp directly:
|
||||
|
||||
```bash
|
||||
gh workflow run desktop-release.yml \
|
||||
@@ -397,14 +455,18 @@ 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)
|
||||
For a fresh release with a custom ramp, follow the [emergency release procedure](#emergency-release-rollout_hours0)
|
||||
and set `rollout_hours` to your chosen duration.
|
||||
|
||||
### Releasing during an active rollout
|
||||
|
||||
If you ship N+1 while N is still ramping, N+1 starts a fresh rollout from its own publish timestamp. N's rollout effectively ends — the newer manifest supersedes it. Rollout-aware clients revalidate the manifest for up to five seconds before installing a downloaded update on quit. If N+1 has replaced N but the client is not admitted to N+1 yet, it skips the downloaded N and waits rather than installing two updates in succession. If revalidation times out, the app exits without installing the cached update.
|
||||
If you ship N+1 while N is still ramping, N+1 starts a new rollout from its own publish time, and the rollout of N ends because installs no longer see its manifests.
|
||||
|
||||
If N+1 is a hotfix for a bug in N, dispatch `desktop-rollout.yml -f tag=v0.1.<N+1> -f rollout_hours=0` after N+1 publishes so the users who already got N reach the fix fast.
|
||||
An install that holds N as a staged update keeps N when N+1 is a paced release, and installs N when the app quits. It then waits out its cooldown before it takes a later paced release. The hold covers only paced patch releases that the install saw one after the other. If the install missed a release, it evaluates the newest release instead: it replaces N when it is admitted, and drops N when it is not.
|
||||
|
||||
A minor or major release always ends the hold. The version numbers do not show whether a fix shipped between `0.17.4` and `0.18.0`, so the install treats `0.18.0` as if it missed a release.
|
||||
|
||||
Before an install at quit, the app asks GitHub for the latest release for up to five seconds. If that check does not finish in time, the app exits without installing the staged update.
|
||||
|
||||
### macOS system floor
|
||||
|
||||
@@ -417,10 +479,10 @@ macOS 13 maps to Darwin 22. The two values use different version domains; do not
|
||||
|
||||
### Limitations
|
||||
|
||||
- **No pause / kill switch.** To stop new admissions, ship a superseding release. Clients revalidate on quit and will not install the superseded download, but a client that already completed installation cannot be recalled; ship a hotfix `+1` patch.
|
||||
- **No rollback.** `allowDowngrade = false`. Bad release = ship a hotfix.
|
||||
- **Bootstrap caveat.** Clients running a build older than the rollout feature ignore `rolloutHours` and admit immediately. Rollout protection only applies to clients running the rollout-aware version or later.
|
||||
- **Up to ~30 min automatic admission latency.** Renderer polls every 30 minutes, so a stable user may take up to that long to be evaluated against the rollout window. Clicking **Check** is manual and bypasses rollout admission.
|
||||
- A release cannot be recalled from an install that runs it. `allowDowngrade` is `false`. [Halt](#halt-a-release) the release to protect the other installs, then [ship a fix](#fix-a-bad-release).
|
||||
- An emergency release reaches a running install at its next check, up to 6 hours after its previous one. A manual check sees it at once.
|
||||
- Installs older than the canary and cooldown build have neither. They ramp in a straight line over `rolloutHours` and check every 30 minutes. Installs older than the staged rollout ignore `rolloutHours` and update at once.
|
||||
- The app window starts every automatic check. A release whose window does not load cannot update itself, and its users must download a new build from the website. Smoke the packaged app before you publish.
|
||||
|
||||
## Mobile builds (EAS)
|
||||
|
||||
|
||||
+17
-4
@@ -202,10 +202,23 @@ owner wraps cached preparation, network catch-up, accepted timeline application,
|
||||
behind one interface. React supplies transport and projection operations without selecting a cache
|
||||
path or issuing a separate persistence notification.
|
||||
|
||||
Active-agent list reconciliation does not own transcript lifetime. An archived agent's fresh
|
||||
history response can arrive before the active-list response that omits it. Clearing history there
|
||||
would discard accepted rows while the viewed owner still considers them synchronized. Entity
|
||||
deletion clears the transcript; list membership changes do not.
|
||||
The viewed-timeline owner also owns how long a transcript stays in memory. An active agent's
|
||||
transcript stays resident while its chat is hidden, so switching back to it needs no fetch. An
|
||||
archived agent's transcript stays resident only while its chat is shown, for example when it is
|
||||
opened from History. When an agent is archived, or the active list drops it because its workspace
|
||||
was archived, the owner releases the transcript unless the chat is shown. It also releases the
|
||||
transcript when the chat stops being shown. A released chat leaves the opened chats. When it is
|
||||
shown again, it reads the replica cache and catches up again. A history page, live event, or cache
|
||||
read that arrives after the release is dropped.
|
||||
|
||||
The active-list reconciliation does not release transcripts itself. An archived agent's fresh
|
||||
history response can arrive before the active-list response that omits it, while the chat is
|
||||
open in History. Clearing history there would discard rows the user is reading.
|
||||
|
||||
An agent counts as archived when the active list omits it, when its row has an archive timestamp,
|
||||
or when the workspace list omits its workspace. The workspace check matters because a workspace
|
||||
archive can complete while one of its agents keeps a row with no archive timestamp. Until a list
|
||||
first hydrates, it marks no agent as archived. Deleting the agent clears the transcript.
|
||||
|
||||
Removing the host from the registry is the destructive boundary: it stops the runtime and clears the
|
||||
session and host-scoped setup state together.
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
|
||||
sha256-6XXAVBTH6rIdg5eQ9cUeUwV22ikVqTtdWo7i9DYO+/M=
|
||||
|
||||
Generated
+1
@@ -40625,6 +40625,7 @@
|
||||
"p-limit": "^7.3.0",
|
||||
"p-memoize": "^8.0.0",
|
||||
"p-throttle": "^8.1.0",
|
||||
"parse5": "^7.3.0",
|
||||
"pino": "^10.2.0",
|
||||
"pino-pretty": "^13.1.3",
|
||||
"qrcode": "^1.5.4",
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
closeRelayPairing,
|
||||
emptyHome,
|
||||
loadingScreen,
|
||||
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,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,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);
|
||||
@@ -118,9 +119,8 @@ export function SettingsRowHeader({
|
||||
</View>
|
||||
) : null}
|
||||
<View style={[contentStyle, 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} />
|
||||
@@ -293,7 +293,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,8 +11,13 @@ 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;
|
||||
};
|
||||
@@ -24,12 +29,16 @@ 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,
|
||||
},
|
||||
@@ -149,13 +158,24 @@ 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"
|
||||
@@ -181,6 +201,10 @@ function mergeDesktopSettings(
|
||||
): DesktopSettings {
|
||||
return {
|
||||
releaseChannel: updates.releaseChannel ?? current.releaseChannel,
|
||||
updates: {
|
||||
...current.updates,
|
||||
...updates.updates,
|
||||
},
|
||||
notifications: {
|
||||
...current.notifications,
|
||||
...updates.notifications,
|
||||
@@ -195,6 +219,7 @@ 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,6 +128,43 @@ 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 }));
|
||||
@@ -340,6 +377,55 @@ 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");
|
||||
@@ -462,6 +548,47 @@ 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,6 +1,7 @@
|
||||
import type {
|
||||
DesktopAppUpdateCheckResult,
|
||||
DesktopAppUpdateCheckIntent,
|
||||
DesktopAppUpdateDownloadProgress,
|
||||
DesktopAppUpdateInstallResult,
|
||||
DesktopReleaseChannel,
|
||||
} from "@/desktop/updates/desktop-updates";
|
||||
@@ -21,6 +22,7 @@ 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;
|
||||
@@ -53,6 +55,7 @@ export interface DesktopAppUpdaterDeps {
|
||||
export interface DesktopAppUpdater {
|
||||
getSnapshot(): DesktopAppUpdaterSnapshot;
|
||||
subscribe(listener: () => void): () => void;
|
||||
setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void;
|
||||
checkForUpdates(options?: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
intent?: DesktopAppUpdateCheckIntent;
|
||||
@@ -66,6 +69,7 @@ export interface DesktopAppUpdater {
|
||||
interface InternalState {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
@@ -76,6 +80,7 @@ interface InternalState {
|
||||
const INITIAL_STATE: InternalState = {
|
||||
status: "idle",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
errorMessage: null,
|
||||
installMessage: null,
|
||||
lastCheckedAt: null,
|
||||
@@ -87,6 +92,7 @@ function buildSnapshot(state: InternalState): DesktopAppUpdaterSnapshot {
|
||||
return {
|
||||
status: state.status,
|
||||
availableUpdate: state.availableUpdate,
|
||||
downloadProgress: state.downloadProgress,
|
||||
errorMessage: state.errorMessage,
|
||||
installMessage: state.installMessage,
|
||||
lastCheckedAt: state.lastCheckedAt,
|
||||
@@ -102,9 +108,113 @@ 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;
|
||||
@@ -113,79 +223,45 @@ 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 i18n.t("desktop.updates.status.installing");
|
||||
return formatInstallingStatusText({ availableUpdate, downloadProgress, formatVersion });
|
||||
}
|
||||
|
||||
if (status === "up-to-date") {
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.upToDate");
|
||||
return lastCheckedAt != null
|
||||
? i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
})
|
||||
: i18n.t("desktop.updates.status.upToDate");
|
||||
}
|
||||
|
||||
if (status === "pending") {
|
||||
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");
|
||||
return formatPendingStatusText({
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (status === "available") {
|
||||
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");
|
||||
return formatAvailableStatusText({
|
||||
availableUpdate,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
});
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -202,6 +278,16 @@ 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;
|
||||
@@ -211,7 +297,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
return null;
|
||||
}
|
||||
const { releaseChannel, intent = "manual", silent = false } = options;
|
||||
if (silent && state.status === "checking") {
|
||||
if (silent && (state.status === "checking" || state.isInstalling)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -241,6 +327,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
...state,
|
||||
status: "error",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
errorMessage: result.errorMessage,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
@@ -248,24 +335,13 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
return 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;
|
||||
}
|
||||
const outcome = resolveCheckOutcome(result);
|
||||
|
||||
commit({
|
||||
...state,
|
||||
status: nextStatus,
|
||||
availableUpdate: nextAvailable,
|
||||
status: outcome.status,
|
||||
availableUpdate: outcome.availableUpdate,
|
||||
downloadProgress: outcome.status === "pending" ? state.downloadProgress : null,
|
||||
errorMessage: null,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
@@ -284,6 +360,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: message,
|
||||
lastCheckedAt: intent === "manual" ? deps.now() : state.lastCheckedAt,
|
||||
});
|
||||
@@ -295,6 +372,10 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
async function installUpdate(options: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
}): Promise<DesktopAppUpdateInstallResult | null> {
|
||||
if (state.isInstalling) {
|
||||
return null;
|
||||
}
|
||||
|
||||
commit({
|
||||
...state,
|
||||
status: "installing",
|
||||
@@ -307,10 +388,23 @@ 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,
|
||||
@@ -326,6 +420,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: message,
|
||||
isInstalling: false,
|
||||
});
|
||||
@@ -341,6 +436,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
setDownloadProgress,
|
||||
checkForUpdates,
|
||||
installUpdate,
|
||||
};
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
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;
|
||||
@@ -17,6 +27,7 @@ export interface DesktopAppUpdateInstallResult {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
message: string;
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
||||
export interface DesktopRuntimeInfo {
|
||||
@@ -115,9 +126,13 @@ 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: result.hasUpdate === true,
|
||||
readyToInstall: result.readyToInstall === true,
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading:
|
||||
typeof result.downloading === "boolean" ? result.downloading : hasUpdate && !readyToInstall,
|
||||
currentVersion: toStringOrNull(result.currentVersion),
|
||||
latestVersion: toStringOrNull(result.latestVersion),
|
||||
body: toStringOrNull(result.body),
|
||||
@@ -126,6 +141,36 @@ 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,
|
||||
}: {
|
||||
@@ -136,10 +181,12 @@ 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,6 +76,50 @@ 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,8 +1,10 @@
|
||||
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 }
|
||||
| { kind: "available"; versionLabel: string | null; readyToInstall?: boolean }
|
||||
| { kind: "downloading"; versionLabel: string | null; percent: number }
|
||||
| { kind: "installing" }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
@@ -31,7 +33,8 @@ export interface ResolveUpdateCalloutInput {
|
||||
isDesktopApp: boolean;
|
||||
status: DesktopAppUpdateStatus;
|
||||
isInstalling: boolean;
|
||||
availableUpdate: { latestVersion?: string | null } | null;
|
||||
availableUpdate: { latestVersion?: string | null; readyToInstall?: boolean } | null;
|
||||
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
}
|
||||
|
||||
@@ -40,6 +43,59 @@ 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 {
|
||||
@@ -50,26 +106,22 @@ 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 ?? null;
|
||||
const latestVersion =
|
||||
input.availableUpdate?.latestVersion ?? input.downloadProgress?.version ?? null;
|
||||
const dismissalKey = `desktop-update:${input.status}:${latestVersion ?? "unknown"}`;
|
||||
|
||||
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 { title, body } = resolveCalloutPresentation({
|
||||
isError,
|
||||
isInstalling,
|
||||
readyToInstall,
|
||||
latestVersion,
|
||||
downloadProgress: input.downloadProgress,
|
||||
errorMessage: input.errorMessage,
|
||||
});
|
||||
|
||||
const actions: UpdateCalloutActionDescriptor[] = [
|
||||
{ role: "changelog", label: i18n.t("desktop.updates.callout.whatsNew") },
|
||||
@@ -79,9 +131,7 @@ export function resolveUpdateCalloutDescriptor(
|
||||
} else {
|
||||
actions.push({
|
||||
role: "install",
|
||||
label: isInstalling
|
||||
? i18n.t("desktop.updates.callout.installingAction")
|
||||
: i18n.t("desktop.updates.callout.installAndRestart"),
|
||||
label: resolveInstallActionLabel({ isDownloading, isInstalling, readyToInstall }),
|
||||
variant: "primary",
|
||||
disabled: isInstalling,
|
||||
});
|
||||
|
||||
@@ -34,9 +34,12 @@ type InstallOutcome =
|
||||
function buildCheckResult(
|
||||
overrides: Partial<DesktopAppUpdateCheckResult> = {},
|
||||
): DesktopAppUpdateCheckResult {
|
||||
const hasUpdate = overrides.hasUpdate ?? false;
|
||||
const readyToInstall = overrides.readyToInstall ?? false;
|
||||
return {
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading: overrides.downloading ?? (hasUpdate && !readyToInstall),
|
||||
currentVersion: null,
|
||||
latestVersion: null,
|
||||
body: null,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Gift } from "lucide-react-native";
|
||||
import { type ReactNode, useEffect, useRef } from "react";
|
||||
import { type ReactNode, useEffect, useMemo, useRef } from "react";
|
||||
import { View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useUnistyles } from "react-native-unistyles";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
type SidebarCalloutAction,
|
||||
SidebarCalloutDescriptionText,
|
||||
@@ -19,9 +20,24 @@ 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} t={t} />;
|
||||
return (
|
||||
<UpdateAvailableDescription
|
||||
versionLabel={body.versionLabel ?? undefined}
|
||||
readyToInstall={body.readyToInstall !== false}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function materializeActions(
|
||||
@@ -42,8 +58,11 @@ export function UpdateCalloutSource() {
|
||||
const { theme } = useUnistyles();
|
||||
const {
|
||||
isDesktopApp,
|
||||
updateMode,
|
||||
isLoadingSettings,
|
||||
status,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
checkForUpdates,
|
||||
installUpdate,
|
||||
@@ -58,7 +77,7 @@ export function UpdateCalloutSource() {
|
||||
void checkForUpdates();
|
||||
});
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp) return;
|
||||
if (!isDesktopApp || isLoadingSettings || updateMode === "off") return;
|
||||
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
|
||||
@@ -71,7 +90,7 @@ export function UpdateCalloutSource() {
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
};
|
||||
}, [isDesktopApp, checkForUpdates]);
|
||||
}, [isDesktopApp, isLoadingSettings, updateMode, checkForUpdates]);
|
||||
|
||||
useEffect(() => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor({
|
||||
@@ -79,6 +98,7 @@ export function UpdateCalloutSource() {
|
||||
status,
|
||||
isInstalling,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
});
|
||||
if (!descriptor) return;
|
||||
@@ -103,6 +123,7 @@ export function UpdateCalloutSource() {
|
||||
}, [
|
||||
availableUpdate,
|
||||
callouts,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
install,
|
||||
isDesktopApp,
|
||||
@@ -117,23 +138,94 @@ 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>
|
||||
{versionLabel
|
||||
? t("desktop.updates.callout.versionReady", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionReady")}
|
||||
</SidebarCalloutDescriptionText>
|
||||
<SidebarCalloutDescriptionText>{summary}</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,30 +1,94 @@
|
||||
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import {
|
||||
checkDesktopAppUpdate,
|
||||
formatVersionWithPrefix,
|
||||
installDesktopAppUpdate,
|
||||
shouldShowDesktopUpdateSection,
|
||||
subscribeDesktopAppUpdateDownloadProgress,
|
||||
type DesktopAppUpdateCheckResult,
|
||||
type DesktopAppUpdateCheckIntent,
|
||||
type DesktopAppUpdateDownloadProgress,
|
||||
type DesktopAppUpdateInstallResult,
|
||||
} from "@/desktop/updates/desktop-updates";
|
||||
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopSettings, type DesktopUpdateMode } 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;
|
||||
@@ -38,22 +102,15 @@ export interface UseDesktopAppUpdaterReturn {
|
||||
|
||||
export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
const isDesktopApp = shouldShowDesktopUpdateSection();
|
||||
const { settings: desktopSettings } = useDesktopSettings();
|
||||
const { settings: desktopSettings, isLoading: isLoadingSettings } = useDesktopSettings();
|
||||
const releaseChannel = desktopSettings.releaseChannel;
|
||||
const updateMode = desktopSettings.updates.mode;
|
||||
const reportError = useDesktopIpcErrorReporter();
|
||||
const updater = getSharedDesktopAppUpdater();
|
||||
|
||||
const updater = useMemo(
|
||||
() =>
|
||||
createDesktopAppUpdater({
|
||||
port: {
|
||||
checkDesktopAppUpdate,
|
||||
installDesktopAppUpdate,
|
||||
},
|
||||
now: () => Date.now(),
|
||||
reportInstallError: reportError,
|
||||
}),
|
||||
[reportError],
|
||||
);
|
||||
useEffect(() => {
|
||||
activeInstallErrorReporter = reportError;
|
||||
}, [reportError]);
|
||||
|
||||
const snapshot = useSyncExternalStore(
|
||||
updater.subscribe,
|
||||
@@ -84,13 +141,20 @@ 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]);
|
||||
}, [checkForUpdates, isDesktopApp, isLoadingSettings, updateMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp || snapshot.status !== "pending") {
|
||||
if (!isDesktopApp || snapshot.status !== "pending" || updateMode === "off") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -101,20 +165,24 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
return () => {
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [checkForUpdates, isDesktopApp, snapshot.status]);
|
||||
}, [checkForUpdates, isDesktopApp, snapshot.status, updateMode]);
|
||||
|
||||
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,6 +32,9 @@ export interface FakeDesktopBridge extends DesktopSettingsBridge {
|
||||
|
||||
const DEFAULT_DESKTOP: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
|
||||
@@ -656,6 +656,7 @@ describe("loadSettingsFromStorage", () => {
|
||||
isElectron: true,
|
||||
settings: {
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true },
|
||||
},
|
||||
|
||||
@@ -1550,6 +1550,8 @@ export const ar: TranslationResources = {
|
||||
status: {
|
||||
checking: "جارٍ التحقق من وجود تحديثات للتطبيق...",
|
||||
installing: "جارٍ تثبيت تحديث التطبيق...",
|
||||
downloadingVersionProgress: "جارٍ تنزيل {{version}}... {{percent}}%",
|
||||
downloadingProgress: "جارٍ تنزيل تحديث التطبيق... {{percent}}%",
|
||||
upToDate: "التطبيق محدث.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "سنخبرك عندما يصبح التحديث جاهزًا.",
|
||||
@@ -1557,6 +1559,14 @@ 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: "تحديث التطبيق جاهز للتثبيت.",
|
||||
@@ -1567,14 +1577,21 @@ 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: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.",
|
||||
@@ -1791,12 +1808,6 @@ export const ar: TranslationResources = {
|
||||
"يتيح لك تطبيق الجوال الأصلي كامل الميزات التحكم في أي كمبيوتر يعمل عليه Paseo من هاتفك",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "اختر طريقة الاتصال",
|
||||
connectDocs: "الوثائق",
|
||||
openConnectDocs: "افتح وثائق الاتصال",
|
||||
recommended: "موصى به",
|
||||
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
|
||||
tailscale: { title: "Tailscale", hint: "يتطلب بعض الإعداد" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1875,6 +1886,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}}",
|
||||
@@ -2656,9 +2693,28 @@ 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: "تثبيت التحديث",
|
||||
@@ -2929,9 +2985,7 @@ export const ar: TranslationResources = {
|
||||
timeout: "نفذ الوقت",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "إقران الأجهزة",
|
||||
rowTitle: "إقران جهاز",
|
||||
rowHint: "امسح رمز QR ضوئيًا أو انسخ رابطًا لتوصيل هاتفك بهذا المضيف",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1577,6 +1577,8 @@ 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.",
|
||||
@@ -1585,6 +1587,14 @@ 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.",
|
||||
@@ -1595,14 +1605,21 @@ 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.",
|
||||
@@ -1820,12 +1837,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" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1904,6 +1915,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}}",
|
||||
@@ -2752,9 +2790,28 @@ 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",
|
||||
@@ -3024,9 +3081,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",
|
||||
|
||||
@@ -1587,6 +1587,8 @@ 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.",
|
||||
@@ -1595,6 +1597,16 @@ 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}}.",
|
||||
@@ -1607,14 +1619,21 @@ 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:
|
||||
@@ -1839,12 +1858,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" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1923,6 +1936,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}}",
|
||||
@@ -2677,9 +2717,28 @@ 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",
|
||||
@@ -2953,9 +3012,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,
|
||||
|
||||
@@ -1580,6 +1580,8 @@ 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.",
|
||||
@@ -1588,6 +1590,16 @@ 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}}.",
|
||||
@@ -1600,14 +1612,21 @@ 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:
|
||||
@@ -1837,12 +1856,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" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1921,6 +1934,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}}",
|
||||
@@ -2677,9 +2716,28 @@ 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",
|
||||
@@ -2955,9 +3013,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,
|
||||
|
||||
@@ -1565,6 +1565,8 @@ export const ja: TranslationResources = {
|
||||
status: {
|
||||
checking: "アプリの更新を確認中...",
|
||||
installing: "アプリの更新をインストール中...",
|
||||
downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%",
|
||||
downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%",
|
||||
upToDate: "アプリは最新です。",
|
||||
upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。",
|
||||
pending: "更新の準備ができたらお知らせします。",
|
||||
@@ -1572,6 +1574,15 @@ 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}}。",
|
||||
@@ -1583,14 +1594,21 @@ 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:
|
||||
@@ -1811,12 +1829,6 @@ export const ja: TranslationResources = {
|
||||
"フル機能のネイティブモバイルアプリで、スマートフォンからどの Paseo コンピューターでも操作できます",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "接続方法を選択",
|
||||
connectDocs: "ドキュメント",
|
||||
openConnectDocs: "接続のドキュメントを開く",
|
||||
recommended: "おすすめ",
|
||||
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
|
||||
tailscale: { title: "Tailscale", hint: "少し設定が必要です" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1895,6 +1907,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}} のパスワード",
|
||||
@@ -2644,9 +2682,28 @@ 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: "更新をインストール",
|
||||
@@ -2921,9 +2978,7 @@ export const ja: TranslationResources = {
|
||||
timeout: "タイムアウト",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "デバイスをペアリング",
|
||||
rowTitle: "デバイスをペアリング",
|
||||
rowHint: "QRコードをスキャンするかリンクをコピーしてスマートフォンをこのホストに接続",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1556,6 +1556,8 @@ export const ko: TranslationResources = {
|
||||
status: {
|
||||
checking: "앱 업데이트 확인 중...",
|
||||
installing: "앱 업데이트 설치 중...",
|
||||
downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%",
|
||||
downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%",
|
||||
upToDate: "앱이 최신 상태입니다.",
|
||||
upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.",
|
||||
pending: "업데이트가 준비되면 알려드리겠습니다.",
|
||||
@@ -1564,6 +1566,15 @@ 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}}에서 마지막으로 확인했습니다.",
|
||||
@@ -1576,14 +1587,21 @@ 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: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.",
|
||||
@@ -1802,12 +1820,6 @@ export const ko: TranslationResources = {
|
||||
"모든 기능을 갖춘 네이티브 모바일 앱으로 휴대폰에서 어떤 Paseo 컴퓨터든 제어할 수 있습니다",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "연결 방법 선택",
|
||||
connectDocs: "문서",
|
||||
openConnectDocs: "연결 문서 열기",
|
||||
recommended: "권장",
|
||||
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
||||
tailscale: { title: "Tailscale", hint: "약간의 설정이 필요합니다" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1886,6 +1898,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}}의 비밀번호",
|
||||
@@ -2634,9 +2672,28 @@ 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: "업데이트 설치",
|
||||
@@ -2907,9 +2964,7 @@ export const ko: TranslationResources = {
|
||||
timeout: "시간 초과",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "기기 페어링",
|
||||
rowTitle: "기기 페어링",
|
||||
rowHint: "QR 코드를 스캔하거나 링크를 복사하여 휴대폰을 이 호스트에 연결하세요",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
|
||||
@@ -1577,6 +1577,8 @@ 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.",
|
||||
@@ -1585,6 +1587,15 @@ 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}}.",
|
||||
@@ -1597,14 +1608,21 @@ 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:
|
||||
@@ -1824,12 +1842,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" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1908,6 +1920,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}}",
|
||||
@@ -2659,9 +2698,28 @@ 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",
|
||||
@@ -2934,9 +2992,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,
|
||||
|
||||
@@ -1571,6 +1571,8 @@ export const ru: TranslationResources = {
|
||||
status: {
|
||||
checking: "Проверка обновлений приложения...",
|
||||
installing: "Установка обновления приложения...",
|
||||
downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Загрузка обновления приложения... {{percent}}%",
|
||||
upToDate: "Установлена последняя версия приложения.",
|
||||
upToDateWithLastChecked:
|
||||
"Установлена последняя версия приложения. Последняя проверка: {{time}}.",
|
||||
@@ -1580,6 +1582,15 @@ 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}}.",
|
||||
@@ -1592,14 +1603,21 @@ 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:
|
||||
@@ -1824,12 +1842,6 @@ export const ru: TranslationResources = {
|
||||
"Полнофункциональное нативное мобильное приложение позволяет управлять любым компьютером с Paseo с телефона",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Выберите способ подключения",
|
||||
connectDocs: "Документация",
|
||||
openConnectDocs: "Открыть документацию по подключению",
|
||||
recommended: "Рекомендуется",
|
||||
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
|
||||
tailscale: { title: "Tailscale", hint: "Требует небольшой настройки" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1908,6 +1920,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}}",
|
||||
@@ -2666,9 +2704,28 @@ 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: "Установить обновление",
|
||||
@@ -2942,10 +2999,7 @@ export const ru: TranslationResources = {
|
||||
timeout: "Время ожидания истекло",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Подключение устройств",
|
||||
rowTitle: "Подключить устройство",
|
||||
rowHint:
|
||||
"Отсканируйте QR-код или скопируйте ссылку, чтобы подключить телефон к этому хосту.",
|
||||
},
|
||||
skills: {
|
||||
sectionTitle: "Навыки оркестрации",
|
||||
|
||||
@@ -1537,6 +1537,8 @@ export const zhCN: TranslationResources = {
|
||||
status: {
|
||||
checking: "正在检查 app 更新...",
|
||||
installing: "正在安装 app 更新...",
|
||||
downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%",
|
||||
downloadingProgress: "正在下载 app 更新... {{percent}}%",
|
||||
upToDate: "App 已是最新版本。",
|
||||
upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。",
|
||||
pending: "更新准备好后会通知你。",
|
||||
@@ -1544,6 +1546,14 @@ 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 更新可安装。",
|
||||
@@ -1554,14 +1564,21 @@ 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 会话。",
|
||||
@@ -1773,12 +1790,6 @@ export const zhCN: TranslationResources = {
|
||||
description: "功能完整的原生移动应用让你可以在手机上控制任意一台 Paseo 电脑",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "选择连接方式",
|
||||
connectDocs: "文档",
|
||||
openConnectDocs: "打开连接文档",
|
||||
recommended: "推荐",
|
||||
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
|
||||
tailscale: { title: "Tailscale", hint: "需要一些设置" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1857,6 +1868,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}} 的密码",
|
||||
@@ -2593,9 +2630,28 @@ 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: "安装更新",
|
||||
@@ -2863,9 +2919,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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -201,15 +201,9 @@ export class AgentStoreProjection {
|
||||
useDraftStore.getState().clearDraftInput({
|
||||
draftKey: buildDraftStoreKey({ serverId: this.serverId, agentId }),
|
||||
});
|
||||
// Only entity deletion destroys the transcript. A filtered active-list
|
||||
// response can arrive after a fresh history response for an archived agent.
|
||||
const store = useSessionStore.getState();
|
||||
const removeKey = withoutAgent(agentId);
|
||||
store.setAgentTimelineCursor(this.serverId, removeKey);
|
||||
store.setAgentTimelineUnsettledTurn(this.serverId, agentId, null);
|
||||
store.setAgentAuthoritativeHistoryApplied(this.serverId, agentId, false);
|
||||
store.setAgentStreamTail(this.serverId, removeKey);
|
||||
store.clearAgentStreamHead(this.serverId, agentId);
|
||||
// Leaving the active list does not release the transcript: an archived chat open in
|
||||
// History stays readable. The viewed timeline owner releases it once nobody shows it.
|
||||
useSessionStore.getState().releaseAgentTimeline(this.serverId, agentId);
|
||||
}
|
||||
|
||||
archive(agentId: string, archivedAt: string): Agent | null {
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ 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";
|
||||
@@ -102,7 +103,7 @@ import {
|
||||
} from "@/i18n/locales";
|
||||
import {
|
||||
HostConnectionsPage,
|
||||
HostPairDevicePage,
|
||||
HostDevicesPage,
|
||||
HostAgentsPage,
|
||||
HostAgentProfilesPage,
|
||||
HostSettingsPage,
|
||||
@@ -250,7 +251,7 @@ const HOST_SECTION_ITEMS: HostSectionItem[] = [
|
||||
{ id: "host", labelKey: "settings.hostSections.host", icon: Server },
|
||||
{ id: "projects", labelKey: "settings.hostSections.projects", icon: FolderGit2 },
|
||||
{ id: "connections", labelKey: "settings.hostSections.connections", icon: Network },
|
||||
{ id: "pair-device", labelKey: "openProject.tiles.pairDevice.title", icon: Smartphone },
|
||||
{ id: "devices", labelKey: "devices.title", icon: Smartphone },
|
||||
{ id: "agents", labelKey: "settings.hostSections.agents", icon: Bot },
|
||||
{ id: "agent-profiles", labelKey: "settings.hostSections.agentProfiles", icon: Layers },
|
||||
{ id: "metadata", labelKey: "settings.hostSections.metadata", icon: Sparkles },
|
||||
@@ -271,8 +272,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 "agent-profiles":
|
||||
@@ -616,25 +617,92 @@ function HostVersionRow({
|
||||
|
||||
function getUpdateButtonLabel(
|
||||
t: TFunction,
|
||||
isInstalling: boolean,
|
||||
latestVersion: string | null | undefined,
|
||||
input: {
|
||||
isInstalling: boolean;
|
||||
isDownloading: boolean;
|
||||
isActionable: boolean;
|
||||
readyToInstall: boolean;
|
||||
latestVersion: string | null | undefined;
|
||||
},
|
||||
): string {
|
||||
if (isInstalling) return t("settings.about.updates.installing");
|
||||
if (latestVersion) {
|
||||
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) {
|
||||
return t("settings.about.updates.updateTo", {
|
||||
version: formatVersionWithPrefix(latestVersion),
|
||||
version: formatVersionWithPrefix(input.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,
|
||||
@@ -644,12 +712,12 @@ function DesktopAppUpdateRow() {
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!isDesktopApp) {
|
||||
if (!isDesktopApp || isLoadingDesktopSettings || updateMode === "off") {
|
||||
return undefined;
|
||||
}
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
return undefined;
|
||||
}, [checkForUpdates, isDesktopApp]),
|
||||
}, [checkForUpdates, isDesktopApp, isLoadingDesktopSettings, updateMode]),
|
||||
);
|
||||
|
||||
const handleCheckForUpdates = useCallback(() => {
|
||||
@@ -673,17 +741,36 @@ 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({
|
||||
title: t("settings.about.updates.installTitle"),
|
||||
message: t("settings.about.updates.installMessage"),
|
||||
confirmLabel: t("settings.about.updates.installConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
})
|
||||
void confirmDialog(getUpdateConfirmDialogCopy(t, isUpdateReady))
|
||||
.then((confirmed) => {
|
||||
if (!confirmed) {
|
||||
return;
|
||||
@@ -698,10 +785,7 @@ function DesktopAppUpdateRow() {
|
||||
t("settings.about.updates.alertMessage"),
|
||||
);
|
||||
});
|
||||
}, [installUpdate, isDesktopApp, t]);
|
||||
|
||||
const isUpdateReady = availableUpdate?.readyToInstall === true;
|
||||
const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null;
|
||||
}, [installUpdate, isDesktopApp, isUpdateReady, t]);
|
||||
|
||||
if (!isDesktopApp) {
|
||||
return null;
|
||||
@@ -722,6 +806,18 @@ 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>
|
||||
@@ -733,6 +829,7 @@ function DesktopAppUpdateRow() {
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
{downloadPercent !== null ? <DesktopUpdateProgressBar percent={downloadPercent} /> : null}
|
||||
{errorMessage ? <Text style={styles.aboutErrorText}>{errorMessage}</Text> : null}
|
||||
</View>
|
||||
<View style={styles.aboutUpdateActions}>
|
||||
@@ -746,9 +843,15 @@ function DesktopAppUpdateRow() {
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={handleInstallUpdate}
|
||||
disabled={isChecking || isInstalling || !isUpdateReady}
|
||||
disabled={isChecking || isInstalling || !isUpdateActionable}
|
||||
>
|
||||
{getUpdateButtonLabel(t, isInstalling, readyUpdateVersion)}
|
||||
{getUpdateButtonLabel(t, {
|
||||
isInstalling,
|
||||
isDownloading: isInstalling && downloadProgress != null,
|
||||
isActionable: isUpdateActionable,
|
||||
readyToInstall: isUpdateReady,
|
||||
latestVersion: actionableVersion,
|
||||
})}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
@@ -1640,6 +1743,19 @@ 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 {
|
||||
@@ -38,7 +37,7 @@ import { startDesktopDaemon, stopDesktopDaemon } from "@/desktop/daemon/desktop-
|
||||
import { LocalDaemonSection } from "@/desktop/components/desktop-updates-section";
|
||||
import { useDaemonStatus } from "@/desktop/hooks/use-daemon-status";
|
||||
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
|
||||
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||
import { WaysToConnect } from "@/devices";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
|
||||
import {
|
||||
@@ -265,19 +264,14 @@ export function HostConnectionsPage({ serverId }: { serverId: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function HostPairDevicePage({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
export function HostDevicesPage({ serverId }: { serverId: string }) {
|
||||
const host = useHostProfile(serverId);
|
||||
|
||||
if (!host) {
|
||||
return <HostNotFound />;
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsSection title={t("settings.host.pairDevices.title")}>
|
||||
<PairDeviceRow serverId={serverId} />
|
||||
</SettingsSection>
|
||||
);
|
||||
return <WaysToConnect serverId={serverId} />;
|
||||
}
|
||||
|
||||
export function HostAgentsPage({ serverId }: { serverId: string }) {
|
||||
@@ -1130,39 +1124,6 @@ function AppendSystemPromptCard({ serverId }: { serverId: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PairDeviceRow({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const { theme } = useUnistyles();
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
const handleOpen = useCallback(() => setIsModalOpen(true), []);
|
||||
const handleClose = useCallback(() => setIsModalOpen(false), []);
|
||||
|
||||
return (
|
||||
<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,
|
||||
|
||||
@@ -603,6 +603,8 @@ interface SessionStoreActions {
|
||||
message: UserMessageItem,
|
||||
) => boolean;
|
||||
clearAgentStreamHead: (serverId: string, agentId: string) => void;
|
||||
/** Drops every piece of one chat's resident transcript: rows, cursors, paging and sync marks. */
|
||||
releaseAgentTimeline: (serverId: string, agentId: string) => void;
|
||||
setAgentTimelineCursor: (
|
||||
serverId: string,
|
||||
state:
|
||||
@@ -1342,6 +1344,35 @@ export const useSessionStore = create<SessionStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
releaseAgentTimeline: (serverId, agentId) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
if (!session) return prev;
|
||||
const timelineKeys = [
|
||||
"agentStreamTail",
|
||||
"agentStreamHead",
|
||||
"agentTasks",
|
||||
"agentTimelineCursor",
|
||||
"agentTimelineUnsettledTurn",
|
||||
"agentTimelineHasOlder",
|
||||
"agentTimelineHasNewer",
|
||||
"agentTimelineOlderFetchInFlight",
|
||||
"agentHistorySyncGeneration",
|
||||
"agentAuthoritativeHistoryApplied",
|
||||
] as const satisfies readonly (keyof SessionState)[];
|
||||
let next: SessionState | null = null;
|
||||
for (const key of timelineKeys) {
|
||||
const current: Map<string, unknown> = session[key];
|
||||
if (!current.has(agentId)) continue;
|
||||
const without = new Map(current);
|
||||
without.delete(agentId);
|
||||
next = { ...(next ?? session), [key]: without };
|
||||
}
|
||||
if (!next) return prev;
|
||||
return { ...prev, sessions: { ...prev.sessions, [serverId]: next } };
|
||||
});
|
||||
},
|
||||
|
||||
setAgentTimelineCursor: (serverId, state) => {
|
||||
set((prev) => {
|
||||
const session = prev.sessions[serverId];
|
||||
|
||||
@@ -165,6 +165,7 @@ it("feeds restored layout to timeline sync as a release signal, not a subscripti
|
||||
const sync = createViewedTimelineSync({
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
prepare: async () => undefined,
|
||||
isArchived: () => false,
|
||||
canCheckFreshness: () => false,
|
||||
applyCurrentTimeline: () => undefined,
|
||||
observe: (agentIds) => {
|
||||
|
||||
@@ -7,9 +7,17 @@ import {
|
||||
} from "@/runtime/replica-cache/row-store-sqlite";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
AgentSnapshotPayload,
|
||||
AgentStreamEventPayload,
|
||||
WorkspaceDescriptorPayload,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { FetchAgentsEntry } from "@getpaseo/client/internal/daemon-client";
|
||||
import { AgentDirectoryReplica } from "@/runtime/directory-sync/agent-replica";
|
||||
import { WorkspaceDirectoryReplica } from "@/runtime/directory-sync/workspace-replica";
|
||||
import type { CachedTimeline } from "@/runtime/replica-cache";
|
||||
import {
|
||||
normalizeWorkspaceDescriptor,
|
||||
selectAgentTimelineState,
|
||||
selectAgentTimelineTurnPresentation,
|
||||
selectAgentTurnPresentation,
|
||||
@@ -1802,3 +1810,365 @@ describe("SQLite baseline restoration", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("archived timeline lifetime", () => {
|
||||
const ACTIVE = "active-agent";
|
||||
const OTHER = "other-agent";
|
||||
const ARCHIVED = "archived-agent";
|
||||
/** An agent whose row never got its archive timestamp, in a workspace that was archived. */
|
||||
const IN_ARCHIVED_WORKSPACE = "agent-in-archived-workspace";
|
||||
const WORKSPACE = "workspace";
|
||||
const ARCHIVED_WORKSPACE = "archived-workspace";
|
||||
const openOwners: ViewedTimelineOwner[] = [];
|
||||
afterEach(() => {
|
||||
for (const owner of openOwners.splice(0)) owner.dispose();
|
||||
});
|
||||
|
||||
function agentPayload(
|
||||
id: string,
|
||||
archivedAt?: string,
|
||||
workspaceId: string = WORKSPACE,
|
||||
): AgentSnapshotPayload {
|
||||
return {
|
||||
id,
|
||||
workspaceId,
|
||||
provider: "codex",
|
||||
cwd: "/repo",
|
||||
model: null,
|
||||
createdAt: "2026-07-17T00:00:00.000Z",
|
||||
updatedAt: "2026-07-17T00:01:00.000Z",
|
||||
lastUserMessageAt: null,
|
||||
status: "idle",
|
||||
capabilities: {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: true,
|
||||
supportsMcpServers: true,
|
||||
supportsReasoningStream: true,
|
||||
supportsToolInvocations: true,
|
||||
},
|
||||
currentModeId: null,
|
||||
availableModes: [],
|
||||
pendingPermissions: [],
|
||||
persistence: null,
|
||||
title: id,
|
||||
labels: {},
|
||||
...(archivedAt ? { archivedAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function directoryEntry(id: string): FetchAgentsEntry {
|
||||
return {
|
||||
agent: agentPayload(id),
|
||||
project: {
|
||||
projectKey: "/repo",
|
||||
projectName: "repo",
|
||||
checkout: {
|
||||
cwd: "/repo",
|
||||
isGit: false,
|
||||
currentBranch: null,
|
||||
remoteUrl: null,
|
||||
worktreeRoot: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
mainRepoRoot: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function historyPage(agentId: string): TimelineResponsePayload {
|
||||
return {
|
||||
requestId: `tail-${agentId}`,
|
||||
agentId,
|
||||
agent: null,
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
reset: false,
|
||||
epoch: "epoch-1",
|
||||
window: { minSeq: 1, maxSeq: 1, nextSeq: 2 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 1 },
|
||||
entries: [
|
||||
{
|
||||
provider: "codex",
|
||||
item: { type: "assistant_message", text: `history of ${agentId}` },
|
||||
timestamp: "2026-08-26T10:00:00.000Z",
|
||||
seqStart: 1,
|
||||
seqEnd: 1,
|
||||
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
|
||||
collapsed: [],
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
hasNewer: false,
|
||||
hasOlder: false,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A host with an active directory and a viewed-timeline owner. Fetches reach the store the
|
||||
* way the host runtime delivers them: the agent row first, then the page, whether or not
|
||||
* the catch-up that asked for it is still current.
|
||||
*/
|
||||
function openHost(
|
||||
activeAgentIds: string[],
|
||||
storage: TimelineReplicaStorage = {
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: () => undefined,
|
||||
},
|
||||
) {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const directory = new AgentDirectoryReplica(
|
||||
SERVER_ID,
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
const workspaces = new WorkspaceDirectoryReplica(SERVER_ID);
|
||||
workspaces.commitSnapshot(
|
||||
{
|
||||
workspaces: new Map([[WORKSPACE, normalizeWorkspaceDescriptor(workspaceDescriptor())]]),
|
||||
projects: new Map(),
|
||||
},
|
||||
[],
|
||||
);
|
||||
directory.commitSnapshot(activeAgentIds.map(directoryEntry), []);
|
||||
const fetches: string[] = [];
|
||||
const held = new Map<string, () => void>();
|
||||
const holding = new Set<string>();
|
||||
const replica = createTimelineReplica({
|
||||
serverId: SERVER_ID,
|
||||
storage,
|
||||
prepareAgent: async () => undefined,
|
||||
});
|
||||
const owner: ViewedTimelineOwner = createViewedTimelineOwner({
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness: () => undefined,
|
||||
ports: {
|
||||
canCheckFreshness: () => false,
|
||||
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
|
||||
readCursor: () => undefined,
|
||||
fetchPage: async (agentId) => {
|
||||
fetches.push(agentId);
|
||||
if (holding.has(agentId)) {
|
||||
await new Promise<void>((resolve) => held.set(agentId, resolve));
|
||||
}
|
||||
if (agentId === ARCHIVED) {
|
||||
directory.submitTimelineAgent(
|
||||
directory.captureTimeline(agentId),
|
||||
agentPayload(agentId, "2026-09-11T00:00:00.000Z"),
|
||||
);
|
||||
}
|
||||
if (agentId === IN_ARCHIVED_WORKSPACE) {
|
||||
directory.submitTimelineAgent(
|
||||
directory.captureTimeline(agentId),
|
||||
agentPayload(agentId, undefined, ARCHIVED_WORKSPACE),
|
||||
);
|
||||
}
|
||||
owner.applyTimelineResponse(historyPage(agentId));
|
||||
return { hasNewer: false, endCursor: null };
|
||||
},
|
||||
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
||||
reportError: () => undefined,
|
||||
},
|
||||
});
|
||||
owner.setConnected(true);
|
||||
openOwners.push(owner);
|
||||
return {
|
||||
directory,
|
||||
workspaces,
|
||||
owner,
|
||||
fetches,
|
||||
view(agentIds: string[]) {
|
||||
owner.replaceVisibleAgentIds("workspace", agentIds);
|
||||
},
|
||||
hold(agentId: string) {
|
||||
holding.add(agentId);
|
||||
},
|
||||
async deliverHeld(agentId: string) {
|
||||
await expect.poll(() => held.has(agentId)).toBe(true);
|
||||
held.get(agentId)?.();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function workspaceDescriptor(): WorkspaceDescriptorPayload {
|
||||
return {
|
||||
id: WORKSPACE,
|
||||
projectId: "project",
|
||||
projectDisplayName: "project",
|
||||
projectRootPath: "/repo",
|
||||
workspaceDirectory: "/repo",
|
||||
projectKind: "git",
|
||||
workspaceKind: "worktree",
|
||||
name: WORKSPACE,
|
||||
title: WORKSPACE,
|
||||
status: "done",
|
||||
activityAt: null,
|
||||
statusEnteredAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
};
|
||||
}
|
||||
|
||||
function timelineStatus(agentId: string): string {
|
||||
return selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], agentId).status;
|
||||
}
|
||||
|
||||
function residentAgentIds(): string[] {
|
||||
const session = useSessionStore.getState().sessions[SERVER_ID];
|
||||
if (!session) return [];
|
||||
return [
|
||||
...new Set([
|
||||
...session.agentStreamTail.keys(),
|
||||
...session.agentStreamHead.keys(),
|
||||
...session.agentTimelineCursor.keys(),
|
||||
...session.agentAuthoritativeHistoryApplied.keys(),
|
||||
...session.agentTimelineHasOlder.keys(),
|
||||
...session.agentTimelineHasNewer.keys(),
|
||||
...session.agentHistorySyncGeneration.keys(),
|
||||
]),
|
||||
].sort();
|
||||
}
|
||||
|
||||
it("keeps hidden active chats cached and switches back without a fetch", async () => {
|
||||
const host = openHost([ACTIVE, OTHER]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([OTHER]);
|
||||
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
|
||||
host.view([ACTIVE]);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(timelineStatus(ACTIVE)).toBe("synced");
|
||||
expect(timelineStatus(OTHER)).toBe("synced");
|
||||
expect(host.fetches).toEqual([ACTIVE, OTHER]);
|
||||
});
|
||||
|
||||
it("releases a hidden chat's timeline when its agent is archived", async () => {
|
||||
const host = openHost([ACTIVE, OTHER]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([OTHER]);
|
||||
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
|
||||
|
||||
host.directory.applyDelta({ kind: "remove", agentId: ACTIVE });
|
||||
|
||||
expect(timelineStatus(ACTIVE)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([OTHER]);
|
||||
});
|
||||
|
||||
it("releases an archived chat's timeline once its tab is no longer shown", async () => {
|
||||
const host = openHost([ACTIVE]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
|
||||
host.directory.archive(ACTIVE, "2026-09-11T00:00:00.000Z");
|
||||
expect(timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([]);
|
||||
|
||||
expect(timelineStatus(ACTIVE)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("releases every timeline of a workspace when the active list drops its agents", async () => {
|
||||
const host = openHost([ACTIVE, OTHER]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([OTHER]);
|
||||
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
|
||||
host.view([]);
|
||||
|
||||
host.directory.commitSnapshot([], []);
|
||||
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("releases hidden timelines of a removed workspace whose agent rows still look active", async () => {
|
||||
const host = openHost([ACTIVE, OTHER]);
|
||||
host.view([ACTIVE]);
|
||||
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
|
||||
host.view([OTHER]);
|
||||
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
|
||||
|
||||
host.workspaces.removeWorkspaceSnapshot(WORKSPACE);
|
||||
|
||||
expect(timelineStatus(OTHER)).toBe("synced");
|
||||
expect(residentAgentIds()).toEqual([OTHER]);
|
||||
host.view([]);
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("releases a History chat whose unarchived row belongs to an archived workspace", async () => {
|
||||
const host = openHost([ACTIVE]);
|
||||
host.view([IN_ARCHIVED_WORKSPACE]);
|
||||
await expect.poll(() => timelineStatus(IN_ARCHIVED_WORKSPACE)).toBe("synced");
|
||||
|
||||
host.view([]);
|
||||
|
||||
expect(timelineStatus(IN_ARCHIVED_WORKSPACE)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps an archived chat open from History through active-list syncs and releases it on leave", async () => {
|
||||
const host = openHost([ACTIVE]);
|
||||
host.view([ARCHIVED]);
|
||||
await expect.poll(() => timelineStatus(ARCHIVED)).toBe("synced");
|
||||
|
||||
host.directory.commitSnapshot([directoryEntry(ACTIVE)], []);
|
||||
host.directory.applyDelta({ kind: "remove", agentId: ARCHIVED });
|
||||
expect(timelineStatus(ARCHIVED)).toBe("synced");
|
||||
|
||||
host.view([]);
|
||||
expect(timelineStatus(ARCHIVED)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
|
||||
host.view([ARCHIVED]);
|
||||
await expect.poll(() => timelineStatus(ARCHIVED)).toBe("synced");
|
||||
expect(host.fetches).toEqual([ARCHIVED, ARCHIVED]);
|
||||
});
|
||||
|
||||
it("ignores a History read that answers after the archived chat was left", async () => {
|
||||
const host = openHost([ACTIVE]);
|
||||
host.hold(ARCHIVED);
|
||||
host.view([ARCHIVED]);
|
||||
await expect.poll(() => host.fetches).toEqual([ARCHIVED]);
|
||||
|
||||
host.view([]);
|
||||
await host.deliverHeld(ARCHIVED);
|
||||
|
||||
expect(timelineStatus(ARCHIVED)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not paint a cached archived chat back after it was left", async () => {
|
||||
let finishRead!: () => void;
|
||||
const readStarted = new Promise<void>((resolve) => {
|
||||
finishRead = resolve;
|
||||
});
|
||||
let reading = false;
|
||||
const host = openHost([ACTIVE], {
|
||||
readTimeline: async (_serverId, agentId) => {
|
||||
reading = true;
|
||||
await readStarted;
|
||||
return { ...cachedTimeline(), agentId };
|
||||
},
|
||||
commitTimeline: () => undefined,
|
||||
});
|
||||
host.view([ARCHIVED]);
|
||||
await expect.poll(() => reading).toBe(true);
|
||||
|
||||
host.view([]);
|
||||
finishRead();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(timelineStatus(ARCHIVED)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -208,6 +208,7 @@ class TimelineWorld {
|
||||
},
|
||||
onCatchUpOwed: () => undefined,
|
||||
onCatchUpSettled: () => undefined,
|
||||
isArchived: () => false,
|
||||
prepare: async (agentId) => {
|
||||
this.cacheRequests.push(agentId);
|
||||
this.cacheRequestWaiters.shift()?.(agentId);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
useSessionStore,
|
||||
type AgentTimelineCursorState,
|
||||
type AgentTimelineState,
|
||||
type SessionState,
|
||||
} from "@/stores/session-store";
|
||||
import { useCreateFlowStore } from "@/stores/create-flow-store";
|
||||
import type { AgentSnapshotPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
@@ -102,6 +103,8 @@ export interface TimelineReplica {
|
||||
timelineUpdated(agentId: string): void;
|
||||
catchUpOwed(agentId: string): void;
|
||||
catchUpSettled(agentId: string): void;
|
||||
/** Forgets a released chat's cached range, so showing it again reads the cache afresh. */
|
||||
release(agentId: string): void;
|
||||
}
|
||||
|
||||
class TimelineReplicaOwner implements TimelineReplica {
|
||||
@@ -187,6 +190,10 @@ class TimelineReplicaOwner implements TimelineReplica {
|
||||
if (this.preparations.has(agentId)) this.settledDuringPreparation.add(agentId);
|
||||
useSessionStore.getState().setAgentTimelineUnsettledTurn(this.serverId, agentId, null);
|
||||
}
|
||||
|
||||
release(agentId: string): void {
|
||||
this.cachedRanges.delete(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
export function createTimelineReplica(input: {
|
||||
@@ -375,6 +382,11 @@ function buildCurrentTimelinePage(
|
||||
|
||||
export interface ViewedTimelineSyncPorts {
|
||||
prepare(agentId: string): Promise<void>;
|
||||
/**
|
||||
* Whether the agent left the active list: it, or its workspace, is archived. A hidden chat
|
||||
* of an archived agent leaves the opened chats, so showing it again reads it afresh.
|
||||
*/
|
||||
isArchived(agentId: string): boolean;
|
||||
replaceDemandedAgentIds(agentIds: string[]): void;
|
||||
/** Whether the daemon answers with each cursor's freshness in the subscribe response. */
|
||||
canCheckFreshness(): boolean;
|
||||
@@ -447,9 +459,17 @@ export interface ViewedTimelineSync extends ViewedTimelineUiBridge {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/** What the timeline owner needs from membership beyond the UI-facing surface. */
|
||||
export interface ViewedTimelineMembership extends ViewedTimelineSync {
|
||||
isVisible(agentId: string): boolean;
|
||||
/** Re-reads `isArchived` for the opened chats, after the active list changed. */
|
||||
archiveChanged(): void;
|
||||
}
|
||||
|
||||
export type ViewedTimelineOwnerPorts = Omit<
|
||||
ViewedTimelineSyncPorts,
|
||||
| "prepare"
|
||||
| "isArchived"
|
||||
| "replaceDemandedAgentIds"
|
||||
| "onCatchUpEnded"
|
||||
| "onCatchUpOwed"
|
||||
@@ -477,8 +497,14 @@ export function createViewedTimelineOwner(input: {
|
||||
ports: ViewedTimelineOwnerPorts;
|
||||
}): ViewedTimelineOwner {
|
||||
const forcedTailReplacements = new Set<string>();
|
||||
const isArchived = (agentId: string) =>
|
||||
isAgentArchived(useSessionStore.getState().sessions[input.serverId], agentId);
|
||||
// Active chats stay resident while hidden so switching back needs no fetch. An archived
|
||||
// chat is resident only while it is shown, as when it is open from History.
|
||||
const isResident = (agentId: string) => sync.isVisible(agentId) || !isArchived(agentId);
|
||||
const sync = createViewedTimelineSync({
|
||||
...input.ports,
|
||||
isArchived,
|
||||
fetchLatestTail: async (agentId) => {
|
||||
forcedTailReplacements.add(agentId);
|
||||
try {
|
||||
@@ -487,7 +513,11 @@ export function createViewedTimelineOwner(input: {
|
||||
forcedTailReplacements.delete(agentId);
|
||||
}
|
||||
},
|
||||
prepare: (agentId) => input.replica.prepare(agentId),
|
||||
prepare: async (agentId) => {
|
||||
await input.replica.prepare(agentId);
|
||||
// A cache read that lands after its archived chat was left paints a chat nobody shows.
|
||||
releaseHiddenArchivedTimelines();
|
||||
},
|
||||
readCursor: (agentId) => input.replica.readCursor(agentId) ?? input.ports.readCursor(agentId),
|
||||
replaceDemandedAgentIds: input.replaceDemandedAgentIds,
|
||||
applyCurrentTimeline: (agentId) => {
|
||||
@@ -514,9 +544,40 @@ export function createViewedTimelineOwner(input: {
|
||||
recoverTimelineGap: (agentId, cursor) => sync.recoverGap(agentId, cursor),
|
||||
onCommitted: (agentId) => input.replica.timelineUpdated(agentId),
|
||||
});
|
||||
const releaseHiddenArchivedTimelines = () => {
|
||||
const session = useSessionStore.getState().sessions[input.serverId];
|
||||
if (!session) return;
|
||||
for (const agentId of selectResidentTimelineAgentIds(session)) {
|
||||
if (isResident(agentId)) continue;
|
||||
streamQueue.flushAgent(agentId);
|
||||
input.replica.release(agentId);
|
||||
useSessionStore.getState().releaseAgentTimeline(input.serverId, agentId);
|
||||
}
|
||||
};
|
||||
// Archiving an agent or its workspace reaches this host as the agent leaving the active list.
|
||||
let observedSession = useSessionStore.getState().sessions[input.serverId];
|
||||
const stopObservingArchive = useSessionStore.subscribe((state) => {
|
||||
const session = state.sessions[input.serverId];
|
||||
const changed =
|
||||
session?.agents !== observedSession?.agents ||
|
||||
session?.agentDetails !== observedSession?.agentDetails ||
|
||||
session?.hasHydratedAgents !== observedSession?.hasHydratedAgents ||
|
||||
session?.workspaces !== observedSession?.workspaces ||
|
||||
session?.hasHydratedWorkspaces !== observedSession?.hasHydratedWorkspaces;
|
||||
observedSession = session;
|
||||
if (!changed) return;
|
||||
sync.archiveChanged();
|
||||
releaseHiddenArchivedTimelines();
|
||||
});
|
||||
return {
|
||||
...sync,
|
||||
replaceVisibleAgentIds(sourceId, agentIds) {
|
||||
sync.replaceVisibleAgentIds(sourceId, agentIds);
|
||||
releaseHiddenArchivedTimelines();
|
||||
},
|
||||
applyTimelineResponse(receivedPayload) {
|
||||
// A read that answers after its archived chat was released must not bring it back.
|
||||
if (!isResident(receivedPayload.agentId)) return;
|
||||
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
|
||||
const accepted = applyAuthoritativeTimelineResponse({
|
||||
serverId: input.serverId,
|
||||
@@ -528,6 +589,7 @@ export function createViewedTimelineOwner(input: {
|
||||
if (accepted) input.replica.timelineUpdated(payload.agentId);
|
||||
},
|
||||
applyStreamEvent(agentId, event) {
|
||||
if (!isResident(agentId)) return;
|
||||
streamQueue.enqueue(agentId, event);
|
||||
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
|
||||
if (turnLiveness.length === 0) return;
|
||||
@@ -539,12 +601,38 @@ export function createViewedTimelineOwner(input: {
|
||||
streamQueue.flushAgent(agentId);
|
||||
},
|
||||
dispose() {
|
||||
stopObservingArchive();
|
||||
streamQueue.dispose({ flush: true });
|
||||
sync.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An agent is archived once the hydrated active list lacks it, its row carries an archive
|
||||
* timestamp, or the hydrated workspace list lacks its workspace. Workspace archive can leave
|
||||
* an agent row without a timestamp. Until a list hydrates, it rules nothing out.
|
||||
*/
|
||||
function isAgentArchived(session: SessionState | undefined, agentId: string): boolean {
|
||||
if (!session?.hasHydratedAgents) return false;
|
||||
const agent = session.agents.get(agentId) ?? session.agentDetails.get(agentId);
|
||||
if (!agent || agent.archivedAt != null) return true;
|
||||
return (
|
||||
session.hasHydratedWorkspaces &&
|
||||
agent.workspaceId !== undefined &&
|
||||
!session.workspaces.has(agent.workspaceId)
|
||||
);
|
||||
}
|
||||
|
||||
function selectResidentTimelineAgentIds(session: SessionState): Set<string> {
|
||||
return new Set([
|
||||
...session.agentStreamTail.keys(),
|
||||
...session.agentStreamHead.keys(),
|
||||
...session.agentTimelineCursor.keys(),
|
||||
...session.agentAuthoritativeHistoryApplied.keys(),
|
||||
]);
|
||||
}
|
||||
|
||||
const MAX_HIDDEN_CATCH_UPS = 2;
|
||||
|
||||
type CatchUpStatus = "running" | "complete" | "error";
|
||||
@@ -608,7 +696,7 @@ function sameAgentIds(left: string[], right: string[]): boolean {
|
||||
return left.length === right.length && left.every((agentId, index) => agentId === right[index]);
|
||||
}
|
||||
|
||||
export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): ViewedTimelineSync {
|
||||
export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): ViewedTimelineMembership {
|
||||
const sources = new Map<string, string[]>();
|
||||
const catchUps = new Map<string, CatchUpState>();
|
||||
const catchUpGenerations = new Map<string, number>();
|
||||
@@ -788,10 +876,12 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
|
||||
const ensureCacheLoaded = (agentId: string): void => {
|
||||
if (loadedCache.has(agentId) || cacheLoads.has(agentId)) return;
|
||||
const load = ports
|
||||
const load: Promise<void> = ports
|
||||
.prepare(agentId)
|
||||
.catch((error) => ports.reportError(error))
|
||||
.finally(() => {
|
||||
// A released chat forgot this load; showing it again starts its own.
|
||||
if (cacheLoads.get(agentId) !== load) return;
|
||||
cacheLoads.delete(agentId);
|
||||
loadedCache.add(agentId);
|
||||
const pending = pendingCatchUps.get(agentId);
|
||||
@@ -1079,10 +1169,29 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
};
|
||||
|
||||
const publishVisibleMembership = () => {
|
||||
commitDesiredMembership(normalizeAgentIds([...openedAgentIds, ...visibleAgentIds()]));
|
||||
const visible = visibleAgentIds();
|
||||
const kept = openedAgentIds.filter(
|
||||
(agentId) => visible.includes(agentId) || !ports.isArchived(agentId),
|
||||
);
|
||||
if (kept.length !== openedAgentIds.length) {
|
||||
for (const agentId of openedAgentIds) {
|
||||
if (kept.includes(agentId)) continue;
|
||||
loadedCache.delete(agentId);
|
||||
cacheLoads.delete(agentId);
|
||||
}
|
||||
openedAgentIds = kept;
|
||||
}
|
||||
commitDesiredMembership(normalizeAgentIds([...openedAgentIds, ...visible]));
|
||||
};
|
||||
|
||||
return {
|
||||
isVisible(agentId) {
|
||||
for (const agentIds of sources.values()) if (agentIds.includes(agentId)) return true;
|
||||
return false;
|
||||
},
|
||||
archiveChanged() {
|
||||
publishVisibleMembership();
|
||||
},
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
|
||||
@@ -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",
|
||||
"agent-profiles",
|
||||
"metadata",
|
||||
@@ -531,6 +531,7 @@ export const HOST_SECTION_SLUGS = [
|
||||
export type HostSectionSlug = (typeof HOST_SECTION_SLUGS)[number];
|
||||
|
||||
const LEGACY_HOST_SECTION_SLUGS: Record<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,9 +55,12 @@ 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. */
|
||||
@@ -110,6 +113,7 @@ 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;
|
||||
}
|
||||
@@ -140,11 +144,22 @@ 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 {
|
||||
@@ -182,10 +197,15 @@ export async function installDesktopRuntime(
|
||||
}
|
||||
}
|
||||
|
||||
function buildAppUpdateCheckResult(hasUpdate: boolean, readyToInstall: boolean) {
|
||||
function buildAppUpdateCheckResult(
|
||||
hasUpdate: boolean,
|
||||
readyToInstall: boolean,
|
||||
downloading = hasUpdate && !readyToInstall,
|
||||
) {
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading,
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: hasUpdate ? (cfg.latestVersion ?? "1.2.3") : null,
|
||||
body: null,
|
||||
@@ -194,19 +214,78 @@ export async function installDesktopRuntime(
|
||||
}
|
||||
|
||||
function checkAppUpdate(intent: unknown) {
|
||||
if (intent === "automatic" && updateMode === "off") {
|
||||
return buildAppUpdateCheckResult(false, false, false);
|
||||
}
|
||||
if (!cfg.manualUpdateBypassesRollout) {
|
||||
return buildAppUpdateCheckResult(
|
||||
cfg.updateAvailable === true,
|
||||
cfg.updateAvailable === true && (cfg.updateReadyToInstall ?? true),
|
||||
);
|
||||
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);
|
||||
}
|
||||
|
||||
if (intent === "manual") {
|
||||
manualUpdateAdmitted = true;
|
||||
return buildAppUpdateCheckResult(true, false);
|
||||
return buildAppUpdateCheckResult(true, false, updateMode === "automatic");
|
||||
}
|
||||
|
||||
return buildAppUpdateCheckResult(manualUpdateAdmitted, manualUpdateAdmitted);
|
||||
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();
|
||||
}
|
||||
|
||||
const desktopBridge: {
|
||||
@@ -217,7 +296,9 @@ export async function installDesktopRuntime(
|
||||
open: (options?: Record<string, unknown>) => Promise<string | string[] | null>;
|
||||
};
|
||||
getPendingOpenProject: () => Promise<string | null>;
|
||||
events: { on: () => Promise<() => void> };
|
||||
events: {
|
||||
on: (event: string, handler: (payload: unknown) => void) => Promise<() => void>;
|
||||
};
|
||||
editor?: {
|
||||
listTargets: () => Promise<DesktopEditorTargetConfig[]>;
|
||||
openTarget: (input: DesktopEditorOpenRecord) => Promise<void>;
|
||||
@@ -226,18 +307,15 @@ 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") {
|
||||
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.",
|
||||
};
|
||||
return installAppUpdate();
|
||||
}
|
||||
|
||||
if (command === "desktop_daemon_status") {
|
||||
@@ -250,26 +328,11 @@ export async function installDesktopRuntime(
|
||||
|
||||
if (command === "get_desktop_settings") {
|
||||
await waitForDesktopSettingsResponse();
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true },
|
||||
};
|
||||
return buildDesktopSettings();
|
||||
}
|
||||
|
||||
if (command === "patch_desktop_settings") {
|
||||
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 },
|
||||
};
|
||||
return patchDesktopSettings(args);
|
||||
}
|
||||
|
||||
if (command === "stop_desktop_daemon") {
|
||||
@@ -299,7 +362,19 @@ export async function installDesktopRuntime(
|
||||
},
|
||||
},
|
||||
getPendingOpenProject: async () => null,
|
||||
events: { on: async () => () => undefined },
|
||||
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);
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if (cfg.editorTargets) {
|
||||
|
||||
@@ -91,6 +91,74 @@ 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,13 +14,22 @@ import {
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
paseoHome: "",
|
||||
settingsError: null as Error | null,
|
||||
settings: {
|
||||
releaseChannel: "stable",
|
||||
releaseChannel: "stable" as "stable" | "beta",
|
||||
updates: {
|
||||
mode: "automatic" as "automatic" | "notify" | "off",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
daemon: {
|
||||
manageBuiltInDaemon: true,
|
||||
keepRunningAfterQuit: true,
|
||||
},
|
||||
},
|
||||
checkForAppUpdate: vi.fn(),
|
||||
downloadAndInstallUpdate: vi.fn(),
|
||||
runExternalCliJsonCommand: vi.fn(),
|
||||
runExternalCliTextCommand: vi.fn(),
|
||||
createNodeEntrypointInvocation: vi.fn(() => ({
|
||||
@@ -41,6 +50,8 @@ 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) },
|
||||
}));
|
||||
@@ -65,7 +76,12 @@ vi.mock("@getpaseo/server/daemon-control", async (importOriginal) => ({
|
||||
|
||||
vi.mock("../settings/desktop-settings-electron.js", () => ({
|
||||
getDesktopSettingsStore: () => ({
|
||||
get: async () => mocks.settings,
|
||||
get: async () => {
|
||||
if (mocks.settingsError) {
|
||||
throw mocks.settingsError;
|
||||
}
|
||||
return mocks.settings;
|
||||
},
|
||||
patch: vi.fn(),
|
||||
migrateLegacyRendererSettings: vi.fn(),
|
||||
}),
|
||||
@@ -79,6 +95,12 @@ 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,
|
||||
@@ -93,6 +115,8 @@ 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();
|
||||
@@ -182,6 +206,54 @@ 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,7 +481,17 @@ async function getLocalDaemonVersion(): Promise<{ version: string | null; error:
|
||||
async function resolveRequestedReleaseChannel(
|
||||
args: Record<string, unknown> | undefined,
|
||||
): Promise<AppReleaseChannel> {
|
||||
return parseReleaseChannel(args) ?? (await getDesktopSettingsStore().get()).releaseChannel;
|
||||
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";
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -541,10 +551,12 @@ 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: await resolveRequestedReleaseChannel(args),
|
||||
intent: parseAppUpdateCheckIntent(args),
|
||||
releaseChannel,
|
||||
intent,
|
||||
});
|
||||
},
|
||||
install_app_update: async (args) => {
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
import { chmod, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AUTOMATIC_CHECK_INTERVAL_MS,
|
||||
UPDATE_COOLDOWN_MS,
|
||||
createAppUpdatePacing,
|
||||
} from "./app-update-pacing";
|
||||
|
||||
const HOUR_MS = 3_600_000;
|
||||
const START = Date.parse("2026-04-28T12:00:00.000Z");
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
|
||||
});
|
||||
|
||||
async function createUserData(): Promise<string> {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "paseo-update-pacing-"));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
interface Install {
|
||||
filePath: string;
|
||||
errors: unknown[];
|
||||
advance(ms: number): void;
|
||||
setClock(time: number): void;
|
||||
/** Starts the app again, as a new process would, on the given version. */
|
||||
launch(version: string): ReturnType<typeof createAppUpdatePacing>;
|
||||
readFile(): Promise<unknown>;
|
||||
}
|
||||
|
||||
async function createInstall(input?: { filePath?: string }): Promise<Install> {
|
||||
const filePath = input?.filePath ?? path.join(await createUserData(), "app-update-pacing.json");
|
||||
const errors: unknown[] = [];
|
||||
let now = START;
|
||||
return {
|
||||
filePath,
|
||||
errors,
|
||||
advance(ms) {
|
||||
now += ms;
|
||||
},
|
||||
setClock(time) {
|
||||
now = time;
|
||||
},
|
||||
launch(version) {
|
||||
return createAppUpdatePacing({
|
||||
filePath: () => filePath,
|
||||
currentVersion: () => version,
|
||||
now: () => now,
|
||||
reportError: (error) => errors.push(error),
|
||||
});
|
||||
},
|
||||
async readFile() {
|
||||
return JSON.parse(await readFile(filePath, "utf8"));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("automatic check interval", () => {
|
||||
it("is due on a fresh install", async () => {
|
||||
const install = await createInstall();
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
});
|
||||
|
||||
it("is not due again until 6 hours after a recorded check", async () => {
|
||||
const install = await createInstall();
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
await pacing.recordAutomaticCheck();
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(false);
|
||||
|
||||
install.advance(AUTOMATIC_CHECK_INTERVAL_MS - 1);
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(false);
|
||||
|
||||
install.advance(1);
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
});
|
||||
|
||||
it("stays due until a check is recorded, so a failed check is retried", async () => {
|
||||
const install = await createInstall();
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
install.advance(HOUR_MS);
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
});
|
||||
|
||||
it("remembers the last check across restarts", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.3").recordAutomaticCheck();
|
||||
|
||||
install.advance(HOUR_MS);
|
||||
expect(await install.launch("1.2.3").isAutomaticCheckDue()).toBe(false);
|
||||
|
||||
install.advance(AUTOMATIC_CHECK_INTERVAL_MS);
|
||||
expect(await install.launch("1.2.3").isAutomaticCheckDue()).toBe(true);
|
||||
});
|
||||
|
||||
it("is due when the last check is in the future because the clock moved back", async () => {
|
||||
const install = await createInstall();
|
||||
install.setClock(START + 365 * 24 * HOUR_MS);
|
||||
await install.launch("1.2.3").recordAutomaticCheck();
|
||||
|
||||
install.setClock(START);
|
||||
const pacing = install.launch("1.2.3");
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
|
||||
await pacing.recordAutomaticCheck();
|
||||
expect(await install.readFile()).toMatchObject({ lastAutoCheckAt: START });
|
||||
});
|
||||
|
||||
it("is due after the clock jumps forward", async () => {
|
||||
const install = await createInstall();
|
||||
const pacing = install.launch("1.2.3");
|
||||
await pacing.recordAutomaticCheck();
|
||||
|
||||
install.setClock(START + 365 * 24 * HOUR_MS);
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("update cooldown", () => {
|
||||
it("does not start on a fresh install", async () => {
|
||||
const install = await createInstall();
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
expect(await install.readFile()).toEqual({
|
||||
lastAutoCheckAt: null,
|
||||
lastVersionSeen: "1.2.3",
|
||||
lastAutoUpdateAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not start when the app upgrades from a build that kept no pacing state", async () => {
|
||||
const install = await createInstall();
|
||||
// The earlier build never wrote the file, so there is no version to compare with.
|
||||
const pacing = install.launch("1.2.4");
|
||||
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
expect(await install.readFile()).toMatchObject({
|
||||
lastVersionSeen: "1.2.4",
|
||||
lastAutoUpdateAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("starts when the app launches on a newer version and lasts 72 hours", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.3").start();
|
||||
|
||||
install.advance(HOUR_MS);
|
||||
const pacing = install.launch("1.2.4");
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(true);
|
||||
expect(await install.readFile()).toMatchObject({
|
||||
lastVersionSeen: "1.2.4",
|
||||
lastAutoUpdateAt: START + HOUR_MS,
|
||||
});
|
||||
|
||||
install.advance(UPDATE_COOLDOWN_MS - 1);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(true);
|
||||
|
||||
install.advance(1);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
});
|
||||
|
||||
it("starts when a prerelease build is replaced by its release", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.3.0-beta.2").start();
|
||||
|
||||
expect(await install.launch("1.3.0").isInUpdateCooldown()).toBe(true);
|
||||
});
|
||||
|
||||
it("is not restarted by launching the same version again", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.3").start();
|
||||
await install.launch("1.2.4").start();
|
||||
|
||||
install.advance(UPDATE_COOLDOWN_MS - HOUR_MS);
|
||||
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(true);
|
||||
|
||||
install.advance(HOUR_MS);
|
||||
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(false);
|
||||
expect(await install.readFile()).toMatchObject({ lastAutoUpdateAt: START });
|
||||
});
|
||||
|
||||
it("is not started by a downgrade, and a downgrade keeps a running cooldown", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.4").start();
|
||||
|
||||
install.advance(HOUR_MS);
|
||||
expect(await install.launch("1.2.3").isInUpdateCooldown()).toBe(false);
|
||||
expect(await install.readFile()).toMatchObject({
|
||||
lastVersionSeen: "1.2.4",
|
||||
lastAutoUpdateAt: null,
|
||||
});
|
||||
|
||||
install.advance(HOUR_MS);
|
||||
await install.launch("1.2.5").start();
|
||||
install.advance(HOUR_MS);
|
||||
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(true);
|
||||
expect(await install.readFile()).toMatchObject({
|
||||
lastVersionSeen: "1.2.5",
|
||||
lastAutoUpdateAt: START + 2 * HOUR_MS,
|
||||
});
|
||||
});
|
||||
|
||||
it("is not restarted by switching between two installed builds", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.3").start();
|
||||
await install.launch("1.2.4").start();
|
||||
|
||||
install.advance(UPDATE_COOLDOWN_MS);
|
||||
for (let round = 0; round < 3; round += 1) {
|
||||
expect(await install.launch("1.2.3").isInUpdateCooldown()).toBe(false);
|
||||
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(false);
|
||||
}
|
||||
expect(await install.readFile()).toMatchObject({
|
||||
lastVersionSeen: "1.2.4",
|
||||
lastAutoUpdateAt: START,
|
||||
});
|
||||
});
|
||||
|
||||
it("is not started when the stored version cannot be compared", async () => {
|
||||
const install = await createInstall();
|
||||
await writeFile(
|
||||
install.filePath,
|
||||
JSON.stringify({ lastAutoCheckAt: null, lastVersionSeen: "nightly", lastAutoUpdateAt: null }),
|
||||
);
|
||||
|
||||
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(false);
|
||||
expect(await install.readFile()).toMatchObject({ lastVersionSeen: "1.2.4" });
|
||||
});
|
||||
|
||||
it("is over when the recorded update is in the future because the clock moved back", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.3").start();
|
||||
install.setClock(START + 365 * 24 * HOUR_MS);
|
||||
await install.launch("1.2.4").start();
|
||||
|
||||
install.setClock(START);
|
||||
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(false);
|
||||
});
|
||||
|
||||
it("is over after the clock jumps forward", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.3").start();
|
||||
const pacing = install.launch("1.2.4");
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(true);
|
||||
|
||||
install.setClock(START + 365 * 24 * HOUR_MS);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
});
|
||||
|
||||
it("is measured from launch, even when nothing asks until later", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.3").start();
|
||||
const pacing = install.launch("1.2.4");
|
||||
await pacing.start();
|
||||
|
||||
install.advance(UPDATE_COOLDOWN_MS);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("damaged pacing state", () => {
|
||||
const damagedFiles: Array<[string, string]> = [
|
||||
["an empty file", ""],
|
||||
["truncated JSON", '{"lastAutoCheckAt": 17773'],
|
||||
["binary garbage", "\u0000\u0001�\u0000"],
|
||||
["a JSON array", "[1, 2, 3]"],
|
||||
["JSON null", "null"],
|
||||
["a JSON number", "42"],
|
||||
["a JSON string", '"hello"'],
|
||||
];
|
||||
|
||||
for (const [name, contents] of damagedFiles) {
|
||||
it(`treats ${name} as a fresh install and replaces it`, async () => {
|
||||
const install = await createInstall();
|
||||
await writeFile(install.filePath, contents);
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
expect(await install.readFile()).toEqual({
|
||||
lastAutoCheckAt: null,
|
||||
lastVersionSeen: "1.2.3",
|
||||
lastAutoUpdateAt: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
it("drops each field that has the wrong shape", async () => {
|
||||
const install = await createInstall();
|
||||
await writeFile(
|
||||
install.filePath,
|
||||
JSON.stringify({
|
||||
lastAutoCheckAt: "yesterday",
|
||||
lastVersionSeen: 5,
|
||||
lastAutoUpdateAt: { at: START },
|
||||
}),
|
||||
);
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
});
|
||||
|
||||
it("drops timestamps that are not real times", async () => {
|
||||
const install = await createInstall();
|
||||
for (const timestamp of ["-1", "1e400", "NaN"]) {
|
||||
await writeFile(
|
||||
install.filePath,
|
||||
`{"lastAutoCheckAt": ${timestamp}, "lastVersionSeen": "1.2.3", "lastAutoUpdateAt": ${timestamp}}`,
|
||||
);
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the valid fields next to a damaged one", async () => {
|
||||
const install = await createInstall();
|
||||
await writeFile(
|
||||
install.filePath,
|
||||
JSON.stringify({
|
||||
lastAutoCheckAt: START,
|
||||
lastVersionSeen: "1.2.3",
|
||||
lastAutoUpdateAt: "garbage",
|
||||
futureField: true,
|
||||
}),
|
||||
);
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(false);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores a temp file left behind by a crash in the middle of a write", async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.3").recordAutomaticCheck();
|
||||
await writeFile(`${install.filePath}.tmp.999.crashed`, '{"lastAutoCheckAt": 1');
|
||||
|
||||
const pacing = install.launch("1.2.3");
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(false);
|
||||
expect(install.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("leaves one complete file after every write", async () => {
|
||||
const install = await createInstall();
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
await Promise.all(
|
||||
Array.from({ length: 25 }, async () => {
|
||||
await pacing.recordAutomaticCheck();
|
||||
await pacing.isAutomaticCheckDue();
|
||||
}),
|
||||
);
|
||||
|
||||
expect(await readdir(path.dirname(install.filePath))).toEqual(["app-update-pacing.json"]);
|
||||
expect(await install.readFile()).toEqual({
|
||||
lastAutoCheckAt: START,
|
||||
lastVersionSeen: "1.2.3",
|
||||
lastAutoUpdateAt: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("pacing state that cannot be stored", () => {
|
||||
it("never throttles checks and never starts a cooldown when the file cannot be written", async () => {
|
||||
const userData = await createUserData();
|
||||
const blocker = path.join(userData, "not-a-directory");
|
||||
await writeFile(blocker, "");
|
||||
const install = await createInstall({ filePath: path.join(blocker, "app-update-pacing.json") });
|
||||
|
||||
for (const version of ["1.2.3", "1.2.4", "1.2.5"]) {
|
||||
const pacing = install.launch(version);
|
||||
await pacing.recordAutomaticCheck();
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
}
|
||||
expect(install.errors.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// Windows has no directory write permission to revoke, and root ignores it.
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"does not restart the cooldown on every launch when a version advance cannot be stored",
|
||||
async () => {
|
||||
const install = await createInstall();
|
||||
await install.launch("1.2.3").start();
|
||||
const stateDir = path.dirname(install.filePath);
|
||||
|
||||
await chmod(stateDir, 0o555);
|
||||
try {
|
||||
for (let launch = 0; launch < 3; launch += 1) {
|
||||
install.advance(HOUR_MS);
|
||||
const pacing = install.launch("1.2.4");
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
await pacing.recordAutomaticCheck();
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
}
|
||||
expect(await install.readFile()).toMatchObject({ lastVersionSeen: "1.2.3" });
|
||||
expect(install.errors.length).toBeGreaterThan(0);
|
||||
} finally {
|
||||
await chmod(stateDir, 0o755);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the last stored check time when a later write fails", async () => {
|
||||
const userData = await createUserData();
|
||||
const stateDir = path.join(userData, "state");
|
||||
await mkdir(stateDir);
|
||||
const install = await createInstall({
|
||||
filePath: path.join(stateDir, "app-update-pacing.json"),
|
||||
});
|
||||
const pacing = install.launch("1.2.3");
|
||||
await pacing.recordAutomaticCheck();
|
||||
|
||||
await rm(stateDir, { recursive: true });
|
||||
await writeFile(stateDir, "");
|
||||
install.advance(AUTOMATIC_CHECK_INTERVAL_MS);
|
||||
await pacing.recordAutomaticCheck();
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
});
|
||||
|
||||
it("treats an unreadable file as a fresh install", async () => {
|
||||
const install = await createInstall();
|
||||
await mkdir(install.filePath);
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
await expect(pacing.recordAutomaticCheck()).resolves.toBeUndefined();
|
||||
expect(install.errors.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("drops a change when the finished file cannot replace the stored one", async () => {
|
||||
const install = await createInstall();
|
||||
// A directory at the file path lets the temp file be written but not renamed into place.
|
||||
await mkdir(install.filePath);
|
||||
const pacing = install.launch("1.2.3");
|
||||
|
||||
await pacing.recordAutomaticCheck();
|
||||
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
expect(await readdir(path.dirname(install.filePath))).toEqual(["app-update-pacing.json"]);
|
||||
});
|
||||
|
||||
it("stays open when the file path or the running version cannot be resolved", async () => {
|
||||
const errors: unknown[] = [];
|
||||
const brokenPath = createAppUpdatePacing({
|
||||
filePath: () => {
|
||||
throw new Error("userData is not available");
|
||||
},
|
||||
currentVersion: () => "1.2.3",
|
||||
now: () => START,
|
||||
reportError: (error) => errors.push(error),
|
||||
});
|
||||
const install = await createInstall();
|
||||
const brokenVersion = createAppUpdatePacing({
|
||||
filePath: () => install.filePath,
|
||||
currentVersion: () => {
|
||||
throw new Error("version is not available");
|
||||
},
|
||||
now: () => START,
|
||||
reportError: (error) => errors.push(error),
|
||||
});
|
||||
|
||||
for (const pacing of [brokenPath, brokenVersion]) {
|
||||
await expect(pacing.start()).resolves.toBeUndefined();
|
||||
await expect(pacing.recordAutomaticCheck()).resolves.toBeUndefined();
|
||||
expect(await pacing.isAutomaticCheckDue()).toBe(true);
|
||||
expect(await pacing.isInUpdateCooldown()).toBe(false);
|
||||
}
|
||||
expect(errors.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
import { isNewerVersion } from "./app-update-version.js";
|
||||
|
||||
export const AUTOMATIC_CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
||||
export const UPDATE_COOLDOWN_MS = 72 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Paces automatic updates so frequent releases stay calm: automatic checks run
|
||||
* at most once per interval, and a paced release is deferred for the cooldown
|
||||
* after the app last moved to a newer version.
|
||||
*
|
||||
* Every answer fails open. Missing, damaged, unreadable or unwritable state, a
|
||||
* clock that jumped, and any unexpected error all answer "check now" and "not in
|
||||
* cooldown". No method rejects.
|
||||
*/
|
||||
export interface AppUpdatePacing {
|
||||
/** Loads the stored state and notes the running version. Call once at startup. */
|
||||
start(): Promise<void>;
|
||||
isAutomaticCheckDue(): Promise<boolean>;
|
||||
recordAutomaticCheck(): Promise<void>;
|
||||
isInUpdateCooldown(): Promise<boolean>;
|
||||
}
|
||||
|
||||
export interface AppUpdatePacingDeps {
|
||||
filePath(): string;
|
||||
currentVersion(): string;
|
||||
now(): number;
|
||||
reportError?(error: unknown): void;
|
||||
}
|
||||
|
||||
const TimestampSchema = z.number().finite().nonnegative().nullable().catch(null);
|
||||
|
||||
// Loose, so a field added by a newer build survives a launch of this one.
|
||||
const PacingStateSchema = z.looseObject({
|
||||
lastAutoCheckAt: TimestampSchema,
|
||||
lastVersionSeen: z.string().min(1).nullable().catch(null),
|
||||
lastAutoUpdateAt: TimestampSchema,
|
||||
});
|
||||
|
||||
type PacingState = z.output<typeof PacingStateSchema>;
|
||||
|
||||
const EMPTY_STATE: PacingState = {
|
||||
lastAutoCheckAt: null,
|
||||
lastVersionSeen: null,
|
||||
lastAutoUpdateAt: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* A window is open only while `now` sits inside it. A timestamp in the future
|
||||
* comes from a clock that moved back, and it must not hold the window open
|
||||
* until the clock catches up.
|
||||
*/
|
||||
function isWithinWindow(startedAt: number | null, now: number, durationMs: number): boolean {
|
||||
if (startedAt === null) return false;
|
||||
const elapsed = now - startedAt;
|
||||
return elapsed >= 0 && elapsed < durationMs;
|
||||
}
|
||||
|
||||
function isMissingFileError(error: unknown): boolean {
|
||||
return error instanceof Error && (error as NodeJS.ErrnoException).code === "ENOENT";
|
||||
}
|
||||
|
||||
export function createAppUpdatePacing(deps: AppUpdatePacingDeps): AppUpdatePacing {
|
||||
// `state` always equals what is on disk. A change that cannot be stored is
|
||||
// dropped, so a version advance that fails to persist cannot restart the
|
||||
// cooldown on every launch.
|
||||
let state: PacingState = EMPTY_STATE;
|
||||
let loaded = false;
|
||||
let operationQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
function enqueue<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = operationQueue.then(operation, operation);
|
||||
operationQueue = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function readState(filePath: string): Promise<PacingState> {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(filePath, "utf8");
|
||||
} catch (error) {
|
||||
if (!isMissingFileError(error)) deps.reportError?.(error);
|
||||
return EMPTY_STATE;
|
||||
}
|
||||
|
||||
try {
|
||||
return PacingStateSchema.parse(JSON.parse(raw));
|
||||
} catch (error) {
|
||||
deps.reportError?.(error);
|
||||
return EMPTY_STATE;
|
||||
}
|
||||
}
|
||||
|
||||
async function store(next: PacingState): Promise<void> {
|
||||
const filePath = deps.filePath();
|
||||
const tempFilePath = `${filePath}.tmp.${process.pid}.${randomUUID()}`;
|
||||
try {
|
||||
await mkdir(path.dirname(filePath), { recursive: true });
|
||||
await writeFile(tempFilePath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
|
||||
await rename(tempFilePath, filePath);
|
||||
state = next;
|
||||
} catch (error) {
|
||||
deps.reportError?.(error);
|
||||
await rm(tempFilePath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async function noteRunningVersion(): Promise<void> {
|
||||
const currentVersion = deps.currentVersion();
|
||||
const previousVersion = state.lastVersionSeen;
|
||||
if (previousVersion === currentVersion) return;
|
||||
|
||||
// `lastVersionSeen` is the newest version this install has run. A launch of
|
||||
// an older build leaves it alone, so switching between two installed builds
|
||||
// cannot restart the cooldown each time the newer one starts.
|
||||
if (previousVersion !== null && isNewerVersion(previousVersion, currentVersion)) return;
|
||||
|
||||
// With no earlier version to compare (first launch, or the first launch of
|
||||
// a build that keeps this state), the app did not necessarily update.
|
||||
const updated = previousVersion !== null && isNewerVersion(currentVersion, previousVersion);
|
||||
await store({
|
||||
...state,
|
||||
lastVersionSeen: currentVersion,
|
||||
lastAutoUpdateAt: updated ? deps.now() : state.lastAutoUpdateAt,
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureLoaded(): Promise<void> {
|
||||
if (loaded) return;
|
||||
state = await readState(deps.filePath());
|
||||
await noteRunningVersion();
|
||||
loaded = true;
|
||||
}
|
||||
|
||||
function withState<T>(fallback: T, read: () => T | Promise<T>): Promise<T> {
|
||||
return enqueue(async () => {
|
||||
try {
|
||||
await ensureLoaded();
|
||||
return await read();
|
||||
} catch (error) {
|
||||
deps.reportError?.(error);
|
||||
return fallback;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
start: () => withState(undefined, () => undefined),
|
||||
isAutomaticCheckDue: () =>
|
||||
withState(
|
||||
true,
|
||||
() => !isWithinWindow(state.lastAutoCheckAt, deps.now(), AUTOMATIC_CHECK_INTERVAL_MS),
|
||||
),
|
||||
recordAutomaticCheck: () =>
|
||||
withState(undefined, () => store({ ...state, lastAutoCheckAt: deps.now() })),
|
||||
isInUpdateCooldown: () =>
|
||||
withState(false, () =>
|
||||
isWithinWindow(state.lastAutoUpdateAt, deps.now(), UPDATE_COOLDOWN_MS),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -1,156 +1,234 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { bucketFromStagingUserId, shouldAdmitAppUpdate } from "./app-update-rollout";
|
||||
import {
|
||||
isPacedRelease,
|
||||
rolloutAdmissionPercent,
|
||||
rolloutBucket,
|
||||
rolloutManifestSchema,
|
||||
shouldAdmitAppUpdate,
|
||||
} from "./app-update-rollout";
|
||||
|
||||
describe("shouldAdmitAppUpdate", () => {
|
||||
it("keeps automatic stable updates behind the rollout window", () => {
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "automatic",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T12:00:00.000Z"),
|
||||
bucket: 0.51,
|
||||
}),
|
||||
).toBe(false);
|
||||
const RELEASE_DATE = "2026-04-28T00:00:00.000Z";
|
||||
const RELEASE_TIME = Date.parse(RELEASE_DATE);
|
||||
const HOUR_MS = 3_600_000;
|
||||
const MAX_BUCKET = (0x100000000 - 1) / 0x100000000;
|
||||
|
||||
function admitsStable(input: {
|
||||
ageHours: number;
|
||||
bucket: number;
|
||||
rolloutHours?: number;
|
||||
intent?: "automatic" | "manual";
|
||||
}): boolean {
|
||||
return shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: input.intent ?? "automatic",
|
||||
rolloutHours: input.rolloutHours ?? 18,
|
||||
releaseDate: RELEASE_DATE,
|
||||
now: RELEASE_TIME + input.ageHours * HOUR_MS,
|
||||
bucket: input.bucket,
|
||||
});
|
||||
}
|
||||
|
||||
describe("rolloutAdmissionPercent", () => {
|
||||
it("holds the default 18 hour rollout at 5% for 8 hours, then ramps linearly to 100%", () => {
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 0 })).toBe(5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 4 })).toBe(5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 8 })).toBe(5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 13 })).toBe(52.5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 18 })).toBe(100);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 500 })).toBe(100);
|
||||
});
|
||||
|
||||
it("lets manual stable checks bypass rollout admission", () => {
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "manual",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T12:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
it("never decreases as a release ages", () => {
|
||||
let previous = 0;
|
||||
for (let ageHours = 0; ageHours <= 20; ageHours += 0.25) {
|
||||
const percent = rolloutAdmissionPercent({ rolloutHours: 18, ageHours });
|
||||
expect(percent).toBeGreaterThanOrEqual(previous);
|
||||
previous = percent;
|
||||
}
|
||||
});
|
||||
|
||||
it("admits beta, missing rollout hours, zero-hour rollout, and missing release date", () => {
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "beta",
|
||||
intent: "automatic",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "automatic",
|
||||
rolloutHours: undefined,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "automatic",
|
||||
rolloutHours: 0,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "automatic",
|
||||
rolloutHours: 24,
|
||||
releaseDate: undefined,
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
it("shortens the canary hold to half of a rollout shorter than 16 hours", () => {
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 6, ageHours: 2.9 })).toBe(5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 6, ageHours: 3 })).toBe(5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 6, ageHours: 4.5 })).toBe(52.5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 6, ageHours: 6 })).toBe(100);
|
||||
});
|
||||
|
||||
it("blocks future automatic releases and admits the same release manually", () => {
|
||||
const input = {
|
||||
channel: "stable" as const,
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T02:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0,
|
||||
};
|
||||
|
||||
expect(shouldAdmitAppUpdate({ ...input, intent: "automatic" })).toBe(false);
|
||||
expect(shouldAdmitAppUpdate({ ...input, intent: "manual" })).toBe(true);
|
||||
it("keeps the canary hold at 8 hours when a rollout is slowed down", () => {
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 72, ageHours: 8 })).toBe(5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 72, ageHours: 40 })).toBe(52.5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 72, ageHours: 72 })).toBe(100);
|
||||
});
|
||||
|
||||
it("blocks the bucket-zero client at exact release time, admits as soon as time advances", () => {
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "automatic",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T00:00:00.000Z"),
|
||||
bucket: 0,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "automatic",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T00:00:00.001Z"),
|
||||
bucket: 0,
|
||||
}),
|
||||
).toBe(true);
|
||||
it("completes a tiny rollout without dividing by zero", () => {
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 0.001, ageHours: 0 })).toBe(5);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 0.001, ageHours: 0.001 })).toBe(100);
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: Number.MIN_VALUE, ageHours: 1 })).toBe(100);
|
||||
});
|
||||
|
||||
it("admits the highest-bucket automatic client at and past the rollout end", () => {
|
||||
const maxBucket = (0x100000000 - 1) / 0x100000000;
|
||||
it("treats a release dated slightly in the future as just released", () => {
|
||||
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: -1 })).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldAdmitAppUpdate", () => {
|
||||
it("admits only the canary bucket during the canary hold", () => {
|
||||
expect(admitsStable({ ageHours: 0, bucket: 0 })).toBe(true);
|
||||
expect(admitsStable({ ageHours: 4, bucket: 0.049 })).toBe(true);
|
||||
expect(admitsStable({ ageHours: 4, bucket: 0.05 })).toBe(false);
|
||||
expect(admitsStable({ ageHours: 8, bucket: 0.05 })).toBe(false);
|
||||
expect(admitsStable({ ageHours: 8, bucket: MAX_BUCKET })).toBe(false);
|
||||
});
|
||||
|
||||
it("admits by bucket along the ramp", () => {
|
||||
expect(admitsStable({ ageHours: 13, bucket: 0.52 })).toBe(true);
|
||||
expect(admitsStable({ ageHours: 13, bucket: 0.53 })).toBe(false);
|
||||
});
|
||||
|
||||
it("admits every bucket at and after the rollout end", () => {
|
||||
expect(admitsStable({ ageHours: 18, bucket: MAX_BUCKET })).toBe(true);
|
||||
expect(admitsStable({ ageHours: 24 * 365, bucket: MAX_BUCKET })).toBe(true);
|
||||
});
|
||||
|
||||
it("lets manual checks bypass the rollout", () => {
|
||||
expect(admitsStable({ ageHours: 1, bucket: MAX_BUCKET, intent: "manual" })).toBe(true);
|
||||
expect(admitsStable({ ageHours: -48, bucket: MAX_BUCKET, intent: "manual" })).toBe(true);
|
||||
});
|
||||
|
||||
it("admits everyone to an emergency release with rolloutHours 0", () => {
|
||||
expect(admitsStable({ ageHours: 0, bucket: MAX_BUCKET, rolloutHours: 0 })).toBe(true);
|
||||
expect(admitsStable({ ageHours: -48, bucket: MAX_BUCKET, rolloutHours: 0 })).toBe(true);
|
||||
});
|
||||
|
||||
it("admits beta, missing rollout hours, and a missing or unparseable release date", () => {
|
||||
const base = {
|
||||
intent: "automatic" as const,
|
||||
rolloutHours: 18,
|
||||
releaseDate: RELEASE_DATE,
|
||||
now: RELEASE_TIME + HOUR_MS,
|
||||
bucket: MAX_BUCKET,
|
||||
};
|
||||
|
||||
expect(shouldAdmitAppUpdate({ ...base, channel: "beta" })).toBe(true);
|
||||
expect(shouldAdmitAppUpdate({ ...base, channel: "stable", rolloutHours: undefined })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(shouldAdmitAppUpdate({ ...base, channel: "stable", releaseDate: undefined })).toBe(true);
|
||||
expect(shouldAdmitAppUpdate({ ...base, channel: "stable", releaseDate: "not a date" })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a client whose clock is slightly behind the release date in the canary hold", () => {
|
||||
expect(admitsStable({ ageHours: -1, bucket: 0.049 })).toBe(true);
|
||||
expect(admitsStable({ ageHours: -1, bucket: 0.05 })).toBe(false);
|
||||
expect(admitsStable({ ageHours: -2, bucket: 0.05 })).toBe(false);
|
||||
});
|
||||
|
||||
it("admits a client whose clock is too far behind the release date to place on the curve", () => {
|
||||
// With releases shipping more often than the clock error, this client
|
||||
// would otherwise see every release as unreleased and never update.
|
||||
expect(admitsStable({ ageHours: -2.01, bucket: MAX_BUCKET })).toBe(true);
|
||||
expect(admitsStable({ ageHours: -24 * 365, bucket: MAX_BUCKET })).toBe(true);
|
||||
});
|
||||
|
||||
it("treats garbage manifest rollout fields as missing and admits", () => {
|
||||
const parsed = rolloutManifestSchema.parse({
|
||||
rolloutHours: "not a number",
|
||||
releaseDate: 12345,
|
||||
});
|
||||
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "automatic",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-29T00:00:00.000Z"),
|
||||
bucket: maxBucket,
|
||||
rolloutHours: parsed.rolloutHours,
|
||||
releaseDate: parsed.releaseDate,
|
||||
now: RELEASE_TIME + HOUR_MS,
|
||||
bucket: MAX_BUCKET,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "automatic",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2027-04-28T00:00:00.000Z"),
|
||||
bucket: maxBucket,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("parses the stamped rollout fields that older clients already read", () => {
|
||||
expect(rolloutManifestSchema.parse({ rolloutHours: 18, releaseDate: RELEASE_DATE })).toEqual({
|
||||
rolloutHours: 18,
|
||||
releaseDate: RELEASE_DATE,
|
||||
});
|
||||
expect(rolloutManifestSchema.parse({ rolloutHours: "18" }).rolloutHours).toBe(18);
|
||||
expect(rolloutManifestSchema.parse({ rolloutHours: -1 }).rolloutHours).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPacedRelease", () => {
|
||||
it("paces only stable releases with a positive rollout duration", () => {
|
||||
expect(isPacedRelease({ channel: "stable", rolloutHours: 18 })).toBe(true);
|
||||
expect(isPacedRelease({ channel: "stable", rolloutHours: 0.5 })).toBe(true);
|
||||
expect(isPacedRelease({ channel: "stable", rolloutHours: 0 })).toBe(false);
|
||||
expect(isPacedRelease({ channel: "stable", rolloutHours: undefined })).toBe(false);
|
||||
expect(isPacedRelease({ channel: "beta", rolloutHours: 18 })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rolloutBucket", () => {
|
||||
const stagingUserId = "3f2c1b6e-8a4d-5c7e-9b1a-2d3e4f5a6b7c";
|
||||
|
||||
function stagingUserIdAt(index: number): string {
|
||||
return `00000000-0000-5000-8000-${index.toString(16).padStart(12, "0")}`;
|
||||
}
|
||||
|
||||
it("is stable for one install and one version", () => {
|
||||
expect(rolloutBucket(stagingUserId, "1.2.4")).toBe(rolloutBucket(stagingUserId, "1.2.4"));
|
||||
});
|
||||
|
||||
it("always lands in [0, 1)", () => {
|
||||
for (let index = 0; index < 2000; index += 1) {
|
||||
const bucket = rolloutBucket(stagingUserIdAt(index), "1.2.4");
|
||||
expect(bucket).toBeGreaterThanOrEqual(0);
|
||||
expect(bucket).toBeLessThan(1);
|
||||
}
|
||||
});
|
||||
|
||||
it("gives one install a different bucket for each version", () => {
|
||||
const buckets = new Set(
|
||||
Array.from({ length: 50 }, (_, patch) => rolloutBucket(stagingUserId, `1.2.${patch}`)),
|
||||
);
|
||||
expect(buckets.size).toBe(50);
|
||||
});
|
||||
|
||||
it("admits when releaseDate is unparseable", () => {
|
||||
expect(
|
||||
shouldAdmitAppUpdate({
|
||||
channel: "stable",
|
||||
intent: "automatic",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "not a date",
|
||||
now: Date.parse("2026-04-28T12:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
it("spreads installs evenly so about 5% land in the canary", () => {
|
||||
const installs = 20_000;
|
||||
let canary = 0;
|
||||
for (let index = 0; index < installs; index += 1) {
|
||||
if (rolloutBucket(stagingUserIdAt(index), "1.2.4") < 0.05) canary += 1;
|
||||
}
|
||||
expect(canary / installs).toBeGreaterThan(0.04);
|
||||
expect(canary / installs).toBeLessThan(0.06);
|
||||
});
|
||||
|
||||
it("maps the maximum 32-bit slot to a bucket strictly less than 1", () => {
|
||||
const allOnes = "ffffffff-ffff-ffff-ffff-ffffffffffff";
|
||||
const allZeros = "00000000-0000-0000-0000-000000000000";
|
||||
it("picks a fresh canary group for each version", () => {
|
||||
const installs = 20_000;
|
||||
let canaryForBoth = 0;
|
||||
for (let index = 0; index < installs; index += 1) {
|
||||
const id = stagingUserIdAt(index);
|
||||
if (rolloutBucket(id, "1.2.4") < 0.05 && rolloutBucket(id, "1.2.5") < 0.05) {
|
||||
canaryForBoth += 1;
|
||||
}
|
||||
}
|
||||
// Independent 5% groups overlap in about 0.25% of installs. A sticky bucket
|
||||
// would overlap in all 5%.
|
||||
expect(canaryForBoth / installs).toBeLessThan(0.01);
|
||||
});
|
||||
|
||||
expect(bucketFromStagingUserId(allOnes)).toBeLessThan(1);
|
||||
expect(bucketFromStagingUserId(allOnes)).toBeGreaterThan(0.999);
|
||||
expect(bucketFromStagingUserId(allZeros)).toBe(0);
|
||||
it("never leaves an install outside the canary for every version", () => {
|
||||
for (let index = 0; index < 200; index += 1) {
|
||||
const id = stagingUserIdAt(index);
|
||||
let canaryReleases = 0;
|
||||
for (let patch = 0; patch < 400; patch += 1) {
|
||||
if (rolloutBucket(id, `1.2.${patch}`) < 0.05) canaryReleases += 1;
|
||||
}
|
||||
expect(canaryReleases).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { UUID } from "builder-util-runtime";
|
||||
import { createHash } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
|
||||
export type AppReleaseChannel = "stable" | "beta";
|
||||
export type AppUpdateCheckIntent = "automatic" | "manual";
|
||||
|
||||
const HOUR_MS = 3_600_000;
|
||||
const CANARY_PERCENT = 5;
|
||||
const MAX_CANARY_HOURS = 8;
|
||||
// A release date this far ahead of the local clock means the clock is wrong,
|
||||
// not that the release is new. One hour of daylight-saving error stays inside.
|
||||
const CLOCK_SKEW_TOLERANCE_HOURS = 2;
|
||||
|
||||
export const rolloutManifestSchema = z.object({
|
||||
rolloutHours: z
|
||||
.union([z.number(), z.string().transform(Number)])
|
||||
@@ -13,6 +20,37 @@ export const rolloutManifestSchema = z.object({
|
||||
releaseDate: z.string().optional().catch(undefined),
|
||||
});
|
||||
|
||||
/**
|
||||
* A paced release reaches automatic clients gradually. Every other release
|
||||
* (beta, `rolloutHours: 0`, or no usable `rolloutHours`) reaches them at once.
|
||||
*/
|
||||
export function isPacedRelease(args: {
|
||||
channel: AppReleaseChannel;
|
||||
rolloutHours: number | undefined;
|
||||
}): boolean {
|
||||
return args.channel === "stable" && args.rolloutHours != null && args.rolloutHours > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Share of automatic clients admitted to a paced release: a canary hold at 5%,
|
||||
* then a linear ramp to 100% at `rolloutHours`.
|
||||
*/
|
||||
export function rolloutAdmissionPercent(args: { rolloutHours: number; ageHours: number }): number {
|
||||
const ageHours = Math.max(0, args.ageHours);
|
||||
if (ageHours >= args.rolloutHours) return 100;
|
||||
|
||||
const canaryHours = Math.min(MAX_CANARY_HOURS, args.rolloutHours / 2);
|
||||
if (ageHours <= canaryHours) return CANARY_PERCENT;
|
||||
|
||||
const rampProgress = (ageHours - canaryHours) / (args.rolloutHours - canaryHours);
|
||||
return Math.min(100, CANARY_PERCENT + (100 - CANARY_PERCENT) * rampProgress);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every branch that cannot place the client on the rollout curve admits it.
|
||||
* A client must never be refused a release because of bad metadata or a bad
|
||||
* local clock.
|
||||
*/
|
||||
export function shouldAdmitAppUpdate(args: {
|
||||
channel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
@@ -22,21 +60,26 @@ export function shouldAdmitAppUpdate(args: {
|
||||
bucket: number;
|
||||
}): boolean {
|
||||
if (args.intent === "manual") return true;
|
||||
if (args.channel !== "stable") return true;
|
||||
if (args.rolloutHours == null) return true;
|
||||
if (args.rolloutHours === 0) return true;
|
||||
if (!isPacedRelease(args) || args.rolloutHours == null) return true;
|
||||
if (!args.releaseDate) return true;
|
||||
|
||||
const releaseTime = new Date(args.releaseDate).getTime();
|
||||
if (Number.isNaN(releaseTime)) return true;
|
||||
|
||||
const ageHours = (args.now - releaseTime) / 3_600_000;
|
||||
if (ageHours < 0) return false;
|
||||
const ageHours = (args.now - releaseTime) / HOUR_MS;
|
||||
if (Number.isNaN(ageHours)) return true;
|
||||
if (ageHours < -CLOCK_SKEW_TOLERANCE_HOURS) return true;
|
||||
|
||||
const pct = Math.min(100, (ageHours / args.rolloutHours) * 100);
|
||||
return args.bucket * 100 < pct;
|
||||
const percent = rolloutAdmissionPercent({ rolloutHours: args.rolloutHours, ageHours });
|
||||
return args.bucket * 100 < percent;
|
||||
}
|
||||
|
||||
export function bucketFromStagingUserId(stagingUserId: string): number {
|
||||
return UUID.parse(stagingUserId).readUInt32BE(12) / 0x100000000;
|
||||
/**
|
||||
* Position of one install in one release's rollout, in [0, 1). Salting with the
|
||||
* version gives every release a different canary group, so no install is first
|
||||
* for every release and none is last for every release.
|
||||
*/
|
||||
export function rolloutBucket(stagingUserId: string, version: string): number {
|
||||
const digest = createHash("sha256").update(`${stagingUserId}:${version}`).digest();
|
||||
return digest.readUInt32BE(0) / 0x100000000;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,13 +1,26 @@
|
||||
import type { DesktopUpdateMode } from "../settings/desktop-settings.js";
|
||||
import type { AppUpdatePacing } from "./app-update-pacing.js";
|
||||
import {
|
||||
isPacedRelease,
|
||||
rolloutManifestSchema,
|
||||
shouldAdmitAppUpdate,
|
||||
type AppReleaseChannel,
|
||||
type AppUpdateCheckIntent,
|
||||
} from "./app-update-rollout.js";
|
||||
import { isNextPatchRelease } from "./app-update-version.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;
|
||||
@@ -19,6 +32,7 @@ export interface AppUpdateInstallResult {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
message: string;
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
||||
export interface RuntimeUpdateInfo {
|
||||
@@ -28,6 +42,13 @@ export interface RuntimeUpdateInfo {
|
||||
rolloutHours?: unknown;
|
||||
}
|
||||
|
||||
export interface RuntimeDownloadProgressInfo {
|
||||
percent: number;
|
||||
transferred: number;
|
||||
total: number;
|
||||
bytesPerSecond: number;
|
||||
}
|
||||
|
||||
export interface RuntimeUpdateCheckResult {
|
||||
isUpdateAvailable: boolean;
|
||||
updateInfo: RuntimeUpdateInfo;
|
||||
@@ -35,8 +56,10 @@ 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;
|
||||
}
|
||||
@@ -47,11 +70,19 @@ 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): void;
|
||||
quitAndInstall(
|
||||
input: AppUpdateInstallRequest,
|
||||
): Promise<AppUpdateInstallLaunchResult> | AppUpdateInstallLaunchResult;
|
||||
}
|
||||
|
||||
export interface AppUpdateService {
|
||||
@@ -59,6 +90,7 @@ export interface AppUpdateService {
|
||||
currentVersion: string;
|
||||
releaseChannel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
autoDownload?: boolean;
|
||||
}): Promise<AppUpdateCheckResult>;
|
||||
downloadAndInstallUpdate(
|
||||
input: {
|
||||
@@ -78,8 +110,14 @@ export interface AppUpdateServiceDeps {
|
||||
runtime: AppUpdateRuntime;
|
||||
isPackaged(): boolean;
|
||||
now(): number;
|
||||
bucket(): Promise<number>;
|
||||
/** Position of this install in the rollout of `version`, in [0, 1). */
|
||||
bucket(version: string): Promise<number>;
|
||||
pacing: AppUpdatePacing;
|
||||
updateMode?: () => DesktopUpdateMode | Promise<DesktopUpdateMode>;
|
||||
onDownloadProgress?(progress: AppUpdateDownloadProgress | null): void;
|
||||
reportSettingsError?(error: unknown): void;
|
||||
reportCheckError?(error: unknown): void;
|
||||
reportAdmissionError?(error: unknown): void;
|
||||
reportRuntimeError?(error: unknown): void;
|
||||
reportInstallError?(message: string): void;
|
||||
}
|
||||
@@ -88,14 +126,23 @@ function buildCheckResult(input: {
|
||||
currentVersion: string;
|
||||
hasUpdate: boolean;
|
||||
readyToInstall: boolean;
|
||||
downloading?: boolean;
|
||||
info?: RuntimeUpdateInfo | null;
|
||||
errorMessage?: string | null;
|
||||
}): AppUpdateCheckResult {
|
||||
const { currentVersion, hasUpdate, readyToInstall, info, errorMessage = null } = input;
|
||||
const {
|
||||
currentVersion,
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading = false,
|
||||
info,
|
||||
errorMessage = null,
|
||||
} = input;
|
||||
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading,
|
||||
currentVersion,
|
||||
latestVersion: info?.version ?? currentVersion,
|
||||
body: typeof info?.releaseNotes === "string" ? info.releaseNotes : null,
|
||||
@@ -117,11 +164,14 @@ async function performQuitAndInstall(
|
||||
},
|
||||
): Promise<void> {
|
||||
if (onBeforeQuit) await onBeforeQuit();
|
||||
runtime.quitAndInstall({
|
||||
const launch = await 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 {
|
||||
@@ -145,17 +195,45 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
let configuredReleaseChannel: AppReleaseChannel | null = null;
|
||||
let preparationError: { version: string; message: string } | null = null;
|
||||
let preparingUpdateVersion: string | null = null;
|
||||
// The newest release seen in an unbroken run of paced releases since the
|
||||
// staged update became ready. Null whenever nothing is staged.
|
||||
let stagedChainHead: string | null = null;
|
||||
let currentAutoDownload = true;
|
||||
let checkQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
function isReadyToInstallVersion(version: string): boolean {
|
||||
return downloadedUpdateVersion === version;
|
||||
}
|
||||
|
||||
function setStagedUpdate(version: string | null): void {
|
||||
downloadedUpdateVersion = version;
|
||||
stagedChainHead = version;
|
||||
}
|
||||
|
||||
function clearUpdateState(): void {
|
||||
cachedUpdateInfo = null;
|
||||
downloadedUpdateVersion = null;
|
||||
setStagedUpdate(null);
|
||||
preparationError = null;
|
||||
preparingUpdateVersion = null;
|
||||
deps.onDownloadProgress?.(null);
|
||||
}
|
||||
|
||||
/** What is already known about an update, without asking the release feed. */
|
||||
function buildKnownUpdateResult(currentVersion: string): AppUpdateCheckResult {
|
||||
const info = cachedUpdateInfo;
|
||||
if (!info || info.version === currentVersion) {
|
||||
return buildCheckResult({ currentVersion, hasUpdate: false, readyToInstall: false });
|
||||
}
|
||||
|
||||
const readyToInstall = isReadyToInstallVersion(info.version);
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: true,
|
||||
readyToInstall,
|
||||
downloading: !readyToInstall && preparingUpdateVersion === info.version,
|
||||
info,
|
||||
errorMessage: preparationError?.version === info.version ? preparationError.message : null,
|
||||
});
|
||||
}
|
||||
|
||||
function buildPreviouslyAdmittedUpdateResult(
|
||||
@@ -166,54 +244,149 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
if (!info || info.version === currentVersion || info.version !== checkedInfo.version) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: true,
|
||||
readyToInstall: isReadyToInstallVersion(info.version),
|
||||
info,
|
||||
errorMessage: preparationError?.version === info.version ? preparationError.message : null,
|
||||
});
|
||||
return buildKnownUpdateResult(currentVersion);
|
||||
}
|
||||
|
||||
function configureRuntime(releaseChannel: AppReleaseChannel, intent: AppUpdateCheckIntent): void {
|
||||
/**
|
||||
* A staged update is not replaced by the paced release that follows it, so
|
||||
* an install that is slow to restart does not download every release. The
|
||||
* hold covers only a run of paced releases seen one after the other: a gap
|
||||
* means a release was missed, and the missed one may have been the fix for
|
||||
* the staged one. Emergency releases and manual checks always replace it.
|
||||
*/
|
||||
function stagedUpdateHoldsAgainst(
|
||||
info: RuntimeUpdateInfo,
|
||||
releaseChannel: AppReleaseChannel,
|
||||
): boolean {
|
||||
const staged = downloadedUpdateVersion;
|
||||
if (staged === null || stagedChainHead === null) return false;
|
||||
if (cachedUpdateInfo?.version !== staged || info.version === staged) return false;
|
||||
|
||||
const { rolloutHours } = rolloutManifestSchema.parse(info);
|
||||
if (!isPacedRelease({ channel: releaseChannel, rolloutHours })) return false;
|
||||
|
||||
return info.version === stagedChainHead || isNextPatchRelease(stagedChainHead, info.version);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an automatic check may take this release now. Any failure to
|
||||
* decide admits the release: an install is never refused an update because
|
||||
* its own rollout state could not be read.
|
||||
*/
|
||||
async function admitsAutomatically(
|
||||
info: RuntimeUpdateInfo,
|
||||
releaseChannel: AppReleaseChannel,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const { rolloutHours, releaseDate } = rolloutManifestSchema.parse(info);
|
||||
if (!isPacedRelease({ channel: releaseChannel, rolloutHours })) return true;
|
||||
if (stagedUpdateHoldsAgainst(info, releaseChannel)) return false;
|
||||
if (await deps.pacing.isInUpdateCooldown()) return false;
|
||||
|
||||
return shouldAdmitAppUpdate({
|
||||
channel: releaseChannel,
|
||||
intent: "automatic",
|
||||
rolloutHours,
|
||||
releaseDate,
|
||||
now: deps.now(),
|
||||
bucket: await deps.bucket(info.version),
|
||||
});
|
||||
} catch (error) {
|
||||
deps.reportAdmissionError?.(error);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** An admitted update that is neither downloaded nor downloading. */
|
||||
function hasUnpreparedUpdate(currentVersion: string): boolean {
|
||||
const info = cachedUpdateInfo;
|
||||
return (
|
||||
info !== null &&
|
||||
info.version !== currentVersion &&
|
||||
!isReadyToInstallVersion(info.version) &&
|
||||
preparingUpdateVersion !== info.version
|
||||
);
|
||||
}
|
||||
|
||||
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 {
|
||||
if (configuredReleaseChannel !== releaseChannel) {
|
||||
clearUpdateState();
|
||||
configuredReleaseChannel = releaseChannel;
|
||||
}
|
||||
currentAutoDownload = initialAutoDownload;
|
||||
|
||||
deps.runtime.configure({
|
||||
releaseChannel,
|
||||
autoDownload: initialAutoDownload,
|
||||
shouldAdmitUpdate: async (info) => {
|
||||
const parsed = rolloutManifestSchema.parse(info);
|
||||
return shouldAdmitAppUpdate({
|
||||
channel: releaseChannel,
|
||||
intent,
|
||||
rolloutHours: parsed.rolloutHours,
|
||||
releaseDate: parsed.releaseDate,
|
||||
now: deps.now(),
|
||||
bucket: await deps.bucket(),
|
||||
});
|
||||
// A manual check needs no rollout or pacing state, so nothing that
|
||||
// breaks that state can stop the user from updating by hand.
|
||||
const admitted = intent === "manual" || (await admitsAutomatically(info, releaseChannel));
|
||||
// Read the mode after every other await, so a mode saved during the
|
||||
// check is the one that decides.
|
||||
const liveMode = await resolveUpdateMode();
|
||||
if (intent === "automatic" && liveMode === "off") {
|
||||
return false;
|
||||
}
|
||||
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 && preparingUpdateVersion === null) {
|
||||
if (!alreadyReady) setStagedUpdate(null);
|
||||
if (!alreadyReady && currentAutoDownload && 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.
|
||||
cachedUpdateInfo ??= info;
|
||||
downloadedUpdateVersion = info.version;
|
||||
setStagedUpdate(info.version);
|
||||
if (preparingUpdateVersion === info.version) {
|
||||
preparingUpdateVersion = null;
|
||||
}
|
||||
if (preparationError?.version === info.version) {
|
||||
preparationError = null;
|
||||
}
|
||||
deps.onDownloadProgress?.(null);
|
||||
},
|
||||
onError(error) {
|
||||
if (preparingUpdateVersion) {
|
||||
@@ -223,6 +396,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
};
|
||||
preparingUpdateVersion = null;
|
||||
}
|
||||
deps.onDownloadProgress?.(null);
|
||||
deps.reportRuntimeError?.(error);
|
||||
},
|
||||
});
|
||||
@@ -237,15 +411,110 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
return result;
|
||||
}
|
||||
|
||||
async function checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent,
|
||||
}: {
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The release feed answered with a release this check may not take. An
|
||||
* update admitted earlier survives only when the feed still names it, or
|
||||
* when it is staged and holds against the release the feed names now.
|
||||
*/
|
||||
function resolveUnavailableUpdateResult(
|
||||
check: {
|
||||
currentVersion: string;
|
||||
releaseChannel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
},
|
||||
info: RuntimeUpdateInfo,
|
||||
): AppUpdateCheckResult {
|
||||
const admittedUpdate = buildPreviouslyAdmittedUpdateResult(check.currentVersion, info);
|
||||
if (admittedUpdate) {
|
||||
return admittedUpdate;
|
||||
}
|
||||
|
||||
if (check.intent === "automatic" && stagedUpdateHoldsAgainst(info, check.releaseChannel)) {
|
||||
stagedChainHead = info.version;
|
||||
return buildKnownUpdateResult(check.currentVersion);
|
||||
}
|
||||
|
||||
clearUpdateState();
|
||||
return buildCheckResult({
|
||||
currentVersion: check.currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reasons to ask the release feed before the next check is due: a change of
|
||||
* channel makes the known update stale, and an update that should be
|
||||
* downloading but is not needs the check to start it again.
|
||||
*/
|
||||
function mustCheckNow(
|
||||
currentVersion: string,
|
||||
releaseChannel: AppReleaseChannel,
|
||||
autoDownload: boolean,
|
||||
): boolean {
|
||||
const channelChanged =
|
||||
configuredReleaseChannel !== null && configuredReleaseChannel !== releaseChannel;
|
||||
return channelChanged || (autoDownload && hasUnpreparedUpdate(currentVersion));
|
||||
}
|
||||
|
||||
interface UpdateCheckInput {
|
||||
currentVersion: string;
|
||||
releaseChannel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
}): Promise<AppUpdateCheckResult> {
|
||||
autoDownload?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* `spaced` checks are the background ones the app makes on its own. On the
|
||||
* stable channel they ask the release feed at most once per pacing interval
|
||||
* and answer from what is already known in between.
|
||||
*/
|
||||
async function runUpdateCheck(
|
||||
{ currentVersion, releaseChannel, intent, autoDownload }: UpdateCheckInput,
|
||||
{ spaced }: { spaced: boolean },
|
||||
): Promise<AppUpdateCheckResult> {
|
||||
if (!deps.isPackaged()) {
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
@@ -255,10 +524,43 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
}
|
||||
|
||||
return runCheckExclusively(async () => {
|
||||
configureRuntime(releaseChannel, intent);
|
||||
const respectsInterval = spaced && intent === "automatic" && releaseChannel === "stable";
|
||||
const checkIsDue = respectsInterval ? await deps.pacing.isAutomaticCheckDue() : true;
|
||||
|
||||
const mode = deps.updateMode ? await resolveUpdateMode() : "automatic";
|
||||
if (intent === "automatic" && mode === "off") {
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
|
||||
const initialAutoDownload = resolveAutoDownload(mode, autoDownload);
|
||||
if (!checkIsDue && !mustCheckNow(currentVersion, releaseChannel, initialAutoDownload)) {
|
||||
return buildKnownUpdateResult(currentVersion);
|
||||
}
|
||||
|
||||
if (intent === "manual") {
|
||||
preparationError = null;
|
||||
}
|
||||
configureRuntime(releaseChannel, intent, initialAutoDownload, autoDownload);
|
||||
|
||||
try {
|
||||
const result = await deps.runtime.checkForUpdates();
|
||||
// Only a check that read the release feed counts. A failed check
|
||||
// throws, and an unreadable feed answers null: both run again at the
|
||||
// next opportunity.
|
||||
if (respectsInterval && result) {
|
||||
await deps.pacing.recordAutomaticCheck();
|
||||
}
|
||||
if (intent === "automatic" && deps.updateMode && (await resolveUpdateMode()) === "off") {
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
if (!result || !result.updateInfo) {
|
||||
clearUpdateState();
|
||||
return buildCheckResult({
|
||||
@@ -269,48 +571,13 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
}
|
||||
|
||||
if (!result.isUpdateAvailable) {
|
||||
const admittedUpdate = buildPreviouslyAdmittedUpdateResult(
|
||||
currentVersion,
|
||||
return resolveUnavailableUpdateResult(
|
||||
{ currentVersion, releaseChannel, intent },
|
||||
result.updateInfo,
|
||||
);
|
||||
if (admittedUpdate) {
|
||||
return admittedUpdate;
|
||||
}
|
||||
|
||||
clearUpdateState();
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
return resolveAvailableUpdateResult(currentVersion, result.updateInfo);
|
||||
} catch (error) {
|
||||
deps.reportCheckError?.(error);
|
||||
return buildCheckResult({
|
||||
@@ -323,6 +590,10 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
});
|
||||
}
|
||||
|
||||
function checkForAppUpdate(input: UpdateCheckInput): Promise<AppUpdateCheckResult> {
|
||||
return runUpdateCheck(input, { spaced: true });
|
||||
}
|
||||
|
||||
async function downloadAndInstallUpdate(
|
||||
{
|
||||
currentVersion,
|
||||
@@ -341,22 +612,41 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
};
|
||||
}
|
||||
|
||||
const check = await checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent: "manual",
|
||||
});
|
||||
const check = await runUpdateCheck(
|
||||
{ currentVersion, releaseChannel, intent: "manual", autoDownload: false },
|
||||
{ spaced: 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,
|
||||
@@ -367,14 +657,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) {
|
||||
if (
|
||||
attemptedVersion !== readyVersion &&
|
||||
cachedUpdateInfo?.version === readyVersion &&
|
||||
!signal?.aborted
|
||||
) {
|
||||
clearPreparingVersion(attemptedVersion);
|
||||
if (shouldRetryStaleDownloadError(attemptedVersion, readyVersion, signal)) {
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
@@ -384,8 +674,10 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
// event clears that version, then the next iteration starts the newly
|
||||
// validated release instead of treating the stale artifact as ready.
|
||||
if (attemptedVersion === readyVersion && !isReadyToInstallVersion(readyVersion)) {
|
||||
downloadedUpdateVersion = readyVersion;
|
||||
preparingUpdateVersion = null;
|
||||
setStagedUpdate(readyVersion);
|
||||
clearPreparingVersion(readyVersion);
|
||||
} else if (preparingUpdateVersion === attemptedVersion) {
|
||||
clearPreparingVersion(attemptedVersion);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,30 +709,19 @@ 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 {
|
||||
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.",
|
||||
};
|
||||
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.",
|
||||
};
|
||||
}
|
||||
}
|
||||
await performQuitAndInstall(deps.runtime, {
|
||||
targetVersion: readyVersion,
|
||||
@@ -454,12 +735,14 @@ 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -476,12 +759,16 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
if (!deps.isPackaged() || !downloadedUpdateVersion) {
|
||||
return false;
|
||||
}
|
||||
if ((await resolveUpdateMode()) !== "automatic") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const check = await checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent: "automatic",
|
||||
});
|
||||
// The staged update is validated against the release feed before every
|
||||
// install, however recently the app last checked.
|
||||
const check = await runUpdateCheck(
|
||||
{ currentVersion, releaseChannel, intent: "automatic" },
|
||||
{ spaced: false },
|
||||
);
|
||||
if (signal.aborted || !check.hasUpdate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isNewerVersion, isNextPatchRelease } from "./app-update-version";
|
||||
|
||||
describe("isNewerVersion", () => {
|
||||
it("orders releases by major, minor, then patch", () => {
|
||||
expect(isNewerVersion("0.17.5", "0.17.4")).toBe(true);
|
||||
expect(isNewerVersion("0.18.0", "0.17.9")).toBe(true);
|
||||
expect(isNewerVersion("1.0.0", "0.99.99")).toBe(true);
|
||||
expect(isNewerVersion("0.17.10", "0.17.9")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not call the same or an older version newer", () => {
|
||||
expect(isNewerVersion("0.17.4", "0.17.4")).toBe(false);
|
||||
expect(isNewerVersion("0.17.3", "0.17.4")).toBe(false);
|
||||
expect(isNewerVersion("0.16.9", "0.17.0")).toBe(false);
|
||||
});
|
||||
|
||||
it("orders a release after its own prereleases", () => {
|
||||
expect(isNewerVersion("0.17.0", "0.17.0-beta.2")).toBe(true);
|
||||
expect(isNewerVersion("0.17.0-beta.2", "0.17.0")).toBe(false);
|
||||
expect(isNewerVersion("0.17.0-beta.2", "0.16.4")).toBe(true);
|
||||
});
|
||||
|
||||
it("orders prereleases numerically, not as text", () => {
|
||||
expect(isNewerVersion("0.17.0-beta.10", "0.17.0-beta.9")).toBe(true);
|
||||
expect(isNewerVersion("0.17.0-beta.2", "0.17.0-beta.2")).toBe(false);
|
||||
expect(isNewerVersion("0.17.0-beta.1", "0.17.0-alpha.5")).toBe(true);
|
||||
expect(isNewerVersion("0.17.0-beta.1.1", "0.17.0-beta.1")).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores a leading v and build metadata", () => {
|
||||
expect(isNewerVersion("v0.17.5", "0.17.4")).toBe(true);
|
||||
expect(isNewerVersion("0.17.5+build.7", "0.17.5")).toBe(false);
|
||||
});
|
||||
|
||||
it("never calls a version newer when either side is not a version", () => {
|
||||
expect(isNewerVersion("0.17.5", "")).toBe(false);
|
||||
expect(isNewerVersion("0.17.5", "latest")).toBe(false);
|
||||
expect(isNewerVersion("nightly", "0.17.4")).toBe(false);
|
||||
expect(isNewerVersion("0.17", "0.16.0")).toBe(false);
|
||||
expect(isNewerVersion("0.17.5.1", "0.17.4")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isNextPatchRelease", () => {
|
||||
it("accepts only the patch release that directly follows", () => {
|
||||
expect(isNextPatchRelease("0.17.4", "0.17.5")).toBe(true);
|
||||
expect(isNextPatchRelease("0.17.9", "0.17.10")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a skipped release, the same release, and an older release", () => {
|
||||
expect(isNextPatchRelease("0.17.4", "0.17.6")).toBe(false);
|
||||
expect(isNextPatchRelease("0.17.4", "0.17.4")).toBe(false);
|
||||
expect(isNextPatchRelease("0.17.4", "0.17.3")).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a minor or major bump", () => {
|
||||
expect(isNextPatchRelease("0.17.4", "0.18.0")).toBe(false);
|
||||
expect(isNextPatchRelease("0.17.4", "1.17.5")).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects prereleases and anything that is not a version", () => {
|
||||
expect(isNextPatchRelease("0.17.4", "0.17.5-beta.1")).toBe(false);
|
||||
expect(isNextPatchRelease("0.17.4-beta.1", "0.17.5")).toBe(false);
|
||||
expect(isNextPatchRelease("0.17.4", "next")).toBe(false);
|
||||
expect(isNextPatchRelease("", "0.17.5")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
interface ParsedVersion {
|
||||
core: [number, number, number];
|
||||
prerelease: string[];
|
||||
}
|
||||
|
||||
const VERSION_PATTERN = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
const NUMERIC_IDENTIFIER = /^\d+$/;
|
||||
|
||||
function parseVersion(version: string): ParsedVersion | null {
|
||||
const match = VERSION_PATTERN.exec(version.trim());
|
||||
if (!match) return null;
|
||||
return {
|
||||
core: [Number(match[1]), Number(match[2]), Number(match[3])],
|
||||
prerelease: match[4] ? match[4].split(".") : [],
|
||||
};
|
||||
}
|
||||
|
||||
function comparePrereleaseIdentifier(left: string, right: string): number {
|
||||
const leftNumeric = NUMERIC_IDENTIFIER.test(left);
|
||||
const rightNumeric = NUMERIC_IDENTIFIER.test(right);
|
||||
if (leftNumeric && rightNumeric) return Number(left) - Number(right);
|
||||
if (leftNumeric) return -1;
|
||||
if (rightNumeric) return 1;
|
||||
if (left === right) return 0;
|
||||
return left < right ? -1 : 1;
|
||||
}
|
||||
|
||||
function comparePrerelease(left: string[], right: string[]): number {
|
||||
// A release sorts after its own prereleases.
|
||||
if (left.length === 0 || right.length === 0) return right.length - left.length;
|
||||
|
||||
for (let index = 0; index < Math.min(left.length, right.length); index += 1) {
|
||||
const order = comparePrereleaseIdentifier(left[index], right[index]);
|
||||
if (order !== 0) return order;
|
||||
}
|
||||
return left.length - right.length;
|
||||
}
|
||||
|
||||
function compareVersions(left: ParsedVersion, right: ParsedVersion): number {
|
||||
for (let index = 0; index < left.core.length; index += 1) {
|
||||
const order = left.core[index] - right.core[index];
|
||||
if (order !== 0) return order;
|
||||
}
|
||||
return comparePrerelease(left.prerelease, right.prerelease);
|
||||
}
|
||||
|
||||
/** False when either side is not a version, so an unknown version never counts as an update. */
|
||||
export function isNewerVersion(candidate: string, baseline: string): boolean {
|
||||
const parsedCandidate = parseVersion(candidate);
|
||||
const parsedBaseline = parseVersion(baseline);
|
||||
if (!parsedCandidate || !parsedBaseline) return false;
|
||||
return compareVersions(parsedCandidate, parsedBaseline) > 0;
|
||||
}
|
||||
|
||||
/** True only for the release that directly follows `previous` on the same minor line. */
|
||||
export function isNextPatchRelease(previous: string, next: string): boolean {
|
||||
const parsedPrevious = parseVersion(previous);
|
||||
const parsedNext = parseVersion(next);
|
||||
if (!parsedPrevious || !parsedNext) return false;
|
||||
if (parsedPrevious.prerelease.length > 0 || parsedNext.prerelease.length > 0) return false;
|
||||
|
||||
const [previousMajor, previousMinor, previousPatch] = parsedPrevious.core;
|
||||
const [nextMajor, nextMinor, nextPatch] = parsedNext.core;
|
||||
return (
|
||||
nextMajor === previousMajor && nextMinor === previousMinor && nextPatch === previousPatch + 1
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,26 @@
|
||||
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 } = vi.hoisted(() => {
|
||||
const handlers = new Map<string, (value: unknown) => void>();
|
||||
const { autoUpdaterMock, getAllWindowsMock, desktopSettingsMock } = vi.hoisted(() => {
|
||||
const handlers = new Map<string, Set<(value: unknown) => void>>();
|
||||
return {
|
||||
getAllWindowsMock: vi.fn<() => unknown[]>(() => []),
|
||||
desktopSettingsMock: {
|
||||
mode: "automatic" as "automatic" | "notify" | "off",
|
||||
error: null as Error | null,
|
||||
},
|
||||
autoUpdaterMock: {
|
||||
handlers,
|
||||
handlers: {
|
||||
get: (event: string) => (value: unknown) => {
|
||||
for (const listener of handlers.get(event) ?? []) {
|
||||
listener(value);
|
||||
}
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
error: vi.fn((message: unknown) => console.error(message)),
|
||||
@@ -18,7 +30,15 @@ const { autoUpdaterMock } = vi.hoisted(() => {
|
||||
checkForUpdates: vi.fn(),
|
||||
downloadUpdate: vi.fn(),
|
||||
on: vi.fn((event: string, handler: (value: unknown) => void) => {
|
||||
handlers.set(event, handler);
|
||||
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);
|
||||
}),
|
||||
quitAndInstall: vi.fn(),
|
||||
},
|
||||
@@ -27,9 +47,30 @@ const { autoUpdaterMock } = vi.hoisted(() => {
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: {
|
||||
// No userData path: update pacing has no state file here, so it paces nothing.
|
||||
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", () => ({
|
||||
@@ -37,12 +78,11 @@ vi.mock("electron-updater", () => ({
|
||||
}));
|
||||
|
||||
import {
|
||||
bucketFromStagingUserId,
|
||||
checkForAppUpdate,
|
||||
createAppUpdateLifecycleLogger,
|
||||
downloadAndInstallUpdate,
|
||||
resolveStagingUserId,
|
||||
rolloutManifestSchema,
|
||||
shouldAdmitToRollout,
|
||||
runElectronQuitAndInstall,
|
||||
shouldInstallAppUpdateOnQuit,
|
||||
} from "./auto-updater";
|
||||
|
||||
@@ -67,6 +107,7 @@ describe("checkForAppUpdate", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -97,6 +138,248 @@ 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 });
|
||||
@@ -151,156 +434,7 @@ describe("shouldInstallAppUpdateOnQuit", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldAdmitToRollout", () => {
|
||||
it("admits beta, missing rollout hours, zero-hour rollout, and missing release date", () => {
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "beta",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: undefined,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 0,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 24,
|
||||
releaseDate: undefined,
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("blocks future releases and respects the linear threshold mid-rollout", () => {
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T02:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T01:00:00.000Z"),
|
||||
bucket: 0,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T12:00:00.000Z"),
|
||||
bucket: 0.49,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T12:00:00.000Z"),
|
||||
bucket: 0.51,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("blocks the bucket-zero client at exact release time, admits as soon as time advances", () => {
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T00:00:00.000Z"),
|
||||
bucket: 0,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-28T00:00:00.001Z"),
|
||||
bucket: 0,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("admits the highest-bucket client at and past the rollout end", () => {
|
||||
const maxBucket = (0x100000000 - 1) / 0x100000000;
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2026-04-29T00:00:00.000Z"),
|
||||
bucket: maxBucket,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "2026-04-28T00:00:00.000Z",
|
||||
now: Date.parse("2027-04-28T00:00:00.000Z"),
|
||||
bucket: maxBucket,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("admits when releaseDate is unparseable", () => {
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: 24,
|
||||
releaseDate: "not a date",
|
||||
now: Date.parse("2026-04-28T12:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("treats garbage manifest rollout fields as missing and admits", () => {
|
||||
const parsed = rolloutManifestSchema.parse({
|
||||
rolloutHours: "not a number",
|
||||
releaseDate: 12345,
|
||||
});
|
||||
|
||||
expect(
|
||||
shouldAdmitToRollout({
|
||||
channel: "stable",
|
||||
rolloutHours: parsed.rolloutHours,
|
||||
releaseDate: parsed.releaseDate,
|
||||
now: Date.parse("2026-04-28T12:00:00.000Z"),
|
||||
bucket: 0.99,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("maps the maximum 32-bit slot to a bucket strictly less than 1", () => {
|
||||
const allOnes = "ffffffff-ffff-ffff-ffff-ffffffffffff";
|
||||
const allZeros = "00000000-0000-0000-0000-000000000000";
|
||||
expect(bucketFromStagingUserId(allOnes)).toBeLessThan(1);
|
||||
expect(bucketFromStagingUserId(allOnes)).toBeGreaterThan(0.999);
|
||||
expect(bucketFromStagingUserId(allZeros)).toBe(0);
|
||||
});
|
||||
|
||||
describe("resolveStagingUserId", () => {
|
||||
it("creates and then reuses the on-disk staging user id", async () => {
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "paseo-updater-id-"));
|
||||
const filePath = path.join(tempDir, ".updaterId");
|
||||
|
||||
@@ -1,35 +1,36 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { app } from "electron";
|
||||
import { app, autoUpdater as electronAutoUpdater, BrowserWindow } 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";
|
||||
import { createAppUpdatePacing } from "./app-update-pacing.js";
|
||||
import {
|
||||
bucketFromStagingUserId,
|
||||
rolloutManifestSchema,
|
||||
shouldAdmitAppUpdate,
|
||||
rolloutBucket,
|
||||
type AppReleaseChannel,
|
||||
type AppUpdateCheckIntent,
|
||||
} from "./app-update-rollout.js";
|
||||
|
||||
export {
|
||||
bucketFromStagingUserId,
|
||||
rolloutManifestSchema,
|
||||
shouldAdmitAppUpdate,
|
||||
type AppReleaseChannel,
|
||||
type AppUpdateCheckIntent,
|
||||
type AppUpdateCheckResult,
|
||||
type AppUpdateDownloadProgress,
|
||||
type AppUpdateInstallResult,
|
||||
};
|
||||
|
||||
@@ -88,16 +89,6 @@ function isUpdateChannelNotPublished(error: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export function shouldAdmitToRollout(args: {
|
||||
channel: AppReleaseChannel;
|
||||
rolloutHours: number | undefined;
|
||||
releaseDate: string | undefined;
|
||||
now: number;
|
||||
bucket: number;
|
||||
}): boolean {
|
||||
return shouldAdmitAppUpdate({ ...args, intent: "automatic" });
|
||||
}
|
||||
|
||||
export async function resolveStagingUserId(filePath: string): Promise<string> {
|
||||
try {
|
||||
const id = (await readFile(filePath, "utf8")).trim();
|
||||
@@ -140,11 +131,143 @@ 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 {
|
||||
autoUpdater.autoDownload = true;
|
||||
this.configuration = input;
|
||||
autoUpdater.autoDownload = input.autoDownload;
|
||||
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
|
||||
@@ -155,7 +278,7 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
autoUpdater.allowDowngrade = false;
|
||||
autoUpdater.isUserWithinRollout = async (info) => {
|
||||
try {
|
||||
return await input.shouldAdmitUpdate(info as RuntimeUpdateInfo);
|
||||
return await (this.configuration?.shouldAdmitUpdate(info as RuntimeUpdateInfo) ?? true);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
@@ -179,19 +302,26 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
autoUpdater.on("update-available", (info) => {
|
||||
const updateInfo = info as RuntimeUpdateInfo;
|
||||
updateLifecycleLog.updateAvailable(updateInfo.version);
|
||||
input.onUpdateAvailable(updateInfo);
|
||||
this.configuration?.onUpdateAvailable(updateInfo);
|
||||
});
|
||||
autoUpdater.on("download-progress", (progress) => {
|
||||
this.configuration?.onDownloadProgress(progress as RuntimeDownloadProgressInfo);
|
||||
});
|
||||
autoUpdater.on("update-downloaded", (info) => {
|
||||
const updateInfo = info as RuntimeUpdateInfo;
|
||||
updateLifecycleLog.updateDownloaded(updateInfo.version);
|
||||
input.onUpdateDownloaded(updateInfo);
|
||||
this.configuration?.onUpdateDownloaded(updateInfo);
|
||||
});
|
||||
autoUpdater.on("error", (error) => {
|
||||
if (isUpdateChannelNotPublished(error)) return;
|
||||
input.onError(error);
|
||||
this.configuration?.onError(error);
|
||||
});
|
||||
}
|
||||
|
||||
setAutoDownload(enabled: boolean): void {
|
||||
autoUpdater.autoDownload = enabled;
|
||||
}
|
||||
|
||||
async checkForUpdates(): Promise<RuntimeUpdateCheckResult | null> {
|
||||
try {
|
||||
const result = await autoUpdater.checkForUpdates();
|
||||
@@ -211,25 +341,57 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
return autoUpdater.downloadUpdate();
|
||||
}
|
||||
|
||||
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void {
|
||||
quitAndInstall({
|
||||
targetVersion,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
}: AppUpdateInstallRequest): Promise<AppUpdateInstallLaunchResult> {
|
||||
broadcastDownloadProgress(null);
|
||||
autoUpdater.autoRunAppAfterInstall = isForceRunAfter;
|
||||
updateLifecycleLog.quitAndInstallRequested({
|
||||
targetVersion,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
});
|
||||
autoUpdater.quitAndInstall(isSilent, isForceRunAfter);
|
||||
return runElectronQuitAndInstall({
|
||||
platform: process.platform,
|
||||
updater: autoUpdater,
|
||||
nativeUpdater: electronAutoUpdater,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const appUpdatePacing = createAppUpdatePacing({
|
||||
filePath: () => path.join(app.getPath("userData"), "app-update-pacing.json"),
|
||||
currentVersion: () => app.getVersion(),
|
||||
now: () => Date.now(),
|
||||
reportError: (error) => {
|
||||
console.warn("[auto-updater] Update pacing state is unavailable, not pacing updates:", error);
|
||||
},
|
||||
});
|
||||
|
||||
const appUpdateService = createAppUpdateService({
|
||||
runtime: new ElectronAppUpdateRuntime(),
|
||||
isPackaged: () => app.isPackaged,
|
||||
now: () => Date.now(),
|
||||
bucket: async () => bucketFromStagingUserId(await getStagingUserId()),
|
||||
bucket: async (version) => rolloutBucket(await getStagingUserId(), version),
|
||||
pacing: appUpdatePacing,
|
||||
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);
|
||||
},
|
||||
reportAdmissionError: (error) => {
|
||||
console.warn("[auto-updater] Failed to place this install in the rollout, admitting:", error);
|
||||
},
|
||||
reportRuntimeError: (error) => {
|
||||
console.error("[auto-updater] Updater event failed:", error);
|
||||
},
|
||||
@@ -242,20 +404,32 @@ const appUpdateService = createAppUpdateService({
|
||||
// Public API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Notes the running version, so the launch that follows an update starts the
|
||||
* update cooldown. Call once when the app is ready. Never rejects.
|
||||
*/
|
||||
export function startAppUpdatePacing(): Promise<void> {
|
||||
if (!app.isPackaged) return Promise.resolve();
|
||||
return appUpdatePacing.start();
|
||||
}
|
||||
|
||||
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,
|
||||
|
||||
@@ -106,7 +106,7 @@ import {
|
||||
import { runDesktopStartup } from "./desktop-startup.js";
|
||||
import { registerBrowserAutomationIpc } from "./features/browser-automation/ipc.js";
|
||||
import { BrowserKeyboard } from "./features/browser-keyboard/index.js";
|
||||
import { installAppUpdateOnQuit } from "./features/auto-updater.js";
|
||||
import { installAppUpdateOnQuit, startAppUpdatePacing } from "./features/auto-updater.js";
|
||||
import {
|
||||
buildAgentDeepLinkRoute,
|
||||
parseAgentDeepLink,
|
||||
@@ -945,6 +945,7 @@ async function bootstrap(): Promise<void> {
|
||||
}
|
||||
|
||||
await app.whenReady();
|
||||
void startAppUpdatePacing();
|
||||
|
||||
const appDistDir = getAppDistDir();
|
||||
protocol.handle(APP_SCHEME, (request) => {
|
||||
@@ -1058,10 +1059,18 @@ const quitLifecycle = createQuitLifecycle({
|
||||
showShutdownFeedback: showDaemonShutdownDialog,
|
||||
}),
|
||||
installAppUpdateOnQuit: async (signal) => {
|
||||
const settings = await getDesktopSettingsStore().get();
|
||||
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,
|
||||
);
|
||||
}
|
||||
return installAppUpdateOnQuit({
|
||||
currentVersion: app.getVersion(),
|
||||
releaseChannel: settings.releaseChannel,
|
||||
releaseChannel,
|
||||
signal,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -81,6 +81,7 @@ describe("desktop-settings", () => {
|
||||
|
||||
expect(settings).toEqual({
|
||||
releaseChannel: "stable",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: true,
|
||||
@@ -97,12 +98,14 @@ 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,
|
||||
@@ -112,6 +115,65 @@ 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);
|
||||
@@ -270,6 +332,7 @@ describe("desktop-settings", () => {
|
||||
|
||||
expect(migrated).toEqual({
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: false,
|
||||
@@ -315,6 +378,7 @@ 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,8 +6,13 @@ 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;
|
||||
};
|
||||
@@ -19,6 +24,7 @@ export interface DesktopSettings {
|
||||
|
||||
interface DesktopSettingsPatch {
|
||||
releaseChannel?: AppReleaseChannel;
|
||||
updates?: Partial<DesktopSettings["updates"]>;
|
||||
notifications?: Partial<DesktopSettings["notifications"]>;
|
||||
daemon?: Partial<DesktopSettings["daemon"]>;
|
||||
}
|
||||
@@ -31,6 +37,9 @@ export interface DesktopSettingsStore {
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
@@ -43,6 +52,13 @@ 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({
|
||||
@@ -60,6 +76,7 @@ const DaemonSchema = z
|
||||
const DesktopSettingsSchema = z
|
||||
.looseObject({
|
||||
releaseChannel: ReleaseChannelSchema.catch(DEFAULT_DESKTOP_SETTINGS.releaseChannel),
|
||||
updates: UpdatesSchema,
|
||||
notifications: NotificationsSchema,
|
||||
daemon: DaemonSchema,
|
||||
})
|
||||
@@ -95,6 +112,11 @@ 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;
|
||||
}
|
||||
@@ -106,6 +128,7 @@ 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 },
|
||||
};
|
||||
@@ -125,6 +148,7 @@ 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,
|
||||
@@ -144,6 +168,13 @@ 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) {
|
||||
@@ -197,6 +228,7 @@ function mergeDesktopSettings(
|
||||
return {
|
||||
...current,
|
||||
releaseChannel: patch.releaseChannel ?? current.releaseChannel,
|
||||
updates: { ...current.updates, ...patch.updates },
|
||||
notifications: { ...current.notifications, ...patch.notifications },
|
||||
daemon: { ...current.daemon, ...patch.daemon },
|
||||
};
|
||||
@@ -232,22 +264,26 @@ export function createDesktopSettingsStore({
|
||||
}): DesktopSettingsStore {
|
||||
const filePath = path.join(userDataPath, DESKTOP_SETTINGS_FILENAME);
|
||||
let cachedDocument: PersistedDesktopSettingsDocument | null = null;
|
||||
let persistQueue: Promise<void> = Promise.resolve();
|
||||
let operationQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
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;
|
||||
function enqueueOperation<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = operationQueue.then(operation, operation);
|
||||
operationQueue = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function loadDocument(): Promise<PersistedDesktopSettingsDocument> {
|
||||
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> {
|
||||
if (cachedDocument) {
|
||||
return cachedDocument;
|
||||
}
|
||||
@@ -260,7 +296,7 @@ export function createDesktopSettingsStore({
|
||||
throw error;
|
||||
}
|
||||
const document = buildDefaultDocument();
|
||||
await persistDocument(document);
|
||||
await writeDocument(document);
|
||||
return document;
|
||||
}
|
||||
const document = coerceDocument(JSON.parse(raw));
|
||||
@@ -268,58 +304,67 @@ export function createDesktopSettingsStore({
|
||||
return document;
|
||||
}
|
||||
|
||||
async function initializeLegacyRendererMigration(): Promise<PersistedDesktopSettingsDocument> {
|
||||
async function initializeLegacyRendererMigrationUnlocked(): Promise<PersistedDesktopSettingsDocument> {
|
||||
try {
|
||||
return await loadDocument();
|
||||
return await loadDocumentUnlocked();
|
||||
} catch {
|
||||
const document = buildDefaultDocument();
|
||||
await persistDocument(document);
|
||||
await writeDocument(document);
|
||||
return document;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async get(): Promise<DesktopSettings> {
|
||||
const document = await loadDocument();
|
||||
const document = await enqueueOperation(async () => {
|
||||
if (cachedDocument) {
|
||||
return cachedDocument;
|
||||
}
|
||||
return loadDocumentUnlocked();
|
||||
});
|
||||
return toDesktopSettings(document.settings);
|
||||
},
|
||||
|
||||
async patch(patch: unknown): Promise<DesktopSettings> {
|
||||
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 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);
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
},
|
||||
|
||||
async migrateLegacyRendererSettings(legacySettings: unknown): Promise<DesktopSettings> {
|
||||
const current = await initializeLegacyRendererMigration();
|
||||
if (current.migrations.legacyRendererSettingsImported) {
|
||||
return toDesktopSettings(current.settings);
|
||||
}
|
||||
return enqueueOperation(async () => {
|
||||
const current = await initializeLegacyRendererMigrationUnlocked();
|
||||
if (current.migrations.legacyRendererSettingsImported) {
|
||||
return toDesktopSettings(current.settings);
|
||||
}
|
||||
|
||||
const next = mergeDesktopSettings(
|
||||
current.settings,
|
||||
pickDesktopSettingsFromLegacyRendererSettings(legacySettings),
|
||||
);
|
||||
await persistDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported: true,
|
||||
},
|
||||
const next = mergeDesktopSettings(
|
||||
current.settings,
|
||||
pickDesktopSettingsFromLegacyRendererSettings(legacySettings),
|
||||
);
|
||||
await writeDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported: true,
|
||||
},
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -63,6 +63,7 @@ const ADAPTER_CAPABILITIES = [
|
||||
"prompt.command",
|
||||
"session.configure",
|
||||
"permission",
|
||||
"request.cancel",
|
||||
] as const;
|
||||
|
||||
interface AcpBoundarySession {
|
||||
@@ -105,6 +106,8 @@ export async function createAcpProviderConnection(
|
||||
const listeners = new Set<(event: ProviderEvent) => void>();
|
||||
const sessions = new Map<string, AcpBoundarySession>();
|
||||
const inFlight = new Set<Promise<void>>();
|
||||
// Catalogue and listing requests each run a probe runtime that cancellation stops.
|
||||
const cancellable = new Map<string, AbortController>();
|
||||
let closed = false;
|
||||
let closePromise: Promise<void> | null = null;
|
||||
const emit = (event: ProviderEvent) => {
|
||||
@@ -128,16 +131,31 @@ export async function createAcpProviderConnection(
|
||||
if (closed) throw new Error("ACP provider connection is closed");
|
||||
input = ProviderInputSchema.parse(input);
|
||||
validateAdmission(input, { capabilities, sessions });
|
||||
if (input.type === "request.cancel") {
|
||||
cancellable.get(input.requestId)?.abort(new Error("Paseo canceled the request"));
|
||||
return;
|
||||
}
|
||||
const admitted = input;
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
if (admitted.type === "catalog" || admitted.type === "sessions") {
|
||||
cancellable.set(admitted.requestId, controller);
|
||||
}
|
||||
const operation = Promise.resolve().then(async () => {
|
||||
if (closed) return undefined;
|
||||
await dispatch(input, state);
|
||||
await dispatch(admitted, state, signal);
|
||||
return undefined;
|
||||
});
|
||||
const settled = operation.catch((error) => {
|
||||
emitOperationFailure(input, emit, error);
|
||||
if (!signal.aborted) emitOperationFailure(admitted, emit, error);
|
||||
});
|
||||
inFlight.add(settled);
|
||||
void settled.finally(() => inFlight.delete(settled));
|
||||
void settled.finally(() => {
|
||||
inFlight.delete(settled);
|
||||
if ("requestId" in admitted && cancellable.get(admitted.requestId) === controller) {
|
||||
cancellable.delete(admitted.requestId);
|
||||
}
|
||||
});
|
||||
},
|
||||
onEvent(listener) {
|
||||
listeners.add(listener);
|
||||
@@ -147,6 +165,9 @@ export async function createAcpProviderConnection(
|
||||
if (closePromise) return closePromise;
|
||||
closed = true;
|
||||
closePromise = (async () => {
|
||||
for (const controller of cancellable.values()) {
|
||||
controller.abort(new Error("ACP provider connection closed"));
|
||||
}
|
||||
await Promise.all(inFlight);
|
||||
const active = [...sessions.values()];
|
||||
sessions.clear();
|
||||
@@ -209,13 +230,17 @@ function emitOperationFailure(
|
||||
}
|
||||
}
|
||||
|
||||
async function dispatch(input: ProviderInput, state: AcpConnectionState): Promise<void> {
|
||||
async function dispatch(
|
||||
input: Exclude<ProviderInput, { type: "request.cancel" }>,
|
||||
state: AcpConnectionState,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
switch (input.type) {
|
||||
case "catalog":
|
||||
await discover(input, state);
|
||||
await discover(input, state, signal);
|
||||
return;
|
||||
case "sessions":
|
||||
await listSessions(input, state);
|
||||
await listSessions(input, state, signal);
|
||||
return;
|
||||
case "session.open":
|
||||
await openSession(input, state);
|
||||
@@ -263,58 +288,91 @@ async function dispatch(input: ProviderInput, state: AcpConnectionState): Promis
|
||||
}
|
||||
}
|
||||
|
||||
async function discover(
|
||||
input: Extract<ProviderInput, { type: "catalog" }>,
|
||||
/**
|
||||
* Runs one request in its own short-lived runtime and publishes its result before shutting the
|
||||
* runtime down, so a slow session close cannot delay the reply. Aborting `signal` until shutdown
|
||||
* ends closes the runtime, which terminates its process and fails whatever the request awaits.
|
||||
*/
|
||||
async function withRequestRuntime<Result>(
|
||||
state: AcpConnectionState,
|
||||
request: {
|
||||
boundarySessionId: string;
|
||||
cwd?: string;
|
||||
signal: AbortSignal;
|
||||
run(runtime: AcpRuntime): Promise<Result>;
|
||||
publish(result: Result): void;
|
||||
},
|
||||
): Promise<void> {
|
||||
const { signal } = request;
|
||||
const runtime = await AcpRuntime.start({
|
||||
options: state.options,
|
||||
launch: state.launch,
|
||||
boundarySessionId: "catalog",
|
||||
cwd: input.cwd,
|
||||
boundarySessionId: request.boundarySessionId,
|
||||
cwd: request.cwd,
|
||||
env: {},
|
||||
emit: state.emit,
|
||||
signal,
|
||||
});
|
||||
const closeOnAbort = () => void runtime.close().catch(() => undefined);
|
||||
signal.addEventListener("abort", closeOnAbort, { once: true });
|
||||
try {
|
||||
let catalog = await runtime.discover(input.cwd);
|
||||
const context = runtime.configContext();
|
||||
for (const transformer of state.options.transformers ?? []) {
|
||||
if (transformer.discover) {
|
||||
catalog = await transformer.discover(catalog, context);
|
||||
}
|
||||
}
|
||||
state.emit({ type: "catalog", requestId: input.requestId, catalog });
|
||||
signal.throwIfAborted();
|
||||
const result = await request.run(runtime);
|
||||
signal.throwIfAborted();
|
||||
request.publish(result);
|
||||
} finally {
|
||||
await runtime.closeSession();
|
||||
await (signal.aborted ? runtime.close() : runtime.closeSession());
|
||||
signal.removeEventListener("abort", closeOnAbort);
|
||||
}
|
||||
}
|
||||
|
||||
async function discover(
|
||||
input: Extract<ProviderInput, { type: "catalog" }>,
|
||||
state: AcpConnectionState,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
await withRequestRuntime(state, {
|
||||
boundarySessionId: "catalog",
|
||||
cwd: input.cwd,
|
||||
signal,
|
||||
async run(runtime) {
|
||||
let catalog = await runtime.discover(input.cwd);
|
||||
const context = runtime.configContext();
|
||||
for (const transformer of state.options.transformers ?? []) {
|
||||
if (transformer.discover) {
|
||||
catalog = await transformer.discover(catalog, context);
|
||||
}
|
||||
}
|
||||
return catalog;
|
||||
},
|
||||
publish(catalog) {
|
||||
state.emit({ type: "catalog", requestId: input.requestId, catalog });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function listSessions(
|
||||
input: Extract<ProviderInput, { type: "sessions" }>,
|
||||
state: AcpConnectionState,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
const runtime = await AcpRuntime.start({
|
||||
options: state.options,
|
||||
launch: state.launch,
|
||||
await withRequestRuntime(state, {
|
||||
boundarySessionId: "sessions",
|
||||
env: {},
|
||||
emit: state.emit,
|
||||
signal,
|
||||
run: (runtime) => runtime.listSessions({ cwd: input.cwd, limit: input.limit }),
|
||||
publish(selected) {
|
||||
state.emit({
|
||||
type: "sessions",
|
||||
requestId: input.requestId,
|
||||
sessions: selected.map((session) => ({
|
||||
persistence: nativePersistence(session.sessionId),
|
||||
cwd: session.cwd,
|
||||
title: session.title ?? undefined,
|
||||
updatedAt: session.updatedAt ?? undefined,
|
||||
})),
|
||||
});
|
||||
},
|
||||
});
|
||||
try {
|
||||
const selected = await runtime.listSessions({ cwd: input.cwd, limit: input.limit });
|
||||
state.emit({
|
||||
type: "sessions",
|
||||
requestId: input.requestId,
|
||||
sessions: selected.map((session) => ({
|
||||
persistence: nativePersistence(session.sessionId),
|
||||
cwd: session.cwd,
|
||||
title: session.title ?? undefined,
|
||||
updatedAt: session.updatedAt ?? undefined,
|
||||
})),
|
||||
});
|
||||
} finally {
|
||||
await runtime.close();
|
||||
}
|
||||
}
|
||||
|
||||
function retireSession(state: AcpConnectionState, sessionId: string): void {
|
||||
@@ -379,6 +437,8 @@ interface StartRuntimeOptions {
|
||||
cwd?: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
wrap?: readonly [string, ...string[]];
|
||||
/** Aborting it during startup closes the runtime and rejects with the abort reason. */
|
||||
signal?: AbortSignal;
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: () => void;
|
||||
}
|
||||
@@ -484,6 +544,7 @@ class AcpRuntime {
|
||||
private lastUsage: ProviderUsage = {};
|
||||
|
||||
static async start(options: StartRuntimeOptions): Promise<AcpRuntime> {
|
||||
options.signal?.throwIfAborted();
|
||||
let child: ChildProcessWithoutNullStreams | null = null;
|
||||
let spawnFailure: Promise<never> | null = null;
|
||||
let stream: Stream;
|
||||
@@ -524,6 +585,9 @@ class AcpRuntime {
|
||||
}
|
||||
const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options);
|
||||
onPartialWireRead = () => runtime.notePartialWireRead();
|
||||
// Closing ends the transport, which fails the pending initialize below.
|
||||
const closeOnAbort = () => void runtime.close().catch(() => undefined);
|
||||
options.signal?.addEventListener("abort", closeOnAbort, { once: true });
|
||||
try {
|
||||
const initialize = withTimeout(
|
||||
runtime.call(
|
||||
@@ -539,11 +603,15 @@ class AcpRuntime {
|
||||
const initialized = spawnFailure
|
||||
? await Promise.race([initialize, spawnFailure])
|
||||
: await initialize;
|
||||
options.signal?.throwIfAborted();
|
||||
runtime.agentCapabilities = initialized.agentCapabilities ?? {};
|
||||
return runtime;
|
||||
} catch (error) {
|
||||
await runtime.close();
|
||||
options.signal?.throwIfAborted();
|
||||
throw error;
|
||||
} finally {
|
||||
options.signal?.removeEventListener("abort", closeOnAbort);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import diagnosticsChannel from "node:diagnostics_channel";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -2259,6 +2260,150 @@ lines.on("line", (line) => {
|
||||
});
|
||||
});
|
||||
|
||||
async function hangingCatalogAgent(): Promise<{ executable: string; catalogCwd: string }> {
|
||||
const catalogCwd = await mkdtemp(path.join(tmpdir(), "paseo-acp-hanging-catalog-"));
|
||||
temporaryDirectories.push(catalogCwd);
|
||||
// The catalogue probe records its PID and stays resident like an agent that ignores EOF.
|
||||
const executable = await fakeAcp(`const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const readline = require("node:readline");
|
||||
const catalogCwd = ${JSON.stringify(catalogCwd)};
|
||||
const lines = readline.createInterface({ input: process.stdin });
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
lines.on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } });
|
||||
else if (message.method === "session/new" && message.params.cwd === catalogCwd) {
|
||||
setInterval(() => undefined, 1_000);
|
||||
fs.writeFileSync(path.join(catalogCwd, "probe.pid"), String(process.pid));
|
||||
}
|
||||
else if (message.method === "session/new") send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-1", modes: null, configOptions: [] } });
|
||||
else if (message.method === "session/prompt") send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } });
|
||||
});`);
|
||||
return { executable, catalogCwd };
|
||||
}
|
||||
|
||||
function readIfPresent(file: string): Promise<string> {
|
||||
return readFile(file, "utf8").catch(() => "");
|
||||
}
|
||||
|
||||
async function probePid(catalogCwd: string): Promise<number> {
|
||||
const file = path.join(catalogCwd, "probe.pid");
|
||||
await expect.poll(() => readIfPresent(file), { timeout: 5_000 }).not.toBe("");
|
||||
return Number(await readFile(file, "utf8"));
|
||||
}
|
||||
|
||||
function isRunning(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return (error as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
}
|
||||
|
||||
describe("runAcpProvider catalogue requests whose session/new never answers", () => {
|
||||
it("offers request cancellation", async () => {
|
||||
const { executable } = await hangingCatalogAgent();
|
||||
const { connection } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
try {
|
||||
expect(connection.capabilities).toContain("request.cancel");
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops the probe process when Paseo cancels the request and keeps open sessions running", async () => {
|
||||
const { executable, catalogCwd } = await hangingCatalogAgent();
|
||||
const { connection, events } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
|
||||
await connection.send({ type: "catalog", requestId: "catalog-1", cwd: catalogCwd });
|
||||
const pid = await probePid(catalogCwd);
|
||||
expect(isRunning(pid)).toBe(true);
|
||||
|
||||
await connection.send({ type: "request.cancel", requestId: "catalog-1" });
|
||||
await expect.poll(() => isRunning(pid), { timeout: 3_000 }).toBe(false);
|
||||
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "after-cancel",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "still there?" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.turn" && event.state === "completed",
|
||||
);
|
||||
expect(
|
||||
events.filter((event) => "requestId" in event && event.requestId === "catalog-1"),
|
||||
).toEqual([]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("publishes the catalogue before the probe session starts closing", async () => {
|
||||
const closeMarker = path.join(
|
||||
await mkdtemp(path.join(tmpdir(), "paseo-acp-catalog-close-")),
|
||||
"close-started",
|
||||
);
|
||||
temporaryDirectories.push(path.dirname(closeMarker));
|
||||
// session/close never answers, so the probe's shutdown runs into its close timeout.
|
||||
const executable = await fakeAcp(`const fs = require("node:fs");
|
||||
const readline = require("node:readline");
|
||||
const lines = readline.createInterface({ input: process.stdin });
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
lines.on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } });
|
||||
else if (message.method === "session/new") send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "catalog-native", modes: null, configOptions: [] } });
|
||||
else if (message.method === "session/close") fs.writeFileSync(${JSON.stringify(closeMarker)}, "started");
|
||||
});`);
|
||||
const { connection, events } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
let closingWhenPublished: boolean | undefined;
|
||||
connection.onEvent((event) => {
|
||||
if (event.type === "catalog") closingWhenPublished = existsSync(closeMarker);
|
||||
});
|
||||
try {
|
||||
await connection.send({ type: "catalog", requestId: "catalog-1" });
|
||||
await waitForEvent(events, (event) => event.type === "catalog");
|
||||
expect(closingWhenPublished).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores cancellation of a request that already finished", async () => {
|
||||
const executable = await fakeAcp(basicAgent);
|
||||
const { connection, events } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
try {
|
||||
await connection.send({ type: "catalog", requestId: "catalog-1" });
|
||||
await waitForEvent(events, (event) => event.type === "catalog");
|
||||
await expect(
|
||||
connection.send({ type: "request.cancel", requestId: "catalog-1" }),
|
||||
).resolves.toBeUndefined();
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops the probe process when the connection closes", async () => {
|
||||
const { executable, catalogCwd } = await hangingCatalogAgent();
|
||||
const { connection } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
await connection.send({ type: "catalog", requestId: "catalog-1", cwd: catalogCwd });
|
||||
const pid = await probePid(catalogCwd);
|
||||
|
||||
await connection.close();
|
||||
expect(isRunning(pid)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runAcpProvider streamed chunks without messageId (#4699)", () => {
|
||||
interface Chunk {
|
||||
kind: "agent_message_chunk" | "agent_thought_chunk";
|
||||
|
||||
@@ -23,6 +23,7 @@ export const PROVIDER_CAPABILITIES = [
|
||||
"session.unarchive",
|
||||
"permission",
|
||||
"permission.tool_policy",
|
||||
"request.cancel",
|
||||
"timeline.plugin",
|
||||
] as const;
|
||||
|
||||
@@ -387,7 +388,13 @@ export type ProviderInput =
|
||||
| { type: "session.archive"; requestId: string; persistence: ProviderPersistence }
|
||||
| { type: "session.unarchive"; requestId: string; persistence: ProviderPersistence }
|
||||
| { type: "session.can_stop_runtime"; requestId: string; sessionId: string }
|
||||
| { type: "session.close"; requestId: string; sessionId: string };
|
||||
| { type: "session.close"; requestId: string; sessionId: string }
|
||||
/**
|
||||
* Paseo stopped waiting for the request with this `requestId`, such as a catalogue refresh that
|
||||
* passed its deadline. Stop its work and release what it started; Paseo ignores later events for
|
||||
* it. Sent only when the connection offers `request.cancel`.
|
||||
*/
|
||||
| { type: "request.cancel"; requestId: string };
|
||||
|
||||
export interface ProviderThinkingOption {
|
||||
id: string;
|
||||
@@ -803,6 +810,8 @@ export function requiredProviderCapabilities(input: ProviderInput): readonly Pro
|
||||
switch (input.type) {
|
||||
case "session.can_stop_runtime":
|
||||
return ["session.can_stop_runtime"];
|
||||
case "request.cancel":
|
||||
return ["request.cancel"];
|
||||
case "catalog":
|
||||
case "session.interrupt":
|
||||
case "session.close":
|
||||
@@ -1135,6 +1144,7 @@ export const ProviderInputSchema: z.ZodType<ProviderInput> = z.discriminatedUnio
|
||||
})
|
||||
.strict(),
|
||||
z.object({ type: z.literal("session.close"), requestId: idSchema, sessionId: idSchema }).strict(),
|
||||
z.object({ type: z.literal("request.cancel"), requestId: idSchema }).strict(),
|
||||
]);
|
||||
|
||||
const modeSchema = z
|
||||
|
||||
@@ -1552,9 +1552,17 @@ export const WaitForFinishRequestSchema = z.object({
|
||||
timeoutMs: z.number().int().positive().optional(),
|
||||
});
|
||||
|
||||
export const DaemonTailscaleSetRequestSchema = z.object({
|
||||
type: z.literal("daemon.tailscale.set.request"),
|
||||
requestId: z.string(),
|
||||
enabled: z.boolean(),
|
||||
confirmed: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const DaemonGetStatusRequestSchema = z.object({
|
||||
type: z.literal("daemon.get_status.request"),
|
||||
requestId: z.string(),
|
||||
includeProviders: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const DaemonGetPairingOfferRequestSchema = z.object({
|
||||
@@ -3622,6 +3630,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
SendAgentMessageRequestSchema,
|
||||
WaitForFinishRequestSchema,
|
||||
DaemonGetStatusRequestSchema,
|
||||
DaemonTailscaleSetRequestSchema,
|
||||
DaemonGetPairingOfferRequestSchema,
|
||||
DaemonConfigReloadRequestSchema,
|
||||
HubManagementDaemonConnectRequestSchema,
|
||||
@@ -4046,6 +4055,7 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
forgeSearch: z.boolean().optional(),
|
||||
// COMPAT(daemonStatusRpc): added in v0.1.76, remove gate after 2026-11-18.
|
||||
daemonStatusRpc: z.boolean().optional(),
|
||||
tailscale: z.boolean().optional(),
|
||||
// COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14.
|
||||
daemonConfigReload: z.boolean().optional(),
|
||||
// COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18.
|
||||
@@ -5577,6 +5587,32 @@ export const GetDaemonConfigResponseMessageSchema = z.object({
|
||||
.passthrough(),
|
||||
});
|
||||
|
||||
const TailscaleStatusSchema = z.object({
|
||||
ip: z.string().nullable(),
|
||||
address: z.string().nullable(),
|
||||
state: z.enum(["unavailable", "off", "waiting", "on"]),
|
||||
lockedBy: z.enum(["main", "launch"]).optional(),
|
||||
// COMPAT(tailscale): keep lockedBy "main" for older clients when the main listener is a socket.
|
||||
mainIsSocket: z.literal(true).optional(),
|
||||
// Whether turning off Tailscale would disconnect the source of this request.
|
||||
disconnectsCurrentConnection: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const ExtraListenerStatusSchema = z.object({
|
||||
address: z.string(),
|
||||
state: z.enum(["waiting", "listening"]),
|
||||
});
|
||||
|
||||
export const DaemonTailscaleSetResponseSchema = z.object({
|
||||
type: z.literal("daemon.tailscale.set.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
confirmationRequired: z.boolean(),
|
||||
tailscale: TailscaleStatusSchema,
|
||||
extraListeners: z.array(ExtraListenerStatusSchema),
|
||||
}),
|
||||
});
|
||||
|
||||
export const DaemonGetStatusResponseSchema = z.object({
|
||||
type: z.literal("daemon.get_status.response"),
|
||||
payload: z
|
||||
@@ -5588,6 +5624,8 @@ export const DaemonGetStatusResponseSchema = z.object({
|
||||
nodePath: z.string(),
|
||||
startedAt: z.string().nullable().optional(),
|
||||
listen: z.string().nullable(),
|
||||
tailscale: TailscaleStatusSchema.optional(),
|
||||
extraListeners: z.array(ExtraListenerStatusSchema).optional(),
|
||||
relay: z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
@@ -7802,6 +7840,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
SendAgentMessageResponseMessageSchema,
|
||||
SetVoiceModeResponseMessageSchema,
|
||||
DaemonGetStatusResponseSchema,
|
||||
DaemonTailscaleSetResponseSchema,
|
||||
DaemonGetPairingOfferResponseSchema,
|
||||
DaemonConfigReloadResponseSchema,
|
||||
HubManagementDaemonConnectResponseSchema,
|
||||
@@ -8564,3 +8603,6 @@ export function parseServerInfoStatusPayload(payload: unknown): ServerInfoStatus
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
export type TailscaleStatus = z.infer<typeof TailscaleStatusSchema>;
|
||||
export type DaemonTailscaleSetResponse = z.infer<typeof DaemonTailscaleSetResponseSchema>;
|
||||
|
||||
@@ -139,6 +139,7 @@
|
||||
"p-limit": "^7.3.0",
|
||||
"p-memoize": "^8.0.0",
|
||||
"p-throttle": "^8.1.0",
|
||||
"parse5": "^7.3.0",
|
||||
"pino": "^10.2.0",
|
||||
"pino-pretty": "^13.1.3",
|
||||
"qrcode": "^1.5.4",
|
||||
|
||||
@@ -1618,6 +1618,11 @@ export class AgentManager {
|
||||
return this.backgroundWork.summary(agentId);
|
||||
}
|
||||
|
||||
/** The live session started work that will start another turn by itself. */
|
||||
hasPendingWakeup(agentId: string): boolean {
|
||||
return this.agents.get(agentId)?.session.hasPendingWakeup?.() ?? false;
|
||||
}
|
||||
|
||||
private publishBackgroundWork(agentId: string, items: AgentBackgroundWorkItem[] | null): void {
|
||||
if (items) this.dispatch({ type: "background_work", agentId, items });
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ const sourceSchema = z.discriminatedUnion("kind", [
|
||||
agentId: agentIdSchema,
|
||||
serverId: z.string().min(1).optional(),
|
||||
title: z.string().min(1).optional(),
|
||||
event: z.enum(["finished", "errored", "permission-required", "closed"]),
|
||||
// "message" reports a child that ended its turn but has not finished its work.
|
||||
event: z.enum(["message", "finished", "errored", "permission-required", "closed"]),
|
||||
}),
|
||||
]);
|
||||
export type AgentPromptSource = z.infer<typeof sourceSchema>;
|
||||
|
||||
@@ -774,6 +774,11 @@ export interface AgentSession {
|
||||
* An optional additional veto: missing methods use daemon baseline eligibility;
|
||||
* implemented checks that reject or return false keep the runtime resident. */
|
||||
canStopRuntime?(): Promise<boolean>;
|
||||
/**
|
||||
* True while work this session started will start another turn by itself, such as a
|
||||
* background task that reports back when it ends. Recurring triggers do not count.
|
||||
*/
|
||||
hasPendingWakeup?(): boolean;
|
||||
/** Release live runtime resources without archiving or deleting the durable native session. */
|
||||
close(): Promise<void>;
|
||||
listCommands?(): Promise<AgentSlashCommand[]>;
|
||||
|
||||
@@ -243,6 +243,8 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
deps.backgroundWork.setDaemonBackgroundWork({
|
||||
...backgroundWorkKey(watcher.agentId, url),
|
||||
kind: "monitor",
|
||||
// A watch waits on the forge, like a heartbeat waits on its cron: listed, not Running.
|
||||
countsAsRunning: false,
|
||||
description: describeWatch(forge, url),
|
||||
startedAt: watcher.startedAt ?? new Date().toISOString(),
|
||||
stop: async () => {
|
||||
|
||||
@@ -146,8 +146,8 @@ test("lists and stops each agent's subscription through the background work regi
|
||||
canStop: true,
|
||||
});
|
||||
expect(second).toMatchObject({ id: first.id, description: first.description });
|
||||
expect(h.backgroundWork.summary("first")).toEqual({ count: 1 });
|
||||
expect(h.backgroundWork.summary("second")).toEqual({ count: 1 });
|
||||
expect(h.backgroundWork.summary("first")).toEqual({ count: 1, runningCount: 0 });
|
||||
expect(h.backgroundWork.summary("second")).toEqual({ count: 1, runningCount: 0 });
|
||||
|
||||
await h.watches.subscribe("first", url);
|
||||
await h.observations.get(url)!.snapshot(initial);
|
||||
@@ -417,7 +417,7 @@ test("recovers active watches even when pruning archived watchers cannot be writ
|
||||
});
|
||||
await h.watches.start();
|
||||
expect(h.backgroundWork.list("archived")).toEqual([]);
|
||||
expect(h.backgroundWork.summary("active")).toEqual({ count: 1 });
|
||||
expect(h.backgroundWork.summary("active")).toEqual({ count: 1, runningCount: 0 });
|
||||
await expect(h.watches.unsubscribe("archived", url)).resolves.toMatchObject({ removed: false });
|
||||
await expect(h.watches.subscribe("active", url)).resolves.toMatchObject({ subscribed: true });
|
||||
expect(await readFile(backup, "utf8")).toBe(stored);
|
||||
|
||||
+269
-12
@@ -3,7 +3,8 @@ import { HostObservationError } from "../host-operations/index.js";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { formatAgentMessage, parseAgentMessage } from "../agent-messages/envelope.js";
|
||||
import type { WaitForFinishResult } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AgentMessageDelivery } from "../agent-messages/index.js";
|
||||
import { buildStoredAgentPayload } from "../agent-projections.js";
|
||||
@@ -12,8 +13,11 @@ import {
|
||||
createFinishSubscriptions,
|
||||
createJsonFinishSubscriptionStore,
|
||||
type FinishObservation,
|
||||
type FinishSubscription,
|
||||
type FinishSubscriptions,
|
||||
type PendingWork,
|
||||
} from "./index.js";
|
||||
import type { FinishObservationResult } from "./internal/observation-buffer.js";
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
@@ -25,21 +29,32 @@ function deferred<T>() {
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
class Observation implements FinishObservation {
|
||||
waits: Array<{ signal: AbortSignal; result: ReturnType<typeof deferred<WaitForFinishResult>> }> =
|
||||
[];
|
||||
waits: Array<{
|
||||
signal: AbortSignal;
|
||||
childAgentId: string;
|
||||
result: ReturnType<typeof deferred<FinishObservationResult>>;
|
||||
}> = [];
|
||||
permission = deferred<void>();
|
||||
opening: Promise<void> = Promise.resolve();
|
||||
openedSignals: AbortSignal[] = [];
|
||||
async open(_record: unknown, signal: AbortSignal) {
|
||||
/** Work that will start each child's next turn by itself, as the local host reports it. */
|
||||
work = new Map<string, PendingWork[]>();
|
||||
async open(record: FinishSubscription, signal: AbortSignal) {
|
||||
this.openedSignals.push(signal);
|
||||
await this.opening;
|
||||
return { next: () => this.wait(signal), close: async () => {} };
|
||||
return { next: () => this.wait(record.childAgentId, signal), close: async () => {} };
|
||||
}
|
||||
async wait(signal: AbortSignal) {
|
||||
pendingWork(record: FinishSubscription): PendingWork[] {
|
||||
return this.work.get(record.childAgentId) ?? [];
|
||||
}
|
||||
waitsFor(childAgentId: string) {
|
||||
return this.waits.filter((entry) => entry.childAgentId === childAgentId);
|
||||
}
|
||||
async wait(childAgentId: string, signal: AbortSignal) {
|
||||
signal.throwIfAborted();
|
||||
const result = deferred<WaitForFinishResult>();
|
||||
const result = deferred<FinishObservationResult>();
|
||||
signal.addEventListener("abort", () => result.reject(new Error("Stopped")), { once: true });
|
||||
this.waits.push({ signal, result });
|
||||
this.waits.push({ signal, childAgentId, result });
|
||||
return result.promise;
|
||||
}
|
||||
afterPermission() {
|
||||
@@ -48,9 +63,18 @@ class Observation implements FinishObservation {
|
||||
}
|
||||
class Delivery implements AgentMessageDelivery {
|
||||
prompts: string[] = [];
|
||||
/** Prompts as the recipient's provider receives them, inside their envelope. */
|
||||
enqueued: string[] = [];
|
||||
acknowledgments: Array<ReturnType<typeof deferred<"steered">>> = [];
|
||||
enqueue(message: Parameters<AgentMessageDelivery["enqueue"]>[0]) {
|
||||
this.prompts.push(String(message.prompt));
|
||||
this.enqueued.push(
|
||||
formatAgentMessage({
|
||||
id: "notification",
|
||||
source: message.source ?? null,
|
||||
text: String(message.prompt),
|
||||
}),
|
||||
);
|
||||
const acknowledgment = deferred<"steered">();
|
||||
this.acknowledgments.push(acknowledgment);
|
||||
return {
|
||||
@@ -68,7 +92,12 @@ afterEach(async () => {
|
||||
for (const service of services.splice(0)) await service.close();
|
||||
await Promise.all(homes.splice(0).map((home) => rm(home, { recursive: true, force: true })));
|
||||
});
|
||||
async function scenario(directory?: string, removalFailures = 0, retryDelayMs = 1) {
|
||||
async function scenario(
|
||||
directory?: string,
|
||||
removalFailures = 0,
|
||||
retryDelayMs = 1,
|
||||
followLimitMs?: number,
|
||||
) {
|
||||
const home = directory ?? (await mkdtemp(join(tmpdir(), "finish-recovery-")));
|
||||
if (!directory) homes.push(home);
|
||||
const durableStore = createJsonFinishSubscriptionStore(home);
|
||||
@@ -89,10 +118,12 @@ async function scenario(directory?: string, removalFailures = 0, retryDelayMs =
|
||||
store,
|
||||
messages: () => delivery,
|
||||
open: observation.open.bind(observation),
|
||||
pendingWork: observation.pendingWork.bind(observation),
|
||||
callerIsActive: async () => active,
|
||||
serverId: "origin",
|
||||
logger: createTestLogger(),
|
||||
retryDelayMs,
|
||||
...(followLimitMs === undefined ? {} : { followLimitMs }),
|
||||
});
|
||||
services.push(service);
|
||||
await service.start();
|
||||
@@ -108,12 +139,16 @@ async function scenario(directory?: string, removalFailures = 0, retryDelayMs =
|
||||
};
|
||||
}
|
||||
const intent = { callerAgentId: "parent", childAgentId: "child" };
|
||||
function outcome(status: "idle" | "running" | "closed" | "error" = "closed"): WaitForFinishResult {
|
||||
function outcome(
|
||||
status: "idle" | "running" | "closed" | "error" = "closed",
|
||||
childAgentId = "child",
|
||||
lastMessage = "Partial work saved",
|
||||
): WaitForFinishResult {
|
||||
return {
|
||||
status: status === "error" ? "error" : "idle",
|
||||
final: buildStoredAgentPayload(
|
||||
{
|
||||
id: "child",
|
||||
id: childAgentId,
|
||||
provider: "codex",
|
||||
cwd: "/tmp",
|
||||
title: "Child",
|
||||
@@ -125,7 +160,7 @@ function outcome(status: "idle" | "running" | "closed" | "error" = "closed"): Wa
|
||||
["codex"],
|
||||
(_provider, own) => own ?? {},
|
||||
),
|
||||
lastMessage: "Partial work saved",
|
||||
lastMessage,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
@@ -485,6 +520,7 @@ test("finish recovery protects callers before durable intent has loaded", async
|
||||
},
|
||||
messages: () => s.delivery,
|
||||
open: s.observation.open.bind(s.observation),
|
||||
pendingWork: s.observation.pendingWork.bind(s.observation),
|
||||
callerIsActive: async () => true,
|
||||
serverId: "origin",
|
||||
logger: createTestLogger(),
|
||||
@@ -521,3 +557,224 @@ test("an undispatched follow-up does not block the running child's permission no
|
||||
expect(state.delivery.prompts[0]).toContain("approval");
|
||||
expect(await state.store.list()).toHaveLength(2);
|
||||
});
|
||||
|
||||
describe("a child that ends its turn while it is still working", () => {
|
||||
async function following(state: Awaited<ReturnType<typeof scenario>>) {
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
state.observation.work.set("child", ["background work"]);
|
||||
state.observation.waits[0]!.result.resolve(outcome("idle", "child", "Waiting for the build"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
state.delivery.acknowledgments[0]!.resolve("steered");
|
||||
await until(() => state.observation.waits.length === 2);
|
||||
}
|
||||
|
||||
test("reports one interim notice, then finished with the reply of the turn that settles it", async () => {
|
||||
const state = await scenario();
|
||||
await following(state);
|
||||
const interim = state.delivery.prompts[0]!;
|
||||
expect(interim).toContain("Agent child (Child) ended its turn but is still working");
|
||||
expect(interim).toContain("background work");
|
||||
expect(interim).toContain("This is not its final reply");
|
||||
expect(interim).toContain("Waiting for the build");
|
||||
expect(interim).not.toContain("Child) finished.");
|
||||
expect(parseAgentMessage(state.delivery.enqueued[0]!)).toMatchObject({
|
||||
source: { kind: "agent-notification", event: "message" },
|
||||
});
|
||||
expect(await state.store.list()).toEqual([
|
||||
expect.objectContaining({ followingSince: expect.any(String) }),
|
||||
]);
|
||||
|
||||
state.observation.work.set("child", []);
|
||||
state.observation.waits[1]!.result.resolve(outcome("idle", "child", "FINAL: done"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished.");
|
||||
expect(state.delivery.prompts[1]).toContain("FINAL: done");
|
||||
expect(parseAgentMessage(state.delivery.enqueued[1]!)).toMatchObject({
|
||||
source: { event: "finished" },
|
||||
});
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await expect.poll(async () => (await state.store.list()).length).toBe(0);
|
||||
// A turn a person starts after the child settled has no observer left to report it.
|
||||
expect(state.observation.waits).toHaveLength(2);
|
||||
expect(state.service.hasPendingForCaller("parent")).toBe(false);
|
||||
});
|
||||
|
||||
test("stays silent for turns that end while work is still pending", async () => {
|
||||
const state = await scenario();
|
||||
await following(state);
|
||||
state.observation.waits[1]!.result.resolve(outcome("idle", "child", "Still waiting"));
|
||||
await until(() => state.observation.waits.length === 3);
|
||||
expect(state.delivery.prompts).toHaveLength(1);
|
||||
state.observation.work.set("child", []);
|
||||
state.observation.waits[2]!.result.resolve(outcome("idle", "child", "FINAL"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("finished.");
|
||||
});
|
||||
|
||||
test("sends finished when its work drains while it is idle, without another turn", async () => {
|
||||
const state = await scenario();
|
||||
await following(state);
|
||||
state.observation.work.set("child", []);
|
||||
state.observation.waits[1]!.result.resolve({
|
||||
...outcome("idle", "child", "Waiting for the build"),
|
||||
workChanged: true,
|
||||
});
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished.");
|
||||
});
|
||||
|
||||
test("ignores a work change before the child's first turn ends", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
state.observation.waits[0]!.result.resolve({ ...outcome("idle"), workChanged: true });
|
||||
await until(() => state.observation.waits.length === 2);
|
||||
expect(state.delivery.prompts).toEqual([]);
|
||||
state.observation.waits[1]!.result.resolve(outcome("idle"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.prompts[0]).toContain("finished.");
|
||||
});
|
||||
|
||||
test("restart while following neither repeats the notice nor loses the final finish", async () => {
|
||||
const first = await scenario();
|
||||
await following(first);
|
||||
await first.service.close();
|
||||
const restarted = await scenario(first.home);
|
||||
await until(() => restarted.observation.waits.length === 1);
|
||||
restarted.observation.work.set("child", ["queued messages"]);
|
||||
restarted.observation.waits[0]!.result.resolve(outcome("idle", "child", "Still waiting"));
|
||||
await until(() => restarted.observation.waits.length === 2);
|
||||
expect(restarted.delivery.prompts).toEqual([]);
|
||||
restarted.observation.work.set("child", []);
|
||||
restarted.observation.waits[1]!.result.resolve(outcome("idle", "child", "FINAL"));
|
||||
await until(() => restarted.delivery.prompts.length === 1);
|
||||
expect(restarted.delivery.prompts[0]).toContain("finished.");
|
||||
expect(restarted.delivery.prompts[0]).toContain("FINAL");
|
||||
});
|
||||
|
||||
test("a permission request raised after waking up reaches the parent", async () => {
|
||||
const state = await scenario();
|
||||
await following(state);
|
||||
const result = outcome("running");
|
||||
result.status = "permission";
|
||||
result.final!.pendingPermissions = [
|
||||
{ id: "plan", name: "ExitPlanMode", input: {}, kind: "plan" } as NonNullable<
|
||||
typeof result.final
|
||||
>["pendingPermissions"][number],
|
||||
];
|
||||
state.observation.waits[1]!.result.resolve(result);
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("needs permission");
|
||||
expect(state.delivery.prompts[1]).toContain("respond_to_permission");
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await until(() => state.observation.waits.length === 3);
|
||||
state.observation.work.set("child", []);
|
||||
state.observation.waits[2]!.result.resolve(outcome("idle", "child", "Plan approved and done"));
|
||||
await until(() => state.delivery.prompts.length === 3);
|
||||
expect(state.delivery.prompts[2]).toContain("finished.");
|
||||
expect(state.delivery.prompts[2]).toContain("Plan approved and done");
|
||||
});
|
||||
|
||||
test("a helper waiting on its own delegated agent is followed until that delegation settles", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register({ callerAgentId: "parent", childAgentId: "helper" });
|
||||
await state.service.register({ callerAgentId: "helper", childAgentId: "sub" });
|
||||
await until(() => state.observation.waits.length === 2);
|
||||
const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!;
|
||||
|
||||
wait("helper").result.resolve(outcome("idle", "helper", "Waiting for my helper"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.prompts[0]).toContain("ended its turn but is still working");
|
||||
expect(state.delivery.prompts[0]).toContain("agents it is waiting on");
|
||||
state.delivery.acknowledgments[0]!.resolve("steered");
|
||||
|
||||
wait("sub").result.resolve(outcome("idle", "sub", "Sub result"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Agent sub (Child) finished.");
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await until(() => !state.service.hasPendingForCaller("helper"));
|
||||
|
||||
await until(() => state.observation.waitsFor("helper").length === 2);
|
||||
wait("helper", 1).result.resolve(outcome("idle", "helper", "Helper final"));
|
||||
await until(() => state.delivery.prompts.length === 3);
|
||||
expect(state.delivery.prompts[2]).toContain("Agent helper (Child) finished.");
|
||||
expect(state.delivery.prompts[2]).toContain("Helper final");
|
||||
});
|
||||
|
||||
test("a followed helper settles when its last delegation ends without reporting to it", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register({ callerAgentId: "parent", childAgentId: "helper" });
|
||||
await state.service.register({
|
||||
callerAgentId: "helper",
|
||||
childAgentId: "sub",
|
||||
requireParentOwnership: true,
|
||||
});
|
||||
await until(() => state.observation.waits.length === 2);
|
||||
const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!;
|
||||
|
||||
wait("helper").result.resolve(outcome("idle", "helper", "Waiting for my helper"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.prompts[0]).toContain("ended its turn but is still working");
|
||||
state.delivery.acknowledgments[0]!.resolve("steered");
|
||||
|
||||
// The sub was detached from the helper, so its result is not reported to the helper.
|
||||
wait("sub").result.resolve(outcome("idle", "sub", "Sub result"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Agent helper (Child) finished.");
|
||||
expect(state.delivery.prompts[1]).toContain("Waiting for my helper");
|
||||
expect(state.delivery.prompts[1]).not.toContain("Sub result");
|
||||
});
|
||||
|
||||
test("agents that only wait on each other settle and both callers hear finished", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register({ callerAgentId: "parent", childAgentId: "helper" });
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
// The helper asks its parent a question and waits for the answer.
|
||||
await state.service.register({ callerAgentId: "helper", childAgentId: "parent" });
|
||||
await until(() => state.observation.waits.length === 2);
|
||||
const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!;
|
||||
|
||||
state.observation.work.set("parent", ["turn"]);
|
||||
wait("helper").result.resolve(outcome("idle", "helper", "Asked my parent"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.prompts[0]).toContain("Agent helper (Child) ended its turn");
|
||||
state.delivery.acknowledgments[0]!.resolve("steered");
|
||||
|
||||
// The parent answers. It waits on the helper, and the helper waits only on it.
|
||||
state.observation.work.set("parent", []);
|
||||
wait("parent").result.resolve(outcome("idle", "parent", "The answer"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Agent parent (Child) finished.");
|
||||
expect(state.delivery.prompts[1]).toContain("The answer");
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await until(() => !state.service.hasPendingForCaller("helper"));
|
||||
|
||||
await until(() => state.observation.waitsFor("helper").length === 2);
|
||||
wait("helper", 1).result.resolve(outcome("idle", "helper", "Helper final"));
|
||||
await until(() => state.delivery.prompts.length === 3);
|
||||
expect(state.delivery.prompts[2]).toContain("Agent helper (Child) finished.");
|
||||
expect(state.delivery.prompts[2]).toContain("Helper final");
|
||||
});
|
||||
|
||||
test("stops following at the follow limit and says the child is still working", async () => {
|
||||
const state = await scenario(undefined, 0, 1, 50);
|
||||
await following(state);
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Agent child (Child) is still working");
|
||||
expect(state.delivery.prompts[1]).toContain("This finish subscription has ended");
|
||||
expect(state.delivery.prompts[1]).not.toContain("finished.");
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await expect.poll(async () => (await state.store.list()).length).toBe(0);
|
||||
});
|
||||
|
||||
test("errors while following end the subscription as they do today", async () => {
|
||||
const state = await scenario();
|
||||
await following(state);
|
||||
state.observation.waits[1]!.result.resolve(outcome("error"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("errored");
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await expect.poll(async () => (await state.store.list()).length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,10 +7,17 @@ import type { FinishObservationResult } from "./internal/observation-buffer.js";
|
||||
import type { AgentMessageDelivery } from "../agent-messages/index.js";
|
||||
import { getParentAddressFromLabels } from "@getpaseo/protocol/agent-labels";
|
||||
import {
|
||||
endsSubscription,
|
||||
formatFinishNotificationBody,
|
||||
finishNotificationEvents,
|
||||
type FinishNotificationReason,
|
||||
} from "./internal/notification.js";
|
||||
import {
|
||||
createFollowing,
|
||||
FOLLOW_LIMIT,
|
||||
type FollowOutcome,
|
||||
type Notice,
|
||||
} from "./internal/following.js";
|
||||
export { createJsonFinishSubscriptionStore } from "./internal/json-store.js";
|
||||
|
||||
export interface FinishSubscription {
|
||||
@@ -20,7 +27,17 @@ export interface FinishSubscription {
|
||||
serverId?: string;
|
||||
/** Creation subscriptions stop reporting after the child is detached. */
|
||||
requireParentOwnership?: boolean;
|
||||
/**
|
||||
* Set once the child ended a turn while it was still working and the caller was told so.
|
||||
* The subscription then follows the child until it settles or the follow limit passes.
|
||||
*/
|
||||
followingSince?: string;
|
||||
}
|
||||
/**
|
||||
* Work that will start the child's next turn without a new prompt from the caller.
|
||||
* Recurring triggers such as heartbeats are not pending work: they never settle.
|
||||
*/
|
||||
export type PendingWork = "turn" | "background work" | "queued messages" | "delegated agents";
|
||||
export interface FinishSubscriptionStore {
|
||||
list(): Promise<FinishSubscription[]>;
|
||||
put(subscription: FinishSubscription): Promise<void>;
|
||||
@@ -32,6 +49,8 @@ export interface FinishObservationSession {
|
||||
}
|
||||
export interface FinishObservation {
|
||||
open(subscription: FinishSubscription, signal: AbortSignal): Promise<FinishObservationSession>;
|
||||
/** The child's own pending work. Empty when its host cannot tell, as for remote children. */
|
||||
pendingWork(subscription: FinishSubscription): readonly PendingWork[];
|
||||
}
|
||||
interface Dependencies extends FinishObservation {
|
||||
store: FinishSubscriptionStore;
|
||||
@@ -40,6 +59,8 @@ interface Dependencies extends FinishObservation {
|
||||
serverId: string;
|
||||
logger: Logger;
|
||||
retryDelayMs?: number;
|
||||
/** How long a child that is still working is followed before the subscription gives up. */
|
||||
followLimitMs?: number;
|
||||
}
|
||||
export interface FinishRegistration {
|
||||
/** The prompt was accepted. Replaces preceding registrations for this pair. */
|
||||
@@ -64,10 +85,13 @@ interface Watch {
|
||||
decide(accepted: boolean): void;
|
||||
pending: boolean;
|
||||
task?: Promise<void>;
|
||||
/** Decides a followed child's state again; see `createFollowing`. */
|
||||
recheck?(): void;
|
||||
}
|
||||
function key(record: FinishSubscription): string {
|
||||
return JSON.stringify([record.callerAgentId, record.childAgentId, record.serverId]);
|
||||
}
|
||||
const DEFAULT_FOLLOW_LIMIT_MS = 24 * 60 * 60_000;
|
||||
|
||||
/** Owns durable intent, live observation, supersession, and dispatch acknowledgment. */
|
||||
export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptions {
|
||||
@@ -109,6 +133,18 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
if (!group.size && watches.get(key(watch.records[0]!)) === group)
|
||||
watches.delete(key(watch.records[0]!));
|
||||
}
|
||||
/**
|
||||
* A watch that ends without telling its caller leaves that caller's own watchers with no event:
|
||||
* the caller may have no work left now.
|
||||
*/
|
||||
function recheckCallerOf(watch: Watch): void {
|
||||
const { callerAgentId } = watch.records[0]!;
|
||||
for (const group of watches.values())
|
||||
for (const watcher of group) {
|
||||
const record = watcher.records[0]!;
|
||||
if (record.childAgentId === callerAgentId && !record.serverId) watcher.recheck?.();
|
||||
}
|
||||
}
|
||||
async function remove(watch: Watch): Promise<void> {
|
||||
// Only IDs captured by this observer are eligible; newer registrations survive.
|
||||
for (const record of watch.records) await deps.store.remove(record.id);
|
||||
@@ -169,19 +205,19 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
}
|
||||
async function deliver(
|
||||
record: FinishSubscription,
|
||||
result: FinishObservationResult,
|
||||
notice: Notice,
|
||||
permissions: Set<string>,
|
||||
signal: AbortSignal,
|
||||
): Promise<boolean> {
|
||||
const requests = result.final?.pendingPermissions ?? [];
|
||||
const reason = reasonFor(result);
|
||||
): Promise<void> {
|
||||
const { reason, result } = notice;
|
||||
const requests = result?.final?.pendingPermissions ?? [];
|
||||
for (const id of permissions)
|
||||
if (!requests.some((request) => request.id === id)) permissions.delete(id);
|
||||
const acknowledgments: Promise<unknown>[] = [];
|
||||
for (const request of reason === "needs permission" ? requests : [undefined]) {
|
||||
if (signal.aborted) return false;
|
||||
if (signal.aborted) return;
|
||||
if (request && permissions.has(request.id)) continue;
|
||||
const title = result.final?.title ?? record.childAgentId;
|
||||
const title = result?.final?.title ?? record.childAgentId;
|
||||
const receipt = deps.messages().enqueue({
|
||||
recipientId: record.callerAgentId,
|
||||
prompt: formatFinishNotificationBody({
|
||||
@@ -189,8 +225,9 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
serverId: record.serverId ?? deps.serverId,
|
||||
title,
|
||||
reason,
|
||||
lastAssistantMessage: result.lastMessage,
|
||||
lastAssistantMessage: result?.lastMessage ?? null,
|
||||
permissionRequest: request,
|
||||
pendingWork: notice.work,
|
||||
}),
|
||||
source: {
|
||||
kind: "agent-notification",
|
||||
@@ -211,9 +248,42 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
);
|
||||
}
|
||||
await abortable(Promise.all(acknowledgments), signal);
|
||||
if (signal.aborted) return false;
|
||||
if (reason !== "needs permission") return true;
|
||||
return false;
|
||||
}
|
||||
function delegations(agentId: string): FinishSubscription[] {
|
||||
const records: FinishSubscription[] = [];
|
||||
for (const group of watches.values())
|
||||
for (const watch of group)
|
||||
if (watch.records[0]!.callerAgentId === agentId) records.push(watch.records[0]!);
|
||||
return records;
|
||||
}
|
||||
function delegates(agentId: string): boolean {
|
||||
return registering.has(agentId) || delegations(agentId).length > 0;
|
||||
}
|
||||
/**
|
||||
* Whether one of the agent's delegations can still bring it a notice. A delegate that has settled
|
||||
* is about to report; a delegate that only waits on agents in `chain` never will, so agents that
|
||||
* wait on each other settle together.
|
||||
*/
|
||||
function awaitsDelegates(agentId: string, chain: Set<string>): boolean {
|
||||
if (registering.has(agentId)) return true;
|
||||
chain.add(agentId);
|
||||
return delegations(agentId).some((delegation) => {
|
||||
// A remote delegate's work is known only to its host.
|
||||
if (delegation.serverId) return true;
|
||||
const delegate = delegation.childAgentId;
|
||||
if (chain.has(delegate)) return false;
|
||||
if (deps.pendingWork(delegation).length > 0 || delegations(delegate).length === 0)
|
||||
return true;
|
||||
return awaitsDelegates(delegate, chain);
|
||||
});
|
||||
}
|
||||
/** Everything that will start the child's next turn by itself. */
|
||||
function pendingWork(record: FinishSubscription): PendingWork[] {
|
||||
const work = [...deps.pendingWork(record)];
|
||||
// A remote child's own subscriptions live on its host.
|
||||
if (!record.serverId && awaitsDelegates(record.childAgentId, new Set()))
|
||||
work.push("delegated agents");
|
||||
return work;
|
||||
}
|
||||
async function run(watch: Watch, group: Set<Watch>): Promise<void> {
|
||||
const signal = watch.controller.signal;
|
||||
@@ -224,17 +294,27 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
(intent) => intent.requireParentOwnership === true,
|
||||
),
|
||||
};
|
||||
const following = createFollowing({
|
||||
records: watch.records,
|
||||
store: deps.store,
|
||||
limitMs: deps.followLimitMs ?? DEFAULT_FOLLOW_LIMIT_MS,
|
||||
pendingWork: () => pendingWork(record),
|
||||
reasonFor,
|
||||
});
|
||||
watch.recheck = following.recheck;
|
||||
const permissions = new Set<string>();
|
||||
let observation: FinishObservationSession | undefined;
|
||||
let pending: FinishObservationResult | undefined;
|
||||
let acknowledged = false;
|
||||
/** One outcome and how far it got. Retries resume it: nothing is lost or sent twice. */
|
||||
let current:
|
||||
| { outcome: FollowOutcome; decided: boolean; notice?: Notice; sent: boolean }
|
||||
| undefined;
|
||||
let remoteFailures = 0;
|
||||
let retries = 0;
|
||||
let warned = false;
|
||||
async function observeNext(): Promise<FinishObservationResult | undefined> {
|
||||
async function observeNext(): Promise<FollowOutcome | undefined> {
|
||||
try {
|
||||
observation ??= await deps.open(record, signal);
|
||||
const result = await abortable(observation.next(), signal);
|
||||
const result = await following.next(abortable(observation.next(), signal), signal);
|
||||
remoteFailures = 0;
|
||||
return result;
|
||||
} catch (error) {
|
||||
@@ -254,39 +334,56 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
};
|
||||
}
|
||||
}
|
||||
async function end(notified: boolean): Promise<true> {
|
||||
await remove(watch);
|
||||
stop(watch, group);
|
||||
if (!notified) recheckCallerOf(watch);
|
||||
return true;
|
||||
}
|
||||
async function decide(outcome: FollowOutcome): Promise<Notice | undefined | "suppressed"> {
|
||||
// A queued follow-up cannot start until the current permission is answered.
|
||||
// Its pending registration must not hold the running turn's checkpoint.
|
||||
if (outcome === FOLLOW_LIMIT || outcome.status !== "permission" || watch.pending)
|
||||
await decisions(group);
|
||||
signal.throwIfAborted();
|
||||
if (await suppressed(record, outcome === FOLLOW_LIMIT ? undefined : outcome))
|
||||
return "suppressed";
|
||||
return following.decide(outcome);
|
||||
}
|
||||
/** Handles one outcome. Returns true once the subscription has ended. */
|
||||
async function step(): Promise<boolean> {
|
||||
if (await suppressed(record)) return end(false);
|
||||
if (!current) {
|
||||
const outcome = await observeNext();
|
||||
if (!outcome) {
|
||||
await delay(signal, retries++);
|
||||
return false;
|
||||
}
|
||||
current = { outcome, decided: false, sent: false };
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
if (!current.decided) {
|
||||
const notice = await decide(current.outcome);
|
||||
if (notice === "suppressed") return end(false);
|
||||
current = { ...current, decided: true, notice };
|
||||
}
|
||||
const { notice } = current;
|
||||
if (notice && !current.sent) {
|
||||
await deliver(record, notice, permissions, signal);
|
||||
signal.throwIfAborted();
|
||||
current.sent = true;
|
||||
}
|
||||
// A removal failure retries only the commit, never the already accepted callback.
|
||||
if (notice && endsSubscription(notice.reason)) return end(true);
|
||||
current = undefined;
|
||||
retries = 0;
|
||||
warned = false;
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
while (!signal.aborted) {
|
||||
try {
|
||||
if (await suppressed(record)) {
|
||||
await remove(watch);
|
||||
stop(watch, group);
|
||||
return;
|
||||
}
|
||||
if (!pending) pending = await observeNext();
|
||||
if (!pending) {
|
||||
await delay(signal, retries++);
|
||||
continue;
|
||||
}
|
||||
if (signal.aborted) return;
|
||||
// A queued follow-up cannot start until the current permission is answered.
|
||||
// Its pending registration must not hold the running turn's checkpoint.
|
||||
if (pending.status !== "permission" || watch.pending) await decisions(group);
|
||||
if (signal.aborted) return;
|
||||
if (await suppressed(record, pending)) {
|
||||
await remove(watch);
|
||||
stop(watch, group);
|
||||
return;
|
||||
}
|
||||
if (!acknowledged) acknowledged = await deliver(record, pending, permissions, signal);
|
||||
if (acknowledged) {
|
||||
// A removal failure retries only the commit, never the already accepted callback.
|
||||
await remove(watch);
|
||||
stop(watch, group);
|
||||
return;
|
||||
}
|
||||
pending = undefined;
|
||||
retries = 0;
|
||||
warned = false;
|
||||
if (await step()) return;
|
||||
} catch (error) {
|
||||
if (signal.aborted) return;
|
||||
// Delivery and storage failures retain the captured outcome and durable intent.
|
||||
@@ -308,11 +405,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
|
||||
return {
|
||||
hasPendingForCaller(agentId) {
|
||||
if (recovering || registering.has(agentId)) return true;
|
||||
for (const group of watches.values()) {
|
||||
for (const watch of group) if (watch.records[0]!.callerAgentId === agentId) return true;
|
||||
}
|
||||
return false;
|
||||
return recovering || delegates(agentId);
|
||||
},
|
||||
start: () =>
|
||||
serialize(async () => {
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { setTimeout as pause } from "node:timers/promises";
|
||||
import type { FinishSubscription, FinishSubscriptionStore, PendingWork } from "../index.js";
|
||||
import type { FinishObservationResult } from "./observation-buffer.js";
|
||||
import type { FinishNotificationReason } from "./notification.js";
|
||||
|
||||
/** The followed child is still working when the follow limit passes. */
|
||||
export const FOLLOW_LIMIT = Symbol("follow limit");
|
||||
export type FollowOutcome = FinishObservationResult | typeof FOLLOW_LIMIT;
|
||||
|
||||
/** What the caller is told about one outcome. */
|
||||
export interface Notice {
|
||||
reason: FinishNotificationReason;
|
||||
result: FinishObservationResult | null;
|
||||
work: readonly PendingWork[];
|
||||
}
|
||||
|
||||
interface Options {
|
||||
/** The watch's coalesced records; any one already following makes the watch follow. */
|
||||
records: readonly FinishSubscription[];
|
||||
store: Pick<FinishSubscriptionStore, "put">;
|
||||
limitMs: number;
|
||||
/** Work that will start the child's next turn by itself, read when a turn ends. */
|
||||
pendingWork(): readonly PendingWork[];
|
||||
reasonFor(result: FinishObservationResult): FinishNotificationReason;
|
||||
}
|
||||
|
||||
/**
|
||||
* Separates "the turn ended" from "the child has stopped". A watch waits for its prompt's turn.
|
||||
* If that turn ends while the child still has pending work, the caller is told once and the
|
||||
* watch follows the child: later turn ends and work changes stay silent until the child
|
||||
* settles, which reports `finished`, or until the follow limit passes.
|
||||
*/
|
||||
export function createFollowing(options: Options) {
|
||||
let since = options.records
|
||||
.map((record) => record.followingSince)
|
||||
.filter((value) => value !== undefined)
|
||||
.sort()[0];
|
||||
let latest: FinishObservationResult | null = null;
|
||||
/** Set when something outside the child's own events may have settled it. */
|
||||
let stale = false;
|
||||
let wake: (() => void) | undefined;
|
||||
|
||||
/** The child's last idle outcome, decided again. Nothing while it waits on a permission. */
|
||||
function recheckOutcome(): FinishObservationResult | undefined {
|
||||
stale = false;
|
||||
if (latest?.status !== "idle") return undefined;
|
||||
return { ...latest, workChanged: true };
|
||||
}
|
||||
|
||||
async function follow(): Promise<void> {
|
||||
const followingSince = new Date().toISOString();
|
||||
// Written before the notice is sent, so a restart never repeats it.
|
||||
for (const record of options.records) await options.store.put({ ...record, followingSince });
|
||||
since = followingSince;
|
||||
}
|
||||
|
||||
return {
|
||||
/** The observed outcome, or the follow limit once a followed child runs out of time. */
|
||||
async next(observed: Promise<FinishObservationResult>, signal: AbortSignal) {
|
||||
if (!since) return observed;
|
||||
// The losing side settles when the observation closes.
|
||||
observed.catch(() => undefined);
|
||||
const rechecked = stale && recheckOutcome();
|
||||
if (rechecked) return rechecked;
|
||||
const timer = new AbortController();
|
||||
const limit = pause(
|
||||
Math.max(0, Date.parse(since) + options.limitMs - Date.now()),
|
||||
FOLLOW_LIMIT,
|
||||
{ signal: AbortSignal.any([signal, timer.signal]) },
|
||||
);
|
||||
limit.catch(() => undefined);
|
||||
const recheck = new Promise<FinishObservationResult>((resolve) => {
|
||||
wake = () => {
|
||||
const outcome = recheckOutcome();
|
||||
if (outcome) resolve(outcome);
|
||||
};
|
||||
});
|
||||
try {
|
||||
return await Promise.race<FollowOutcome>([observed, limit, recheck]);
|
||||
} finally {
|
||||
wake = undefined;
|
||||
timer.abort();
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Decides the child's state again without an event from it, as when a delegation of its
|
||||
* own ended without reporting back. Only a followed child is decided again.
|
||||
*/
|
||||
recheck() {
|
||||
if (!since) return;
|
||||
stale = true;
|
||||
wake?.();
|
||||
},
|
||||
/** Returns nothing when the outcome is not worth telling the caller. */
|
||||
async decide(outcome: FollowOutcome): Promise<Notice | undefined> {
|
||||
if (outcome === FOLLOW_LIMIT)
|
||||
return { reason: "is still working", result: latest, work: options.pendingWork() };
|
||||
latest = outcome;
|
||||
const reason = options.reasonFor(outcome);
|
||||
if (reason !== "finished") return { reason, result: outcome, work: [] };
|
||||
// Before the prompt's turn ends, a work change says nothing about its outcome.
|
||||
if (outcome.workChanged && !since) return undefined;
|
||||
const work = options.pendingWork();
|
||||
if (!work.length) return { reason, result: outcome, work };
|
||||
if (since) return undefined;
|
||||
await follow();
|
||||
return { reason: "ended its turn but is still working", result: outcome, work };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -11,6 +11,7 @@ const recordsSchema = z.array(
|
||||
childAgentId: z.string().min(1),
|
||||
serverId: z.string().min(1).optional(),
|
||||
requireParentOwnership: z.boolean().optional(),
|
||||
followingSince: z.iso.datetime().optional(),
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { AgentPermissionRequest } from "../../agent-sdk-types.js";
|
||||
import type { PendingWork } from "../index.js";
|
||||
export type FinishNotificationReason =
|
||||
/** The turn ended while work that will wake the child is pending. The subscription stays. */
|
||||
| "ended its turn but is still working"
|
||||
/** The follow limit passed while the child was still working. The subscription ends. */
|
||||
| "is still working"
|
||||
| "host unreachable"
|
||||
| "host removed"
|
||||
| "finished"
|
||||
@@ -19,8 +24,23 @@ export const finishNotificationEvents = {
|
||||
"is unavailable": "closed",
|
||||
// Use the existing failure event so older clients still parse agent-message metadata.
|
||||
"was canceled": "errored",
|
||||
// Not a finish: the existing neutral event keeps older clients parsing the metadata.
|
||||
"ended its turn but is still working": "message",
|
||||
"is still working": "message",
|
||||
} as const;
|
||||
|
||||
/** Permission requests and the still-working notice leave the subscription in place. */
|
||||
export function endsSubscription(reason: FinishNotificationReason): boolean {
|
||||
return reason !== "needs permission" && reason !== "ended its turn but is still working";
|
||||
}
|
||||
|
||||
const PENDING_WORK_DESCRIPTIONS: Record<PendingWork, string> = {
|
||||
turn: "a turn in progress",
|
||||
"background work": "background work that will wake it",
|
||||
"queued messages": "queued messages",
|
||||
"delegated agents": "agents it is waiting on",
|
||||
};
|
||||
|
||||
const FINISH_NOTIFICATION_MESSAGE_LIMIT = 4000;
|
||||
|
||||
interface FinishNotificationBodyInput {
|
||||
@@ -30,6 +50,7 @@ interface FinishNotificationBodyInput {
|
||||
reason: FinishNotificationReason;
|
||||
lastAssistantMessage: string | null;
|
||||
permissionRequest?: AgentPermissionRequest;
|
||||
pendingWork?: readonly PendingWork[];
|
||||
}
|
||||
|
||||
export function formatFinishNotificationBody(params: FinishNotificationBodyInput): string {
|
||||
@@ -40,9 +61,20 @@ export function formatFinishNotificationBody(params: FinishNotificationBodyInput
|
||||
: `Could not observe child agent ${params.childAgentId} on host ${params.serverId} after three failed attempts.`;
|
||||
return `${host}\n\nStatus of child agent ${params.childAgentId} (${params.title}) is unknown.\n\nServer: ${params.serverId}\n\nThis finish subscription has ended. Reassess the delegated work; reconnecting will not resume notifications.`;
|
||||
}
|
||||
const statusLine = `Agent ${params.childAgentId} (${params.title}) ${params.reason}.`;
|
||||
const work = params.pendingWork?.length
|
||||
? `: ${params.pendingWork.map((item) => PENDING_WORK_DESCRIPTIONS[item]).join(", ")}`
|
||||
: "";
|
||||
const statusLine = `Agent ${params.childAgentId} (${params.title}) ${params.reason}${work}.`;
|
||||
const sections = [statusLine];
|
||||
if (params.serverId) sections.push(`Server: ${params.serverId}`);
|
||||
if (params.reason === "ended its turn but is still working")
|
||||
sections.push(
|
||||
"This is not its final reply. You will be notified when it finishes, errors, or needs permission.",
|
||||
);
|
||||
if (params.reason === "is still working")
|
||||
sections.push(
|
||||
"This finish subscription has ended without a final reply. Check the agent with `get_agent_status`.",
|
||||
);
|
||||
if (params.reason === "needs permission" && params.permissionRequest) {
|
||||
sections.push(
|
||||
"Respond with `respond_to_permission` using the `agentId` and `requestId` below.",
|
||||
|
||||
+3
-1
@@ -2,6 +2,8 @@ import type { WaitForFinishResult } from "@getpaseo/client/internal/daemon-clien
|
||||
|
||||
export type FinishObservationResult = WaitForFinishResult & {
|
||||
reason?: "was canceled" | "host unreachable" | "host removed";
|
||||
/** The idle child's background work changed without a turn ending. */
|
||||
workChanged?: true;
|
||||
};
|
||||
|
||||
/** Coalesces duplicate checkpoints and retains one terminal result while delivery is pending. */
|
||||
@@ -23,7 +25,7 @@ export function createObservationBuffer(signal: AbortSignal) {
|
||||
if (result.status === "permission") {
|
||||
for (const request of result.final?.pendingPermissions ?? [])
|
||||
if (!delivered.has(request.id)) permissions.set(request.id, result);
|
||||
} else terminal = result;
|
||||
} else if (!result.workChanged || !terminal || terminal.workChanged) terminal = result;
|
||||
wake?.();
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -33,6 +33,12 @@ function observeState(
|
||||
return;
|
||||
}
|
||||
if (event?.type === "turn_started") return;
|
||||
if (event?.type === "background_work") {
|
||||
// An idle child's work can settle without another turn.
|
||||
if (snapshot.status === "idle")
|
||||
buffer.push({ status: "idle", final: snapshot, lastMessage, error: null, workChanged: true });
|
||||
return;
|
||||
}
|
||||
if (event?.type === "permission_requested") {
|
||||
buffer.push({
|
||||
status: "permission",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user