Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9406: gate stable release promotion and recover updater failures (#10750)
Multica Eve0a4795db3cd2
diff --git a/.github/RELEASING.md b/.github/RELEASING.mdindex 93e9328be0..7d5044e620 100644--- a/.github/RELEASING.md+++ b/.github/RELEASING.md@@ -46,3 +46,55 @@ unresolved reachable vulnerability.Every Go binary retains its compiler version in the standard Go build metadata;use `go version -m <binary>` when auditing a downloaded release artifact.++## Stable release promotion++GoReleaser publishes a public release with `make_latest: false`. Installed stable+clients and CLI entry points that read Latest keep using the previous complete+version while Desktop artifacts are uploading. Homebrew continues to publish+normally because CLI archives are already public; container tags are independent.+The release page and GitHub notifications can show the new release before promotion.++`.github/workflows/promote-release.yml` is the only entry point for changing+Latest. The Linux/Windows Desktop matrix calls it after both builds succeed.+After the manual macOS release has signed, notarized, verified, and uploaded both+architectures, the release-desktop skill dispatches the same workflow:++```bash+gh workflow run promote-release.yml --repo multica-ai/multica --ref main -f tag=vX.Y.Z+```++The workflow uses the reviewed validator from `main`, not executable code from the+requested tag. It serializes promotion globally and only promotes a stable+semantic version newer than the current Latest. Repeating a completed promotion+or finishing an older release after a hotfix leaves Latest unchanged.++The gate checks all six update metadata files (`latest-mac.yml`,+`latest-x64-mac.yml`, `latest.yml`, `latest-arm64.yml`, `latest-linux.yml`, and+`latest-linux-arm64.yml`), their version against the tag, and each referenced+artifact's architecture, upload status, and byte size. It also requires all six+CLI targets in both legacy and versioned archive names plus `checksums.txt`.+macOS update metadata must reference the ZIP; Windows requires EXE and Linux+AppImage. Missing blockmaps do not block promotion. The macOS `afterSign` hook+runs `spctl` and `stapler validate` after notarization and before packaging/upload+for explicit publishing builds. The release skill requires code signing so an+unsigned build cannot skip that hook. These host checks do not run for unsigned+local builds or other platforms. The gate does not download large binaries to+recalculate SHA-512.++Missing or inconsistent assets produce a `waiting` result with a list of blockers+and leave Latest unchanged. This is normal when macOS and CI finish in either+order. The next completed upload path tries again. API/authentication failures+fail the job. Inspect the promotion run result; a successful dispatch only means+the run was queued. If needed, correct the failed upload and dispatch the workflow+again. Do not bypass the gate with a direct `gh release edit --latest`.++Land this workflow on `main` before the first release using `make_latest: false`.+Until promotion succeeds, stable clients stay on the previous version. Existing+clients need no changes to benefit from the release ordering fix; friendly failure+messages and download recovery require the newly shipped Desktop client.++For a faulty release, publish a higher patch version through the same gate.+Do not move Latest backwards: already installed Windows arm64 clients predating+the downgrade guard may install the older binary. Removing `make_latest: false`+reintroduces the incomplete-release window and is not a version rollback.diff --git a/.github/ci-paths.json b/.github/ci-paths.jsonindex 3ffc2b4f63..8af660684d 100644--- a/.github/ci-paths.json+++ b/.github/ci-paths.json@@ -101,6 +101,11 @@".github/ci-paths.json"],"scripts": [+ ".goreleaser.yml",+ ".github/workflows/release.yml",+ ".github/workflows/promote-release.yml",+ "scripts/promote-release.mjs",+ "scripts/promote-release.test.mjs","scripts/generate-attachment-text-preview.mjs","scripts/generate-reserved-slugs.mjs","scripts/selfhost-config.test.sh",diff --git a/.github/workflows/promote-release.yml b/.github/workflows/promote-release.ymlnew file mode 100644index 0000000000..2796233448--- /dev/null+++ b/.github/workflows/promote-release.yml@@ -0,0 +1,45 @@+name: Promote release++on:+ workflow_dispatch:+ inputs:+ tag:+ description: Stable release tag to validate and promote (vX.Y.Z)+ required: true+ type: string+ workflow_call:+ inputs:+ tag:+ required: true+ type: string++permissions:+ contents: write++jobs:+ promote:+ if: github.repository == 'multica-ai/multica'+ runs-on: ubuntu-latest+ timeout-minutes: 10+ concurrency:+ group: promote-stable-release+ cancel-in-progress: false+ steps:+ # Use the reviewed gate on main, including for retries of older tags.+ # Never run code from a caller-supplied tag with the write token.+ - uses: actions/checkout@v4+ with:+ ref: main+ persist-credentials: false+ - uses: pnpm/action-setup@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: pnpm+ - run: pnpm install --frozen-lockfile --ignore-scripts --filter multica+ - name: Validate artifacts and promote Latest+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ RELEASE_TAG: ${{ inputs.tag }}+ GH_REPO: multica-ai/multica+ run: node scripts/promote-release.mjsdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 06aca794aa..c51dbad99b 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -460,3 +460,10 @@ jobs:# Windows signing later.CSC_IDENTITY_AUTO_DISCOVERY: "false"run: node scripts/package.mjs --${{ matrix.target }} --x64 --arm64 --publish always++ promote:+ needs: [verify, desktop]+ if: needs.verify.outputs.is_stable == 'true'+ uses: ./.github/workflows/promote-release.yml+ with:+ tag: ${{ needs.verify.outputs.tag_name }}diff --git a/.goreleaser.yml b/.goreleaser.ymlindex c581e2f736..e734f19a43 100644--- a/.goreleaser.yml+++ b/.goreleaser.yml@@ -3,6 +3,9 @@ version: 2project_name: multicarelease:+ # Keep stable update clients on the previous complete release until the+ # shared promotion workflow has verified every platform's artifacts.+ make_latest: false# GitHub rejects duplicate asset names with 422. On a same-tag rerun,# replace only the matching CLI artifact and retry the upload; unrelated# release assets (for example manually published macOS builds) stay intact.diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.ymlindex e55fa0d2cb..fa519d9d00 100644--- a/apps/desktop/electron-builder.yml+++ b/apps/desktop/electron-builder.yml@@ -39,6 +39,7 @@ asarUnpack:# latest-x64-mac.yml so installed macOS 12 clients skip updates they cannot# launch. See scripts/mac-update-floor.cjs for why this can't be plain config.beforePack: ./scripts/mac-update-floor.cjs+afterSign: ./scripts/verify-mac-release.mjsmac:# Electron 44 requires macOS 13 Ventura; declare it on every mac bundle.minimumSystemVersion: "13.0.0"diff --git a/apps/desktop/scripts/verify-mac-release.mjs b/apps/desktop/scripts/verify-mac-release.mjsnew file mode 100644index 0000000000..ea94af431e--- /dev/null+++ b/apps/desktop/scripts/verify-mac-release.mjs@@ -0,0 +1,16 @@+import { execFileSync } from "node:child_process";+import { join } from "node:path";++export function verifyMacRelease(context, execute = execFileSync) {+ if (context.electronPlatformName !== "darwin") return;+ const policy = context.packager.info.options.publish;+ if (!policy || policy === "never") return;+ // afterSign runs after built-in notarization, before ZIP/DMG creation and+ // publication. Checking in the skill after upload would race CI promotion.+ const app = join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`);+ const options = { stdio: "inherit", timeout: 60_000 };+ execute("spctl", ["--assess", "--type", "execute", "--verbose", app], options);+ execute("xcrun", ["stapler", "validate", app], options);+}++export default verifyMacRelease;diff --git a/apps/desktop/scripts/verify-mac-release.test.mjs b/apps/desktop/scripts/verify-mac-release.test.mjsnew file mode 100644index 0000000000..542a6449d5--- /dev/null+++ b/apps/desktop/scripts/verify-mac-release.test.mjs@@ -0,0 +1,43 @@+// @vitest-environment node+import { createRequire } from "node:module";+import { describe, expect, it, vi } from "vitest";++import { verifyMacRelease } from "./verify-mac-release.mjs";+const context = (publish = "always", platform = "darwin") => ({+ appOutDir: "/build path/mac-arm64",+ electronPlatformName: platform,+ packager: { info: { options: { publish } }, appInfo: { productFilename: "Multica" } },+});++describe("macOS release validation before upload", () => {+ it("loads through electron-builder's actual hook resolver", async () => {+ const require = createRequire(import.meta.url);+ const { resolveFunction } = createRequire(require.resolve("electron-builder"))("app-builder-lib/out/util/resolve");+ const hook = await resolveFunction("module", new URL("./verify-mac-release.mjs", import.meta.url).pathname, "afterSign");+ const execute = vi.fn();+ hook(context(), execute);+ expect(execute).toHaveBeenCalledTimes(2);+ });+ it.each(["always", "onTag", "onTagOrDraft"])("assesses the notarized app when publishing with %s", (policy) => {+ const execute = vi.fn();+ verifyMacRelease(context(policy), execute);+ expect(execute.mock.calls.map(([command, args]) => [command, args])).toEqual([+ ["spctl", ["--assess", "--type", "execute", "--verbose", "/build path/mac-arm64/Multica.app"]],+ ["xcrun", ["stapler", "validate", "/build path/mac-arm64/Multica.app"]],+ ]);+ expect(execute.mock.calls.every(([, , options]) => options.timeout === 60_000)).toBe(true);+ });++ it.each(["spctl", "xcrun"])("stops publication when %s fails", (failing) => {+ const execute = vi.fn((command) => { if (command === failing) throw new Error("validation failed"); });+ expect(() => verifyMacRelease(context(), execute)).toThrow("validation failed");+ if (failing === "spctl") expect(execute).toHaveBeenCalledTimes(1);+ });++ it("keeps unsigned local builds and other platforms unchanged", () => {+ const execute = vi.fn();+ for (const policy of ["never", ""]) verifyMacRelease(context(policy), execute);+ for (const platform of ["win32", "linux"]) verifyMacRelease(context("always", platform), execute);+ expect(execute).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/updater-errors.test.ts b/apps/desktop/src/main/updater-errors.test.tsnew file mode 100644index 0000000000..a5fdd1b13c--- /dev/null+++ b/apps/desktop/src/main/updater-errors.test.ts@@ -0,0 +1,20 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { classifyUpdaterError } from "./updater-errors";++describe("classifyUpdaterError", () => {+ it.each([+ [{ code: "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND", message: "raw headers and stack" }, "unavailable"],+ [{ code: "ERR_UPDATER_LATEST_VERSION_NOT_FOUND" }, "unavailable"],+ [{ statusCode: 503 }, "unavailable"],+ [{ code: "ENOTFOUND" }, "network"],+ [new Error("net::ERR_INTERNET_DISCONNECTED"), "network"],+ [new Error("request failed ETIMEDOUT"), "network"],+ [{ statusCode: 403 }, "unknown"],+ [{ code: "ERR_UPDATER_INVALID_SIGNATURE" }, "unknown"],+ [null, "unknown"],+ ["private raw response", "unknown"],+ ])("classifies %j as %s", (error, expected) => {+ expect(classifyUpdaterError(error)).toBe(expected);+ });+});diff --git a/apps/desktop/src/main/updater-errors.ts b/apps/desktop/src/main/updater-errors.tsnew file mode 100644index 0000000000..e053c33f5a--- /dev/null+++ b/apps/desktop/src/main/updater-errors.ts@@ -0,0 +1,19 @@+import type { UpdaterFailureReason } from "../shared/updater-types";++export function classifyUpdaterError(error: unknown): UpdaterFailureReason {+ const details = typeof error === "object" && error !== null+ ? error as { code?: unknown; message?: unknown; statusCode?: unknown }+ : {};+ const code = typeof details.code === "string" ? details.code : "";+ const message = typeof details.message === "string" ? details.message : "";+ if (code === "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND"+ || code === "ERR_UPDATER_LATEST_VERSION_NOT_FOUND"+ || [404, 502, 503, 504].includes(Number(details.statusCode))) {+ return "unavailable";+ }+ // electron-updater sometimes wraps the network error without keeping code.+ if (/\b(ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENETUNREACH|EHOSTUNREACH|ERR_INTERNET_DISCONNECTED|ERR_NAME_NOT_RESOLVED|ERR_CONNECTION_RESET|ERR_CONNECTION_TIMED_OUT|ERR_NETWORK_CHANGED)\b/.test(`${code} ${message}`)) {+ return "network";+ }+ return "unknown";+}diff --git a/apps/desktop/src/main/updater.test.ts b/apps/desktop/src/main/updater.test.tsindex 4c271e0340..670fb244cd 100644--- a/apps/desktop/src/main/updater.test.ts+++ b/apps/desktop/src/main/updater.test.ts@@ -274,6 +274,71 @@ describe("setupAutoUpdater", () => {});});+ it("returns a safe reason instead of the raw check failure", async () => {+ const { win, send } = makeWindow();+ setupAutoUpdater(() => [win]);+ const error = Object.assign(new Error("private headers and stack"), { code: "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND" });+ ctx.checkForUpdates.mockRejectedValueOnce(error);+ await expect(invokeIpc("updater:check")).resolves.toEqual({+ ok: false,+ reason: "unavailable",+ error: "Unable to check for updates. Please try again later.",+ });+ emitUpdater("error", error);+ expect(send).not.toHaveBeenCalled();+ await invokeIpc("updater:get-preferences");+ });++ it("broadcasts a download failure once and exposes a recoverable state", async () => {+ const { win, send } = makeWindow();+ setupAutoUpdater(() => [win]);+ let rejectDownload!: (error: Error) => void;+ const downloadPromise = new Promise<unknown>((_resolve, reject) => { rejectDownload = reject; });+ ctx.checkForUpdates.mockImplementationOnce(async () => {+ emitUpdater("update-available", { version: "0.3.18" });+ return { updateInfo: { version: "0.3.18" }, isUpdateAvailable: true, downloadPromise };+ });+ await invokeIpc("updater:check");+ const error = Object.assign(new Error("secret download response"), { code: "ECONNRESET" });+ emitUpdater("error", error);+ rejectDownload(error);+ await vi.advanceTimersByTimeAsync(0);+ expect(send.mock.calls.filter(([channel, state]) => channel === "updater:download-state" && state.status === "error")).toEqual([+ ["updater:download-state", { status: "error", reason: "network" }],+ ]);+ await expect(invokeIpc("updater:get-download-state")).resolves.toEqual({ status: "error", reason: "network" });+ emitUpdater("update-available", { version: "0.3.18" });+ emitUpdater("update-downloaded", { version: "0.3.18" });+ await expect(invokeIpc("updater:get-download-state")).resolves.toEqual({ status: "downloaded", version: "0.3.18" });+ });++ it("handles a rejected download promise even without an updater error event", async () => {+ const { win, send } = makeWindow();+ setupAutoUpdater(() => [win]);+ ctx.checkForUpdates.mockImplementationOnce(async () => {+ emitUpdater("update-available", { version: "0.3.18" });+ return {+ updateInfo: { version: "0.3.18" }, isUpdateAvailable: true,+ downloadPromise: Promise.reject(new Error("download failed")),+ };+ });+ await invokeIpc("updater:check");+ await vi.advanceTimersByTimeAsync(0);+ expect(send).toHaveBeenCalledWith("updater:download-state", { status: "error", reason: "unknown" });+ });++ it("coalesces concurrent manual checks", async () => {+ setupAutoUpdater(() => []);+ let resolve!: (value: { updateInfo: { version: string }; isUpdateAvailable: boolean }) => void;+ ctx.checkForUpdates.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));+ const first = invokeIpc("updater:check");+ const second = invokeIpc("updater:check");+ expect(ctx.checkForUpdates).toHaveBeenCalledTimes(1);+ resolve({ updateInfo: { version: "0.3.18" }, isUpdateAvailable: false });+ await Promise.all([first, second]);+ await invokeIpc("updater:get-preferences");+ });+it("skips update progress when the BrowserWindow has already been destroyed", () => {setupAutoUpdater(() => [makeDestroyedWindow()]);diff --git a/apps/desktop/src/main/updater.ts b/apps/desktop/src/main/updater.tsindex 5c84dfa3fd..151c73a261 100644--- a/apps/desktop/src/main/updater.ts+++ b/apps/desktop/src/main/updater.ts@@ -2,6 +2,7 @@ import { autoUpdater, type UpdateDownloadedEvent } from "electron-updater";import { app, type BrowserWindow, type MessageBoxOptions, ipcMain } from "electron";import type {ManualUpdateCheckResult,+ UpdaterDownloadState,UpdaterPreferences,} from "../shared/updater-types";import {@@ -11,6 +12,7 @@ import {updaterPreferencesPath,} from "./updater-preferences";import type { DaemonInstallPrep } from "./update-install-gate";+import { classifyUpdaterError } from "./updater-errors";// Silent background updates: electron-updater downloads on its own as soon// as `update-available` fires; we only surface UI when the package is fully@@ -97,6 +99,7 @@ export function createElectronBusyInstallPrompt(type RendererChannel =| "updater:update-available"| "updater:download-progress"+ | "updater:download-state"| "updater:update-downloaded";function isDestroyedObjectError(err: unknown): boolean {@@ -120,35 +123,6 @@ function sendToLiveRenderer(}}-// Single-flight guard around checkForUpdates(). With autoDownload=true the-// startup, periodic, and manual triggers can all kick off downloads, and-// overlapping calls have caused duplicate download warnings in the past-// (see electronjs.org/docs/latest/api/auto-updater). Coalesce concurrent-// callers onto the same in-flight promise.-let inFlightCheck: Promise<unknown> | null = null;-function checkForUpdatesOnce(): Promise<unknown> {- if (inFlightCheck) return inFlightCheck;- const p = autoUpdater- .checkForUpdates()- .then((result) => {- // checkForUpdates resolves as soon as metadata is fetched; the actual- // download (when autoDownload=true) is exposed on result.downloadPromise.- // Without a handler a download failure becomes an unhandled rejection- // in the main process — Node may terminate it on future versions.- void (result as { downloadPromise?: Promise<unknown> } | null)?.downloadPromise?.catch(- (err) => {- console.error("Failed to download update:", err);- },- );- return result;- })- .finally(() => {- if (inFlightCheck === p) inFlightCheck = null;- });- inFlightCheck = p;- return p;-}-export function setupAutoUpdater(getMainWindows: () => readonly BrowserWindow[],options: SetupAutoUpdaterOptions = {},@@ -157,6 +131,34 @@ export function setupAutoUpdater(const broadcast = (channel: RendererChannel, payload: unknown) => {for (const win of getMainWindows()) sendToLiveRenderer(win, channel, payload);};+ let downloadState: UpdaterDownloadState = { status: "idle" };+ const setDownloadState = (state: UpdaterDownloadState) => {+ downloadState = state;+ broadcast("updater:download-state", state);+ };+ const reportDownloadFailure = (err: unknown) => {+ if (downloadState.status === "downloading") {+ setDownloadState({ status: "error", reason: classifyUpdaterError(err) });+ }+ };+ // Startup, periodic, and manual checks share one in-flight metadata request.+ let inFlightCheck: ReturnType<typeof autoUpdater.checkForUpdates> | null = null;+ function checkForUpdatesOnce(): ReturnType<typeof autoUpdater.checkForUpdates> {+ if (inFlightCheck) return inFlightCheck;+ const pending = autoUpdater.checkForUpdates().then((result) => {+ // Metadata resolves before the automatic download. Handle rejection even+ // when a provider does not emit an error event for that failure.+ void result?.downloadPromise?.catch((err) => {+ console.error("Failed to download update:", err);+ reportDownloadFailure(err);+ });+ return result;+ }).finally(() => {+ if (inFlightCheck === pending) inFlightCheck = null;+ });+ inFlightCheck = pending;+ return pending;+ }const platform = options.platform ?? process.platform;// Only Windows locks a running executable against replacement; macOS and// Linux keep their existing update path untouched.@@ -280,6 +282,7 @@ export function setupAutoUpdater(}autoUpdater.on("update-available", (info) => {+ setDownloadState({ status: "downloading", version: info.version });// Forwarded for renderer-side state tracking only; the notification UI// does not render an "available" affordance with autoDownload=true.broadcast("updater:update-available", {@@ -296,6 +299,7 @@ export function setupAutoUpdater(autoUpdater.on("update-downloaded", (info: UpdateDownloadedEvent) => {updateReadyToInstall = true;+ setDownloadState({ status: "downloaded", version: info.version });broadcast("updater:update-downloaded", {version: info.version,releaseNotes: info.releaseNotes,@@ -304,8 +308,11 @@ export function setupAutoUpdater(autoUpdater.on("error", (err) => {console.error("Auto-updater error:", err);+ reportDownloadFailure(err);});+ ipcMain.handle("updater:get-download-state", (): UpdaterDownloadState => downloadState);+// Retained for IPC back-compat with older renderer bundles. With// autoDownload=true the renderer no longer triggers this path.ipcMain.handle("updater:download", () => {@@ -373,11 +380,14 @@ export function setupAutoUpdater(currentVersion,latestVersion: result?.updateInfo.version ?? currentVersion,available: result?.isUpdateAvailable ?? false,+ downloadState,};} catch (err) {+ console.error("Manual update check failed:", err);return {ok: false,- error: err instanceof Error ? err.message : String(err),+ error: "Unable to check for updates. Please try again later.",+ reason: classifyUpdaterError(err),};}});diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.tsindex 94680fcbea..2b5355ebd5 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -10,6 +10,7 @@ import type {} from "../shared/issue-window";import type {ManualUpdateCheckResult,+ UpdaterDownloadState,UpdaterPreferences,} from "../shared/updater-types";import type {@@ -250,6 +251,8 @@ interface DaemonAPI {}interface UpdaterAPI {+ getDownloadState: () => Promise<UpdaterDownloadState>;+ onDownloadState: (callback: (state: UpdaterDownloadState) => void) => () => void;onUpdateAvailable: (callback: (info: { version: string; releaseNotes?: string }) => void) => () => void;onDownloadProgress: (callback: (progress: { percent: number }) => void) => () => void;onUpdateDownloaded: (diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex ba79e2a6f2..4a6ad6684c 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -4,6 +4,7 @@ import type { RuntimeConfigResult } from "../shared/runtime-config";import type { FreezeBreadcrumb } from "../shared/freeze-breadcrumb";import type {ManualUpdateCheckResult,+ UpdaterDownloadState,UpdaterPreferences,} from "../shared/updater-types";import {@@ -505,6 +506,12 @@ const daemonAPI = {};const updaterAPI = {+ getDownloadState: (): Promise<UpdaterDownloadState> => ipcRenderer.invoke("updater:get-download-state"),+ onDownloadState: (callback: (state: UpdaterDownloadState) => void) => {+ const handler = (_: unknown, state: UpdaterDownloadState) => callback(state);+ ipcRenderer.on("updater:download-state", handler);+ return () => ipcRenderer.removeListener("updater:download-state", handler);+ },onUpdateAvailable: (callback: (info: { version: string; releaseNotes?: string }) => void) => {const handler = (_: unknown, info: { version: string; releaseNotes?: string }) => callback(info);ipcRenderer.on("updater:update-available", handler);diff --git a/apps/desktop/src/renderer/src/components/updates-settings-tab.test.tsx b/apps/desktop/src/renderer/src/components/updates-settings-tab.test.tsxindex 9bee2f4c27..fb3810ada6 100644--- a/apps/desktop/src/renderer/src/components/updates-settings-tab.test.tsx+++ b/apps/desktop/src/renderer/src/components/updates-settings-tab.test.tsx@@ -1,10 +1,14 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { act } from "@testing-library/react";+import type { UpdaterDownloadState } from "../../../shared/updater-types";const mocks = vi.hoisted(() => ({getPreferences: vi.fn(),setAutomaticUpdates: vi.fn(),checkForUpdates: vi.fn(),+ getDownloadState: vi.fn(),+ unsubscribe: vi.fn(),toastSuccess: vi.fn(),toastError: vi.fn(),}));@@ -25,6 +29,12 @@ const translations = {downloading: "Downloading v{{version}}",check_now: "Check now",checking: "Checking",+ check_unavailable: "Unable to check right now. Try later.",+ check_network: "Check your connection and try again.",+ check_failed: "Unable to check. Please retry.",+ download_failed: "Download failed. You can keep using this version.",+ download_ready: "v{{version}} is ready to install.",+ retry: "Retry",},},};@@ -53,6 +63,8 @@ vi.mock("sonner", () => ({import { UpdatesSettingsTab } from "./updates-settings-tab";+let downloadListener: (state: UpdaterDownloadState) => void;+describe("UpdatesSettingsTab", () => {beforeEach(() => {mocks.getPreferences.mockReset().mockResolvedValue({@@ -60,6 +72,8 @@ describe("UpdatesSettingsTab", () => {});mocks.setAutomaticUpdates.mockReset();mocks.checkForUpdates.mockReset();+ mocks.getDownloadState.mockReset().mockResolvedValue({ status: "idle" });+ mocks.unsubscribe.mockReset();mocks.toastSuccess.mockReset();mocks.toastError.mockReset();@@ -73,10 +87,67 @@ describe("UpdatesSettingsTab", () => {getPreferences: mocks.getPreferences,setAutomaticUpdates: mocks.setAutomaticUpdates,checkForUpdates: mocks.checkForUpdates,+ getDownloadState: mocks.getDownloadState,+ onDownloadState: (listener: typeof downloadListener) => {+ downloadListener = listener;+ return mocks.unsubscribe;+ },},});});+ it("replaces raw errors with a localized message and retries successfully", async () => {+ mocks.checkForUpdates.mockResolvedValueOnce({ ok: false, reason: "unavailable", error: "private HTTP headers and stack" });+ mocks.checkForUpdates.mockResolvedValueOnce({ ok: true, available: false, downloadState: { status: "idle" } });+ render(<UpdatesSettingsTab />);+ fireEvent.click(screen.getByRole("button", { name: "Check now" }));+ expect(await screen.findByRole("status")).toHaveTextContent("Unable to check right now");+ expect(screen.queryByText(/private HTTP/)).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ expect(await screen.findByText("Up to date")).toBeInTheDocument();+ });++ it("recovers when the check IPC itself rejects", async () => {+ mocks.checkForUpdates.mockRejectedValue(new Error("private IPC exception"));+ render(<UpdatesSettingsTab />);+ fireEvent.click(screen.getByRole("button", { name: "Check now" }));+ expect(await screen.findByRole("status")).toHaveTextContent("Unable to check. Please retry.");+ expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled();+ });++ it("keeps a download error when metadata arrives later", async () => {+ let resolve!: (result: unknown) => void;+ mocks.checkForUpdates.mockImplementation(() => new Promise((done) => { resolve = done; }));+ render(<UpdatesSettingsTab />);+ fireEvent.click(screen.getByRole("button", { name: "Check now" }));+ act(() => {+ downloadListener({ status: "downloading", version: "1.2.4" });+ downloadListener({ status: "error", reason: "network" });+ });+ await act(async () => { resolve({ ok: true, available: true, latestVersion: "1.2.4", downloadState: { status: "downloading", version: "1.2.4" } }); });+ expect(screen.getByRole("status")).toHaveTextContent("Download failed");+ expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled();+ });++ it("restores an in-progress download and shows completion", async () => {+ mocks.getDownloadState.mockResolvedValue({ status: "downloading", version: "1.2.4" });+ const { unmount } = render(<UpdatesSettingsTab />);+ expect(await screen.findByText("Downloading v1.2.4")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Check now" })).toBeDisabled();+ act(() => downloadListener({ status: "downloaded", version: "1.2.4" }));+ expect(screen.getByRole("status")).toHaveTextContent("v1.2.4 is ready to install.");+ expect(screen.queryByText("Downloading v1.2.4")).not.toBeInTheDocument();+ unmount();+ expect(mocks.unsubscribe).toHaveBeenCalledOnce();+ });++ it("keeps automatic failures quiet when no manual check is active", async () => {+ render(<UpdatesSettingsTab />);+ await waitFor(() => expect(mocks.getDownloadState).toHaveBeenCalled());+ act(() => downloadListener({ status: "error", reason: "network" }));+ expect(screen.queryByRole("status")).not.toBeInTheDocument();+ });+it("loads the persisted preference and saves changes from the switch", async () => {mocks.getPreferences.mockResolvedValue({ automaticUpdates: false });mocks.setAutomaticUpdates.mockResolvedValue({ automaticUpdates: true });diff --git a/apps/desktop/src/renderer/src/components/updates-settings-tab.tsx b/apps/desktop/src/renderer/src/components/updates-settings-tab.tsxindex d8e7710949..ef7c7c3441 100644--- a/apps/desktop/src/renderer/src/components/updates-settings-tab.tsx+++ b/apps/desktop/src/renderer/src/components/updates-settings-tab.tsx@@ -1,17 +1,28 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { AlertCircle, ArrowDownToLine, Check, Loader2 } from "@multica/ui/icons";import { Button } from "@multica/ui/components/ui/button";import { Switch } from "@multica/ui/components/ui/switch";import { useT } from "@multica/views/i18n";import { SettingsCard, SettingsRow, SettingsTab } from "@multica/views/settings";import { toast } from "sonner";+import type { UpdaterDownloadState, UpdaterFailureReason } from "../../../shared/updater-types";type CheckState =| { status: "idle" }| { status: "checking" }| { status: "up-to-date" }| { status: "available"; latestVersion: string }- | { status: "error"; message: string };+ | { status: "downloaded"; latestVersion: string }+ | { status: "error"; reason: UpdaterFailureReason; downloading?: boolean };++function downloadCheckState(state: UpdaterDownloadState): CheckState {+ switch (state.status) {+ case "downloading": return { status: "available", latestVersion: state.version };+ case "downloaded": return { status: "downloaded", latestVersion: state.version };+ case "error": return { status: "error", reason: state.reason, downloading: true };+ default: return { status: "idle" };+ }+}export function UpdatesSettingsTab() {const { t } = useT("settings");@@ -20,6 +31,29 @@ export function UpdatesSettingsTab() {const [preferencesReady, setPreferencesReady] = useState(false);const [savingPreference, setSavingPreference] = useState(false);const currentVersion = window.desktopAPI.appInfo.version;+ const downloadRevision = useRef(0);++ useEffect(() => {+ let mounted = true;+ let receivedEvent = false;+ const unsubscribe = window.updater.onDownloadState((download) => {+ receivedEvent = true;+ if (download.status === "idle") return;+ downloadRevision.current++;+ setState((previous) => {+ // Automatic failures stay quiet unless this page is following a check+ // or download. A ready download still uses the existing install banner.+ if (download.status === "error" && previous.status !== "checking" && previous.status !== "available") return previous;+ return downloadCheckState(download);+ });+ });+ void window.updater.getDownloadState().then((download) => {+ if (mounted && !receivedEvent && (download.status === "downloading" || download.status === "downloaded")) {+ setState(downloadCheckState(download));+ }+ }).catch(() => { /* A manual check can still recover when IPC is available. */ });+ return () => { mounted = false; unsubscribe(); };+ }, []);useEffect(() => {let mounted = true;@@ -61,18 +95,31 @@ export function UpdatesSettingsTab() {const handleCheck = useCallback(async () => {setState({ status: "checking" });- const result = await window.updater.checkForUpdates();- if (!result.ok) {- setState({ status: "error", message: result.error });- return;+ const revision = downloadRevision.current;+ try {+ const result = await window.updater.checkForUpdates();+ // A download event can arrive before the metadata IPC response.+ if (revision !== downloadRevision.current) return;+ if (!result.ok) {+ setState({ status: "error", reason: result.reason });+ return;+ }+ setState(result.downloadState.status === "downloaded" || (result.available && result.downloadState.status !== "idle")+ ? downloadCheckState(result.downloadState)+ : result.available+ ? { status: "available", latestVersion: result.latestVersion }+ : { status: "up-to-date" });+ } catch {+ if (revision === downloadRevision.current) setState({ status: "error", reason: "unknown" });}- setState(- result.available- ? { status: "available", latestVersion: result.latestVersion }- : { status: "up-to-date" },- );}, []);+ const failureMessage = state.status !== "error" ? ""+ : state.downloading ? t(($) => $.desktop.updates.download_failed)+ : state.reason === "network" ? t(($) => $.desktop.updates.check_network)+ : state.reason === "unavailable" ? t(($) => $.desktop.updates.check_unavailable)+ : t(($) => $.desktop.updates.check_failed);+return (<SettingsTabtitle={t(($) => $.desktop.updates.title)}@@ -117,9 +164,15 @@ export function UpdatesSettingsTab() {</p>)}{state.status === "error" && (- <p className="mt-2 inline-flex items-center gap-1.5 text-destructive">- <AlertCircle className="size-3.5" />- {state.message}+ <p role="status" className="mt-2 inline-flex items-center gap-1.5">+ <AlertCircle className="size-3.5 shrink-0" />+ {failureMessage}+ </p>+ )}+ {state.status === "downloaded" && (+ <p role="status" className="mt-2 inline-flex items-center gap-1.5">+ <Check className="size-3.5 shrink-0 text-success" />+ {t(($) => $.desktop.updates.download_ready, { version: state.latestVersion })}</p>)}</>@@ -129,7 +182,8 @@ export function UpdatesSettingsTab() {variant="outline"size="sm"onClick={handleCheck}- disabled={state.status === "checking"}+ disabled={state.status === "checking" || state.status === "available"}+ aria-busy={state.status === "checking"}>{state.status === "checking" ? (<>@@ -137,7 +191,7 @@ export function UpdatesSettingsTab() {{t(($) => $.desktop.updates.checking)}</>) : (- t(($) => $.desktop.updates.check_now)+ state.status === "error" ? t(($) => $.desktop.updates.retry) : t(($) => $.desktop.updates.check_now))}</Button></SettingsRow>diff --git a/apps/desktop/src/shared/updater-types.ts b/apps/desktop/src/shared/updater-types.tsindex 3c6d28b93b..2c1efe9d79 100644--- a/apps/desktop/src/shared/updater-types.ts+++ b/apps/desktop/src/shared/updater-types.ts@@ -2,11 +2,20 @@ export interface UpdaterPreferences {automaticUpdates: boolean;}+export type UpdaterFailureReason = "unavailable" | "network" | "unknown";++export type UpdaterDownloadState =+ | { status: "idle" }+ | { status: "downloading"; version: string }+ | { status: "downloaded"; version: string }+ | { status: "error"; reason: UpdaterFailureReason };+export type ManualUpdateCheckResult =| {ok: true;currentVersion: string;latestVersion: string;available: boolean;+ downloadState: UpdaterDownloadState;}- | { ok: false; error: string };+ | { ok: false; error: string; reason: UpdaterFailureReason };diff --git a/apps/docs/content/docs/desktop-app.fr.mdx b/apps/docs/content/docs/desktop-app.fr.mdxindex 31f47877bc..88545dfb7c 100644--- a/apps/docs/content/docs/desktop-app.fr.mdx+++ b/apps/docs/content/docs/desktop-app.fr.mdx@@ -90,6 +90,8 @@ Vous pouvez consulter l'état et les journaux du runtime dans les paramètres deLa mise à jour automatique est activée par défaut. L'application recherche et télécharge les nouvelles versions en arrière-plan ; une fois une version téléchargée, vous pouvez redémarrer pour l'installer immédiatement ou la laisser s'installer à la prochaine fermeture. Vous pouvez aussi désactiver les vérifications automatiques ou rechercher manuellement de nouvelles versions dans **Paramètres → Mises à jour**.+Si une vérification manuelle ou un téléchargement échoue, les réglages affichent un court message et un bouton **Réessayer**. Vous pouvez continuer à utiliser la version actuelle pendant ce temps.+Les mises à jour sont distribuées par système d'exploitation et par architecture de processeur :- Windows arm64 et macOS x64 (Intel) utilisent chacun leur propre flux de mise à jour ;diff --git a/apps/docs/content/docs/desktop-app.ja.mdx b/apps/docs/content/docs/desktop-app.ja.mdxindex afee2ac3cf..70cb842d97 100644--- a/apps/docs/content/docs/desktop-app.ja.mdx+++ b/apps/docs/content/docs/desktop-app.ja.mdx@@ -90,6 +90,8 @@ Desktop では、このコンピューター上で音声を文字に変換し、自動更新はデフォルトで有効です。アプリはバックグラウンドで新しいバージョンを確認してダウンロードします。ダウンロードが完了したら、すぐに再起動してインストールすることも、次回終了時にインストールさせることもできます。**設定 → アップデート** で自動確認をオフにしたり、手動で新しいバージョンを確認したりもできます。+手動確認やダウンロードに失敗した場合、設定画面に短いメッセージと**再試行**ボタンが表示されます。現在のバージョンを使い続けながら再試行できます。+更新は OS と CPU アーキテクチャごとに配布されます:- Windows arm64 と macOS x64(Intel)は、それぞれ専用の更新フィードを使います。diff --git a/apps/docs/content/docs/desktop-app.ko.mdx b/apps/docs/content/docs/desktop-app.ko.mdxindex dfe714f738..3642150dce 100644--- a/apps/docs/content/docs/desktop-app.ko.mdx+++ b/apps/docs/content/docs/desktop-app.ko.mdx@@ -90,6 +90,8 @@ Desktop 설정에서 실행 상태와 로그를 확인할 수 있습니다. 도자동 업데이트는 기본으로 켜져 있습니다. 앱이 백그라운드에서 새 버전을 확인하고 다운로드합니다. 다운로드가 끝나면 즉시 다시 시작해 설치하거나 다음 종료 시 설치할 수 있습니다. **설정 → 업데이트**에서 자동 확인을 끄거나 새 버전을 직접 확인할 수도 있습니다.+수동 확인이나 다운로드에 실패하면 설정에 짧은 안내와 **다시 시도** 버튼이 표시됩니다. 다시 시도하는 동안 현재 버전을 계속 사용할 수 있습니다.+업데이트는 운영체제와 프로세서 아키텍처에 따라 배포됩니다.- Windows arm64와 macOS x64(Intel)는 각각 별도 업데이트 소스를 사용합니다.diff --git a/apps/docs/content/docs/desktop-app.mdx b/apps/docs/content/docs/desktop-app.mdxindex c19e83c56c..a93db0de8f 100644--- a/apps/docs/content/docs/desktop-app.mdx+++ b/apps/docs/content/docs/desktop-app.mdx@@ -92,6 +92,8 @@ You can check runtime status and logs in Desktop's settings. If a tool isn't detAuto-update is on by default. The app checks for and downloads new versions in the background; once a download finishes you can restart to install immediately or let it install on the next quit. Under **Settings → Updates** you can turn off automatic checks or check for new versions manually.+If a manual check or download fails, Settings shows a short message and a **Retry** button. You can keep using the current version while retrying.+Updates are distributed per OS and CPU architecture:- Windows arm64 and macOS x64 (Intel) each use their own update feed;diff --git a/apps/docs/content/docs/desktop-app.zh-Hant.mdx b/apps/docs/content/docs/desktop-app.zh-Hant.mdxindex f958d20eb0..cd9e010556 100644--- a/apps/docs/content/docs/desktop-app.zh-Hant.mdx+++ b/apps/docs/content/docs/desktop-app.zh-Hant.mdx@@ -90,6 +90,8 @@ Desktop 可以在本機把語音轉成文字,填入聊天、評論、回覆和自動更新預設開啟。應用在後臺檢查並下載新版本,下載完成後可以立即重啟安裝,也可以等下次退出時安裝。在 **設定 → 更新** 中可以關閉自動檢查,或手動檢查新版本。+手動檢查或下載失敗時,設定頁會顯示簡短提示和**重試**按鈕。重試期間可以繼續使用目前版本。+更新按作業系統和處理器架構分發:- Windows arm64 和 macOS x64(Intel)使用各自獨立的更新源;diff --git a/apps/docs/content/docs/desktop-app.zh.mdx b/apps/docs/content/docs/desktop-app.zh.mdxindex 7dc49e35db..754c1be8cf 100644--- a/apps/docs/content/docs/desktop-app.zh.mdx+++ b/apps/docs/content/docs/desktop-app.zh.mdx@@ -92,6 +92,8 @@ Desktop 可以在本机把语音转成文字,填入聊天、评论、回复和自动更新默认开启。应用在后台检查并下载新版本,下载完成后可以立即重启安装,也可以等下次退出时安装。在 **设置 → 更新** 中可以关闭自动检查,或手动检查新版本。+手动检查或下载失败时,设置页会显示简短提示和**重试**按钮。重试期间可以继续使用当前版本。+更新按操作系统和处理器架构分发:- Windows arm64 和 macOS x64(Intel)使用各自独立的更新源;diff --git a/package.json b/package.jsonindex d86a321e37..42074db696 100644--- a/package.json+++ b/package.json@@ -72,6 +72,7 @@"pg": "^8.20.0","postcss": "catalog:","turbo": "^2.5.4",- "typescript": "catalog:"+ "typescript": "catalog:",+ "yaml": "catalog:"}}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex ccb9599cbb..df4cc5143d 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1471,7 +1471,13 @@"up_to_date": "You're on the latest version.","downloading": "v{{version}} is downloading in the background — you'll be notified when it's ready to install.","check_now": "Check now",- "checking": "Checking…"+ "checking": "Checking…",+ "check_unavailable": "Unable to check for updates right now. Please try again later.",+ "check_network": "Cannot reach the update service. Check your connection and try again.",+ "check_failed": "Unable to check for updates. Please try again.",+ "download_failed": "Update download failed. You can keep using the current version and retry.",+ "download_ready": "v{{version}} is ready to install.",+ "retry": "Retry"},"daemon": {"title": "Daemon",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex 3c8c0aaa85..b50956db9f 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -1471,7 +1471,13 @@"up_to_date": "Tienes la última versión.","downloading": "v{{version}} se está descargando en segundo plano: te avisaremos cuando esté lista para instalar.","check_now": "Buscar ahora",- "checking": "Comprobando…"+ "checking": "Comprobando…",+ "check_unavailable": "No se pueden buscar actualizaciones ahora. Inténtalo más tarde.",+ "check_network": "No se puede conectar con el servicio de actualizaciones. Revisa tu conexión e inténtalo de nuevo.",+ "check_failed": "No se pudieron buscar actualizaciones. Inténtalo de nuevo.",+ "download_failed": "La descarga falló. Puedes seguir usando la versión actual e intentarlo de nuevo.",+ "download_ready": "v{{version}} está lista para instalar.",+ "retry": "Reintentar"},"daemon": {"title": "Daemon",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 171a49301e..b34dae5aef 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -1471,7 +1471,13 @@"up_to_date": "Vous avez la dernière version.","downloading": "La v{{version}} se télécharge en arrière-plan — vous serez averti quand elle sera prête à installer.","check_now": "Vérifier maintenant",- "checking": "Vérification…"+ "checking": "Vérification…",+ "check_unavailable": "Impossible de rechercher les mises à jour pour le moment. Réessayez plus tard.",+ "check_network": "Impossible de joindre le service de mise à jour. Vérifiez votre connexion et réessayez.",+ "check_failed": "La recherche de mises à jour a échoué. Réessayez.",+ "download_failed": "Le téléchargement a échoué. Vous pouvez continuer à utiliser la version actuelle et réessayer.",+ "download_ready": "La version {{version}} est prête à être installée.",+ "retry": "Réessayer"},"daemon": {"title": "Démon",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex f6e1786168..82e6350ea2 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1460,7 +1460,13 @@"up_to_date": "最新バージョンを使用しています。","downloading": "v{{version}} をバックグラウンドでダウンロード中です。インストールの準備が整うとお知らせします。","check_now": "今すぐ確認",- "checking": "確認中…"+ "checking": "確認中…",+ "check_unavailable": "現在アップデートを確認できません。しばらくしてから再試行してください。",+ "check_network": "更新サービスに接続できません。ネットワーク接続を確認して再試行してください。",+ "check_failed": "アップデートの確認に失敗しました。再試行してください。",+ "download_failed": "更新のダウンロードに失敗しました。現在のバージョンを使い続け、再試行できます。",+ "download_ready": "v{{version}} をインストールできます。",+ "retry": "再試行"},"daemon": {"title": "デーモン",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 73abb251e9..5bbc52e81f 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -1203,7 +1203,13 @@"up_to_date": "최신 버전입니다.","downloading": "v{{version}}을(를) 백그라운드에서 다운로드 중입니다. 설치 준비가 끝나면 알림을 드립니다.","check_now": "지금 확인",- "checking": "확인 중..."+ "checking": "확인 중...",+ "check_unavailable": "지금 업데이트를 확인할 수 없습니다. 잠시 후 다시 시도하세요.",+ "check_network": "업데이트 서비스에 연결할 수 없습니다. 네트워크 연결을 확인하고 다시 시도하세요.",+ "check_failed": "업데이트 확인에 실패했습니다. 다시 시도하세요.",+ "download_failed": "업데이트 다운로드에 실패했습니다. 현재 버전을 계속 사용하면서 다시 시도할 수 있습니다.",+ "download_ready": "v{{version}} 설치 준비가 완료되었습니다.",+ "retry": "다시 시도"},"daemon": {"title": "데몬",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 59454af3e6..91ea25ff1d 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -1492,7 +1492,13 @@"up_to_date": "У вас установлена последняя версия.","downloading": "v{{version}} загружается в фоновом режиме — вы получите уведомление, когда она будет готова к установке.","check_now": "Проверить сейчас",- "checking": "Проверка…"+ "checking": "Проверка…",+ "check_unavailable": "Сейчас не удаётся проверить обновления. Повторите попытку позже.",+ "check_network": "Не удаётся подключиться к службе обновлений. Проверьте соединение и повторите попытку.",+ "check_failed": "Не удалось проверить обновления. Повторите попытку.",+ "download_failed": "Не удалось загрузить обновление. Можно продолжить работу с текущей версией и повторить попытку.",+ "download_ready": "Версия {{version}} готова к установке.",+ "retry": "Повторить"},"daemon": {"title": "Демон",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 98be67768a..c9e5b5de40 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1460,7 +1460,13 @@"up_to_date": "已是最新版本。","downloading": "v{{version}} 正在后台下载——准备好安装时会通知你。","check_now": "立即检查",- "checking": "检查中..."+ "checking": "检查中...",+ "check_unavailable": "暂时无法检查更新,请稍后重试。",+ "check_network": "无法连接更新服务,请检查网络后重试。",+ "check_failed": "检查更新失败,请重试。",+ "download_failed": "更新下载失败,可以继续使用当前版本并重试。",+ "download_ready": "v{{version}} 已可安装。",+ "retry": "重试"},"daemon": {"title": "守护进程",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex aa7d83a3bd..519a7906ee 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -1460,7 +1460,13 @@"up_to_date": "已是最新版本。","downloading": "v{{version}} 正在後臺下載——準備好安裝時會通知你。","check_now": "立即檢查",- "checking": "檢查中..."+ "checking": "檢查中...",+ "check_unavailable": "暫時無法檢查更新,請稍後重試。",+ "check_network": "無法連線至更新服務,請檢查網路後重試。",+ "check_failed": "檢查更新失敗,請重試。",+ "download_failed": "更新下載失敗,可以繼續使用目前版本並重試。",+ "download_ready": "v{{version}} 已可安裝。",+ "retry": "重試"},"daemon": {"title": "守護程序",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2202f0e658..0bb8815615 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -248,6 +248,9 @@ importers:typescript:specifier: 'catalog:'version: '@typescript/[email protected]'+ yaml:+ specifier: 'catalog:'+ version: 2.9.0apps/desktop:dependencies:diff --git a/scripts/ci-scope.test.mjs b/scripts/ci-scope.test.mjsindex 0ed1494a5b..65c0ccf2db 100644--- a/scripts/ci-scope.test.mjs+++ b/scripts/ci-scope.test.mjs@@ -17,6 +17,9 @@ function filterFiles(files) {for (const [name, files, selected] of [["readme only", ["README.md"], []],+ ["stable release promotion", [".github/workflows/promote-release.yml"], ["scripts"]],+ ["release orchestration", [".github/workflows/release.yml"], ["scripts"]],+ ["release creation", [".goreleaser.yml"], ["scripts"]],["docs only", ["apps/docs/content/docs/guide.mdx"], ["quality", "docs"]],["docs test", ["apps/docs/lib/unrendered-bold.test.ts"], ["quality", "docs"]],["web changelog", ["apps/web/features/landing/i18n/en.ts"], ["frontend", "quality"]],diff --git a/scripts/promote-release.mjs b/scripts/promote-release.mjsnew file mode 100644index 0000000000..9c31aa93d6--- /dev/null+++ b/scripts/promote-release.mjs@@ -0,0 +1,134 @@+import { execFileSync } from "node:child_process";+import { pathToFileURL } from "node:url";+import { parse } from "yaml";++export const channels = [+ ["latest-mac.yml", "mac", "arm64", "zip"],+ ["latest-x64-mac.yml", "mac", "x64", "zip"],+ ["latest.yml", "windows", "x64", "exe"],+ ["latest-arm64.yml", "windows", "arm64", "exe"],+ ["latest-linux.yml", "linux", "x64", "AppImage"],+ ["latest-linux-arm64.yml", "linux", "arm64", "AppImage"],+];++function stableVersion(tag) {+ if (!/^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(tag)) {+ throw new Error(`Expected a stable vX.Y.Z tag, got ${tag}`);+ }+ return tag.slice(1).split(".").map(BigInt);+}++export function isNewer(tag, latestTag) {+ const target = stableVersion(tag);+ if (latestTag === null) return true;+ const latest = stableVersion(latestTag);+ for (let i = 0; i < target.length; i++) {+ if (target[i] !== latest[i]) return target[i] > latest[i];+ }+ return false;+}++export async function validateRelease(tag, release, assets, readMetadata) {+ stableVersion(tag);+ if (release.tag_name !== tag || release.draft || release.prerelease) {+ throw new Error("Promotion requires the matching published stable release");+ }+ const version = tag.slice(1);+ const uploaded = new Map(assets.filter((asset) =>+ asset.state === "uploaded" && Number.isSafeInteger(asset.size) && asset.size > 0,+ ).map((asset) => [asset.name, asset]));+ const problems = [];+ for (const [name, platform, arch, extension] of channels) {+ const asset = uploaded.get(name);+ if (!asset) { problems.push(`Missing ${name}`); continue; }+ // Authentication/transport failures are workflow errors, not incomplete+ // artifacts. Only malformed metadata belongs in the waiting result.+ const contents = await readMetadata(asset);+ try {+ const metadata = parse(contents);+ if (metadata?.version !== version) throw new Error(`version must be ${version}`);+ if (!Array.isArray(metadata.files) || metadata.files.length === 0) {+ throw new Error("files must contain update artifacts");+ }+ // electron-builder uses package-format architecture names on Linux:+ // AppImage/RPM can use x86_64 or aarch64, while DEB uses amd64/arm64.+ const arches = platform === "linux"+ ? arch === "x64" ? ["x64", "x86_64", "amd64"] : ["arm64", "aarch64"]+ : [arch];+ const expected = arches.map((cpu) => `multica-desktop-${version}-${platform}-${cpu}`);+ let hasUpdatePackage = false;+ for (const file of metadata.files) {+ if (typeof file?.url !== "string") throw new Error("invalid files[].url");+ const filename = decodeURIComponent(file.url);+ if (!expected.some((prefix) => filename.startsWith(`${prefix}.`)) || /[/\\]/.test(filename)) {+ throw new Error(`wrong version/platform/architecture in ${file.url}`);+ }+ const binary = uploaded.get(filename);+ if (!binary) throw new Error(`missing ${filename}`);+ if (!Number.isSafeInteger(file.size) || file.size !== binary.size) {+ throw new Error(`size mismatch for ${filename}`);+ }+ if (expected.some((prefix) => filename === `${prefix}.${extension}`)) hasUpdatePackage = true;+ }+ if (!hasUpdatePackage) throw new Error(`missing ${extension} update package`);+ } catch (error) {+ problems.push(`${name}: ${error.message}`);+ }+ }+ // Both naming schemes are consumed by shipped CLI clients/installers.+ for (const os of ["darwin", "linux", "windows"]) {+ for (const arch of ["amd64", "arm64"]) {+ const ext = os === "windows" ? "zip" : "tar.gz";+ for (const name of [`multica_${os}_${arch}.${ext}`, `multica-cli-${version}-${os}-${arch}.${ext}`]) {+ if (!uploaded.has(name)) problems.push(`Missing ${name}`);+ }+ }+ }+ if (!uploaded.has("checksums.txt")) problems.push("Missing checksums.txt");+ return problems;+}++// All callers run in the workflow's single stable-channel concurrency group.+// Missing uploads are a normal waiting state; malformed API/auth responses fail.+export async function promoteRelease({ tag, getRelease, getAssets, readMetadata, getLatest, promote }) {+ stableVersion(tag);+ const release = await getRelease(tag);+ const problems = await validateRelease(tag, release, await getAssets(release.id), readMetadata);+ if (problems.length) return { status: "waiting", problems };+ // Read Latest immediately before writing it, inside the serialized job.+ const latest = await getLatest();+ if (!isNewer(tag, latest)) return { status: "skipped", latest };+ await promote(tag);+ return { status: "promoted" };+}++function gh(args) {+ return execFileSync("gh", args, { encoding: "utf8", timeout: 60_000, maxBuffer: 8 * 1024 * 1024 });+}++export async function main() {+ const tag = process.env.RELEASE_TAG;+ stableVersion(tag);+ const repo = process.env.GH_REPO;+ if (repo !== "multica-ai/multica") throw new Error("GH_REPO must be multica-ai/multica");+ const api = (path) => JSON.parse(gh(["api", `repos/${repo}/${path}`]));+ const result = await promoteRelease({+ tag,+ getRelease: (tag) => api(`releases/tags/${encodeURIComponent(tag)}`),+ getAssets: (id) => JSON.parse(gh(["api", `repos/${repo}/releases/${id}/assets?per_page=100`, "--paginate", "--slurp"])).flat(),+ readMetadata: (asset) => gh(["api", `repos/${repo}/releases/assets/${asset.id}`, "-H", "Accept: application/octet-stream"]),+ getLatest: () => {+ try { return api("releases/latest").tag_name; }+ catch (error) {+ if (/\(HTTP 404\)/.test(String(error.stderr))) return null;+ throw error;+ }+ },+ promote: (tag) => gh(["release", "edit", tag, "--repo", repo, "--latest"]),+ });+ console.log(JSON.stringify(result, null, 2));+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main().catch((error) => { console.error(error.message); process.exitCode = 1; });+}diff --git a/scripts/promote-release.test.mjs b/scripts/promote-release.test.mjsnew file mode 100644index 0000000000..7b62c0696e--- /dev/null+++ b/scripts/promote-release.test.mjs@@ -0,0 +1,134 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { parse, stringify } from "yaml";+import { channels, isNewer, promoteRelease, validateRelease } from "./promote-release.mjs";++function fixture(tag = "v0.10.0") {+ const version = tag.slice(1);+ const assets = [];+ const metadata = new Map();+ const add = (name) => { const asset = { id: assets.length + 1, name, size: 123, state: "uploaded" }; assets.push(asset); return asset; };+ for (const [name, platform, arch, ext] of channels) {+ add(name);+ const cpu = platform === "linux" && arch === "x64" ? "x86_64" : arch;+ const file = add(`multica-desktop-${version}-${platform}-${cpu}.${ext}`);+ const files = [{ url: file.name, size: file.size, sha512: "hash" }];+ if (platform === "linux") {+ const rpm = add(`multica-desktop-${version}-linux-${arch === "x64" ? "x86_64" : "aarch64"}.rpm`);+ files.push({ url: rpm.name, size: rpm.size, sha512: "hash" });+ }+ metadata.set(name, stringify({ version, files }));+ }+ for (const os of ["darwin", "linux", "windows"]) {+ for (const arch of ["amd64", "arm64"]) {+ const ext = os === "windows" ? "zip" : "tar.gz";+ add(`multica_${os}_${arch}.${ext}`);+ add(`multica-cli-${version}-${os}-${arch}.${ext}`);+ }+ }+ add("checksums.txt");+ const calls = [];+ const release = { id: 42, tag_name: tag, draft: false, prerelease: false };+ const options = { tag, getRelease: async () => release, getAssets: async () => assets,+ readMetadata: async (asset) => metadata.get(asset.name), getLatest: async () => "v0.9.0",+ promote: async (tag) => { calls.push(tag); } };+ return { tag, assets, metadata, release, calls, options };+}++test("every missing upload keeps Latest unchanged and can be retried", async () => {+ for (let i = 0; i < fixture().assets.length; i++) {+ const f = fixture();+ const [missing] = f.assets.splice(i, 1);+ assert.equal((await promoteRelease(f.options)).status, "waiting", missing.name);+ assert.deepEqual(f.calls, []);+ f.assets.push(missing);+ assert.equal((await promoteRelease(f.options)).status, "promoted");+ assert.deepEqual(f.calls, [f.tag]);+ }+});++test("upload completion works in either platform order", async () => {+ for (const reverse of [false, true]) {+ const f = fixture();+ const completed = [...f.assets];+ if (reverse) completed.reverse();+ f.assets.length = 0;+ for (const asset of completed) {+ assert.equal((await promoteRelease(f.options)).status, "waiting");+ f.assets.push(asset);+ }+ assert.equal((await promoteRelease(f.options)).status, "promoted");+ }+});++test("bad metadata and incomplete assets cannot promote", async () => {+ for (const mutate of [+ (m) => { m.version = "0.9.0"; },+ (m) => { m.files = []; },+ (m) => { m.files[0].url = "missing.zip"; },+ (m) => { m.files[0].url = "https://example.com/other.zip"; },+ (m) => { m.files[0].url = "multica-desktop-0.10.0-mac-x64.zip"; },+ (m) => { m.files[0].size++; },+ (m) => { delete m.files[0].size; },+ ]) {+ const f = fixture();+ const metadata = parse(f.metadata.get("latest-mac.yml"));+ mutate(metadata);+ f.metadata.set("latest-mac.yml", stringify(metadata));+ assert.equal((await promoteRelease(f.options)).status, "waiting");+ assert.deepEqual(f.calls, []);+ }+ const f = fixture();+ f.metadata.set("latest-mac.yml", "files: [\n");+ assert.equal((await promoteRelease(f.options)).status, "waiting");+ f.assets[0].state = "starter";+ assert.equal((await promoteRelease(f.options)).status, "waiting");+});++test("semantic version ordering prevents a late older release and repeated promotion", async () => {+ assert.equal(isNewer("v0.10.0", "v0.9.9"), true);+ assert.equal(isNewer("v1.0.0", "v0.99.99"), true);+ assert.equal(isNewer("v0.10.0", null), true);+ for (const latest of ["v0.10.0", "v0.10.1", "v1.0.0"]) {+ const f = fixture();+ f.options.getLatest = async () => latest;+ assert.equal((await promoteRelease(f.options)).status, "skipped");+ assert.deepEqual(f.calls, []);+ }+ for (const tag of ["v01.2.3", "v1.2.3-rc.1", "v1.2.3;echo nope", "1.2.3"]) {+ assert.throws(() => isNewer(tag, null), /stable/);+ }+});++test("API failures and unpublished releases fail closed", async () => {+ for (const key of ["getRelease", "getAssets", "readMetadata", "getLatest", "promote"]) {+ const f = fixture();+ f.options[key] = async () => { throw new Error("API unavailable"); };+ await assert.rejects(promoteRelease(f.options), /API unavailable/);+ }+ for (const change of [{ draft: true }, { prerelease: true }, { tag_name: "v0.9.0" }]) {+ const f = fixture();+ Object.assign(f.release, change);+ await assert.rejects(validateRelease(f.tag, f.release, f.assets, f.options.readMetadata), /published stable/);+ }+});++test("promotion is serialized across tags and both upload paths use the gate", () => {+ const workflow = parse(readFileSync(new URL("../.github/workflows/promote-release.yml", import.meta.url), "utf8"));+ assert.ok(workflow.on.workflow_call);+ assert.ok(workflow.on.workflow_dispatch);+ assert.equal(workflow.permissions.contents, "write");+ const gate = workflow.jobs.promote;+ assert.equal(gate.concurrency["cancel-in-progress"], false);+ assert.doesNotMatch(gate.concurrency.group, /\$\{\{/);+ assert.ok(gate.steps.some((s) => s.uses?.startsWith("actions/checkout@") && s.with.ref === "main"));+ assert.equal(gate["continue-on-error"], undefined);+ const release = parse(readFileSync(new URL("../.github/workflows/release.yml", import.meta.url), "utf8"));+ assert.ok(release.jobs.promote.needs.includes("desktop"));+ assert.ok(release.jobs.promote.needs.includes("verify"));+ assert.equal(release.jobs.promote.uses, "./.github/workflows/promote-release.yml");+ const goreleaser = parse(readFileSync(new URL("../.goreleaser.yml", import.meta.url), "utf8"));+ assert.equal(goreleaser.release.make_latest, false);+ assert.notEqual(goreleaser.release.draft, true);+});