Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 30e7a68742 fix(desktop): read update mode after rollout bucket lookup 2026-11-25 14:23:06 +01:00
Mohamed Boudra 6f12818b69 fix(desktop): consolidate update mode ownership and harden settings fallback 2026-11-25 14:23:06 +01:00
Mohamed Boudra 81be69e25b fix(desktop): preserve quit-lifecycle handoff deadline on macOS 2026-11-25 14:23:06 +01:00
Mohamed Boudra bebcec4e51 fix(desktop): gate queued update checks and await macOS install handoff 2026-11-25 14:23:06 +01:00
Mohamed Boudra b4a0226bb0 fix(desktop): harden update mode races, installer errors, and shared UI state
Address review findings across the desktop updater and settings store:
- Re-evaluate the saved updates.mode before authorizing background downloads during an in-flight manifest check.
- Serialize read-merge-write operations in the desktop settings store so overlapping patches cannot overwrite each other.
- Capture synchronous installer launch errors from quitAndInstall and report failures on both cached and downloaded install paths.
- Share updater state across Settings and the sidebar callout and guard against duplicate install commands and stale download loops.
2026-11-25 14:23:06 +01:00
Mohamed Boudra 16f3a79c8f feat(desktop): add automatic update modes and download progress
Give desktop users control over background updater network traffic with a persisted updates.mode setting (automatic, notify, off; default automatic).

Enforce off and notify behavior in the Electron main process as well as the renderer so automatic checks never leave the machine when opted out, quit-time installs only run in automatic mode, and explicit downloads stream live progress to both the OS window progress bar and the in-app UI.
2026-11-25 14:23:06 +01:00
e108fdc792 fix(app): keep the turn footer on plugin-transformed assistant replies (#10795)
* fix(app): preserve turn footer on plugin-transformed assistant replies

Retain sourceMessageId and sourceText when timeline projection replaces an
assistant_message with plugin items, and recognize projected assistant replies
across turn timing, footer layout, fork boundary resolution, and turn copy
(deduplicating split cards by sourceId).

No plugin SDK changes.

Closes #10438

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(app): keep the replaced row on plugin timeline cards

Projected plugin rows copied fields from the row they replaced one at a
time (sourceId, sourceKind, sourceMessageId, sourceText), and each copy
missed a footer input: turn stats from #10496 were still dropped for a
transformed reply. Projection now keeps the replaced row as `source`,
and `getAssistantReply` reads the reply through it for turn folding,
timing, copy, fork, and turn stats.

Refs #10438

Co-authored-by: Brandon Elliott <brandon.elliott@vercel.com>

* docs(plugins): note that a replaced reply keeps its turn footer

Refs #10438

* test(app): check the turn duration under a plugin-transformed reply

Refs #10438

---------

Co-authored-by: Brandon Elliott <brandon.elliott@vercel.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-25 20:07:08 +07:00
Mohamed Boudra 732b936fb6 fix(codex): keep configured developer instructions when Paseo adds instructions (#10792)
Codex uses a thread's developerInstructions in place of the
developer_instructions in its config. Paseo now reads the configured
value through config/read and sends it ahead of the agent, daemon, and
plugin instructions on thread/start, thread/resume, and rewind forks.

Closes #10644
2026-11-25 20:00:15 +07:00
Mohamed Boudra 5c97cd5903 chore(ci): move dependency signature audit to release preparation (#10800)
Keep lockfile lint in CI. Review the lockfile diff and audit dependency signatures on the release commit before shipping beta or stable releases.
2026-11-25 13:23:22 +01:00
55 changed files with 3156 additions and 385 deletions
-4
View File
@@ -87,10 +87,6 @@ jobs:
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
run: npx --yes lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity
- name: Verify dependency signatures
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
run: npm audit signatures
- name: Lint
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
run: npm run lint
+6 -6
View File
@@ -575,8 +575,9 @@ where the overrides apply; workspace scripts still find the binary through the r
## Dependency signature audit
The `quality` CI job runs `npm audit signatures`. It verifies every lockfile package's registry
signature and, for packages published with provenance, fetches
The [pre-release dependency checks](release.md#pre-release-dependency-checks) include
`npm audit signatures`. The command verifies registry signatures and, for packages published
with provenance, fetches
`/-/npm/v1/attestations/<name>@<version>` from the registry. Cloudflare caches that document
for a year. An edge that cached it in the seconds before the registry attached the publish
attestation keeps serving a document with only the provenance bundle, and npm fails with:
@@ -587,11 +588,10 @@ npm error <name>@<version> has attestations but no corresponding public key(s) c
```
The same package's registry signature verified a moment earlier with the same keys, so the
key list is intact. The failure names one package, repeats only for that package, and depends
on the Azure region the runner landed in, because each region maps to one Cloudflare colo. A
rerun passes only by landing elsewhere.
key list is intact. The failure names one package and depends on which Cloudflare edge serves
the cached attestation.
To confirm, fetch the URL from several runners and compare `content-length`, the `cf-ray` colo
To confirm, fetch the URL from several regions and compare `content-length`, the `cf-ray` colo
suffix, and the number of `attestations` entries (#7730 has the probe). To fix, remove or
replace that version in the lockfile. If the dependent’s range cannot be changed, pin a clean
version in root `overrides`. Report the URL to npm so they purge it.
+7
View File
@@ -883,6 +883,13 @@ its Zod schema, and mounts the component inside the normal plugin runtime and er
optional output `id` distinguishes several stable replacements from the same source item; its output
index is the default.
Each replacement keeps a reference to the source row (`source` on the projected stream item), and
turn logic reads a replaced reply through it. A reply split into several cards stays one reply: turn
folding keeps every card visible, and the turn footer hangs under the last card, copies the original
reply text once, forks at its message, and shows its duration and stats. Read the reply with
`getAssistantReply` (`packages/app/src/types/stream.ts`) instead of checking `kind ===
"assistant_message"`.
Transformers run synchronously and must be deterministic. When several transformers match, the
first one that returns a result owns that source item. Plugin and registration ordering is stable.
See `plugin-examples/timeline-items` for the complete contract.
+33 -11
View File
@@ -17,6 +17,7 @@ A release has exactly two steps. The agent does the first, the user authorizes t
run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag
- push the `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` branch and confirm its `CI` and
`Desktop Packages` runs pass (never wait on `main` CI)
- run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
**Go-ahead** (user says "go ahead"):
@@ -107,6 +108,7 @@ An explicit user instruction can select another base.
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` cancels in-progress
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
6. After go-ahead, run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta). This
publishes to npm and pushes the `v*` tag on the already-verified commit. Because the release
@@ -126,7 +128,9 @@ shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version
as the next unused patch beta, `0.13.4-beta.1`, from the tested beta tag. No `version:all:*` mode
computes that from a prerelease, so run `npm run release:check`, bump with
`npm version 0.13.4-beta.1 --include-workspace-root --no-git-tag-version && git commit -m "chore(release): cut 0.13.4-beta.1"`,
push the release branch for `CI` and `Desktop Packages`, then ship with `npm run release:ship:beta`.
push the release branch for `CI` and `Desktop Packages`, and complete the
[pre-release dependency checks](#pre-release-dependency-checks) before shipping with
`npm run release:ship:beta`.
Record the tested beta tag as its source so its soak still counts for the unchanged content.
## Release inventory
@@ -234,6 +238,7 @@ npm run release:prep:minor
# 2. Push the release branch and wait for CI + Desktop Packages on this commit.
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# 3. After go-ahead and green release-branch checks: publish npm and push the tag.
npm run release:ship
@@ -269,7 +274,8 @@ npm run release:check # Typecheck, build, dry-run pack
npm run version:all:patch
npm run version:all:minor
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
# Wait for CI and Desktop Packages on this branch to pass, then after go-ahead:
# Wait for CI and Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
npm run release:push # Create tag vX.Y.Z on HEAD and push (triggers release workflows)
```
@@ -286,6 +292,7 @@ npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
# 2. Push the release branch and wait for CI + Desktop Packages to pass:
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# 3. After go-ahead:
npm run release:ship:beta
@@ -293,7 +300,8 @@ npm run release:ship:beta
# Later, after soak, promote on release/vX.Y.Z:
npm run release:prep:promote
git push -u origin HEAD
# Wait for CI + Desktop Packages to pass, then after go-ahead:
# Wait for CI + Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:ship
```
@@ -329,22 +337,21 @@ Drafts do not appear in GitHub's releases feed. Updater clients continue to see
### Default behavior
`npm run release:prep:patch` or `npm run release:prep:minor` → push release branch → green checks → `npm run release:ship` → tag push → 36h ramp. No extra action needed.
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 `rollout_hours` input on `desktop-release.yml` is **only read on `workflow_dispatch`** — tag-push runs always default to 36. To get any other rollout duration on a fresh release, use the post-publish flip below.
### Instant-admit release (rollout_hours=0)
Tag-push runs from `npm run release:ship` always stamp 36 hours. To admit everyone immediately (hotfix, doc-only change, a release you want out fast), ship the release normally, wait for it to publish, then flip the manifests:
Follow the [standard stable release procedure](#standard-release-stable). Wait for Desktop
Release to publish, then update the manifests to admit everyone immediately.
```bash
# 1. Ship the verified release branch (36h ramp from tag push).
npm run release:ship
# 2. Wait for Desktop Release to publish the GitHub Release.
# 1. Wait for Desktop Release to publish the GitHub Release.
gh run watch <desktop-release-run-id> --exit-status
# 3. Flip the published manifests to instant admit.
# 2. Flip the published manifests to instant admit.
gh workflow run desktop-rollout.yml \
-f tag=v0.1.64 \
-f rollout_hours=0
@@ -390,7 +397,8 @@ gh workflow run desktop-release.yml \
-f rollout_hours=6
```
This does **not** apply to fresh releases shipped via `npm run release:ship` — tag-push runs always stamp 36. For a fresh release with a custom ramp, ship normally and then dispatch `desktop-rollout.yml` (same pattern as the instant-admit flow above, with your chosen `rollout_hours`).
For a fresh release with a custom ramp, follow the [instant-admit procedure](#instant-admit-release-rollout_hours0)
and set `rollout_hours` to your chosen duration.
### Releasing during an active rollout
@@ -859,6 +867,18 @@ Bullets within each section (Added, Changed, Fixed) follow this order:
2. **Quality-of-life improvements** — polish, performance, smoother interactions.
3. **Internal/infra changes last** — only include if they have a tangible user benefit (e.g. "faster startup" is user-facing even if the fix was internal).
## Pre-release dependency checks
Run these checks from the repository root on the release commit before shipping a beta or stable release.
Use Linux x64 so the audit includes the platform-specific dependencies that the CI job checked.
1. Review changes to dependency versions, download URLs, and integrity hashes in `git diff <previous-release-tag> HEAD -- package-lock.json`.
2. Install the exact dependencies from the release lockfile with `npm ci`.
3. Run `npm audit signatures`. Investigate failures before shipping. See [Dependency signature audit](development.md#dependency-signature-audit) for help.
Checking signatures and reviewing the lockfile diff reduce the risk of shipping compromised dependencies.
These checks help prevent supply-chain attacks from reaching users through Paseo.
## Pre-release sanity check
Before cutting a **stable** release, the release agent reviews the diff as a last line of defence against shipping bugs. Skip this for betas — the beta itself is the smoke test, and gating each beta on a code review defeats the point of using betas as fast release candidates.
@@ -886,6 +906,7 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before running `release:prep:*`
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:ship:beta` published npm and pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
@@ -909,6 +930,7 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:ship` published npm, updated dist-tags, and pushed the `vX.Y.Z` tag without triggering a second CI run
- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta`
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
@@ -1,6 +1,12 @@
import { test } from "../support/fixtures";
import { expect, test } from "../support/fixtures";
import {
expectChatHistoryAttachment,
forkMostRecentAssistantTurnToNewTab,
observeForkAttachment,
} from "../support/helpers/assistant-fork";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import {
ASSISTANT_TEXT,
withTimelinePlugin,
viewInlineThinkingExample,
requestPluginTimeline,
@@ -55,3 +61,24 @@ test("inline-thinking example renders a streamed thought through host UI", async
}, info) => {
await viewInlineThinkingExample(page, info);
});
test("plugin-transformed assistant reply keeps copy, fork, and turn duration in its footer", async ({
page,
}, info) => {
const forkAttachment = observeForkAttachment(page);
await withTimelinePlugin(page, info, "assistant", async (agent) => {
await requestPluginTimeline(agent);
await agent.client.waitForFinish(agent.agentId, 30_000);
await expectWholeCompletedCard(page);
const footer = page.getByTestId("turn-footer").last();
await expect(footer).toBeVisible();
await expect(footer.getByRole("button", { name: "Copy turn" })).toBeVisible();
await expect(footer.getByRole("button", { name: "Fork chat from here" })).toBeVisible();
await expect(footer.getByText(/^Worked for /)).toBeVisible();
await forkMostRecentAssistantTurnToNewTab(page);
await expectChatHistoryAttachment(page);
expect(await forkAttachment.waitForText()).toContain(ASSISTANT_TEXT);
});
});
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
import type { TurnTiming } from "@/timeline/turn-time";
import type { TimelineItemTransform } from "@/plugins/timeline";
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
import type { StreamItem } from "@/types/stream";
import {
orderHeadForStreamRenderStrategy,
@@ -578,4 +580,40 @@ describe("layoutStream", () => {
expect(footerOwners(layout)).toEqual([]);
},
);
it.each(["web", "android"] as const)(
"attaches the turn footer to the final card of a plugin-split reply on %s",
(platform) => {
const metrics = [{ label: "Model", value: "opus" }];
const first = { ...assistantMessage("a1", 2), turnMetrics: [{ label: "Steps", value: "1" }] };
const latest = { ...assistantMessage("a2", 4), turnMetrics: metrics };
const splitIntoCards: TimelineItemTransform = ({ item, sourceId }) =>
item.type !== "assistant_message"
? undefined
: ["text", "card"].map((part) => ({
type: "plugin",
id: `${sourceId}/${part}`,
pluginId: "genui",
kind: `genui-${part}`,
version: 1,
data: {},
}));
const tail = projectPluginTimelineItems(
[userMessage("u1", 1), first, userMessage("u2", 3), latest],
splitIntoCards,
);
const layout = layoutFor({
platform,
tail,
timingIds: ["genui/a1/card", "genui/a2/card"],
});
expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]);
expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe(
first.turnMetrics,
);
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics);
},
);
});
+4 -4
View File
@@ -1,6 +1,6 @@
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
import type { TurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
import { getAssistantReply, type StreamItem } from "@/types/stream";
import { getAssistantMessageSpacing, getGapBetweenStreamItems } from "./spacing";
import type { StreamFrameChildOrder, StreamStrategy } from "./strategy";
import { continuesResponse, continuesTurn, isResponseBoundary } from "./turn-membership";
@@ -72,9 +72,9 @@ function createTurnFooterHost(input: {
timingByItemId: Map<string, TurnTiming>;
}): TurnFooterHost {
const turnMetrics =
input.item.kind === "assistant_message" || input.item.kind === "tool_call"
input.item.kind === "tool_call"
? input.item.turnMetrics
: undefined;
: getAssistantReply(input.item)?.turnMetrics;
return {
itemId: input.item.id,
items: input.items,
@@ -109,7 +109,7 @@ function findTurnFooterSource(input: {
if (!item || (laterItem && !continuesResponse(item, laterItem))) {
return toolFallback;
}
if (item.kind === "assistant_message") {
if (getAssistantReply(item)) {
return { item, items, index };
}
laterItem = item;
@@ -28,7 +28,11 @@ function userMessage(id: string, text: string, seed: number): StreamItem {
};
}
function assistantMessage(id: string, text: string, seed: number): StreamItem {
function assistantMessage(
id: string,
text: string,
seed: number,
): Extract<StreamItem, { kind: "assistant_message" }> {
return {
kind: "assistant_message",
id,
@@ -243,4 +247,38 @@ describe("layout strategy edges", () => {
"content-then-footer",
);
});
it.each(PLATFORMS)("copies a reply split into plugin cards once on %s", (platform) => {
const strategy = strategyFor(platform);
const splitReply = assistantMessage("a2", 'Summary\n\n```ui\nCard("Hi", [])\n```', 3);
const card = (part: string): StreamItem => ({
kind: "plugin",
id: `genui/a2/${part}`,
source: splitReply,
timestamp: splitReply.timestamp,
pluginId: "genui",
pluginItemId: `a2/${part}`,
itemKind: `genui-${part}`,
version: 1,
data: {},
});
const items = orderTailForStreamRenderStrategy({
strategy,
streamItems: [
userMessage("u1", "prompt", 1),
assistantMessage("a1", "Before card", 2),
card("text"),
card("card"),
],
});
const startIndex = items.findIndex((item) => item.id === "genui/a2/card");
expect(
collectAssistantResponseContentForStreamRenderStrategy({
strategy,
items,
startIndex,
}),
).toBe(`Before card\n\n${splitReply.text}`);
});
});
+7 -3
View File
@@ -1,6 +1,6 @@
import type { ComponentType, ReactElement, ReactNode, RefObject } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import type { StreamItem } from "@/types/stream";
import { getAssistantReply, type StreamItem } from "@/types/stream";
import type { ReadingRowReplacements } from "./reading-anchor";
import { continuesResponse } from "./turn-membership";
import type { StreamHistoryBoundary, StreamRenderSegments } from "./model";
@@ -185,6 +185,7 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate
},
collectAssistantResponseContent: (items, startIndex) => {
const messages: string[] = [];
const seenReplies = new Set<StreamItem>();
let laterItem: StreamItem | null = null;
for (
let index = startIndex;
@@ -195,8 +196,11 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate
if (!currentItem || (laterItem && !continuesResponse(currentItem, laterItem))) {
break;
}
if (currentItem.kind === "assistant_message") {
messages.push(currentItem.text);
// A transformer can split one reply into several cards; copy the reply once.
const reply = getAssistantReply(currentItem);
if (reply && !seenReplies.has(reply)) {
seenReplies.add(reply);
messages.push(reply.text);
}
laterItem = currentItem;
}
@@ -112,4 +112,63 @@ describe("resolveAssistantTurnForkBoundary", () => {
}),
).toBeUndefined();
});
it("resolves a fork boundary from the reply a plugin card replaced", () => {
const reply = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
const card: StreamItem = {
kind: "plugin",
id: "genui/assistant-1/1",
source: reply,
timelineCursor: reply.timelineCursor,
timestamp: reply.timestamp,
pluginId: "genui",
pluginItemId: "assistant-1/1",
itemKind: "genui-block",
version: 1,
data: {},
};
expect(
resolveAssistantTurnForkBoundary({
items: [userMessage("user-1", 1), card],
startIndex: 1,
supportsTimelineCursor: true,
}),
).toEqual({
boundaryCursor: { epoch: "timeline-1", seq: 42 },
boundaryMessageId: "msg-assistant-1",
});
expect(
resolveAssistantTurnForkBoundary({
items: [userMessage("user-1", 1), card],
startIndex: 1,
supportsTimelineCursor: false,
}),
).toEqual({ boundaryMessageId: "msg-assistant-1" });
});
it("ignores plugin cards that did not replace a reply", () => {
const appended: StreamItem = {
kind: "plugin",
id: "plugin/card-1",
timelineCursor: { epoch: "timeline-1", seq: 42 },
timestamp: timestamp(2),
pluginId: "plugin",
pluginItemId: "card-1",
itemKind: "card",
version: 1,
data: {},
};
expect(
resolveAssistantTurnForkBoundary({
items: [userMessage("user-1", 1), appended],
startIndex: 1,
supportsTimelineCursor: true,
}),
).toBeUndefined();
});
});
@@ -1,4 +1,4 @@
import type { StreamItem, TimelinePosition } from "@/types/stream";
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
export type AssistantTurnForkBoundary =
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
@@ -9,15 +9,15 @@ export function resolveAssistantTurnForkBoundary(input: {
startIndex: number;
supportsTimelineCursor: boolean;
}): AssistantTurnForkBoundary | undefined {
const item = input.items[input.startIndex];
if (item?.kind !== "assistant_message") {
const reply = getAssistantReply(input.items[input.startIndex]);
if (!reply) {
return undefined;
}
if (input.supportsTimelineCursor && item.timelineCursor) {
if (input.supportsTimelineCursor && reply.timelineCursor) {
return {
boundaryCursor: item.timelineCursor,
...(item.messageId ? { boundaryMessageId: item.messageId } : {}),
boundaryCursor: reply.timelineCursor,
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
};
}
return item.messageId ? { boundaryMessageId: item.messageId } : undefined;
return reply.messageId ? { boundaryMessageId: reply.messageId } : undefined;
}
@@ -16,8 +16,7 @@ function pluginReply(sourceId: string, part = "0"): StreamItem {
return {
kind: "plugin",
id: `math/${sourceId}/${part}`,
sourceId,
sourceKind: "assistant_message",
source: reply(sourceId),
timestamp: at,
pluginId: "math",
pluginItemId: `${sourceId}/${part}`,
@@ -99,10 +98,10 @@ describe("collapseTurns", () => {
expect(result.hostIdByFoldedMessageId.get("intermediate")).toBe("prompt");
});
it.each([undefined, "thought", "tool_call"] as const)(
"does not treat a plugin row with source kind %s as a reply",
(sourceKind) => {
const card = { ...pluginReply("card"), sourceKind };
it.each([undefined, thought("card"), shell("card")])(
"does not treat a plugin row replacing %o as a reply",
(source) => {
const card = { ...pluginReply("card"), source };
const items = [user("prompt"), shell("call"), card];
expect(collapse(items).tail).toEqual(items);
expect(collapse(items).summaryRowsByHostId.size).toBe(0);
@@ -1,6 +1,7 @@
import { isTurnBoundary, isTurnTrigger } from "../turn-membership";
import {
getStreamItemMessageId,
getAssistantReply,
type StreamItem,
type ThoughtItem,
type TimelinePosition,
@@ -103,22 +104,15 @@ function staysVisibleWhenCollapsed(item: StreamItem): boolean {
return isTurnTrigger(item) || item.kind === "compaction";
}
function isAssistantReply(item: StreamItem): boolean {
return (
item.kind === "assistant_message" ||
(item.kind === "plugin" && item.sourceKind === "assistant_message")
);
}
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
for (let index = end - 1; index >= start; index -= 1) {
const item = tail[index]!;
if (!isAssistantReply(item)) continue;
if (!getAssistantReply(item)) continue;
const messageId = getStreamItemMessageId(item);
// A transformer can split one reply into several cards; keep the whole reply visible.
while (index > start) {
const previous = tail[index - 1]!;
if (!isAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break;
if (!getAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break;
index -= 1;
}
return index;
@@ -156,7 +150,7 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse {
}
const folded = tail.slice(runStart, replyIndex);
const tools = summarizeTurn(folded, input.getGroupedCalls);
if (!hasWork(tools) && !folded.some(isAssistantReply)) {
if (!hasWork(tools) && !folded.some((item) => getAssistantReply(item))) {
output.push(...tail.slice(runStart, runEnd));
return;
}
@@ -150,3 +150,44 @@ describe("turn stats", () => {
expect(host.getBoundingClientRect().height).toBe(without);
});
});
const projectedReply: StreamItem = {
kind: "plugin",
id: "genui/reply/1",
source: {
kind: "assistant_message",
id: "reply",
messageId: "provider-reply-1",
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
timelineCursor: { epoch: "e1", seq: 5 },
timestamp: FRIDAY_NIGHT,
},
timelineCursor: { epoch: "e1", seq: 5 },
timestamp: FRIDAY_NIGHT,
pluginId: "genui",
pluginItemId: "reply/1",
itemKind: "genui-block",
version: 1,
data: {},
};
it("renders copy, fork, and duration for a plugin-projected assistant reply", () => {
const onFork = vi.fn();
act(() =>
root.render(
<CompletedTurnFooterRow
strategy={createNativeStreamStrategy()}
items={[projectedReply]}
timing={COMPLETED_TIMING}
startIndex={0}
supportsTimelineCursor={true}
onForkAssistantTurn={onFork}
/>,
),
);
expect(host.querySelector('[aria-label="Copy turn"]')).not.toBeNull();
expect(host.querySelector('[aria-label="Fork chat from here"]')).not.toBeNull();
expect(host.textContent).toContain("Worked for 26s");
});
@@ -4,7 +4,7 @@ import { View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { SPACING, type Theme } from "@/styles/theme";
import type { TurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
import { getAssistantReply, type StreamItem } from "@/types/stream";
import {
collectAssistantResponseContentForStreamRenderStrategy,
type StreamStrategy,
@@ -208,7 +208,7 @@ function CompletedTurnFooter({
return (
<View style={stylesheet.turnFooterSlot}>
<AssistantTurnFooter
getContent={items[startIndex]?.kind === "assistant_message" ? getContent : undefined}
getContent={getAssistantReply(items[startIndex]) ? getContent : undefined}
completedAt={timing?.completedAt}
durationMs={timing?.durationMs}
onFork={boundary && onForkAssistantTurn ? handleFork : undefined}
@@ -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,
@@ -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 },
},
+36
View File
@@ -1541,6 +1541,8 @@ export const ar: TranslationResources = {
status: {
checking: "جارٍ التحقق من وجود تحديثات للتطبيق...",
installing: "جارٍ تثبيت تحديث التطبيق...",
downloadingVersionProgress: "جارٍ تنزيل {{version}}... {{percent}}%",
downloadingProgress: "جارٍ تنزيل تحديث التطبيق... {{percent}}%",
upToDate: "التطبيق محدث.",
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
pending: "سنخبرك عندما يصبح التحديث جاهزًا.",
@@ -1548,6 +1550,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: "تحديث التطبيق جاهز للتثبيت.",
@@ -1558,14 +1568,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: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.",
@@ -2643,9 +2660,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: "تثبيت التحديث",
+36
View File
@@ -1568,6 +1568,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.",
@@ -1576,6 +1578,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.",
@@ -1586,14 +1596,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.",
@@ -2739,9 +2756,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",
+38
View File
@@ -1578,6 +1578,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.",
@@ -1586,6 +1588,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}}.",
@@ -1598,14 +1610,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:
@@ -2664,9 +2683,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",
+38
View File
@@ -1571,6 +1571,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.",
@@ -1579,6 +1581,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}}.",
@@ -1591,14 +1603,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:
@@ -2664,9 +2683,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",
+37
View File
@@ -1556,6 +1556,8 @@ export const ja: TranslationResources = {
status: {
checking: "アプリの更新を確認中...",
installing: "アプリの更新をインストール中...",
downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%",
downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%",
upToDate: "アプリは最新です。",
upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。",
pending: "更新の準備ができたらお知らせします。",
@@ -1563,6 +1565,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}}。",
@@ -1574,14 +1585,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:
@@ -2631,9 +2649,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: "更新をインストール",
+37
View File
@@ -1547,6 +1547,8 @@ export const ko: TranslationResources = {
status: {
checking: "앱 업데이트 확인 중...",
installing: "앱 업데이트 설치 중...",
downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%",
downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%",
upToDate: "앱이 최신 상태입니다.",
upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.",
pending: "업데이트가 준비되면 알려드리겠습니다.",
@@ -1555,6 +1557,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}}에서 마지막으로 확인했습니다.",
@@ -1567,14 +1578,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: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.",
@@ -2621,9 +2639,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: "업데이트 설치",
+37
View File
@@ -1568,6 +1568,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.",
@@ -1576,6 +1578,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}}.",
@@ -1588,14 +1599,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:
@@ -2646,9 +2664,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",
+37
View File
@@ -1562,6 +1562,8 @@ export const ru: TranslationResources = {
status: {
checking: "Проверка обновлений приложения...",
installing: "Установка обновления приложения...",
downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%",
downloadingProgress: "Загрузка обновления приложения... {{percent}}%",
upToDate: "Установлена последняя версия приложения.",
upToDateWithLastChecked:
"Установлена последняя версия приложения. Последняя проверка: {{time}}.",
@@ -1571,6 +1573,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}}.",
@@ -1583,14 +1594,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:
@@ -2653,9 +2671,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: "Установить обновление",
+36
View File
@@ -1528,6 +1528,8 @@ export const zhCN: TranslationResources = {
status: {
checking: "正在检查 app 更新...",
installing: "正在安装 app 更新...",
downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%",
downloadingProgress: "正在下载 app 更新... {{percent}}%",
upToDate: "App 已是最新版本。",
upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。",
pending: "更新准备好后会通知你。",
@@ -1535,6 +1537,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 更新可安装。",
@@ -1545,14 +1555,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 会话。",
@@ -2580,9 +2597,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: "安装更新",
@@ -98,8 +98,7 @@ describe("plugin timeline projection", () => {
{
kind: "plugin",
id: "inline-thinking/thought-1/0",
sourceId: "thought-1",
sourceKind: "thought",
source: { kind: "thought", id: "thought-1" },
data: { text: "First", phase: "streaming" },
},
]);
@@ -192,4 +191,54 @@ describe("plugin timeline projection", () => {
]);
expect(filtered).toEqual([]);
});
it("keeps the replaced reply on every card it was split into", () => {
const source: StreamItem = {
kind: "assistant_message",
id: "assistant-1",
messageId: "provider-msg-1",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
text: 'Summary\n\n```ui\nCard("Hi", [])\n```',
timestamp: new Date("2026-01-01T00:00:02.000Z"),
};
const split: TimelineItemTransform = ({ sourceId }) => [
{
type: "plugin",
id: `${sourceId}/text`,
pluginId: "genui",
kind: "genui-text",
version: 1,
data: { part: "text" },
},
{
type: "plugin",
id: `${sourceId}/card`,
pluginId: "genui",
kind: "genui-block",
version: 1,
data: { part: "card" },
},
];
const projected = projectPluginTimelineItems([source], split);
expect(projected).toMatchObject([
{
kind: "plugin",
id: "genui/assistant-1/text",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
{
kind: "plugin",
id: "genui/assistant-1/card",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
]);
expect(projected.map((item) => item.kind === "plugin" && item.source)).toEqual([
source,
source,
]);
});
});
@@ -95,8 +95,7 @@ function transformSourceItem(
const projected: PluginTimelineStreamItem = {
kind: "plugin",
id: `${pluginItem.pluginId}/${pluginItem.id}`,
sourceId: item.id,
sourceKind: item.kind,
source: item,
timestamp: item.timestamp,
pluginId: pluginItem.pluginId,
pluginItemId: pluginItem.id,
+135 -19
View File
@@ -83,6 +83,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";
@@ -609,25 +610,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,
@@ -637,12 +705,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(() => {
@@ -666,17 +734,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;
@@ -691,10 +778,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;
@@ -715,6 +799,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>
@@ -726,6 +822,7 @@ function DesktopAppUpdateRow() {
})}
</Text>
) : null}
{downloadPercent !== null ? <DesktopUpdateProgressBar percent={downloadPercent} /> : null}
{errorMessage ? <Text style={styles.aboutErrorText}>{errorMessage}</Text> : null}
</View>
<View style={styles.aboutUpdateActions}>
@@ -739,9 +836,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>
@@ -1506,6 +1609,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",
@@ -247,3 +247,37 @@ it("times a heartbeat that ends with tools and no assistant text", () => {
});
assert.equal(timing.byItemId.get("last")?.durationMs, 5000);
});
it("times a reply that a plugin split into cards", () => {
const userAt = new Date("2026-05-15T00:00:00.000Z");
const replyAt = new Date("2026-05-15T00:00:06.000Z");
const reply: StreamItem = {
kind: "assistant_message",
id: "a1",
text: "Intro",
timestamp: replyAt,
};
const card = (part: string): StreamItem => ({
kind: "plugin",
id: `genui/a1/${part}`,
source: reply,
timestamp: replyAt,
pluginId: "genui",
pluginItemId: `a1/${part}`,
itemKind: `genui-${part}`,
version: 1,
data: {},
});
const timing = deriveStreamTurnTiming({
isTurnActive: false,
activeTurnStartedAt: null,
tail: [user("u1", userAt), card("text"), card("card")],
head: [],
});
assert.deepEqual(timing.byItemId.get("genui/a1/card"), {
completedAt: replyAt,
durationMs: 6000,
});
});
+2 -2
View File
@@ -1,4 +1,4 @@
import type { StreamItem } from "@/types/stream";
import { getAssistantReply, type StreamItem } from "@/types/stream";
import { startsNewTurn, isTurnTrigger } from "@/agent-stream/turn-membership";
export interface TurnTiming {
@@ -70,7 +70,7 @@ function walkTurns(
assistantIds = [];
}
lastItemAt = item.timestamp;
if (item.kind === "assistant_message") {
if (getAssistantReply(item)) {
assistantIds.push(item.id);
}
previousItem = item;
+16 -5
View File
@@ -783,7 +783,7 @@ export type AgentToolCallItem = ToolCallItem & {
/** Find and scrolling address a plugin row by the source it replaces. */
export function getStreamItemMessageId(item: StreamItem): string {
if (item.kind === "plugin") return item.sourceId ?? item.id;
if (item.kind === "plugin") return item.source?.id ?? item.id;
return item.id;
}
@@ -791,6 +791,15 @@ export function isAgentToolCallItem(item: StreamItem): item is AgentToolCallItem
return item.kind === "tool_call" && item.payload.source === "agent";
}
/** The assistant reply a row shows: the row itself, or the reply a timeline plugin replaced. */
export function getAssistantReply(
item: StreamItem | null | undefined,
): AssistantMessageItem | null {
if (item?.kind === "assistant_message") return item;
if (item?.kind === "plugin" && item.source?.kind === "assistant_message") return item.source;
return null;
}
type NotificationLevel = "info" | "warning" | "error";
export interface NotificationItem {
@@ -818,10 +827,12 @@ export interface CompactionItem {
export interface PluginTimelineStreamItem {
kind: "plugin";
id: string;
/** The id of the stream item a timeline transformer replaced; set only by projection. */
sourceId?: string;
/** The original row kind, retained by projection for turn folding. */
sourceKind?: StreamItem["kind"];
/**
* The row a timeline transformer replaced; set only by projection. Turn folding, timing, and the
* turn footer read the replaced row through it, so a transformed reply keeps its copy, fork,
* duration, and stats.
*/
source?: StreamItem;
timelineCursor?: TimelinePosition;
turnId?: string;
timestamp: Date;
+109 -34
View File
@@ -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) {
+68
View File
@@ -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", () => {
+15 -3
View File
@@ -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) => {
@@ -1,10 +1,14 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import type { DesktopUpdateMode } from "../settings/desktop-settings";
import {
createAppUpdateService,
type AppUpdateDownloadProgress,
type AppUpdateInstallRequest,
type AppUpdateRuntime,
type AppUpdateRuntimeConfiguration,
type RuntimeDownloadProgressInfo,
type RuntimeUpdateCheckResult,
type RuntimeUpdateInfo,
} from "./app-update-service";
@@ -26,6 +30,8 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
resolve(): void;
reject(error: Error): void;
} | null = null;
lastAutoDownload: boolean | null = null;
nextQuitAndInstallResult: { started: boolean; errorMessage?: string } | null = null;
checkCount = 0;
downloadCallCount = 0;
requestedDownloadVersions: string[] = [];
@@ -35,9 +41,18 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
configure(input: AppUpdateRuntimeConfiguration): void {
this.configuration = input;
this.lastAutoDownload = input.autoDownload;
this.gate = input.shouldAdmitUpdate;
}
setAutoDownload(enabled: boolean): void {
this.lastAutoDownload = enabled;
}
emitDownloadProgress(progress: RuntimeDownloadProgressInfo): void {
this.configuration?.onDownloadProgress(progress);
}
nextCheck(result: { isUpdateAvailable: boolean; updateInfo: RuntimeUpdateInfo } | null): void {
this.checks.push(result);
}
@@ -143,21 +158,36 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
}
}
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void {
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest) {
if (this.nextQuitAndInstallResult) {
const outcome = this.nextQuitAndInstallResult;
this.nextQuitAndInstallResult = null;
return outcome;
}
if (this.downloadedUpdate) {
this.installedVersions.push(this.downloadedUpdate.version);
this.installModes.push({ targetVersion, isSilent, isForceRunAfter });
}
return { started: true };
}
}
function createService(input?: { now?: () => number; bucket?: () => Promise<number> }) {
function createService(input?: {
now?: () => number;
bucket?: () => Promise<number>;
updateMode?: () => DesktopUpdateMode | Promise<DesktopUpdateMode>;
reportSettingsError?: (error: unknown) => void;
onDownloadProgress?: (progress: AppUpdateDownloadProgress | null) => void;
}) {
const runtime = new FakeAppUpdateRuntime();
const service = createAppUpdateService({
runtime,
isPackaged: () => true,
now: input?.now ?? (() => Date.parse("2026-04-28T12:00:00.000Z")),
bucket: input?.bucket ?? (async () => 0.99),
updateMode: input?.updateMode,
reportSettingsError: input?.reportSettingsError,
onDownloadProgress: input?.onDownloadProgress,
});
return { runtime, service };
}
@@ -182,6 +212,7 @@ describe("app update service", () => {
expect(result).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
@@ -203,6 +234,7 @@ describe("app update service", () => {
expect(result).toEqual({
hasUpdate: true,
readyToInstall: false,
downloading: true,
currentVersion: "1.2.3",
latestVersion: "1.2.4",
body: null,
@@ -331,6 +363,7 @@ describe("app update service", () => {
expect(result).toEqual({
hasUpdate: true,
readyToInstall: false,
downloading: true,
currentVersion: "1.2.3",
latestVersion: "1.2.5",
body: null,
@@ -361,6 +394,7 @@ describe("app update service", () => {
expect(result).toEqual({
hasUpdate: true,
readyToInstall: false,
downloading: true,
currentVersion: "1.2.3",
latestVersion: "1.2.5",
body: null,
@@ -569,6 +603,7 @@ describe("app update service", () => {
expect(result).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
@@ -590,6 +625,7 @@ describe("app update service", () => {
expect(result).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
@@ -620,6 +656,7 @@ describe("app update service", () => {
expect(retryResult).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
@@ -649,6 +686,7 @@ describe("app update service", () => {
expect(automaticResult).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
@@ -691,6 +729,7 @@ describe("app update service", () => {
expect(automaticResult).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
@@ -721,6 +760,7 @@ describe("app update service", () => {
expect(failedPreparation).toEqual({
hasUpdate: true,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.4",
body: null,
@@ -739,6 +779,7 @@ describe("app update service", () => {
expect(result).toEqual({
hasUpdate: true,
readyToInstall: false,
downloading: true,
currentVersion: "1.2.3",
latestVersion: "1.2.5",
body: null,
@@ -802,6 +843,7 @@ describe("app update service", () => {
expect(result).toEqual({
hasUpdate: true,
readyToInstall: false,
downloading: true,
currentVersion: "1.2.3",
latestVersion: "1.2.5",
body: null,
@@ -834,6 +876,7 @@ describe("app update service", () => {
expect(result).toEqual({
hasUpdate: true,
readyToInstall: true,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.4",
body: null,
@@ -841,4 +884,422 @@ describe("app update service", () => {
errorMessage: null,
});
});
it("reports an available update without downloading when autoDownload is false", async () => {
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
const { runtime, service } = createService({
bucket: async () => 0,
onDownloadProgress: (progress) => progressEvents.push(progress),
});
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const result = await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: false,
});
expect(runtime.lastAutoDownload).toBe(false);
expect(result).toEqual({
hasUpdate: true,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.4",
body: null,
date: "2026-04-28T00:00:00.000Z",
errorMessage: null,
});
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const activeDownload = runtime.beginUpdateDownload(rolledOutUpdate);
const installPending = service.downloadAndInstallUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
});
await Promise.resolve();
runtime.emitDownloadProgress({
percent: 45,
transferred: 45,
total: 100,
bytesPerSecond: 10,
});
activeDownload.resolve();
const installResult = await installPending;
expect(installResult.installed).toBe(true);
expect(progressEvents).toContainEqual({
version: "1.2.4",
percent: 45,
transferred: 45,
total: 100,
bytesPerSecond: 10,
});
expect(progressEvents[progressEvents.length - 1]).toBeNull();
});
it("allows retrying the same version after a transient download failure in notify/off mode", async () => {
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
const { runtime, service } = createService({
bucket: async () => 0,
onDownloadProgress: (progress) => progressEvents.push(progress),
});
// 1. Discover v1.2.4 without auto-downloading.
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const discovered = await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "manual",
autoDownload: false,
});
expect(discovered).toMatchObject({
hasUpdate: true,
readyToInstall: false,
downloading: false,
latestVersion: "1.2.4",
});
// 2. First explicit download fails transiently mid-transfer.
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const failingDownload = runtime.beginUpdateDownload(rolledOutUpdate);
const failedInstallPromise = service.downloadAndInstallUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
});
await new Promise<void>((resolve) => setImmediate(resolve));
expect(runtime.downloadCallCount).toBe(1);
runtime.emitDownloadProgress({
percent: 37,
transferred: 37,
total: 100,
bytesPerSecond: 10,
});
failingDownload.reject(new Error("ECONNRESET"));
const failedInstall = await failedInstallPromise;
expect(failedInstall).toMatchObject({
installed: false,
errorMessage: "ECONNRESET",
});
expect(progressEvents[progressEvents.length - 1]).toBeNull();
// 3. User retries manual Check for the SAME version (v1.2.4) — must not be stranded on stale error!
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const retryCheck = await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "manual",
autoDownload: false,
});
expect(retryCheck).toMatchObject({
hasUpdate: true,
readyToInstall: false,
downloading: false,
latestVersion: "1.2.4",
errorMessage: null,
});
// 4. Second explicit download succeeds and installs cleanly.
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const retryInstall = await service.downloadAndInstallUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
});
expect(retryInstall.installed).toBe(true);
expect(runtime.installedVersions).toEqual(["1.2.4"]);
});
it("downloads and installs a newer release if one ships after notify discovery", async () => {
const { runtime, service } = createService({ bucket: async () => 0 });
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: false,
});
const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" };
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate });
const result = await service.downloadAndInstallUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
});
expect(result.installed).toBe(true);
expect(runtime.installedVersions).toEqual(["1.2.5"]);
});
it("reuses an already-downloaded update when installing manually after switching to notify/off", async () => {
const { runtime, service } = createService({ bucket: async () => 0 });
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: true,
});
runtime.finishUpdateDownload(rolledOutUpdate);
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const result = await service.downloadAndInstallUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
});
expect(result.installed).toBe(true);
expect(runtime.downloadCallCount).toBe(0);
expect(runtime.installedVersions).toEqual(["1.2.4"]);
});
it("transitions cleanly from notify discovery to automatic background download", async () => {
const { runtime, service } = createService({ bucket: async () => 0 });
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const notifyCheck = await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: false,
});
expect(notifyCheck).toMatchObject({
hasUpdate: true,
readyToInstall: false,
downloading: false,
});
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const autoCheck = await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: true,
});
expect(runtime.lastAutoDownload).toBe(true);
expect(autoCheck).toMatchObject({
hasUpdate: true,
readyToInstall: false,
downloading: true,
});
});
it("clamps NaN and out-of-range download progress values safely", async () => {
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
const { runtime, service } = createService({
bucket: async () => 0,
onDownloadProgress: (progress) => progressEvents.push(progress),
});
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: true,
});
runtime.emitDownloadProgress({
percent: Number.NaN,
transferred: Number.NaN,
total: Number.POSITIVE_INFINITY,
bytesPerSecond: Number.NaN,
});
runtime.emitDownloadProgress({
percent: 140,
transferred: 200,
total: 100,
bytesPerSecond: 50,
});
expect(progressEvents).toContainEqual({
version: "1.2.4",
percent: 0,
transferred: 0,
total: 0,
bytesPerSecond: 0,
});
expect(progressEvents).toContainEqual({
version: "1.2.4",
percent: 100,
transferred: 200,
total: 100,
bytesPerSecond: 50,
});
});
it("applies updated updateMode after rollout bucket lookup before authorizing download", async () => {
let mode: DesktopUpdateMode = "automatic";
let resolveBucket!: (value: number) => void;
const { runtime, service } = createService({
bucket: () =>
new Promise<number>((resolve) => {
resolveBucket = resolve;
}),
updateMode: async () => mode,
});
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const check = service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
});
await vi.waitFor(() => {
expect(resolveBucket).toBeDefined();
});
mode = "notify";
resolveBucket(0);
const result = await check;
expect(runtime.lastAutoDownload).toBe(false);
expect(result).toMatchObject({
hasUpdate: true,
readyToInstall: false,
downloading: false,
latestVersion: "1.2.4",
});
});
it("skips a queued automatic check after Off is saved while an earlier check is in flight", async () => {
let mode: DesktopUpdateMode = "automatic";
const { runtime, service } = createService({
bucket: async () => 0,
updateMode: async () => mode,
});
const firstCheck = runtime.deferNextCheck();
const firstPending = service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
});
const queuedPending = service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
});
await vi.waitFor(() => {
expect(runtime.checkCount).toBe(1);
});
mode = "off";
firstCheck.resolve({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const [firstResult, queuedResult] = await Promise.all([firstPending, queuedPending]);
expect(runtime.checkCount).toBe(1);
expect(firstResult.hasUpdate).toBe(false);
expect(queuedResult.hasUpdate).toBe(false);
});
it("falls back to automatic mode when reading updateMode fails so updates are never stranded", async () => {
const settingsErrors: unknown[] = [];
const { runtime, service } = createService({
bucket: async () => 0,
updateMode: async () => {
throw new SyntaxError("Unexpected token } in JSON");
},
reportSettingsError: (error) => settingsErrors.push(error),
});
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const autoResult = await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
});
expect(autoResult).toMatchObject({
hasUpdate: true,
downloading: true,
latestVersion: "1.2.4",
errorMessage: null,
});
runtime.finishUpdateDownload(rolledOutUpdate);
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
const installedOnQuit = await service.installUpdateOnQuit({
currentVersion: "1.2.3",
releaseChannel: "stable",
signal: new AbortController().signal,
});
expect(installedOnQuit).toBe(true);
expect(settingsErrors.length).toBeGreaterThan(0);
});
it("skips installUpdateOnQuit when updateMode is notify or off", async () => {
let mode: DesktopUpdateMode = "automatic";
const { runtime, service } = createService({
bucket: async () => 0,
updateMode: async () => mode,
});
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
});
runtime.finishUpdateDownload(rolledOutUpdate);
mode = "notify";
expect(
await service.installUpdateOnQuit({
currentVersion: "1.2.3",
releaseChannel: "stable",
signal: new AbortController().signal,
}),
).toBe(false);
mode = "off";
expect(
await service.installUpdateOnQuit({
currentVersion: "1.2.3",
releaseChannel: "stable",
signal: new AbortController().signal,
}),
).toBe(false);
expect(runtime.installedVersions).toEqual([]);
});
it("reports installer launch failures instead of success on both cached and downloaded paths", async () => {
const { runtime, service } = createService({ bucket: async () => 0 });
// Path 1: already downloaded, installer fails to launch
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: true,
});
runtime.finishUpdateDownload(rolledOutUpdate);
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
runtime.nextQuitAndInstallResult = {
started: false,
errorMessage: "EROFS: read-only file system",
};
const cachedFailure = await service.downloadAndInstallUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
});
expect(cachedFailure).toMatchObject({
installed: false,
errorMessage: "EROFS: read-only file system",
});
// Path 2: fresh download, installer fails to launch
const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" };
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate });
runtime.nextQuitAndInstallResult = {
started: false,
errorMessage: "Neither dpkg nor apt command found",
};
const freshFailure = await service.downloadAndInstallUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
});
expect(freshFailure).toMatchObject({
installed: false,
errorMessage: "Neither dpkg nor apt command found",
});
});
});
@@ -1,3 +1,4 @@
import type { DesktopUpdateMode } from "../settings/desktop-settings.js";
import {
rolloutManifestSchema,
shouldAdmitAppUpdate,
@@ -5,9 +6,18 @@ import {
type AppUpdateCheckIntent,
} from "./app-update-rollout.js";
export interface AppUpdateDownloadProgress {
version: string | null;
percent: number;
transferred: number;
total: number;
bytesPerSecond: number;
}
export interface AppUpdateCheckResult {
hasUpdate: boolean;
readyToInstall: boolean;
downloading: boolean;
currentVersion: string;
latestVersion: string;
body: string | null;
@@ -19,6 +29,7 @@ export interface AppUpdateInstallResult {
installed: boolean;
version: string | null;
message: string;
errorMessage?: string | null;
}
export interface RuntimeUpdateInfo {
@@ -28,6 +39,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 +53,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 +67,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 +87,7 @@ export interface AppUpdateService {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
}): Promise<AppUpdateCheckResult>;
downloadAndInstallUpdate(
input: {
@@ -79,6 +108,9 @@ export interface AppUpdateServiceDeps {
isPackaged(): boolean;
now(): number;
bucket(): Promise<number>;
updateMode?: () => DesktopUpdateMode | Promise<DesktopUpdateMode>;
onDownloadProgress?(progress: AppUpdateDownloadProgress | null): void;
reportSettingsError?(error: unknown): void;
reportCheckError?(error: unknown): void;
reportRuntimeError?(error: unknown): void;
reportInstallError?(message: string): void;
@@ -88,14 +120,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 +158,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,6 +189,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
let configuredReleaseChannel: AppReleaseChannel | null = null;
let preparationError: { version: string; message: string } | null = null;
let preparingUpdateVersion: string | null = null;
let currentAutoDownload = true;
let checkQueue: Promise<void> = Promise.resolve();
function isReadyToInstallVersion(version: string): boolean {
@@ -156,6 +201,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
downloadedUpdateVersion = null;
preparationError = null;
preparingUpdateVersion = null;
deps.onDownloadProgress?.(null);
}
function buildPreviouslyAdmittedUpdateResult(
@@ -167,42 +213,89 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
return null;
}
const readyToInstall = isReadyToInstallVersion(info.version);
return buildCheckResult({
currentVersion,
hasUpdate: true,
readyToInstall: isReadyToInstallVersion(info.version),
readyToInstall,
downloading: !readyToInstall && preparingUpdateVersion === info.version,
info,
errorMessage: preparationError?.version === info.version ? preparationError.message : null,
});
}
function configureRuntime(releaseChannel: AppReleaseChannel, intent: AppUpdateCheckIntent): void {
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({
const bucket = await deps.bucket();
const liveMode = await resolveUpdateMode();
if (intent === "automatic" && liveMode === "off") {
return false;
}
const admitted = shouldAdmitAppUpdate({
channel: releaseChannel,
intent,
rolloutHours: parsed.rolloutHours,
releaseDate: parsed.releaseDate,
now: deps.now(),
bucket: await deps.bucket(),
bucket,
});
if (admitted) {
currentAutoDownload = resolveAutoDownload(liveMode, autoDownloadOverride);
deps.runtime.setAutoDownload?.(currentAutoDownload);
}
return admitted;
},
onUpdateAvailable(info) {
const alreadyReady = downloadedUpdateVersion === info.version;
cachedUpdateInfo = info;
downloadedUpdateVersion = alreadyReady ? info.version : null;
if (!alreadyReady && preparingUpdateVersion === 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.
@@ -214,6 +307,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
if (preparationError?.version === info.version) {
preparationError = null;
}
deps.onDownloadProgress?.(null);
},
onError(error) {
if (preparingUpdateVersion) {
@@ -223,6 +317,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
};
preparingUpdateVersion = null;
}
deps.onDownloadProgress?.(null);
deps.reportRuntimeError?.(error);
},
});
@@ -237,14 +332,58 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
return result;
}
function resolveAvailableUpdateResult(
currentVersion: string,
info: RuntimeUpdateInfo,
): AppUpdateCheckResult {
const latestVersion = info.version;
if (latestVersion === currentVersion) {
clearUpdateState();
return buildCheckResult({
currentVersion,
hasUpdate: false,
readyToInstall: false,
});
}
cachedUpdateInfo = info;
const readyToInstall = isReadyToInstallVersion(latestVersion);
const errorMessage =
preparationError?.version === latestVersion ? preparationError.message : null;
if (!errorMessage) {
preparationError = null;
}
if (
!readyToInstall &&
!errorMessage &&
currentAutoDownload &&
preparingUpdateVersion === null
) {
preparingUpdateVersion = latestVersion;
}
return buildCheckResult({
currentVersion,
hasUpdate: true,
readyToInstall,
downloading:
!readyToInstall &&
!errorMessage &&
(currentAutoDownload || preparingUpdateVersion === latestVersion),
info,
errorMessage,
});
}
async function checkForAppUpdate({
currentVersion,
releaseChannel,
intent,
autoDownload,
}: {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
}): Promise<AppUpdateCheckResult> {
if (!deps.isPackaged()) {
return buildCheckResult({
@@ -255,10 +394,33 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
}
return runCheckExclusively(async () => {
configureRuntime(releaseChannel, intent);
const mode = deps.updateMode ? await resolveUpdateMode() : "automatic";
if (intent === "automatic" && mode === "off") {
return buildCheckResult({
currentVersion,
hasUpdate: false,
readyToInstall: false,
});
}
if (intent === "manual") {
preparationError = null;
}
configureRuntime(
releaseChannel,
intent,
resolveAutoDownload(mode, autoDownload),
autoDownload,
);
try {
const result = await deps.runtime.checkForUpdates();
if (intent === "automatic" && deps.updateMode && (await resolveUpdateMode()) === "off") {
return buildCheckResult({
currentVersion,
hasUpdate: false,
readyToInstall: false,
});
}
if (!result || !result.updateInfo) {
clearUpdateState();
return buildCheckResult({
@@ -285,32 +447,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
});
}
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({
@@ -345,18 +482,39 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
currentVersion,
releaseChannel,
intent: "manual",
autoDownload: false,
});
if (!check.hasUpdate) {
return {
installed: false,
version: currentVersion,
message: check.errorMessage ?? "No update available.",
...(check.errorMessage ? { errorMessage: check.errorMessage } : {}),
};
}
return installCachedUpdate(currentVersion, { onBeforeQuit, restart: true });
}
function clearPreparingVersion(version: string): void {
if (preparingUpdateVersion === version) {
preparingUpdateVersion = null;
}
deps.onDownloadProgress?.(null);
}
function shouldRetryStaleDownloadError(
attemptedVersion: string,
readyVersion: string,
signal?: AbortSignal,
): boolean {
return (
attemptedVersion !== readyVersion &&
cachedUpdateInfo?.version === readyVersion &&
!signal?.aborted
);
}
async function ensureUpdateDownloaded(
readyVersion: string,
signal?: AbortSignal,
@@ -367,14 +525,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;
@@ -385,7 +543,9 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
// validated release instead of treating the stale artifact as ready.
if (attemptedVersion === readyVersion && !isReadyToInstallVersion(readyVersion)) {
downloadedUpdateVersion = readyVersion;
preparingUpdateVersion = null;
clearPreparingVersion(readyVersion);
} else if (preparingUpdateVersion === attemptedVersion) {
clearPreparingVersion(attemptedVersion);
}
}
@@ -417,30 +577,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 +603,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,6 +627,9 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
if (!deps.isPackaged() || !downloadedUpdateVersion) {
return false;
}
if ((await resolveUpdateMode()) !== "automatic") {
return false;
}
const check = await checkForAppUpdate({
currentVersion,
@@ -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(),
},
@@ -30,6 +50,26 @@ vi.mock("electron", () => ({
getPath: vi.fn(),
isPackaged: true,
},
autoUpdater: undefined,
BrowserWindow: {
getAllWindows: getAllWindowsMock,
},
}));
vi.mock("../settings/desktop-settings-electron.js", () => ({
getDesktopSettingsStore: () => ({
get: async () => {
if (desktopSettingsMock.error) {
throw desktopSettingsMock.error;
}
return {
releaseChannel: "stable",
updates: { mode: desktopSettingsMock.mode },
notifications: { playSound: true },
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
};
},
}),
}));
vi.mock("electron-updater", () => ({
@@ -40,8 +80,10 @@ import {
bucketFromStagingUserId,
checkForAppUpdate,
createAppUpdateLifecycleLogger,
downloadAndInstallUpdate,
resolveStagingUserId,
rolloutManifestSchema,
runElectronQuitAndInstall,
shouldAdmitToRollout,
shouldInstallAppUpdateOnQuit,
} from "./auto-updater";
@@ -67,6 +109,7 @@ describe("checkForAppUpdate", () => {
expect(result).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
@@ -97,6 +140,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 });
+174 -8
View File
@@ -1,17 +1,21 @@
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";
@@ -30,6 +34,7 @@ export {
type AppReleaseChannel,
type AppUpdateCheckIntent,
type AppUpdateCheckResult,
type AppUpdateDownloadProgress,
type AppUpdateInstallResult,
};
@@ -140,11 +145,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 +292,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 +316,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,14 +355,25 @@ 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,
});
}
}
@@ -227,6 +382,14 @@ const appUpdateService = createAppUpdateService({
isPackaged: () => app.isPackaged,
now: () => Date.now(),
bucket: async () => bucketFromStagingUserId(await getStagingUserId()),
updateMode: async () => (await getDesktopSettingsStore().get()).updates.mode,
onDownloadProgress: broadcastDownloadProgress,
reportSettingsError: (error) => {
console.warn(
"[auto-updater] Failed to read desktop update mode, defaulting to automatic:",
error,
);
},
reportCheckError: (error) => {
console.error("[auto-updater] Failed to check for updates:", error);
},
@@ -246,16 +409,19 @@ 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,
+10 -2
View File
@@ -1058,10 +1058,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);
},
};
}
@@ -1470,6 +1470,31 @@ describe("Codex app-server provider", () => {
}
});
test.each(["thread/start", "thread/resume"] as const)(
"%s appends plugin instructions to the developer instructions configured in Codex",
async (method) => {
const appServer = createFakeCodexAppServer({
"config/read": () => ({ config: { developer_instructions: "Configured role" } }),
});
const provider = createProviderWithFakeAppServer(appServer);
const config = { pluginAppendSystemPrompt: ["Plugin instructions"] };
const session =
method === "thread/start"
? await provider.createSession(createConfig(config))
: await provider.resumeSession({ sessionId: "saved-thread" }, config);
try {
await session.startTurn("hello");
await appServer.waitForTurnStart();
expect(
appServer.requests().find((request) => request.method === method)?.params,
).toMatchObject({ developerInstructions: "Configured role\n\nPlugin instructions" });
appServer.assertNoErrors();
} finally {
await session.close();
}
},
);
test("reopen injects current instructions once, including an explicit empty snapshot", async () => {
const handlers = {
initialize: () => ({ userAgent: "codex/0.165.0" }),
@@ -57,7 +57,7 @@ import path from "node:path";
import { isDeepStrictEqual } from "node:util";
import { z } from "zod";
import { renderPromptAttachmentAsText } from "../prompt-attachments.js";
import { composeAgentSystemPrompt } from "../system-prompt.js";
import { composeAgentSystemPrompt, composeSystemPromptParts } from "../system-prompt.js";
import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js";
import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js";
import {
@@ -3797,6 +3797,7 @@ export class CodexAppServerAgentSession implements AgentSession {
private resolvedWorkspaceWrite: NonNullable<
CodexProviderOptions["sandbox_workspace_write"]
> | null = null;
private configuredDeveloperInstructions: string | undefined;
private resolvedSandboxPolicy: Record<string, unknown> | null = null;
private currentThreadId: string | null = null;
// Codex writes a new thread's rollout at its first turn. Until then the thread exists only
@@ -4062,7 +4063,7 @@ export class CodexAppServerAgentSession implements AgentSession {
this.speedModels =
CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? [];
this.normalizeSpeed();
await this.loadResolvedWorkspaceWrite();
await this.loadResolvedConfig();
await this.loadCollaborationModes();
await this.loadSkills();
@@ -4093,7 +4094,7 @@ export class CodexAppServerAgentSession implements AgentSession {
}
}
private async loadResolvedWorkspaceWrite(): Promise<void> {
private async loadResolvedConfig(): Promise<void> {
if (!this.client) return;
try {
const response = toObjectRecord(
@@ -4101,11 +4102,25 @@ export class CodexAppServerAgentSession implements AgentSession {
);
const config = toObjectRecord(response?.config);
this.resolvedWorkspaceWrite = readSandboxWorkspaceWrite(config?.sandbox_workspace_write);
this.configuredDeveloperInstructions =
typeof config?.developer_instructions === "string"
? config.developer_instructions
: undefined;
} catch (error) {
this.logger.debug({ error }, "Failed to read resolved Codex workspace-write config");
this.logger.debug({ error }, "Failed to read resolved Codex config");
}
}
/**
* Codex uses a thread's developerInstructions in place of the developer_instructions in its
* config, so Paseo's instructions carry the configured ones ahead of them.
*/
private threadDeveloperInstructions(): string | undefined {
const paseoInstructions = composeAgentSystemPrompt(this.config);
if (!paseoInstructions) return undefined;
return composeSystemPromptParts(this.configuredDeveloperInstructions, paseoInstructions);
}
private rememberResolvedSandboxPolicy(response: unknown): void {
const sandbox = toObjectRecord(toObjectRecord(response)?.sandbox);
this.resolvedSandboxPolicy = sandbox ?? null;
@@ -4561,7 +4576,7 @@ export class CodexAppServerAgentSession implements AgentSession {
// the unnamespaced key emitted by earlier Paseo versions.
params.modelProvider = this.deps.customCodexConfig.model_provider;
}
const developerInstructions = composeAgentSystemPrompt(this.config);
const developerInstructions = this.threadDeveloperInstructions();
if (developerInstructions) {
params.developerInstructions = developerInstructions;
}
@@ -5526,7 +5541,7 @@ export class CodexAppServerAgentSession implements AgentSession {
model: this.config.model ?? null,
serviceTier: this.serviceTier,
config: this.buildCodexInnerConfig(),
developerInstructions: composeAgentSystemPrompt(this.config),
developerInstructions: this.threadDeveloperInstructions(),
userMessageTurns: this.codexUserMessageTurns(),
threadRollbackAvailable: this.threadRollbackAvailable,
setThreadId: async (threadId) => {
@@ -6082,7 +6097,7 @@ export class CodexAppServerAgentSession implements AgentSession {
const approvalPolicy = this.hasWorkflowModeOverride ? preset.approvalPolicy : undefined;
const sandbox = this.hasWorkflowModeOverride ? preset.sandbox : undefined;
const innerConfig = this.buildCodexInnerConfig();
const developerInstructions = composeAgentSystemPrompt(this.config);
const developerInstructions = this.threadDeveloperInstructions();
const params: Record<string, unknown> = {
model,
cwd: this.config.cwd ?? null,
-1
View File
@@ -466,7 +466,6 @@ test("quality preserves commands and routes each domain independently after fail
format: ["npm run format:check"],
quality: [
"npx --yes lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity",
"npm audit signatures",
"npm run lint",
"node --test scripts/oxlint/paseo-plugin.test.mjs",
],