Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(tauri): bundle updater fixes (#3714)
Peter Chinman6a06793cc2f6
diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.tsindex 30d673bd13..7cf222ac37 100644--- a/infra/stacks/authentication-service/index.ts+++ b/infra/stacks/authentication-service/index.ts@@ -170,6 +170,20 @@ const POSTHOG_API_KEY: pulumi.Output<string> = aws.secretsmanager.getSecretVersionOutput({ secretId: config.require('posthog_api_key') }).apply((secret) => secret.secretString);+const bundleUpdatePolicyEnvVars = [+ {+ name: 'BUNDLE_UPDATE_POLICY_JSON',+ value: config.get('bundle_update_policy_json'),+ },+ {+ name: 'BUNDLE_UPDATE_POLICY_FILE',+ value: config.get('bundle_update_policy_file'),+ },+].filter(+ (envVar): envVar is { name: string; value: string } =>+ envVar.value != null && envVar.value.length > 0+);+const secretKeyArns = [pulumi.interpolate`${jwtSecretKeyArn}`,pulumi.interpolate`${fusionauthApiKeySecretKeyArn}`,@@ -391,6 +405,7 @@ const service = new AuthenticationService('authentication-service', {name: 'POSTHOG_API_KEY',value: pulumi.interpolate`${POSTHOG_API_KEY}`,},+ ...bundleUpdatePolicyEnvVars,],});diff --git a/js/app/.gitignore b/js/app/.gitignoreindex 76646f14b4..cf66e0885e 100644--- a/js/app/.gitignore+++ b/js/app/.gitignore@@ -10,6 +10,7 @@ node_modules/**/*.turbo.mono+.bundle-smoke/# Environments.venvdiff --git a/js/app/justfile b/js/app/justfileindex 184b104f46..6eeef963d1 100644--- a/js/app/justfile+++ b/js/app/justfile@@ -67,6 +67,11 @@ dist-archive: build-prod(cd packages/app/dist && zip -qr "$TARGET" .)echo "Archive: $TARGET"+bundle-smoke-server *ARGS:+ # Local manual OTA smoke server. Example:+ # just bundle-smoke-server older --host 0.0.0.0 --port 3001+ bun scripts/smoke-bundle-updater-server.ts {{ARGS}}+test-watch:bunx --bun vitestdiff --git a/js/app/packages/app/component/settings/Account.tsx b/js/app/packages/app/component/settings/Account.tsxindex 8dd4b72466..e72458ab17 100644--- a/js/app/packages/app/component/settings/Account.tsx+++ b/js/app/packages/app/component/settings/Account.tsx@@ -101,6 +101,8 @@ function formatBundleUpdateStatus(status: BundleUpdateStatus): string {case 'WaitingForWifi': return 'Waiting for Wi-Fi to download';case 'Downloading': return `Downloading: ${Math.round(status.data.progress)}%`;case 'Unzipping': return `Installing: ${Math.round(status.data.progress)}%`;+ case 'ClearRequired': return 'Cached update revoked';+ case 'NativeUpdateRequired': return 'App update required';case 'Completed': return 'Update ready';case 'Error': return 'An error occurred when checking for updates';}@@ -428,6 +430,7 @@ export function Account() {</Row><Show when={ENABLE_AUTO_UPDATE_UI}>+ <BundleVersionRow /><BundleUpdateRow /></Show>@@ -1039,6 +1042,8 @@ function bundleUpdateAction(return { label: 'Download', action: grantBundleUpdate };case 'WaitingForWifi':return { label: 'Download anyway', action: grantBundleUpdate };+ case 'ClearRequired':+ return { label: 'Reload', action: () => invoke('perform_update') };case 'Completed':return { label: 'Update', action: () => invoke('perform_update') };default:@@ -1046,30 +1051,55 @@ function bundleUpdateAction(}}+type BundleDebugInfo = {+ bundleBuild: number;+ source: 'embedded' | 'ota';+ nativeBuild: number;+};++function BundleVersionRow() {+ if (!isNativeMobilePlatform()) return null;+ const [bundleDebugInfo] = createResource(() =>+ invoke<BundleDebugInfo>('get_bundle_debug_info').catch((error) => {+ console.error('[bundle-update] get_bundle_debug_info failed', error);+ return null;+ })+ );+ return (+ <Show when={bundleDebugInfo()}>+ {(info) => (+ <Row label="Version">+ <span class="text-sm text-ink-muted">+ {info().bundleBuild} ({info().source === 'embedded' ? 'app' : 'ota'})+ {' '}+ - {info().nativeBuild}+ </span>+ </Row>+ )}+ </Show>+ );+}+function BundleUpdateRow() {+ if (!isNativeMobilePlatform()) return null;const tauri = useTauri();+ const status = (): BundleUpdateStatus =>+ tauri?.bundleUpdateStatus() ?? { status: 'Idle' };+ const action = () => bundleUpdateAction(status());return (- <Show when={tauri}>- {(ctx) => {- const status = () => ctx().bundleUpdateStatus();- const action = () => bundleUpdateAction(status());- return (- <Row label="App Update">- <div class="flex items-center gap-3">- <span class="text-sm text-ink-muted">- {formatBundleUpdateStatus(status())}- </span>- <Show when={action()}>- {(a) => (- <Button variant="active" size="sm" depth={3} onClick={a().action}>- {a().label}- </Button>- )}- </Show>- </div>- </Row>- );- }}- </Show>+ <Row label="App Update">+ <div class="flex items-center gap-3">+ <span class="text-sm text-ink-muted">+ {formatBundleUpdateStatus(status())}+ </span>+ <Show when={action()}>+ {(a) => (+ <Button variant="active" size="sm" depth={3} onClick={a().action}>+ {a().label}+ </Button>+ )}+ </Show>+ </div>+ </Row>);}diff --git a/js/app/packages/app/package.json b/js/app/packages/app/package.jsonindex ea0b26f612..d8a8b231ff 100644--- a/js/app/packages/app/package.json+++ b/js/app/packages/app/package.json@@ -6,8 +6,9 @@"version": "2.5.0","scripts": {"dev": "vite -c vite.config.ts",- "build": "vite build -c vite.config.ts && bun run postbuild:semver",+ "build": "vite build -c vite.config.ts && bun run postbuild:semver && bun run postbuild:bundle-manifest","postbuild:semver": "echo $npm_package_version+$(git rev-parse --short HEAD) > ./dist/semver.txt",+ "postbuild:bundle-manifest": "bun ./scripts/write-bundle-manifest.mjs","preview:dev": "vite preview -c vite.config.ts --outDir dist --base /app","preview:prod": "vite preview -c vite.config.ts --outDir dist --base /app","check": "tsc --noEmit --skipLibCheck",diff --git a/js/app/packages/app/scripts/write-bundle-manifest.mjs b/js/app/packages/app/scripts/write-bundle-manifest.mjsnew file mode 100644index 0000000000..8ed35d19ba--- /dev/null+++ b/js/app/packages/app/scripts/write-bundle-manifest.mjs@@ -0,0 +1,40 @@+import { execSync } from 'node:child_process';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++const packageDir = dirname(dirname(fileURLToPath(import.meta.url)));+const packageJson = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8'));++function parseBuildNumber(name, fallback) {+ const value = process.env[name];+ if (value == null || value === '') return fallback;+ if (!/^\d+$/.test(value)) {+ throw new Error(`${name} must be an unsigned integer, got ${JSON.stringify(value)}`);+ }+ return Number(value);+}++function gitSha() {+ try {+ return execSync('git rev-parse --short HEAD', {+ cwd: packageDir,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ }).trim();+ } catch {+ return null;+ }+}++const manifest = {+ schemaVersion: 2,+ bundleBuild: parseBuildNumber('BUNDLE_BUILD_NUMBER', Date.now()),+ minNativeBuild: parseBuildNumber('MIN_NATIVE_BUILD', 0),+ gitSha: gitSha(),+ appVersion: packageJson.version,+};++const outPath = join(packageDir, 'dist', 'bundle-manifest.json');+mkdirSync(dirname(outPath), { recursive: true });+writeFileSync(outPath, `${JSON.stringify(manifest, null, 2)}\n`);diff --git a/js/app/packages/core/mobile/NativeAppUpdateRequiredDialog.tsx b/js/app/packages/core/mobile/NativeAppUpdateRequiredDialog.tsxnew file mode 100644index 0000000000..8e4a7ebe9a--- /dev/null+++ b/js/app/packages/core/mobile/NativeAppUpdateRequiredDialog.tsx@@ -0,0 +1,39 @@+import { Button, Dialog, Surface } from '@ui';++export function NativeAppUpdateRequiredDialog(props: {+ open: boolean;+ onClose: () => void;+}) {+ const title = 'Update Macro App required';+ const description =+ 'There is a new version of Macro App available. Please update your app. You may experience degraded service until the app is updated.';++ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => {+ if (!open) props.onClose();+ }}+ class="w-[90%] max-w-120"+ position="center"+ >+ <Surface depth={2} active>+ <div class="flex flex-col gap-4 px-4 py-5">+ <div class="flex flex-col gap-2">+ <Dialog.Title class="text-lg font-semibold text-ink">+ {title}+ </Dialog.Title>+ <Dialog.Description class="text-sm leading-5 text-ink-extra-muted">+ {description}+ </Dialog.Description>+ </div>+ <div class="flex justify-end">+ <Dialog.CloseButton as={Button} variant="active" size="sm">+ OK+ </Dialog.CloseButton>+ </div>+ </div>+ </Surface>+ </Dialog>+ );+}diff --git a/js/app/packages/tauri/src/TauriProvider.tsx b/js/app/packages/tauri/src/TauriProvider.tsxindex 014aa23f5e..54f295193d 100644--- a/js/app/packages/tauri/src/TauriProvider.tsx+++ b/js/app/packages/tauri/src/TauriProvider.tsx@@ -1,4 +1,5 @@import { useCallKitSetup } from '@channel/Call';+import { NativeAppUpdateRequiredDialog } from '@core/mobile/NativeAppUpdateRequiredDialog';import { isPlatform, isTauri } from '@core/util/platform';import { PlatformNotificationProvider } from '@notifications';import type { RouteSectionProps } from '@solidjs/router';@@ -8,6 +9,7 @@ import { type OsType, type as osType } from '@tauri-apps/plugin-os';import {type Accessor,createContext,+ createEffect,createSignal,type JSX,onCleanup,@@ -29,6 +31,11 @@ export type BundleUpdateStatus =| { status: 'WaitingForWifi' }| { status: 'Downloading'; data: { progress: number } }| { status: 'Unzipping'; data: { progress: number } }+ | { status: 'ClearRequired'; data: { reason: string } }+ | {+ status: 'NativeUpdateRequired';+ data: { bundleBuild: number; minNativeBuild: number };+ }| { status: 'Completed' }| { status: 'Error'; data: { message: string } };@@ -40,6 +47,13 @@ interface TauriContextValue {const TauriContext = createContext<TauriContextValue | undefined>(undefined);+function shouldShowNativeAppUpdateRequiredDialog(status: BundleUpdateStatus) {+ return (+ status.status === 'ClearRequired' ||+ status.status === 'NativeUpdateRequired'+ );+}+function TauriProvider(props: { children: JSX.Element }) {// we only care about this value on android.// ios should use the env(safe-area-inset-top) css properties@@ -47,6 +61,11 @@ function TauriProvider(props: { children: JSX.Element }) {const [insets, setInsets] = createSignal<NotAndroid | Insets>('not-android');const [bundleUpdateStatus, setBundleUpdateStatus] =createSignal<BundleUpdateStatus>({ status: 'Idle' });+ const [+ nativeAppUpdateRequiredDialogOpen,+ setNativeAppUpdateRequiredDialogOpen,+ ] = createSignal(false);+ let hasShownNativeAppUpdateRequiredDialog = false;function performBundleUpdate() {invoke<boolean>('perform_update').catch((e) =>@@ -54,6 +73,18 @@ function TauriProvider(props: { children: JSX.Element }) {);}+ createEffect(() => {+ if (+ hasShownNativeAppUpdateRequiredDialog ||+ !shouldShowNativeAppUpdateRequiredDialog(bundleUpdateStatus())+ ) {+ return;+ }++ hasShownNativeAppUpdateRequiredDialog = true;+ setNativeAppUpdateRequiredDialogOpen(true);+ });+if (isTauri() && isPlatform('ios')) useCallKitSetup();const value: TauriContextValue = {@@ -63,23 +94,9 @@ function TauriProvider(props: { children: JSX.Element }) {};onMount(() => {- console.info('[bundle-update] registering listener');- let loggedDownloading = false;const unlistenPromise = listen<BundleUpdateStatus>('bundle-update-status',(ev) => {- if (ev.payload.status === 'Downloading') {- if (!loggedDownloading) {- console.info(- '[bundle-update] received',- JSON.stringify(ev.payload)- );- loggedDownloading = true;- }- } else {- console.info('[bundle-update] received', JSON.stringify(ev.payload));- loggedDownloading = false;- }setBundleUpdateStatus(ev.payload);});@@ -88,7 +105,6 @@ function TauriProvider(props: { children: JSX.Element }) {);// Fetch current status since events emitted before the listener registered are missedinvoke<BundleUpdateStatus>('get_bundle_update_status').then((status) => {- console.info('[bundle-update] initial status', JSON.stringify(status));setBundleUpdateStatus(status);});onCleanup(() => {@@ -144,6 +160,10 @@ function TauriProvider(props: { children: JSX.Element }) {return (<TauriContext.Provider value={value}><ShareTargetProvider os={value.os}>{props.children}</ShareTargetProvider>+ <NativeAppUpdateRequiredDialog+ open={nativeAppUpdateRequiredDialogOpen()}+ onClose={() => setNativeAppUpdateRequiredDialogOpen(false)}+ /></TauriContext.Provider>);}diff --git a/js/app/scripts/smoke-bundle-updater-server.ts b/js/app/scripts/smoke-bundle-updater-server.tsnew file mode 100644index 0000000000..31b94fc33b--- /dev/null+++ b/js/app/scripts/smoke-bundle-updater-server.ts@@ -0,0 +1,346 @@+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import {+ cpSync,+ existsSync,+ mkdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { networkInterfaces } from 'node:os';++/*+ * Manual smoke server for the native OTA bundle updater.+ *+ * Intended use:+ * 1. Build the embedded app baseline with a deterministic bundle build, e.g.+ * BUNDLE_BUILD_NUMBER=100 MIN_NATIVE_BUILD=0 bun run build+ * 2. Start this server from js/app:+ * just bundle-smoke-server older --host 0.0.0.0 --port 3001+ * 3. Build/run the native app with:+ * MACRO_BUNDLE_UPDATE_BASE_URL=http://<MAC-LAN-IP>:3001+ * BUNDLE_BUILD_NUMBER=100+ * MIN_NATIVE_BUILD=0+ * If testing on a physical iPhone with a plain HTTP LAN URL, iOS ATS may+ * block the request unless you temporarily allow local networking in the+ * app's Info.plist. Do not commit that ATS override; remove it after smoke+ * testing or use an HTTPS tunnel instead.+ * 4. Switch scenarios while the app is running:+ * curl http://<MAC-LAN-IP>:3001/__scenario/update-101+ * curl http://<MAC-LAN-IP>:3001/__scenario/revoke-101+ * curl http://<MAC-LAN-IP>:3001/__scenario/incompatible-102+ *+ * This script creates fixture archives under .bundle-smoke/ from the current+ * packages/app/dist output. Commit this script and the just recipe, but do not+ * commit generated .bundle-smoke artifacts or local IP/build-setting values.+ */++type Scenario =+ | 'older'+ | 'no-update'+ | 'update-101'+ | 'revoke-101'+ | 'incompatible-102';++type BundleArtifact = {+ build: number;+ minNativeBuild: number;+ zipPath: string;+ fileName: string;+ checksum: string;+};++const scenarios = new Set<Scenario>([+ 'older',+ 'no-update',+ 'update-101',+ 'revoke-101',+ 'incompatible-102',+]);++const appRoot = dirname(dirname(fileURLToPath(import.meta.url)));+const distDir = join(appRoot, 'packages', 'app', 'dist');+const packageJsonPath = join(appRoot, 'packages', 'app', 'package.json');+const workDir = join(appRoot, '.bundle-smoke');+const artifactsDir = join(workDir, 'artifacts');++function parseArgs() {+ const args = process.argv.slice(2);+ let host = '0.0.0.0';+ let port = 3001;+ let scenario: Scenario = 'older';+ let prepareOnly = false;+ let help = false;++ for (let i = 0; i < args.length; i += 1) {+ const arg = args[i];+ if (arg === '--help' || arg === '-h') {+ help = true;+ } else if (arg === '--prepare-only') {+ prepareOnly = true;+ } else if (arg === '--host') {+ host = args[++i] ?? host;+ } else if (arg === '--port') {+ port = Number(args[++i] ?? port);+ } else if (arg === '--scenario') {+ scenario = parseScenario(args[++i]);+ } else if (!arg.startsWith('-')) {+ scenario = parseScenario(arg);+ } else {+ throw new Error(`Unknown argument: ${arg}`);+ }+ }++ if (!Number.isInteger(port) || port <= 0) {+ throw new Error(`--port must be a positive integer, got ${port}`);+ }++ return { host, port, scenario, prepareOnly, help };+}++function parseScenario(value: string | undefined): Scenario {+ if (value != null && scenarios.has(value as Scenario)) return value as Scenario;+ throw new Error(+ `Scenario must be one of: ${[...scenarios].join(', ')}. Got ${JSON.stringify(value)}`+ );+}++function printHelp() {+ console.log(`Usage:+ bun scripts/smoke-bundle-updater-server.ts [scenario] [--host 0.0.0.0] [--port 3001]++Scenarios:+ older Advertise bundleBuild 90. A baseline 100 app should get 204.+ no-update Always return 204.+ update-101 Advertise bundleBuild 101.+ revoke-101 Return action: "clear" when current_bundle_build is 101.+ incompatible-102 Return native_update_required for bundleBuild 102 with minNativeBuild 999999.++Runtime controls:+ GET /__scenario+ POST /__scenario/<scenario>+ GET /__scenario/<scenario>++Native build example:+ MACRO_BUNDLE_UPDATE_BASE_URL=http://<LAN-IP>:3001 \\+ BUNDLE_BUILD_NUMBER=100 MIN_NATIVE_BUILD=0 just ios-build+`);+}++function appVersion(): string {+ return JSON.parse(readFileSync(packageJsonPath, 'utf8')).version;+}++function assertDistExists() {+ if (!existsSync(join(distDir, 'index.html'))) {+ throw new Error(+ `Missing ${join(distDir, 'index.html')}. Build the app first, for example:\n` ++ ` BUNDLE_BUILD_NUMBER=100 MIN_NATIVE_BUILD=0 just ios-build`+ );+ }+}++function writeManifest(bundleDir: string, build: number, minNativeBuild: number) {+ writeFileSync(+ join(bundleDir, 'bundle-manifest.json'),+ `${JSON.stringify(+ {+ schemaVersion: 2,+ bundleBuild: build,+ minNativeBuild,+ gitSha: 'smoke',+ appVersion: appVersion(),+ },+ null,+ 2+ )}\n`+ );+}++function zipDir(sourceDir: string, zipPath: string) {+ rmSync(zipPath, { force: true });+ const result = spawnSync('zip', ['-qr', zipPath, '.'], {+ cwd: sourceDir,+ stdio: 'inherit',+ });+ if (result.status !== 0) {+ throw new Error(`zip failed for ${sourceDir}`);+ }+}++function sha256(path: string): string {+ return createHash('sha256').update(readFileSync(path)).digest('hex');+}++function buildArtifact(build: number, minNativeBuild: number): BundleArtifact {+ const bundleDir = join(workDir, `bundle-${build}`);+ const fileName = `bundle-${build}.zip`;+ const zipPath = join(artifactsDir, fileName);++ rmSync(bundleDir, { recursive: true, force: true });+ cpSync(distDir, bundleDir, { recursive: true });+ writeManifest(bundleDir, build, minNativeBuild);+ zipDir(bundleDir, zipPath);++ return {+ build,+ minNativeBuild,+ zipPath,+ fileName,+ checksum: sha256(zipPath),+ };+}++function prepareArtifacts() {+ assertDistExists();+ rmSync(artifactsDir, { recursive: true, force: true });+ mkdirSync(artifactsDir, { recursive: true });+ const artifacts = new Map<number, BundleArtifact>();+ for (const [build, minNativeBuild] of [+ [90, 0],+ [101, 0],+ [102, 999999],+ ] as const) {+ const artifact = buildArtifact(build, minNativeBuild);+ artifacts.set(build, artifact);+ console.log(+ `[bundle-smoke] prepared ${artifact.fileName} checksum=${artifact.checksum}`+ );+ }+ return artifacts;+}++function localUrls(port: number): string[] {+ const urls = [`http://localhost:${port}`];+ for (const entries of Object.values(networkInterfaces())) {+ for (const entry of entries ?? []) {+ if (entry.family === 'IPv4' && !entry.internal) {+ urls.push(`http://${entry.address}:${port}`);+ }+ }+ }+ return urls;+}++function updateResponse(artifact: BundleArtifact, origin: string) {+ return Response.json({+ action: 'update',+ bundleBuild: artifact.build,+ minNativeBuild: artifact.minNativeBuild,+ notes: null,+ url: `${origin}/artifacts/${artifact.fileName}`,+ checksum: artifact.checksum,+ });+}++function nativeUpdateRequiredResponse(artifact: BundleArtifact) {+ return Response.json({+ action: 'native_update_required',+ bundleBuild: artifact.build,+ minNativeBuild: artifact.minNativeBuild,+ });+}++function noContent() {+ return new Response(null, { status: 204 });+}++function notFound() {+ return new Response('not found\n', { status: 404 });+}++function badRequest(message: string) {+ return new Response(`${message}\n`, { status: 400 });+}++function parseQueryBuildNumber(url: URL, name: string): number | null {+ const rawValue = url.searchParams.get(name);+ if (rawValue == null || rawValue.trim() === '') return null;++ const value = Number(rawValue);+ return Number.isFinite(value) && Number.isInteger(value) && value >= 0+ ? value+ : null;+}++const { host, port, scenario: initialScenario, prepareOnly, help } = parseArgs();+if (help) {+ printHelp();+ process.exit(0);+}++const artifacts = prepareArtifacts();+if (prepareOnly) process.exit(0);++let scenario = initialScenario;++const server = Bun.serve({+ hostname: host,+ port,+ fetch(req) {+ const url = new URL(req.url);++ if (url.pathname === '/__scenario') {+ return Response.json({ scenario, scenarios: [...scenarios] });+ }++ if (url.pathname.startsWith('/__scenario/')) {+ scenario = parseScenario(url.pathname.split('/').at(-1));+ console.log(`[bundle-smoke] scenario=${scenario}`);+ return Response.json({ scenario });+ }++ if (url.pathname.startsWith('/artifacts/')) {+ const fileName = url.pathname.split('/').at(-1);+ const artifact = [...artifacts.values()].find((a) => a.fileName === fileName);+ if (!artifact) return notFound();+ return new Response(Bun.file(artifact.zipPath), {+ headers: { 'content-type': 'application/zip' },+ });+ }++ const match = url.pathname.match(/^\/update\/bundle\/([^/]+)\/([^/]+)$/);+ if (!match) return notFound();++ const [, target, arch] = match;+ const currentBundleBuild = parseQueryBuildNumber(url, 'current_bundle_build');+ const nativeBuild = parseQueryBuildNumber(url, 'native_build');+ if (currentBundleBuild == null || nativeBuild == null) {+ return badRequest('current_bundle_build and native_build must be non-negative integers');+ }+ console.log(+ `[bundle-smoke] ${target}/${arch} current=${currentBundleBuild} native=${nativeBuild} scenario=${scenario}`+ );++ if (scenario === 'no-update') return noContent();+ if (scenario === 'revoke-101') {+ if (currentBundleBuild === 101) {+ return Response.json({ action: 'clear', reason: 'bundle_revoked' });+ }+ return noContent();+ }++ const artifact =+ scenario === 'older'+ ? artifacts.get(90)+ : scenario === 'update-101'+ ? artifacts.get(101)+ : artifacts.get(102);++ if (!artifact) return noContent();+ if (artifact.build <= currentBundleBuild) return noContent();+ if (artifact.minNativeBuild > nativeBuild) {+ return nativeUpdateRequiredResponse(artifact);+ }+ return updateResponse(artifact, url.origin);+ },+});++console.log(`[bundle-smoke] scenario=${scenario}`);+console.log(`[bundle-smoke] listening on ${server.hostname}:${server.port}`);+for (const url of localUrls(server.port)) {+ console.log(`[bundle-smoke] ${url}`);+}diff --git a/js/app/tauri/Cargo.lock b/js/app/tauri/Cargo.lockindex 0fbcd05208..82beeb87d2 100644--- a/js/app/tauri/Cargo.lock+++ b/js/app/tauri/Cargo.lock@@ -2797,6 +2797,9 @@ version = "0.1.0"dependencies = ["digest","futures",+ "jni",+ "ndk-context",+ "objc2 0.5.2","reqwest","rootcause","semver",@@ -2975,6 +2978,12 @@ dependencies = ["thiserror 1.0.69",]+[[package]]+name = "ndk-context"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"+[[package]]name = "ndk-sys"version = "0.6.0+11769913"diff --git a/js/app/tauri/macro_bundle_updater_plugin/Cargo.toml b/js/app/tauri/macro_bundle_updater_plugin/Cargo.tomlindex 404d71efde..9644a53a67 100644--- a/js/app/tauri/macro_bundle_updater_plugin/Cargo.toml+++ b/js/app/tauri/macro_bundle_updater_plugin/Cargo.toml@@ -16,10 +16,17 @@ strum = { version = "0.27", features = ["derive"] }tauri = { workspace = true }tauri-plugin-device-info = "1.0.1"thiserror = { workspace = true }-tokio = { workspace = true, features = ["fs", "sync", "time"] }+tokio = { workspace = true, features = ["fs", "macros", "sync", "time"] }tracing = { workspace = true }url = { workspace = true }zip = "6"+[target.'cfg(target_os = "ios")'.dependencies]+objc2 = "0.5"++[target.'cfg(target_os = "android")'.dependencies]+jni = "0.21"+ndk-context = "0.1"+[dev-dependencies]tokio = { workspace = true, features = ["macros", "rt"] }diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs b/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rsindex 4762209070..3227aae69e 100644--- a/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs+++ b/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs@@ -29,13 +29,13 @@ impl BundleRoot {/// Load persisted bundle root from the given cache directory.pub(crate) async fn load(cache_dir: &Path, fs: &impl FsRepo) -> Self {let persist_path = cache_dir.join(BUNDLE_ROOT_FILE);- tracing::info!("Loading bundle root from {persist_path:?}");+ tracing::debug!("Loading bundle root from {persist_path:?}");match fs.read_to_string(&persist_path).await {Ok(contents) => {let path = PathBuf::from(contents.trim());let index = path.join("index.html");if fs.read_to_string(&index).await.is_ok() {- tracing::info!("Restored bundle root: {path:?}");+ tracing::debug!("Restored bundle root: {path:?}");Self(Some(path))} else {tracing::warn!(@@ -48,7 +48,7 @@ impl BundleRoot {}}Err(e) => {- tracing::info!("No persisted bundle root: {e}");+ tracing::debug!("No persisted bundle root: {e}");Self(None)}}@@ -63,7 +63,7 @@ impl BundleRoot {let persist_path = cache_dir.join(BUNDLE_ROOT_FILE);match self.0.as_ref() {Some(root) => {- tracing::info!("Persisting bundle root {root:?} to {persist_path:?}");+ tracing::debug!("Persisting bundle root {root:?} to {persist_path:?}");fs.write(&persist_path, root.to_string_lossy().as_bytes()).await}@@ -81,13 +81,42 @@ impl BundleRoot {self.0 = None;}- /// Read the bundle version from `semver.txt` inside the bundle root.- pub(crate) async fn version(&self, fs: &impl FsRepo) -> Option<semver::Version> {- let semver_path = self.0.as_ref()?.join("semver.txt");- fs.read_to_string(&semver_path)+ /// Read the bundle manifest inside the bundle root.+ pub(crate) async fn manifest(&self, fs: &impl FsRepo) -> Option<BundleManifest> {+ let manifest_path = self.0.as_ref()?.join("bundle-manifest.json");+ BundleManifest::read(&manifest_path, fs).await+ }+}++/// Metadata generated with each JavaScript bundle build.+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct BundleManifest {+ /// Manifest schema version.+ pub schema_version: u64,+ /// Monotonic JavaScript bundle build number.+ pub bundle_build: u64,+ /// Minimum native app build that can safely run this bundle.+ pub min_native_build: u64,+ /// Short git SHA used to build the bundle.+ pub git_sha: Option<String>,+ /// Application package version used for the bundle.+ pub app_version: String,+}++impl BundleManifest {+ /// Read and validate a bundle manifest from disk.+ pub async fn read(path: &Path, fs: &impl FsRepo) -> Option<Self> {+ let manifest = fs+ .read_to_string(path).await.ok()- .and_then(|s| s.trim().parse().ok())+ .and_then(|s| serde_json::from_str::<Self>(&s).ok())?;+ if manifest.schema_version == 2 {+ Some(manifest)+ } else {+ None+ }}}@@ -97,8 +126,10 @@ const MPSC_CHAN_SIZE: usize = 10;/// Application metadata sent to the update server.#[derive(Debug, Clone)]pub struct AppInfo {- /// The currently running app version.- pub current_version: semver::Version,+ /// The current effective JS bundle build.+ pub current_bundle_build: u64,+ /// The native app build number.+ pub native_build: u64,/// CPU architecture.pub arch: Arch,/// Operating system target.@@ -138,12 +169,66 @@ pub enum Arch {Armv7,}+/// Action returned by the bundle update endpoint.+#[derive(Debug, Clone, Deserialize)]+#[serde(tag = "action", rename_all = "lowercase")]+pub enum BundleAction {+ /// Download and apply a newer compatible bundle.+ Update(BundleUpdate),+ /// Clear the active cached OTA bundle.+ Clear(BundleClear),+ /// A newer bundle exists, but the installed native app build is too old.+ #[serde(rename = "native_update_required")]+ NativeUpdateRequired(BundleNativeUpdateRequired),+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn deserializes_native_update_required_action() {+ let action: BundleAction = serde_json::from_str(+ r#"{"action":"native_update_required","bundleBuild":102,"minNativeBuild":999999}"#,+ )+ .unwrap();++ assert!(matches!(+ action,+ BundleAction::NativeUpdateRequired(BundleNativeUpdateRequired {+ bundle_build: 102,+ min_native_build: 999999,+ })+ ));+ }+}++/// A response instructing the client to clear the active OTA bundle.+#[derive(Debug, Clone, Deserialize)]+pub struct BundleClear {+ /// Machine-readable clear reason.+ pub reason: String,+}++/// A response telling the client that the native app must be updated first.+#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BundleNativeUpdateRequired {+ /// The newer bundle build that could not be applied.+ pub bundle_build: u64,+ /// The minimum native build required by that bundle.+ pub min_native_build: u64,+}+/// a struct which indicates how to update only the javascript bundle of the application#[derive(Debug, Clone, Deserialize)]#[non_exhaustive]+#[serde(rename_all = "camelCase")]pub struct BundleUpdate {- /// the version that we are going to update to- pub version: semver::Version,+ /// the bundle build that we are going to update to+ pub bundle_build: u64,+ /// minimum native build required by this bundle+ pub min_native_build: u64,/// some optional notes about the updatepub notes: Option<String>,/// the fully qualified Url where the update bundle exists@@ -338,6 +423,22 @@ pub struct UpdateFoundStatus {pub bundle: BundleUpdate,}+/// A server-side revocation requires clearing the active bundle root.+#[derive(Debug, Clone)]+pub struct ClearRequiredStatus {+ /// Machine-readable clear reason.+ pub reason: String,+}++/// A newer bundle exists but requires a newer native app build.+#[derive(Debug, Clone)]+pub struct NativeUpdateRequiredStatus {+ /// The newer bundle build that could not be applied.+ pub bundle_build: u64,+ /// The minimum native build required by that bundle.+ pub min_native_build: u64,+}+/// A bundle download is in progress.#[derive(Debug, Clone)]pub struct UpdateDownloadingStatus {@@ -354,6 +455,10 @@ pub struct UpdateDownloadingStatus {pub struct UnzipStatus {/// Path to the zip archive being extracted.pub zip_filename: PathBuf,+ /// Expected bundle build in the extracted manifest.+ pub expected_bundle_build: u64,+ /// Expected minimum native build in the extracted manifest.+ pub expected_min_native_build: u64,/// Expected SHA-256 hex digest.pub expected_checksum: String,/// Current extraction progress.@@ -380,6 +485,10 @@ pub enum UpdateStatus {WaitingForWifi(UpdateFoundStatus),/// The app is already on the latest version.NoUpdateNeeded,+ /// The active cached OTA bundle must be cleared.+ ClearRequired(ClearRequiredStatus),+ /// A newer bundle exists but requires a newer native app build.+ NativeUpdateRequired(NativeUpdateRequiredStatus),/// The bundle zip is being downloaded.DownloadingBundle(UpdateDownloadingStatus),/// The downloaded zip is being extracted.diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/domain/ports.rs b/js/app/tauri/macro_bundle_updater_plugin/src/domain/ports.rsindex a2469a5c5c..b399914d8c 100644--- a/js/app/tauri/macro_bundle_updater_plugin/src/domain/ports.rs+++ b/js/app/tauri/macro_bundle_updater_plugin/src/domain/ports.rs@@ -1,18 +1,18 @@use rootcause::Report;use crate::domain::models::{- AppInfo, BundleUpdate, DownloadBundleError, DownloadBundleRequest, UnzipError, UnzipRequest,+ AppInfo, BundleAction, DownloadBundleError, DownloadBundleRequest, UnzipError, UnzipRequest,UpdateError, UpdateStatus,};use std::path::{Path, PathBuf};/// Port for communicating with the update server.pub trait UpdateRepo: Send + Sync + 'static {- /// Check whether a newer bundle version is available.+ /// Check whether a bundle action is available.fn check_for_update(&self,request: AppInfo,- ) -> impl Future<Output = Result<Option<BundleUpdate>, rootcause::Report>> + Send;+ ) -> impl Future<Output = Result<Option<BundleAction>, rootcause::Report>> + Send;/// Download the bundle zip to a local path, streaming progress.fn get_update_bundle<P: AsRef<Path> + Send>(@@ -43,16 +43,11 @@ pub trait FsRepo: Clone + Send + Sync + 'static {) -> impl Future<Output = Result<(), std::io::Error>> + Send;/// List the names of immediate children in `dir`.- fn list_dir_names(- &self,- dir: &Path,- ) -> impl Future<Output = Vec<String>> + Send;+ fn list_dir_names(&self, dir: &Path) -> impl Future<Output = Vec<String>> + Send;/// Recursively remove a directory.- fn remove_dir_all(- &self,- dir: &Path,- ) -> impl Future<Output = Result<(), std::io::Error>> + Send;+ fn remove_dir_all(&self, dir: &Path)+ -> impl Future<Output = Result<(), std::io::Error>> + Send;/// Read a file's contents as a string.fn read_to_string(@@ -68,10 +63,7 @@ pub trait FsRepo: Clone + Send + Sync + 'static {) -> impl Future<Output = Result<(), std::io::Error>> + Send;/// Remove a file. Returns `Ok(())` if the file does not exist.- fn remove_file(- &self,- path: &Path,- ) -> impl Future<Output = Result<(), std::io::Error>> + Send;+ fn remove_file(&self, path: &Path) -> impl Future<Output = Result<(), std::io::Error>> + Send;}/// Port for querying system metadata (version, arch, cache dirs).diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs b/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rsindex 383ce7ce22..abf0638395 100644--- a/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs+++ b/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs@@ -1,6 +1,7 @@use crate::domain::{models::{- BundleRoot, CompletedStatus, ProgressPercentage, UnzipRequest, UnzipStatus,+ BundleAction, BundleManifest, BundleRoot, ClearRequiredStatus, CompletedStatus,+ NativeUpdateRequiredStatus, ProgressPercentage, UnzipRequest, UnzipStatus,UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateGranted, UpdateStatus,},ports::{AutoUpdateService, FsRepo, SystemQuery, UpdateRepo},@@ -18,6 +19,7 @@ const RELOAD_DISPATCH_RETRY_DELAY: Duration = Duration::from_secs(5);pub struct Service<Fs: FsRepo> {handle: WorkerHandle,fs_repo: Fs,+ embedded_bundle_build: u64,bundle_root: BundleRoot,reload_pending: bool,reload_dispatched_at: Option<Instant>,@@ -60,6 +62,7 @@ struct WorkerHandle {/// the name of the app entrypointconst ENTRYPOINT_NAME: &str = "index.html";+const PENDING_BUNDLE_ROOT_FILE: &str = "pending_bundle_root";impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {fn new_handle(update_repo: U, fs_repo: Fs, system_query: Q) -> WorkerHandle {@@ -104,7 +107,11 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {let Ok(status) = self.status_tx.borrow().as_ref().cloned() else {break;};- if let UpdateStatus::NoUpdateNeeded | UpdateStatus::Completed(_) = status {+ if let UpdateStatus::NoUpdateNeeded+ | UpdateStatus::Completed(_)+ | UpdateStatus::ClearRequired(_)+ | UpdateStatus::NativeUpdateRequired(_) = status+ {break;}@@ -114,9 +121,18 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {Ok(UpdateStatus::NoUpdateNeeded)| Ok(UpdateStatus::WaitingForWifi(_))| Ok(UpdateStatus::Completed(_))+ | Ok(UpdateStatus::ClearRequired(_))+ | Ok(UpdateStatus::NativeUpdateRequired(_))| Err(_));+ if let Err(error) = &next {+ tracing::error!(+ error=%error,+ "[bundle-update] update check failed"+ );+ }+let Ok(()) = self.status_tx.send(next) else {break;};@@ -142,6 +158,7 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {Ok(UpdateStatus::CheckingForDownload(app_info))}UpdateStatus::CheckingForDownload(app_info) => {+ let native_build = app_info.native_build;let res = self.update_repo.check_for_update(app_info)@@ -149,12 +166,16 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {.context(UpdateError::DownloadErr)?;match res {- Some(update) => {- // Check if this version was already downloaded in a previous session.+ Some(BundleAction::Update(update)) => {+ // Check if this bundle build was already downloaded in a previous session.if let Ok(update_dir) = self.system_query.get_update_dir().await- && let Some(entrypoint) =- find_cached_bundle(&self.fs_repo, &update_dir, &update.version)- .await+ && let Some(entrypoint) = find_cached_bundle(+ &self.fs_repo,+ &update_dir,+ update.bundle_build,+ native_build,+ )+ .await{return Ok(UpdateStatus::Completed(CompletedStatus { entrypoint }));}@@ -162,6 +183,19 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {bundle: update,}))}+ Some(BundleAction::Clear(clear)) => {+ Ok(UpdateStatus::ClearRequired(ClearRequiredStatus {+ reason: clear.reason,+ }))+ }+ Some(BundleAction::NativeUpdateRequired(required)) => {+ Ok(UpdateStatus::NativeUpdateRequired(+ NativeUpdateRequiredStatus {+ bundle_build: required.bundle_build,+ min_native_build: required.min_native_build,+ },+ ))+ }None => Ok(UpdateStatus::NoUpdateNeeded),}}@@ -192,6 +226,10 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {}}UpdateStatus::NoUpdateNeeded => Ok(UpdateStatus::NoUpdateNeeded),+ UpdateStatus::ClearRequired(clear) => Ok(UpdateStatus::ClearRequired(clear)),+ UpdateStatus::NativeUpdateRequired(required) => {+ Ok(UpdateStatus::NativeUpdateRequired(required))+ }UpdateStatus::DownloadingBundle(status) => {let update_dir = self.system_query@@ -204,6 +242,8 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {.await.context(UpdateError::IoErr)?;+ let expected_bundle_build = status.update.bundle_build;+ let expected_min_native_build = status.update.min_native_build;let expected_checksum = status.update.checksum.clone();let (req, rx) = status.update.into_download_request(&download_filename);@@ -223,6 +263,8 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {.context(UpdateError::DownloadErr)?;Ok(UpdateStatus::UnzippingBundle(UnzipStatus {zip_filename: download_filename,+ expected_bundle_build,+ expected_min_native_build,expected_checksum,progress: ProgressPercentage::default(),}))@@ -238,6 +280,7 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {.parent().unwrap_or(&unzip_status.zip_filename).to_path_buf();+ let update_dir = archive_target.parent().map(Path::to_path_buf);let (req, rx) = UnzipRequest::new(unzip_status.zip_filename, archive_target);let status_tx = self.status_tx.clone();@@ -249,7 +292,40 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {_ => false,}));- let mut entrypoint = self.fs_repo.unzip(req).await.context(UpdateError::Unzip)?;+ let bundle_dir = self.fs_repo.unzip(req).await.context(UpdateError::Unzip)?;+ validate_bundle_dir(+ &self.fs_repo,+ &bundle_dir,+ unzip_status.expected_bundle_build,+ unzip_status.expected_min_native_build,+ self.system_query+ .get_system_info()+ .await+ .context(UpdateError::Other)?+ .native_build,+ )+ .await+ .context(UpdateError::Unzip)?;+ if let Some(update_dir) = update_dir {+ let marker = update_dir.join(PENDING_BUNDLE_ROOT_FILE);+ if let Err(e) =+ persist_pending_bundle(&self.fs_repo, &update_dir, &bundle_dir).await+ {+ tracing::warn!(+ error=?e,+ update_dir=?update_dir,+ marker=?marker,+ bundle_dir=?bundle_dir,+ "[bundle-update] failed to persist pending bundle marker"+ );+ }+ } else {+ tracing::warn!(+ bundle_dir=?bundle_dir,+ "[bundle-update] could not derive update dir for pending bundle marker"+ );+ }+ let mut entrypoint = bundle_dir;entrypoint.push(ENTRYPOINT_NAME);Ok(UpdateStatus::Completed(CompletedStatus { entrypoint }))}@@ -259,7 +335,7 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {async fn should_download_now(&self) -> Result<bool, Report> {let network_type = self.system_query.get_network_type().await?;- tracing::info!(+ tracing::debug!(network_type = network_type.as_deref().unwrap_or("unknown"),"Bundle update network check");@@ -300,47 +376,98 @@ pub(crate) fn next_bundle_index(names: &[String]) -> u64 {.map_or(0, |m| m + 1)}-/// Search existing numeric bundle directories for one whose `semver.txt`-/// matches `version`. Returns the entrypoint path if found.+/// Search existing numeric bundle directories for one whose manifest matches+/// `bundle_build` and is compatible with this native app.async fn find_cached_bundle(fs: &impl FsRepo,update_dir: &std::path::Path,- version: &semver::Version,+ bundle_build: u64,+ native_build: u64,) -> Option<PathBuf> {- let version_str = version.to_string();let names = fs.list_dir_names(update_dir).await;- tracing::info!(- "find_cached_bundle: looking for version {version_str} in {update_dir:?}, found dirs: {names:?}"+ tracing::debug!(+ "find_cached_bundle: looking for bundle build {bundle_build} in {update_dir:?}, found dirs: {names:?}");for name in names {if name.parse::<u64>().is_err() {continue;}let dir = update_dir.join(&name);- let semver_path = dir.join("semver.txt");- match fs.read_to_string(&semver_path).await {- Ok(contents) => {- tracing::info!(- "find_cached_bundle: {semver_path:?} contains {:?}, want {version_str:?}",- contents.trim()- );- if contents.trim() == version_str {- let entrypoint = dir.join(ENTRYPOINT_NAME);- if fs.read_to_string(&entrypoint).await.is_ok() {- tracing::info!("find_cached_bundle: hit — reusing {entrypoint:?}");- return Some(entrypoint);- }- }- }- Err(e) => {- tracing::debug!("find_cached_bundle: no semver.txt in {dir:?}: {e}");+ let Some(manifest) = BundleManifest::read(&dir.join("bundle-manifest.json"), fs).await+ else {+ tracing::debug!("find_cached_bundle: no valid manifest in {dir:?}");+ continue;+ };+ if manifest.bundle_build == bundle_build && manifest.min_native_build <= native_build {+ let entrypoint = dir.join(ENTRYPOINT_NAME);+ if fs.read_to_string(&entrypoint).await.is_ok() {+ tracing::debug!("find_cached_bundle: hit reusing {entrypoint:?}");+ return Some(entrypoint);}}}- tracing::info!("find_cached_bundle: no cached bundle found for {version_str}");+ tracing::debug!("find_cached_bundle: no cached bundle found for {bundle_build}");None}+async fn validate_bundle_dir(+ fs: &impl FsRepo,+ bundle_dir: &Path,+ expected_bundle_build: u64,+ expected_min_native_build: u64,+ native_build: u64,+) -> Result<(), rootcause::Report> {+ let manifest = BundleManifest::read(&bundle_dir.join("bundle-manifest.json"), fs)+ .await+ .ok_or_else(|| report!("Missing or invalid bundle-manifest.json in {bundle_dir:?}"))?;+ if manifest.bundle_build != expected_bundle_build {+ return Err(report!(+ "Downloaded bundle build {} did not match expected {}",+ manifest.bundle_build,+ expected_bundle_build+ ));+ }+ if manifest.min_native_build != expected_min_native_build {+ return Err(report!(+ "Downloaded min native build {} did not match expected {}",+ manifest.min_native_build,+ expected_min_native_build+ ));+ }+ if manifest.min_native_build > native_build {+ return Err(report!(+ "Downloaded bundle requires native build {}, current native build is {}",+ manifest.min_native_build,+ native_build+ ));+ }+ if fs+ .read_to_string(&bundle_dir.join(ENTRYPOINT_NAME))+ .await+ .is_err()+ {+ return Err(report!("Downloaded bundle missing {ENTRYPOINT_NAME}"));+ }+ Ok(())+}++async fn persist_pending_bundle(+ fs: &impl FsRepo,+ cache_dir: &Path,+ bundle_dir: &Path,+) -> Result<(), std::io::Error> {+ fs.write(+ &cache_dir.join(PENDING_BUNDLE_ROOT_FILE),+ bundle_dir.to_string_lossy().as_bytes(),+ )+ .await+}++async fn clear_pending_bundle(fs: &impl FsRepo, cache_dir: &Path) -> Result<(), std::io::Error> {+ fs.remove_file(&cache_dir.join(PENDING_BUNDLE_ROOT_FILE))+ .await+}+/// helper function which pipes the progress of an event from one channel into another/// returning true if the value in the sender channel was modifiedasync fn glue_channels<F>(@@ -364,11 +491,13 @@ impl<Fs: FsRepo> Service<Fs> {update_repo: U,fs_repo: Fs,system_query: Q,+ embedded_bundle_build: u64,) -> Self {let handle = Worker::new_handle(update_repo, fs_repo.clone(), system_query);Service {handle,fs_repo,+ embedded_bundle_build,bundle_root: BundleRoot::new(),reload_pending: false,reload_dispatched_at: None,@@ -376,8 +505,29 @@ impl<Fs: FsRepo> Service<Fs> {}/// Load persisted bundle root from the given cache directory.- pub async fn load_bundle_root(&mut self, cache_dir: &Path) {+ ///+ /// Returns `true` when a completed-but-not-applied bundle was restored and+ /// should be applied before starting a fresh update check.+ pub async fn load_bundle_root(&mut self, cache_dir: &Path, native_build: u64) -> bool {self.bundle_root = BundleRoot::load(cache_dir, &self.fs_repo).await;+ if !self.current_bundle_is_usable(native_build).await {+ tracing::warn!("Clearing unusable persisted bundle root");+ let _ = self.clear_bundle_root(cache_dir).await;+ }+ if self.bundle_root.path().is_some() {+ if let Err(e) = self.clear_pending_bundle(cache_dir).await {+ tracing::warn!(error=?e, "Failed to clear stale pending bundle marker");+ }+ return false;+ }++ self.restore_pending_completed_update(cache_dir, native_build)+ .await+ }++ /// Bundle build embedded in this native app.+ pub fn embedded_bundle_build(&self) -> u64 {+ self.embedded_bundle_build}/// Get the current bundle root path, if an OTA update has been applied.@@ -399,6 +549,17 @@ impl<Fs: FsRepo> Service<Fs> {});}+ let should_clear = {+ let status = self.status().borrow();+ matches!(status.as_ref(), Ok(UpdateStatus::ClearRequired(_)))+ };+ if should_clear {+ self.clear_bundle_root(cache_dir).await?;+ self.reload_pending = true;+ self.reload_dispatched_at = None;+ return Ok(ApplyUpdateResult::ReloadNeeded);+ }+let entrypoint = {let status = self.status().borrow();match status.as_ref() {@@ -412,8 +573,8 @@ impl<Fs: FsRepo> Service<Fs> {.ok_or_else(|| report!("entrypoint {entrypoint:?} has no parent directory"))?.to_path_buf();- tracing::info!("Setting bundle root to {bundle_dir:?}");self.set_bundle_root(bundle_dir.clone(), cache_dir).await?;+ self.clear_pending_bundle(cache_dir).await?;self.reload_pending = true;self.reload_dispatched_at = None;@@ -487,8 +648,104 @@ impl<Fs: FsRepo> Service<Fs> {Ok(())}+ async fn clear_pending_bundle(&self, cache_dir: &Path) -> Result<(), std::io::Error> {+ clear_pending_bundle(&self.fs_repo, cache_dir).await+ }++ async fn restore_pending_completed_update(+ &mut self,+ cache_dir: &Path,+ native_build: u64,+ ) -> bool {+ let marker = cache_dir.join(PENDING_BUNDLE_ROOT_FILE);+ let Ok(contents) = self.fs_repo.read_to_string(&marker).await else {+ return self+ .restore_latest_completed_download(cache_dir, native_build)+ .await;+ };++ let bundle_dir = PathBuf::from(contents.trim());+ self.restore_completed_bundle_dir(cache_dir, native_build, bundle_dir)+ .await+ }++ async fn restore_latest_completed_download(+ &mut self,+ cache_dir: &Path,+ native_build: u64,+ ) -> bool {+ let mut candidates = Vec::new();+ for name in self.fs_repo.list_dir_names(cache_dir).await {+ if name.parse::<u64>().is_err() {+ continue;+ }+ let bundle_dir = cache_dir.join(&name);+ let Some(manifest) =+ BundleManifest::read(&bundle_dir.join("bundle-manifest.json"), &self.fs_repo).await+ else {+ continue;+ };+ if manifest.bundle_build < self.embedded_bundle_build+ || manifest.min_native_build > native_build+ || self+ .fs_repo+ .read_to_string(&bundle_dir.join(ENTRYPOINT_NAME))+ .await+ .is_err()+ {+ continue;+ }+ candidates.push((manifest.bundle_build, bundle_dir));+ }++ let Some((_, bundle_dir)) = candidates+ .into_iter()+ .max_by_key(|(bundle_build, _)| *bundle_build)+ else {+ return false;+ };++ self.restore_completed_bundle_dir(cache_dir, native_build, bundle_dir)+ .await+ }++ async fn restore_completed_bundle_dir(+ &mut self,+ cache_dir: &Path,+ native_build: u64,+ bundle_dir: PathBuf,+ ) -> bool {+ let Some(manifest) =+ BundleManifest::read(&bundle_dir.join("bundle-manifest.json"), &self.fs_repo).await+ else {+ let _ = self.clear_pending_bundle(cache_dir).await;+ return false;+ };++ let entrypoint = bundle_dir.join(ENTRYPOINT_NAME);+ let usable = manifest.bundle_build >= self.embedded_bundle_build+ && manifest.min_native_build <= native_build+ && self.fs_repo.read_to_string(&entrypoint).await.is_ok();+ if !usable {+ let _ = self.clear_pending_bundle(cache_dir).await;+ return false;+ }++ if let Err(e) = self+ .handle+ .status_tx+ .send(Ok(UpdateStatus::Completed(CompletedStatus { entrypoint })))+ {+ tracing::warn!(error=?e, "[bundle-update] failed to restore pending bundle status");+ return false;+ }++ true+ }+/// Clear the bundle root and remove all downloaded bundles.pub async fn clear_bundle_root(&mut self, cache_dir: &Path) -> Result<(), std::io::Error> {+ self.clear_pending_bundle(cache_dir).await?;for name in self.fs_repo.list_dir_names(cache_dir).await {if name.parse::<u64>().is_ok() {let _ = self.fs_repo.remove_dir_all(&cache_dir.join(&name)).await;@@ -498,9 +755,12 @@ impl<Fs: FsRepo> Service<Fs> {self.bundle_root.persist(cache_dir, &self.fs_repo).await}- /// Read the bundle version from `semver.txt` inside the current bundle root.- pub async fn bundle_version(&self) -> Option<semver::Version> {- self.bundle_root.version(&self.fs_repo).await+ /// Read the bundle build from `bundle-manifest.json` inside the current bundle root.+ pub async fn bundle_build(&self) -> Option<u64> {+ self.bundle_root+ .manifest(&self.fs_repo)+ .await+ .map(|manifest| manifest.bundle_build)}/// Remove all numeric bundle subdirectories under `dir` except `keep`.@@ -518,6 +778,25 @@ impl<Fs: FsRepo> Service<Fs> {}}}++ async fn current_bundle_is_usable(&self, native_build: u64) -> bool {+ let Some(path) = self.bundle_root.path() else {+ return true;+ };+ if self+ .fs_repo+ .read_to_string(&path.join(ENTRYPOINT_NAME))+ .await+ .is_err()+ {+ return false;+ }+ let Some(manifest) = self.bundle_root.manifest(&self.fs_repo).await else {+ return false;+ };+ manifest.bundle_build >= self.embedded_bundle_build+ && manifest.min_native_build <= native_build+ }}impl<Fs: FsRepo> AutoUpdateService for Service<Fs> {@@ -602,28 +881,33 @@ mod tests {use super::*;use crate::domain::{models::{- AppInfo, Arch, BundleUpdate, DownloadBundleError, DownloadBundleRequest, Target,- UnzipError,+ AppInfo, Arch, BundleAction, BundleClear, BundleNativeUpdateRequired, BundleUpdate,+ DownloadBundleError, DownloadBundleRequest, Target, UnzipError,},ports::AutoUpdateService,};use std::{+ collections::{HashMap, HashSet},future::pending,+ io::ErrorKind,+ path::Component,+ sync::atomic::{AtomicUsize, Ordering},sync::{Arc, Mutex as StdMutex},time::Duration,};#[derive(Clone)]struct FakeUpdateRepo {- update: Option<BundleUpdate>,+ update: Option<BundleAction>,block_download: bool,+ download_count: Arc<AtomicUsize>,}impl UpdateRepo for FakeUpdateRepo {async fn check_for_update(&self,_request: AppInfo,- ) -> Result<Option<BundleUpdate>, rootcause::Report> {+ ) -> Result<Option<BundleAction>, rootcause::Report> {Ok(self.update.clone())}@@ -631,6 +915,7 @@ mod tests {&self,_request: DownloadBundleRequest<P>,) -> Result<(), Report<DownloadBundleError>> {+ self.download_count.fetch_add(1, Ordering::SeqCst);if self.block_download {pending::<()>().await;}@@ -639,7 +924,80 @@ mod tests {}#[derive(Clone, Default)]- struct FakeFs;+ struct FakeFs {+ state: Arc<StdMutex<FakeFsState>>,+ }++ #[derive(Default)]+ struct FakeFsState {+ files: HashMap<PathBuf, String>,+ dirs: HashSet<PathBuf>,+ removed_dirs: Vec<PathBuf>,+ unzip_target: Option<PathBuf>,+ checksum_should_fail: bool,+ }++ impl FakeFs {+ fn write_file(&self, path: impl Into<PathBuf>, contents: impl Into<String>) {+ let path = path.into();+ let mut state = self.state.lock().unwrap();+ insert_parent_dirs(&mut state.dirs, &path);+ state.files.insert(path, contents.into());+ }++ fn create_dir(&self, path: impl Into<PathBuf>) {+ let path = path.into();+ let mut state = self.state.lock().unwrap();+ insert_dir_and_parents(&mut state.dirs, &path);+ }++ fn set_unzip_target(&self, path: impl Into<PathBuf>) {+ self.state.lock().unwrap().unzip_target = Some(path.into());+ }++ fn file_exists(&self, path: impl AsRef<Path>) -> bool {+ self.state.lock().unwrap().files.contains_key(path.as_ref())+ }++ fn dir_exists(&self, path: impl AsRef<Path>) -> bool {+ self.state.lock().unwrap().dirs.contains(path.as_ref())+ }++ fn removed_dirs(&self) -> Vec<PathBuf> {+ self.state.lock().unwrap().removed_dirs.clone()+ }+ }++ fn insert_parent_dirs(dirs: &mut HashSet<PathBuf>, path: &Path) {+ if let Some(parent) = path.parent() {+ insert_dir_and_parents(dirs, parent);+ }+ }++ fn insert_dir_and_parents(dirs: &mut HashSet<PathBuf>, path: &Path) {+ let mut cur = PathBuf::new();+ for component in path.components() {+ match component {+ Component::RootDir => cur.push(Path::new("/")),+ other => cur.push(other.as_os_str()),+ }+ dirs.insert(cur.clone());+ }+ }++ fn not_found() -> std::io::Error {+ std::io::Error::new(ErrorKind::NotFound, "missing")+ }++ fn immediate_child_name(parent: &Path, child: &Path) -> Option<String> {+ let rel = child.strip_prefix(parent).ok()?;+ let mut components = rel.components();+ let first = components.next()?;+ if matches!(first, Component::CurDir) {+ return None;+ }+ Some(first.as_os_str().to_string_lossy().to_string())+ }impl FsRepo for FakeFs {async fn verify_checksum<P: AsRef<Path> + Send>(@@ -647,37 +1005,77 @@ mod tests {_path: P,_expected: &str,) -> Result<(), UnzipError> {+ if self.state.lock().unwrap().checksum_should_fail {+ return Err(UnzipError::ChecksumMismatch {+ expected: "expected".to_string(),+ actual: "actual".to_string(),+ });+ }Ok(())}async fn unzip(&self, request: UnzipRequest) -> Result<PathBuf, UnzipError> {- Ok(request.archive_target)+ Ok(self+ .state+ .lock()+ .unwrap()+ .unzip_target+ .clone()+ .unwrap_or(request.archive_target))}async fn create_dir_all<P: AsRef<Path> + Send>(&self,- _path: P,+ path: P,) -> Result<(), std::io::Error> {+ self.create_dir(path.as_ref().to_path_buf());Ok(())}- async fn list_dir_names(&self, _dir: &Path) -> Vec<String> {- Vec::new()+ async fn list_dir_names(&self, dir: &Path) -> Vec<String> {+ let state = self.state.lock().unwrap();+ let mut names = HashSet::new();+ for path in state.dirs.iter().chain(state.files.keys()) {+ if path == dir {+ continue;+ }+ if let Some(name) = immediate_child_name(dir, path) {+ names.insert(name);+ }+ }+ let mut names = names.into_iter().collect::<Vec<_>>();+ names.sort();+ names}- async fn remove_dir_all(&self, _dir: &Path) -> Result<(), std::io::Error> {+ async fn remove_dir_all(&self, dir: &Path) -> Result<(), std::io::Error> {+ let mut state = self.state.lock().unwrap();+ state.removed_dirs.push(dir.to_path_buf());+ state.dirs.retain(|path| !path.starts_with(dir));+ state.files.retain(|path, _| !path.starts_with(dir));Ok(())}- async fn read_to_string(&self, _path: &Path) -> Result<String, std::io::Error> {- Err(std::io::Error::new(std::io::ErrorKind::NotFound, "missing"))+ async fn read_to_string(&self, path: &Path) -> Result<String, std::io::Error> {+ self.state+ .lock()+ .unwrap()+ .files+ .get(path)+ .cloned()+ .ok_or_else(not_found)}- async fn write(&self, _path: &Path, _contents: &[u8]) -> Result<(), std::io::Error> {+ async fn write(&self, path: &Path, contents: &[u8]) -> Result<(), std::io::Error> {+ self.write_file(+ path.to_path_buf(),+ String::from_utf8_lossy(contents).to_string(),+ );Ok(())}- async fn remove_file(&self, _path: &Path) -> Result<(), std::io::Error> {+ async fn remove_file(&self, path: &Path) -> Result<(), std::io::Error> {+ self.state.lock().unwrap().files.remove(path);Ok(())}}@@ -686,15 +1084,29 @@ mod tests {struct FakeSystemQuery {network_type: Arc<StdMutex<Option<String>>>,network_type_error: Arc<StdMutex<bool>>,+ native_build: Arc<StdMutex<u64>>,update_dir: PathBuf,}impl FakeSystemQuery {fn new(network_type: &str) -> Self {+ Self::with_update_dir_and_native_build(+ network_type,+ std::env::temp_dir().join("macro_bundle_updater_plugin_tests"),+ 0,+ )+ }++ fn with_update_dir_and_native_build(+ network_type: &str,+ update_dir: PathBuf,+ native_build: u64,+ ) -> Self {Self {network_type: Arc::new(StdMutex::new(Some(network_type.to_string()))),network_type_error: Arc::new(StdMutex::new(false)),- update_dir: std::env::temp_dir().join("macro_bundle_updater_plugin_tests"),+ native_build: Arc::new(StdMutex::new(native_build)),+ update_dir,}}@@ -710,7 +1122,8 @@ mod tests {impl SystemQuery for FakeSystemQuery {async fn get_system_info(&self) -> Result<AppInfo, rootcause::Report> {Ok(AppInfo {- current_version: semver::Version::new(0, 0, 0),+ current_bundle_build: 0,+ native_build: *self.native_build.lock().unwrap(),arch: Arch::Aarch64,target: Target::Ios,})@@ -730,27 +1143,93 @@ mod tests {fn bundle_update() -> BundleUpdate {BundleUpdate {- version: semver::Version::new(1, 2, 3),+ bundle_build: 1,+ min_native_build: 0,notes: None,url: "https://example.com/bundle.zip".parse().unwrap(),checksum: "checksum".to_string(),}}- fn service_with_network(network_type: &str) -> (Service<FakeFs>, FakeSystemQuery) {- let system_query = FakeSystemQuery::new(network_type);- let service = Service::new(+ fn fake_update_repo(+ update: Option<BundleAction>,+ block_download: bool,+ ) -> (FakeUpdateRepo, Arc<AtomicUsize>) {+ let download_count = Arc::new(AtomicUsize::new(0));+ (FakeUpdateRepo {- update: Some(bundle_update()),- block_download: true,+ update,+ block_download,+ download_count: download_count.clone(),},- FakeFs,- system_query.clone(),+ download_count,+ )+ }++ fn cache_dir() -> PathBuf {+ PathBuf::from("/cache")+ }++ fn manifest_json(bundle_build: u64, min_native_build: u64) -> String {+ format!(+ r#"{{"schemaVersion":2,"bundleBuild":{bundle_build},"minNativeBuild":{min_native_build},"gitSha":"test","appVersion":"2.5.0"}}"#+ )+ }++ fn seed_bundle(+ fs: &FakeFs,+ cache_dir: &Path,+ dir_name: &str,+ bundle_build: u64,+ min_native_build: u64,+ ) -> PathBuf {+ let dir = cache_dir.join(dir_name);+ fs.create_dir(dir.clone());+ fs.write_file(dir.join(ENTRYPOINT_NAME), "<html></html>");+ fs.write_file(+ dir.join("bundle-manifest.json"),+ manifest_json(bundle_build, min_native_build),+ );+ dir+ }++ fn seed_persisted_bundle_root(fs: &FakeFs, cache_dir: &Path, bundle_dir: &Path) {+ fs.write_file(+ cache_dir.join("bundle_root"),+ bundle_dir.to_string_lossy().to_string(),);+ }++ fn seed_pending_bundle_root(fs: &FakeFs, cache_dir: &Path, bundle_dir: &Path) {+ fs.write_file(+ cache_dir.join(PENDING_BUNDLE_ROOT_FILE),+ bundle_dir.to_string_lossy().to_string(),+ );+ }++ fn service_with_network(network_type: &str) -> (Service<FakeFs>, FakeSystemQuery) {+ let system_query = FakeSystemQuery::new(network_type);+ let (update_repo, _) = fake_update_repo(Some(BundleAction::Update(bundle_update())), true);+ let service = Service::new(update_repo, FakeFs::default(), system_query.clone(), 0);(service, system_query)}fn service_with_status(status: UpdateStatus) -> (Service<FakeFs>, StartRx) {+ service_with_status_fs_and_embedded_build(status, FakeFs::default(), 0)+ }++ fn service_with_status_and_fs(+ status: UpdateStatus,+ fs_repo: FakeFs,+ ) -> (Service<FakeFs>, StartRx) {+ service_with_status_fs_and_embedded_build(status, fs_repo, 0)+ }++ fn service_with_status_fs_and_embedded_build(+ status: UpdateStatus,+ fs_repo: FakeFs,+ embedded_bundle_build: u64,+ ) -> (Service<FakeFs>, StartRx) {let (status_tx, status_rx) = tokio::sync::watch::channel(Ok(status));let (start_tx, start_rx) = tokio::sync::mpsc::channel(1);(@@ -760,7 +1239,8 @@ mod tests {status_tx,start_tx,},- fs_repo: FakeFs,+ fs_repo,+ embedded_bundle_build,bundle_root: BundleRoot::new(),reload_pending: false,reload_dispatched_at: None,@@ -769,12 +1249,63 @@ mod tests {)}+ fn worker_with_fs_and_native_build(+ fs_repo: FakeFs,+ update: Option<BundleAction>,+ update_dir: PathBuf,+ native_build: u64,+ ) -> Worker<FakeUpdateRepo, FakeFs, FakeSystemQuery> {+ let (status_tx, _status_rx) = tokio::sync::watch::channel(Ok(UpdateStatus::Idle));+ let (_start_tx, start_rx) = tokio::sync::mpsc::channel(1);+ let (update_repo, _) = fake_update_repo(update, false);+ Worker {+ update_repo,+ fs_repo,+ system_query: FakeSystemQuery::with_update_dir_and_native_build(+ "wifi",+ update_dir,+ native_build,+ ),+ status_tx,+ start_rx,+ }+ }++ fn app_info(native_build: u64) -> AppInfo {+ AppInfo {+ current_bundle_build: 0,+ native_build,+ arch: Arch::Aarch64,+ target: Target::Ios,+ }+ }++ fn unzip_status(+ cache_dir: &Path,+ expected_bundle_build: u64,+ expected_min_native_build: u64,+ ) -> UnzipStatus {+ UnzipStatus {+ zip_filename: cache_dir.join("0").join("bundle.zip"),+ expected_bundle_build,+ expected_min_native_build,+ expected_checksum: "checksum".to_string(),+ progress: ProgressPercentage::default(),+ }+ }+fn completed_status() -> UpdateStatus {UpdateStatus::Completed(CompletedStatus {entrypoint: PathBuf::from("/tmp/macro-bundle-test/1/index.html"),})}+ fn clear_required_status() -> UpdateStatus {+ UpdateStatus::ClearRequired(ClearRequiredStatus {+ reason: "bundle_revoked".to_string(),+ })+ }+async fn wait_for_status(service: &Service<FakeFs>,mut predicate: impl FnMut(&UpdateStatus) -> bool,@@ -797,6 +1328,375 @@ mod tests {.expect("timed out waiting for status")}+ #[tokio::test]+ async fn persisted_ota_older_than_embedded_bundle_is_cleared() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "1", 10, 0);+ seed_persisted_bundle_root(&fs, &cache_dir, &bundle_dir);+ seed_bundle(&fs, &cache_dir, "2", 11, 0);+ let (mut service, _start_rx) =+ service_with_status_fs_and_embedded_build(UpdateStatus::Idle, fs.clone(), 20);++ service.load_bundle_root(&cache_dir, 0).await;++ assert!(service.bundle_root_path().is_none());+ assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert!(!fs.dir_exists(cache_dir.join("1")));+ assert!(!fs.dir_exists(cache_dir.join("2")));+ }++ #[tokio::test]+ async fn persisted_ota_with_missing_manifest_is_cleared() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = cache_dir.join("1");+ fs.create_dir(bundle_dir.clone());+ fs.write_file(bundle_dir.join(ENTRYPOINT_NAME), "<html></html>");+ seed_persisted_bundle_root(&fs, &cache_dir, &bundle_dir);+ let (mut service, _start_rx) = service_with_status_and_fs(UpdateStatus::Idle, fs.clone());++ service.load_bundle_root(&cache_dir, 0).await;++ assert!(service.bundle_root_path().is_none());+ assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert!(!fs.dir_exists(cache_dir.join("1")));+ }++ #[tokio::test]+ async fn persisted_ota_with_invalid_manifest_is_cleared() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = cache_dir.join("1");+ fs.create_dir(bundle_dir.clone());+ fs.write_file(bundle_dir.join(ENTRYPOINT_NAME), "<html></html>");+ fs.write_file(bundle_dir.join("bundle-manifest.json"), "{not json");+ seed_persisted_bundle_root(&fs, &cache_dir, &bundle_dir);+ let (mut service, _start_rx) = service_with_status_and_fs(UpdateStatus::Idle, fs.clone());++ service.load_bundle_root(&cache_dir, 0).await;++ assert!(service.bundle_root_path().is_none());+ assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert!(!fs.dir_exists(cache_dir.join("1")));+ }++ #[tokio::test]+ async fn persisted_ota_requiring_too_new_native_build_is_cleared() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "1", 20, 143);+ seed_persisted_bundle_root(&fs, &cache_dir, &bundle_dir);+ let (mut service, _start_rx) = service_with_status_and_fs(UpdateStatus::Idle, fs.clone());++ service.load_bundle_root(&cache_dir, 142).await;++ assert!(service.bundle_root_path().is_none());+ assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert!(!fs.dir_exists(cache_dir.join("1")));+ }++ #[tokio::test]+ async fn persisted_compatible_ota_is_restored() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "1", 20, 143);+ seed_persisted_bundle_root(&fs, &cache_dir, &bundle_dir);+ let (mut service, _start_rx) =+ service_with_status_fs_and_embedded_build(UpdateStatus::Idle, fs.clone(), 10);++ service.load_bundle_root(&cache_dir, 143).await;++ assert_eq!(service.bundle_root_path(), Some(bundle_dir.as_path()));+ assert!(fs.file_exists(cache_dir.join("bundle_root")));+ assert!(fs.dir_exists(cache_dir.join("1")));+ assert!(fs.removed_dirs().is_empty());+ }++ #[tokio::test]+ async fn pending_completed_ota_is_restored_after_restart() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "1", 20, 143);+ seed_pending_bundle_root(&fs, &cache_dir, &bundle_dir);+ let (mut service, _start_rx) =+ service_with_status_fs_and_embedded_build(UpdateStatus::Idle, fs.clone(), 10);++ let restored_pending = service.load_bundle_root(&cache_dir, 143).await;++ assert!(restored_pending);+ let status = service.status().borrow().as_ref().unwrap().clone();+ let UpdateStatus::Completed(completed) = status else {+ panic!("expected completed status");+ };+ assert_eq!(completed.entrypoint, bundle_dir.join(ENTRYPOINT_NAME));+ assert!(fs.file_exists(cache_dir.join(PENDING_BUNDLE_ROOT_FILE)));+ }++ #[tokio::test]+ async fn pending_completed_ota_older_than_embedded_bundle_is_not_restored() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "1", 10, 0);+ seed_pending_bundle_root(&fs, &cache_dir, &bundle_dir);+ let (mut service, _start_rx) =+ service_with_status_fs_and_embedded_build(UpdateStatus::Idle, fs.clone(), 20);++ let restored_pending = service.load_bundle_root(&cache_dir, 0).await;++ assert!(!restored_pending);+ assert!(matches!(+ service.status().borrow().as_ref().unwrap(),+ UpdateStatus::Idle+ ));+ assert!(!fs.file_exists(cache_dir.join(PENDING_BUNDLE_ROOT_FILE)));+ }++ #[tokio::test]+ async fn unmarked_completed_ota_is_restored_from_numeric_cache_dir() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ seed_bundle(&fs, &cache_dir, "1", 20, 0);+ let bundle_dir = seed_bundle(&fs, &cache_dir, "2", 30, 0);+ let (mut service, _start_rx) =+ service_with_status_fs_and_embedded_build(UpdateStatus::Idle, fs.clone(), 10);++ let restored_pending = service.load_bundle_root(&cache_dir, 0).await;++ assert!(restored_pending);+ let status = service.status().borrow().as_ref().unwrap().clone();+ let UpdateStatus::Completed(completed) = status else {+ panic!("expected completed status");+ };+ assert_eq!(completed.entrypoint, bundle_dir.join(ENTRYPOINT_NAME));+ }++ #[tokio::test]+ async fn apply_update_clears_pending_completed_ota_marker() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "1", 20, 0);+ seed_pending_bundle_root(&fs, &cache_dir, &bundle_dir);+ let (mut service, _start_rx) = service_with_status_and_fs(+ UpdateStatus::Completed(CompletedStatus {+ entrypoint: bundle_dir.join(ENTRYPOINT_NAME),+ }),+ fs.clone(),+ );++ let result = service.apply_update(&cache_dir).await.unwrap();++ assert_eq!(result, ApplyUpdateResult::ReloadNeeded);+ assert_eq!(service.bundle_root_path(), Some(bundle_dir.as_path()));+ assert!(!fs.file_exists(cache_dir.join(PENDING_BUNDLE_ROOT_FILE)));+ assert!(fs.file_exists(cache_dir.join("bundle_root")));+ }++ #[tokio::test]+ async fn service_reports_configured_embedded_bundle_build() {+ let (service, _start_rx) = service_with_status_fs_and_embedded_build(+ UpdateStatus::Idle,+ FakeFs::default(),+ 1780346991624,+ );++ assert_eq!(service.embedded_bundle_build(), 1780346991624);+ }++ #[tokio::test]+ async fn cached_download_reuse_matches_by_bundle_build() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ seed_bundle(&fs, &cache_dir, "1", 29, 0);+ let bundle_dir = seed_bundle(&fs, &cache_dir, "2", 30, 0);+ let mut update = bundle_update();+ update.bundle_build = 30;+ let mut worker = worker_with_fs_and_native_build(+ fs,+ Some(BundleAction::Update(update)),+ cache_dir.clone(),+ 0,+ );++ let status = worker+ .next_status(UpdateStatus::CheckingForDownload(app_info(0)))+ .await+ .unwrap();++ assert!(matches!(+ status,+ UpdateStatus::Completed(CompletedStatus { entrypoint })+ if entrypoint == bundle_dir.join(ENTRYPOINT_NAME)+ ));+ }++ #[tokio::test]+ async fn cached_download_with_mismatched_bundle_build_is_not_reused() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ seed_bundle(&fs, &cache_dir, "1", 29, 0);+ let mut update = bundle_update();+ update.bundle_build = 30;+ let mut worker =+ worker_with_fs_and_native_build(fs, Some(BundleAction::Update(update)), cache_dir, 0);++ let status = worker+ .next_status(UpdateStatus::CheckingForDownload(app_info(0)))+ .await+ .unwrap();++ assert!(matches!(status, UpdateStatus::UpdateFound(_)));+ }++ #[tokio::test]+ async fn clear_action_from_server_becomes_clear_required_status() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let mut worker = worker_with_fs_and_native_build(+ fs,+ Some(BundleAction::Clear(BundleClear {+ reason: "bundle_revoked".to_string(),+ })),+ cache_dir,+ 0,+ );++ let status = worker+ .next_status(UpdateStatus::CheckingForDownload(app_info(0)))+ .await+ .unwrap();++ assert!(matches!(+ status,+ UpdateStatus::ClearRequired(ClearRequiredStatus { reason })+ if reason == "bundle_revoked"+ ));+ }++ #[tokio::test]+ async fn native_update_required_action_from_server_becomes_terminal_status() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let mut worker = worker_with_fs_and_native_build(+ fs,+ Some(BundleAction::NativeUpdateRequired(+ BundleNativeUpdateRequired {+ bundle_build: 102,+ min_native_build: 999,+ },+ )),+ cache_dir,+ 142,+ );++ let status = worker+ .next_status(UpdateStatus::CheckingForDownload(app_info(142)))+ .await+ .unwrap();++ assert!(matches!(+ status,+ UpdateStatus::NativeUpdateRequired(NativeUpdateRequiredStatus {+ bundle_build: 102,+ min_native_build: 999,+ })+ ));+ }++ #[tokio::test]+ async fn downloaded_zip_with_valid_manifest_persists_pending_marker() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "0", 40, 0);+ fs.set_unzip_target(bundle_dir.clone());+ let mut worker = worker_with_fs_and_native_build(fs.clone(), None, cache_dir.clone(), 0);++ let status = worker+ .next_status(UpdateStatus::UnzippingBundle(unzip_status(+ &cache_dir, 40, 0,+ )))+ .await+ .unwrap();++ assert!(matches!(status, UpdateStatus::Completed(_)));+ assert_eq!(+ fs.read_to_string(&cache_dir.join(PENDING_BUNDLE_ROOT_FILE))+ .await+ .unwrap(),+ bundle_dir.to_string_lossy()+ );+ }++ #[tokio::test]+ async fn downloaded_zip_with_missing_manifest_is_rejected() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = cache_dir.join("0");+ fs.create_dir(bundle_dir.clone());+ fs.write_file(bundle_dir.join(ENTRYPOINT_NAME), "<html></html>");+ fs.set_unzip_target(bundle_dir);+ let mut worker = worker_with_fs_and_native_build(fs, None, cache_dir.clone(), 0);++ let result = worker+ .next_status(UpdateStatus::UnzippingBundle(unzip_status(+ &cache_dir, 40, 0,+ )))+ .await;++ assert!(result.is_err());+ }++ #[tokio::test]+ async fn downloaded_zip_with_mismatched_bundle_build_is_rejected() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "0", 41, 0);+ fs.set_unzip_target(bundle_dir);+ let mut worker = worker_with_fs_and_native_build(fs, None, cache_dir.clone(), 0);++ let result = worker+ .next_status(UpdateStatus::UnzippingBundle(unzip_status(+ &cache_dir, 40, 0,+ )))+ .await;++ assert!(result.is_err());+ }++ #[tokio::test]+ async fn downloaded_zip_with_mismatched_min_native_build_is_rejected() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "0", 40, 11);+ fs.set_unzip_target(bundle_dir);+ let mut worker = worker_with_fs_and_native_build(fs, None, cache_dir.clone(), 20);++ let result = worker+ .next_status(UpdateStatus::UnzippingBundle(unzip_status(+ &cache_dir, 40, 10,+ )))+ .await;++ assert!(result.is_err());+ }++ #[tokio::test]+ async fn downloaded_zip_requiring_too_new_native_build_is_rejected() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let bundle_dir = seed_bundle(&fs, &cache_dir, "0", 40, 143);+ fs.set_unzip_target(bundle_dir);+ let mut worker = worker_with_fs_and_native_build(fs, None, cache_dir.clone(), 142);++ let result = worker+ .next_status(UpdateStatus::UnzippingBundle(unzip_status(+ &cache_dir, 40, 143,+ )))+ .await;++ assert!(result.is_err());+ }+#[tokio::test]async fn update_found_on_wifi_advances_to_downloading() {let (service, _system_query) = service_with_network("wifi");@@ -908,7 +1808,8 @@ mod tests {status_tx,start_tx,},- fs_repo: FakeFs,+ fs_repo: FakeFs::default(),+ embedded_bundle_build: 0,bundle_root: BundleRoot::new(),reload_pending: false,reload_dispatched_at: None,@@ -926,6 +1827,35 @@ mod tests {assert_eq!(applied, ApplyUpdateResult::NoUpdate);}+ #[tokio::test]+ async fn apply_update_clears_bundle_root_when_server_revokes_active_bundle() {+ let fs = FakeFs::default();+ let cache_dir = cache_dir();+ let active_dir = seed_bundle(&fs, &cache_dir, "1", 20, 0);+ seed_bundle(&fs, &cache_dir, "2", 21, 0);+ fs.create_dir(cache_dir.join("logs"));+ fs.write_file(cache_dir.join("logs").join("trace.txt"), "keep");+ seed_persisted_bundle_root(&fs, &cache_dir, &active_dir);+ let (mut service, _start_rx) =+ service_with_status_and_fs(clear_required_status(), fs.clone());+ service.bundle_root = BundleRoot::from_path(active_dir);++ let applied = service.apply_update(&cache_dir).await.unwrap();++ assert_eq!(applied, ApplyUpdateResult::ReloadNeeded);+ assert!(service.reload_pending);+ assert!(service.bundle_root_path().is_none());+ assert!(!fs.file_exists(cache_dir.join("bundle_root")));+ assert!(!fs.dir_exists(cache_dir.join("1")));+ assert!(!fs.dir_exists(cache_dir.join("2")));+ assert!(fs.dir_exists(cache_dir.join("logs")));+ assert!(fs.file_exists(cache_dir.join("logs").join("trace.txt")));+ let removed_dirs = fs.removed_dirs();+ assert!(removed_dirs.contains(&cache_dir.join("1")));+ assert!(removed_dirs.contains(&cache_dir.join("2")));+ assert!(!removed_dirs.contains(&cache_dir.join("logs")));+ }+#[tokio::test]async fn apply_update_keeps_worker_completed_until_reload_ack() {let (mut service, mut start_rx) = service_with_status(completed_status());diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs b/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rsindex 5862fdc365..bbe1b81893 100644--- a/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs+++ b/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs@@ -12,7 +12,11 @@ use crate::{ports::AutoUpdateService,service::{ApplyUpdateResult, Service},},- outbound::{api_client::BundleClient, fs::FileSystem, system_info::SystemInfo},+ outbound::{+ api_client::BundleClient,+ fs::FileSystem,+ system_info::{SystemInfo, native_build},+ },};/// Concrete service type used by the plugin commands.@@ -50,6 +54,20 @@ pub enum BundleUpdateEvent {/// Extraction progress percentage (0–100).progress: f64,},+ /// The active OTA bundle must be cleared.+ ClearRequired {+ /// Reason the server requested a clear.+ reason: String,+ },+ /// A newer bundle exists but requires a newer native app build.+ NativeUpdateRequired {+ /// The newer bundle build that could not be applied.+ #[serde(rename = "bundleBuild")]+ bundle_build: u64,+ /// The minimum native build required by that bundle.+ #[serde(rename = "minNativeBuild")]+ min_native_build: u64,+ },/// Update applied successfully.Completed,/// An error occurred during the update.@@ -59,17 +77,48 @@ pub enum BundleUpdateEvent {},}+/// Debug metadata about the currently effective JavaScript bundle.+#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct BundleDebugInfo {+ /// Current effective bundle build.+ bundle_build: u64,+ /// Whether the effective bundle came from OTA cache or embedded assets.+ source: BundleDebugSource,+ /// Runtime native app build number.+ native_build: u64,+}++/// Source of the currently effective JavaScript bundle.+#[derive(Clone, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum BundleDebugSource {+ /// The native app's embedded bundle is active.+ Embedded,+ /// A cached OTA bundle is active.+ Ota,+}+impl BundleUpdateEvent {fn new(cur: &Result<UpdateStatus, Report<UpdateError>>) -> Self {match cur.as_ref() {Ok(UpdateStatus::Idle) => BundleUpdateEvent::Idle,Ok(UpdateStatus::CheckingForDownload(_)) => BundleUpdateEvent::CheckingForUpdate,Ok(UpdateStatus::UpdateFound(found)) => BundleUpdateEvent::UpdateFound {- version: found.bundle.version.to_string(),+ version: found.bundle.bundle_build.to_string(),notes: found.bundle.notes.clone(),},Ok(UpdateStatus::WaitingForWifi(_found)) => BundleUpdateEvent::WaitingForWifi,Ok(UpdateStatus::NoUpdateNeeded) => BundleUpdateEvent::NoUpdateNeeded,+ Ok(UpdateStatus::ClearRequired(clear)) => BundleUpdateEvent::ClearRequired {+ reason: clear.reason.clone(),+ },+ Ok(UpdateStatus::NativeUpdateRequired(required)) => {+ BundleUpdateEvent::NativeUpdateRequired {+ bundle_build: required.bundle_build,+ min_native_build: required.min_native_build,+ }+ }Ok(UpdateStatus::DownloadingBundle(dl)) => BundleUpdateEvent::Downloading {progress: dl.progress.value(),},@@ -87,12 +136,16 @@ impl BundleUpdateEvent {/// Tauri plugin that manages OTA bundle updates.pub struct MacroBundleUpdaterPlugin {base_url: Url,+ embedded_bundle_build: u64,}impl MacroBundleUpdaterPlugin {/// Create the plugin targeting the given update server URL.- pub fn new(base_url: Url) -> Self {- Self { base_url }+ pub fn new(base_url: Url, embedded_bundle_build: u64) -> Self {+ Self {+ base_url,+ embedded_bundle_build,+ }}}@@ -120,6 +173,19 @@ pub async fn retry_waiting_for_wifi<R: Runtime>(service.retry_waiting_for_wifi().map_err(|e| e.to_string())}+/// Start a fresh bundle update check.+pub async fn start_update_check<R: Runtime>(+ app_handle: &tauri::AppHandle<R>,+) -> Result<bool, String> {+ let Some(service_state) = app_handle.try_state::<Mutex<PluginService>>() else {+ return Ok(false);+ };++ let service = service_state.lock().await;+ service.start().map_err(|e| e.to_string())?;+ Ok(true)+}+/// Allow a pending bundle update reload to be dispatched again.pub async fn allow_update_reload_retry<R: Runtime>(app_handle: &tauri::AppHandle<R>,@@ -138,6 +204,14 @@ pub async fn allow_update_reload_retry<R: Runtime>(/// not in the `Completed` state (no pending update to commit).pub async fn apply_completed_update<R: Runtime>(app_handle: &tauri::AppHandle<R>,+) -> Result<bool, String> {+ apply_completed_update_from(app_handle, "command").await+}++/// Apply a completed bundle update and include the caller in operational logs.+pub async fn apply_completed_update_from<R: Runtime>(+ app_handle: &tauri::AppHandle<R>,+ source: &'static str,) -> Result<bool, String> {let service_state = app_handle.try_state::<Mutex<PluginService>>()@@ -164,22 +238,20 @@ pub async fn apply_completed_update<R: Runtime>(// Reload to pick up the new bundle. Using location.reload() instead of// navigating to a new URL preserves WKWebView's cookie store.if let Some(webview) = app_handle.webview_windows().values().next() {- tracing::info!("Bundle update complete, reloading to pick up new assets");if let Err(e) = webview.eval("window.location.reload();") {- tracing::warn!(error=?e, "Failed to dispatch bundle update reload");- service_state- .lock()- .await- .unmark_update_reload_dispatched();+ tracing::warn!(+ source,+ error=?e,+ "[bundle-update] failed to dispatch webview reload"+ );+ service_state.lock().await.unmark_update_reload_dispatched();}} else {tracing::warn!(- "Completed bundle update applied but no webview was available to reload"+ source,+ "[bundle-update] completed bundle update applied but no webview was available to reload");- service_state- .lock()- .await- .unmark_update_reload_dispatched();+ service_state.lock().await.unmark_update_reload_dispatched();}}Ok(apply_result != ApplyUpdateResult::NoUpdate)@@ -226,6 +298,25 @@ pub async fn get_bundle_update_status(Ok(BundleUpdateEvent::new(&status))}+/// Return debug metadata for the currently effective JavaScript bundle.+#[tauri::command]+pub async fn get_bundle_debug_info(+ service: tauri::State<'_, Mutex<PluginService>>,+) -> Result<BundleDebugInfo, String> {+ let service = service.lock().await;+ let embedded_bundle_build = service.embedded_bundle_build();+ let cached_bundle_build = service.bundle_build().await;+ Ok(BundleDebugInfo {+ bundle_build: cached_bundle_build.unwrap_or(embedded_bundle_build),+ source: if cached_bundle_build.is_some() {+ BundleDebugSource::Ota+ } else {+ BundleDebugSource::Embedded+ },+ native_build: crate::outbound::system_info::native_build(),+ })+}+/// Clear the downloaded bundle and revert to built-in assets.#[tauri::command]pub async fn clear_bundle<R: Runtime>(@@ -244,7 +335,6 @@ pub async fn clear_bundle<R: Runtime>(.await.map_err(|e| e.to_string())?;- tracing::info!("Bundle cleared, reloading to revert to built-in assets");if let Some(webview) = app_handle.webview_windows().values().next() {let _ = webview.eval("window.location.reload();");}@@ -263,14 +353,74 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {) -> Result<(), Box<dyn std::error::Error>> {let client = BundleClient::new(self.base_url.clone());let fs = FileSystem;- let system_info = SystemInfo::new(app.clone());-- let service = Service::new(client, fs, system_info);+ let system_info = SystemInfo::new(app.clone(), self.embedded_bundle_build);++ let mut service = Service::new(client, fs, system_info, self.embedded_bundle_build);+ let mut acknowledge_setup_apply = false;+ let mut start_update_check = false;+ if let Ok(cache_dir) = app.path().app_cache_dir() {+ let restored_pending = tauri::async_runtime::block_on(async {+ service.load_bundle_root(&cache_dir, native_build()).await+ });+ if restored_pending {+ match tauri::async_runtime::block_on(async {+ service.apply_update(&cache_dir).await+ }) {+ Ok(ApplyUpdateResult::ReloadNeeded) => {+ acknowledge_setup_apply = true;+ }+ Ok(ApplyUpdateResult::ReloadAlreadyDispatched) => {+ acknowledge_setup_apply = true;+ }+ Ok(ApplyUpdateResult::NoUpdate) => {+ tracing::warn!(+ "[bundle-update] restored pending bundle had no update to apply during plugin initialization"+ );+ start_update_check = true;+ }+ Err(e) => {+ tracing::error!(+ "[bundle-update] failed to apply restored pending bundle during plugin initialization: {e}"+ );+ start_update_check = true;+ }+ }+ } else {+ start_update_check = true;+ }+ } else {+ tracing::warn!(+ "[bundle-update] failed to read app cache dir during plugin initialization"+ );+ start_update_check = true;+ }let mut status_rx = service.status().clone();let mut wifi_retry_status_rx = service.status().clone();- let _ = service.start();app.manage(tokio::sync::Mutex::new(service));+ if acknowledge_setup_apply || start_update_check {+ let Some(service_state) = app.try_state::<Mutex<PluginService>>() else {+ tracing::warn!(+ "[bundle-update] plugin service state unavailable during initialization"+ );+ return Ok(());+ };+ let Ok(mut service) = service_state.try_lock() else {+ tracing::warn!("[bundle-update] plugin service state locked during initialization");+ return Ok(());+ };+ if acknowledge_setup_apply {+ if let Err(e) = service.acknowledge_update_reload() {+ tracing::warn!(+ "[bundle-update] failed to acknowledge plugin-initialized bundle apply: {e}"+ );+ }+ } else if let Err(e) = service.start() {+ tracing::warn!(+ "[bundle-update] failed to start update check during plugin initialization: {e}"+ );+ }+ }let app_handle = app.clone();tauri::async_runtime::spawn(async move {@@ -305,10 +455,7 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {tokio::select! {_ = tokio::time::sleep(WIFI_RETRY_INTERVAL) => {match retry_waiting_for_wifi(&app_handle).await {- Ok(true) => tracing::info!(- "[bundle-update] retrying bundle download after Wi-Fi wait"- ),- Ok(false) => {}+ Ok(true) | Ok(false) => {}Err(e) => tracing::warn!("[bundle-update] failed to retry bundle download after Wi-Fi wait: {e}"),diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/api_client.rs b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/api_client.rsindex 8c53e2dd18..f26c89d765 100644--- a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/api_client.rs+++ b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/api_client.rs@@ -1,5 +1,5 @@use crate::domain::{- models::{BundleUpdate, DownloadBundleError, DownloadBundleRequest, Progress},+ models::{BundleAction, DownloadBundleError, DownloadBundleRequest, Progress},ports::UpdateRepo,};use futures::TryStreamExt;@@ -44,7 +44,7 @@ impl UpdateRepo for BundleClient {async fn check_for_update(&self,request: crate::domain::models::AppInfo,- ) -> Result<Option<BundleUpdate>, rootcause::Report> {+ ) -> Result<Option<BundleAction>, rootcause::Report> {let mut url = self.base.clone();url.path_segments_mut().map_err(|_| BundleClientErr::CannotBeABase(self.base.clone()))?@@ -52,8 +52,13 @@ impl UpdateRepo for BundleClient {.push("update").push("bundle").push(request.target.into())- .push(request.arch.into())- .push(&request.current_version.to_string());+ .push(request.arch.into());+ url.query_pairs_mut()+ .append_pair(+ "current_bundle_build",+ &request.current_bundle_build.to_string(),+ )+ .append_pair("native_build", &request.native_build.to_string());let res = self.client.get(url).send().await?.error_for_status()?;diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rsindex 95c0a27e36..390d0c18f9 100644--- a/js/app/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs+++ b/js/app/tauri/macro_bundle_updater_plugin/src/outbound/system_info.rs@@ -1,4 +1,3 @@-use semver::Version;use tauri::{Manager, Runtime};use tauri_plugin_device_info::DeviceInfoExt;@@ -10,12 +9,16 @@ use crate::domain::{/// Queries the running Tauri app for version, architecture, and OS target.pub struct SystemInfo<R: Runtime> {app_handle: tauri::AppHandle<R>,+ embedded_bundle_build: u64,}impl<R: Runtime> SystemInfo<R> {/// Create a new system info query bound to the given app handle.- pub fn new(app_handle: tauri::AppHandle<R>) -> Self {- Self { app_handle }+ pub fn new(app_handle: tauri::AppHandle<R>, embedded_bundle_build: u64) -> Self {+ Self {+ app_handle,+ embedded_bundle_build,+ }}fn get_target(&self) -> Target {@@ -29,19 +32,19 @@ impl<R: Runtime> SystemInfo<R> {}}- async fn get_version(&self) -> Version {- // If an OTA update has been applied, read the version from semver.txt- // in the bundle root so the server can compare build metadata accurately.+ async fn current_bundle_build(&self) -> u64 {+ // If an OTA update has been applied, read the bundle build from its+ // manifest; otherwise report the build embedded with this native app.if let Some(s) = self.app_handle.try_state::<tokio::sync::Mutex<crate::inbound::plugin::PluginService>>(){let service = s.lock().await;- if let Some(v) = service.bundle_version().await {- return v;+ if let Some(build) = service.bundle_build().await {+ return build;}}- self.app_handle.package_info().version.clone()+ self.embedded_bundle_build}fn get_arch(&self) -> Arch {@@ -58,7 +61,8 @@ impl<R: Runtime> SystemInfo<R> {impl<R: Runtime> SystemQuery for SystemInfo<R> {async fn get_system_info(&self) -> Result<AppInfo, rootcause::Report> {Ok(AppInfo {- current_version: self.get_version().await,+ current_bundle_build: self.current_bundle_build().await,+ native_build: native_build(),arch: self.get_arch(),target: self.get_target(),})@@ -80,3 +84,108 @@ impl<R: Runtime> SystemQuery for SystemInfo<R> {.map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))}}++#[cfg(target_os = "ios")]+/// Return the current native app build number.+pub fn native_build() -> u64 {+ use objc2::rc::autoreleasepool;+ use objc2::runtime::AnyObject;+ use objc2::{class, msg_send};+ use std::ffi::{CStr, CString};+ use std::os::raw::c_char;++ autoreleasepool(|_| unsafe {+ let bundle: *mut AnyObject = msg_send![class!(NSBundle), mainBundle];+ if bundle.is_null() {+ return 0;+ }+ let Ok(key) = CString::new("CFBundleVersion") else {+ return 0;+ };+ let key: *mut AnyObject = msg_send![+ class!(NSString),+ stringWithUTF8String: key.as_ptr() as *const c_char+ ];+ let value: *mut AnyObject = msg_send![bundle, objectForInfoDictionaryKey: key];+ if value.is_null() {+ return 0;+ }+ let c_value: *const c_char = msg_send![value, UTF8String];+ if c_value.is_null() {+ return 0;+ }+ CStr::from_ptr(c_value)+ .to_str()+ .ok()+ .and_then(|value| value.parse().ok())+ .unwrap_or(0)+ })+}++#[cfg(target_os = "android")]+/// Return the current native app build number.+pub fn native_build() -> u64 {+ use jni::JavaVM;+ use jni::objects::{JObject, JValue};+ use jni::sys::jint;++ let context = ndk_context::android_context();+ unsafe {+ let Ok(vm) = JavaVM::from_raw(context.vm().cast()) else {+ return 0;+ };+ let Ok(mut env) = vm.attach_current_thread() else {+ return 0;+ };+ let app_context = JObject::from_raw(context.context().cast());+ let Ok(package_manager) = env+ .call_method(+ &app_context,+ "getPackageManager",+ "()Landroid/content/pm/PackageManager;",+ &[],+ )+ .and_then(|value| value.l())+ else {+ return 0;+ };+ let Ok(package_name) = env+ .call_method(&app_context, "getPackageName", "()Ljava/lang/String;", &[])+ .and_then(|value| value.l())+ else {+ return 0;+ };+ let flags = JValue::Int(0 as jint);+ let Ok(package_info) = env+ .call_method(+ package_manager,+ "getPackageInfo",+ "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;",+ &[JValue::Object(&package_name), flags],+ )+ .and_then(|value| value.l())+ else {+ return 0;+ };+ if let Ok(value) = env+ .call_method(&package_info, "getLongVersionCode", "()J", &[])+ .and_then(|value| value.j())+ {+ return u64::try_from(value).unwrap_or(0);+ }+ if env.exception_check().unwrap_or(false) {+ let _ = env.exception_clear();+ }++ env.get_field(&package_info, "versionCode", "I")+ .and_then(|value| value.i())+ .map(|value| u64::try_from(value).unwrap_or(0))+ .unwrap_or(0)+ }+}++#[cfg(not(any(target_os = "ios", target_os = "android")))]+/// Return the current native app build number.+pub fn native_build() -> u64 {+ 0+}diff --git a/js/app/tauri/src-tauri/Cargo.toml b/js/app/tauri/src-tauri/Cargo.tomlindex 6ba754aff6..d449064d32 100644--- a/js/app/tauri/src-tauri/Cargo.toml+++ b/js/app/tauri/src-tauri/Cargo.toml@@ -14,6 +14,7 @@ crate-type = ["cdylib", "rlib", "staticlib"]name = "app_lib"[build-dependencies]+serde_json = "1.0"tauri-build = { version = "2.3.1", features = [] }[features]diff --git a/js/app/tauri/src-tauri/build.rs b/js/app/tauri/src-tauri/build.rsindex 15216cfdbf..3dc37a1a28 100644--- a/js/app/tauri/src-tauri/build.rs+++ b/js/app/tauri/src-tauri/build.rs@@ -1,11 +1,14 @@fn main() {println!("cargo:rerun-if-changed=.macro-tauri-env");+ println!("cargo:rerun-if-changed=../../packages/app/dist/bundle-manifest.json");+ println!("cargo:rerun-if-env-changed=MACRO_BUNDLE_UPDATE_BASE_URL");let contents = std::fs::read_to_string(".macro-tauri-env").unwrap_or_default();+ let raw_app_env = contents.trim();// A missing or blank file falls back to the safe `production` default;// any other content must be a valid environment name.- let app_env = match contents.trim() {+ let app_env = match raw_app_env {"" => "production",other => other,};@@ -19,5 +22,35 @@ fn main() {}}+ let embedded_bundle_build = match read_embedded_bundle_build() {+ Ok(bundle_build) => bundle_build,+ Err(error) if app_env == "production" => {+ panic!("{error}");+ }+ Err(error) => {+ println!("cargo:warning={error}; falling back to embedded bundle build 0");+ 0+ }+ };+ println!("cargo:rustc-env=MACRO_EMBEDDED_BUNDLE_BUILD={embedded_bundle_build}");+ if let Ok(bundle_update_base_url) = std::env::var("MACRO_BUNDLE_UPDATE_BASE_URL") {+ let bundle_update_base_url = bundle_update_base_url.trim();+ if !bundle_update_base_url.is_empty() {+ println!("cargo:rustc-env=MACRO_BUNDLE_UPDATE_BASE_URL={bundle_update_base_url}");+ }+ }+tauri_build::build()}++fn read_embedded_bundle_build() -> Result<u64, String> {+ let path = "../../packages/app/dist/bundle-manifest.json";+ let contents =+ std::fs::read_to_string(path).map_err(|e| format!("failed to read {path}: {e}"))?;+ let manifest = serde_json::from_str::<serde_json::Value>(&contents)+ .map_err(|e| format!("failed to parse {path}: {e}"))?;+ manifest+ .get("bundleBuild")+ .and_then(|value| value.as_u64())+ .ok_or_else(|| format!("{path} missing unsigned integer bundleBuild"))+}diff --git a/js/app/tauri/src-tauri/src/lib.rs b/js/app/tauri/src-tauri/src/lib.rsindex f4eb3bd44f..1918be5053 100644--- a/js/app/tauri/src-tauri/src/lib.rs+++ b/js/app/tauri/src-tauri/src/lib.rs@@ -1,6 +1,7 @@use logger::Logger;use macro_bundle_updater_plugin::inbound::plugin::{- PluginService, allow_update_reload_retry, apply_completed_update, retry_waiting_for_wifi,+ allow_update_reload_retry, apply_completed_update_from, retry_waiting_for_wifi,+ start_update_check,};use navigation_plugin::MacroNavigationPlugin;use navigation_plugin::scheme::MacroScheme;@@ -49,6 +50,12 @@ impl AppEnvironment {}}+ fn bundle_update_base_url(self) -> &'static str {+ option_env!("MACRO_BUNDLE_UPDATE_BASE_URL")+ .filter(|url| !url.trim().is_empty())+ .unwrap_or_else(|| self.auth_service_url())+ }+fn web_origin(self) -> &'static str {match self {Self::Development => "https://dev.macro.com",@@ -57,6 +64,12 @@ impl AppEnvironment {}}+fn embedded_bundle_build() -> u64 {+ env!("MACRO_EMBEDDED_BUNDLE_BUILD")+ .parse()+ .expect("MACRO_EMBEDDED_BUNDLE_BUILD must be an unsigned integer")+}+/// This module provides debuging utilities and should not be compiled in prodiction builds#[cfg(debug_assertions)] // do not remove thismod debug;@@ -161,9 +174,10 @@ pub fn run() {.plugin(macro_bundle_updater_plugin::inbound::plugin::MacroBundleUpdaterPlugin::new(AppEnvironment::current()- .auth_service_url()+ .bundle_update_base_url().parse().expect("valid url"),+ embedded_bundle_build(),),);@@ -198,17 +212,7 @@ pub fn run() {move |ctx, request, responder| {let h = handler.get_or_init(|| {- // Restore persisted bundle root before the first request is servedlet app = ctx.app_handle();- if let Ok(cache_dir) = app.path().app_cache_dir() {- tracing::info!("Protocol handler init: cache_dir={cache_dir:?}");- if let Some(s) = app.try_state::<tokio::sync::Mutex<PluginService>>() {- tauri::async_runtime::block_on(async {- let mut service = s.lock().await;- service.load_bundle_root(&cache_dir).await;- });- }- }tauri_protocol::get(app.clone(), &window_origin)});h(ctx.webview_label(), request, responder);@@ -220,6 +224,7 @@ pub fn run() {macro_bundle_updater_plugin::inbound::plugin::perform_update,macro_bundle_updater_plugin::inbound::plugin::ack_bundle_update_reload,macro_bundle_updater_plugin::inbound::plugin::check_for_update,+ macro_bundle_updater_plugin::inbound::plugin::get_bundle_debug_info,macro_bundle_updater_plugin::inbound::plugin::get_bundle_update_status,macro_bundle_updater_plugin::inbound::plugin::clear_bundle,get_pending_share_filenames,@@ -229,20 +234,6 @@ pub fn run() {staged_upload::upload_staged_file_to_presigned_url,]).setup(|app| {- // Restore persisted bundle root on startup- if let Ok(cache_dir) = app.path().app_cache_dir()- && let Some(s) = app.try_state::<tokio::sync::Mutex<PluginService>>()- {- tauri::async_runtime::block_on(async {- let mut service = s.lock().await;- service.load_bundle_root(&cache_dir).await;- tracing::info!(- "Setup: restored bundle root to {:?}",- service.bundle_root_path()- );- });- }-#[cfg(any(target_os = "linux", all(windows, debug_assertions)))]{use tauri_plugin_deep_link::DeepLinkExt;@@ -265,7 +256,7 @@ pub fn run() {{let app = app_handle.clone();tauri::async_runtime::spawn(async move {- match apply_completed_update(&app).await {+ match apply_completed_update_from(&app, "run_event_ready").await {Ok(_) => {}Err(e) => {tracing::error!("Failed to auto-apply bundle update on ready: {e}");@@ -290,14 +281,30 @@ pub fn run() {"Failed to allow bundle update reload retry on resume: {e}");}- match apply_completed_update(&app).await {- Ok(_) => {}+ match apply_completed_update_from(&app, "run_event_resumed").await {+ Ok(true) => {}+ Ok(false) => {+ if let Err(e) = start_update_check(&app).await {+ tracing::error!(+ "Failed to start bundle update check on resume: {e}"+ );+ }+ }Err(e) => {tracing::error!("Failed to auto-apply bundle update: {e}");}}});}+ #[cfg(not(feature = "auto_apply_update"))]+ {+ let app = app_handle.clone();+ tauri::async_runtime::spawn(async move {+ if let Err(e) = start_update_check(&app).await {+ tracing::error!("Failed to start bundle update check on resume: {e}");+ }+ });+ }}_ => {}});diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex f76122230c..c629fd14e2 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -7436,6 +7436,7 @@ dependencies = ["strum","thiserror 2.0.18","tokio",+ "tower 0.5.3","tracing","url",]diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex 66d51a1f11..594d0fcdcf 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -2,7 +2,7 @@use analytics_client::{AnalyticsClient, AnalyticsClientConfig, GoogleAnalyticsConfig, MetaConfig, PostHogConfig,};-use anyhow::Context;+use anyhow::{Context, anyhow};use config::{Config, Environment};use document_storage_service_client::DocumentStorageServiceClient;use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};@@ -319,6 +319,10 @@ async fn main() -> anyhow::Result<()> {referral_service: Arc::new(referral_service),native_app_service: Arc::new(NativeAppServiceImpl {bundle_fetcher: DefaultBundleFetcher::new(config.environment.app()),+ bundle_policy: native_app_service::domain::models::BundleUpdatePolicy::from_env()+ .map_err(|err| {+ anyhow!("failed to load bundle update policy: {err}")+ })?,platform_data: PlatformData {ios_development_team_id: IOS_DEVELOPMENT_TEAM_ID.to_string(),ios_app_bundle_id: IOS_APP_BUNDLE_ID.to_string(),diff --git a/rust/cloud-storage/native_app_service/Cargo.toml b/rust/cloud-storage/native_app_service/Cargo.tomlindex c2c63a8640..a3db9f4dab 100644--- a/rust/cloud-storage/native_app_service/Cargo.toml+++ b/rust/cloud-storage/native_app_service/Cargo.toml@@ -22,3 +22,4 @@ url = { workspace = true, features = ["serde"] }cool_asserts = "2"strum = { workspace = true, features = ["derive"] }tokio = { workspace = true, features = ["macros", "rt"] }+tower = { workspace = true, features = ["util"] }diff --git a/rust/cloud-storage/native_app_service/src/domain/models.rs b/rust/cloud-storage/native_app_service/src/domain/models.rsindex e9eeb9671a..a62074d4bf 100644--- a/rust/cloud-storage/native_app_service/src/domain/models.rs+++ b/rust/cloud-storage/native_app_service/src/domain/models.rs@@ -5,7 +5,7 @@ use url::Url;/// The possible input desktop operating systems/// See https://v2.tauri.app/plugin/updater/#dynamic-update-server-#[derive(Debug, Deserialize, Clone, Copy)]+#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]#[serde(rename_all = "lowercase")]#[cfg_attr(test, derive(strum::EnumIter))]pub enum DesktopTarget {@@ -18,7 +18,7 @@ pub enum DesktopTarget {}/// The possible input mobile operating systems-#[derive(Debug, Deserialize, Clone, Copy)]+#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]#[serde(rename_all = "lowercase")]#[cfg_attr(test, derive(strum::EnumIter))]pub enum MobileTarget {@@ -29,7 +29,7 @@ pub enum MobileTarget {}/// an enumeration of all possible tauri targets-#[derive(Debug, Deserialize, Clone, Copy)]+#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]#[serde(untagged)]pub enum AllTargets {/// desktop operating system@@ -40,7 +40,7 @@ pub enum AllTargets {/// The possible input architechtures/// See https://v2.tauri.app/plugin/updater/#dynamic-update-server-#[derive(Debug, Deserialize, Clone, Copy)]+#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]#[cfg_attr(test, derive(strum::EnumIter))]#[serde(rename_all = "lowercase")]pub enum Arch {@@ -67,11 +67,43 @@ pub struct DesktopUpdate {inner: BundleUpdate,}+/// Metadata generated with each JavaScript bundle build.+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct BundleManifest {+ /// Manifest schema version.+ pub schema_version: u64,+ /// Monotonic JavaScript bundle build number.+ pub bundle_build: u64,+ /// Minimum native app build that can safely run this bundle.+ pub min_native_build: u64,+ /// Short git SHA used to build the bundle.+ pub git_sha: Option<String>,+ /// Application package version used for the bundle.+ pub app_version: String,+}++/// Action returned by the bundle update endpoint.+#[derive(Debug, Serialize)]+#[serde(tag = "action", rename_all = "lowercase")]+pub enum BundleAction {+ /// Download and apply a newer compatible bundle.+ Update(BundleUpdate),+ /// Clear the active cached OTA bundle.+ Clear(BundleClear),+ /// A newer bundle exists, but the requesting native app build is too old.+ #[serde(rename = "native_update_required")]+ NativeUpdateRequired(BundleNativeUpdateRequired),+}+/// a struct which indicates how to update only the javascript bundle of the application#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]pub struct BundleUpdate {- /// the version that we are going to update to- pub(crate) version: semver::Version,+ /// the bundle build that we are going to update to+ pub(crate) bundle_build: u64,+ /// the minimum native build that can run this bundle+ pub(crate) min_native_build: u64,/// some optional notes about the updatepub(crate) notes: Option<String>,/// the fully qualified Url where the update bundle exists@@ -80,6 +112,23 @@ pub struct BundleUpdate {pub(crate) checksum: String,}+/// A response instructing the client to clear the active OTA bundle.+#[derive(Debug, Serialize)]+pub struct BundleClear {+ /// Machine-readable clear reason.+ pub(crate) reason: String,+}++/// A response telling the client a native app update is required before this bundle can run.+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct BundleNativeUpdateRequired {+ /// The newer bundle build that could not be offered.+ pub(crate) bundle_build: u64,+ /// The minimum native build required by that bundle.+ pub(crate) min_native_build: u64,+}+/// The payload to check if there is a native app js bundle update available#[derive(Debug)]pub struct BundleUpdateRequest {@@ -87,12 +136,74 @@ pub struct BundleUpdateRequest {pub target: AllTargets,/// the arch of the targetpub arch: Arch,- /// the current verison of the bundle- pub semver: semver::Version,+ /// the current effective JS bundle build+ pub current_bundle_build: u64,+ /// the native app build number+ pub native_build: u64,+}++/// Server-side compatibility and revocation rules for JS bundle updates.+#[derive(Debug, Default, Clone, Deserialize)]+#[serde(default, rename_all = "camelCase")]+pub struct BundleUpdatePolicy {+ /// Ordered rules evaluated at request time.+ pub rules: Vec<BundlePolicyRule>,+}++/// One server-side policy rule.+#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BundlePolicyRule {+ /// Whether this rule blocks future updates or revokes active bundles.+ pub action: BundlePolicyAction,+ /// Optional target filter.+ pub target: Option<AllTargets>,+ /// Inclusive minimum native build filter.+ pub native_build_gte: Option<u64>,+ /// Inclusive maximum native build filter.+ pub native_build_lte: Option<u64>,+ /// Inclusive minimum bundle build filter.+ pub bundle_build_gte: Option<u64>,+ /// Inclusive maximum bundle build filter.+ pub bundle_build_lte: Option<u64>,+ /// Optional reason returned for revocation rules.+ pub reason: Option<String>,+}++/// Policy action to apply when a rule matches.+#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum BundlePolicyAction {+ /// Prevent a matching deployed bundle from being offered.+ Block,+ /// Clear a matching active bundle from clients.+ Revoke,+}++impl BundlePolicyRule {+ /// Return whether this rule matches the request target, native build, and bundle build.+ pub fn matches(&self, target: AllTargets, native_build: u64, bundle_build: u64) -> bool {+ if self.target.is_some_and(|expected| expected != target) {+ return false;+ }+ if self.native_build_gte.is_some_and(|min| native_build < min) {+ return false;+ }+ if self.native_build_lte.is_some_and(|max| native_build > max) {+ return false;+ }+ if self.bundle_build_gte.is_some_and(|min| bundle_build < min) {+ return false;+ }+ if self.bundle_build_lte.is_some_and(|max| bundle_build > max) {+ return false;+ }+ true+ }}-/// the name of the semver file as it exists in the s3 bucket-pub static SEMVER_FILE_NAME: &str = "/app/semver.txt";+/// the name of the manifest file as it exists in the s3 bucket+pub static BUNDLE_MANIFEST_FILE_NAME: &str = "/app/bundle-manifest.json";/// the name of the bundle file as it exists in the s3 bucketpub static BUNDLE_ARCHIVE_NAME: &str = "/app/app-archive.zip";@@ -102,9 +213,12 @@ pub enum UpdateErr {/// a network error has occirred#[error("A network error occurred")]Network,- /// failed to parse a semver string- #[error("Failed to parse semver")]- Semver,+ /// failed to parse a bundle manifest+ #[error("Failed to parse bundle manifest")]+ Manifest,+ /// failed to parse the update policy+ #[error("Failed to parse bundle update policy")]+ Policy,}/// contains information about bundle ids for various app platformsdiff --git a/rust/cloud-storage/native_app_service/src/domain/ports.rs b/rust/cloud-storage/native_app_service/src/domain/ports.rsindex b233685de8..bca69f98be 100644--- a/rust/cloud-storage/native_app_service/src/domain/ports.rs+++ b/rust/cloud-storage/native_app_service/src/domain/ports.rs@@ -1,30 +1,32 @@-use crate::domain::models::{BundleUpdate, BundleUpdateRequest, PlatformVerifier, UpdateErr};+use crate::domain::models::{+ BundleAction, BundleManifest, BundleUpdateRequest, PlatformVerifier, UpdateErr,+};use rootcause::Report;use url::Url;/// outbound trait for sending network requests to query the bundle state-pub trait GetJsBundleSemver: Send + Sync + 'static {- /// fetch the semver of the current app over the network- fn get_app_semver(+pub trait GetJsBundleManifest: Send + Sync + 'static {+ /// fetch the manifest of the current app bundle over the network+ fn get_app_bundle_manifest(&self,- ) -> impl Future<Output = Result<semver::Version, Report<UpdateErr>>> + Send;+ ) -> impl Future<Output = Result<BundleManifest, Report<UpdateErr>>> + Send;/// get the Url of the bundlefn get_app_bundle_path(&self) -> Url;- /// get the SHA-256 hex digest of the bundle archive for the given version+ /// get the SHA-256 hex digest of the bundle archive for the given bundle buildfn get_app_bundle_checksum(&self,- version: &semver::Version,+ bundle_build: u64,) -> impl Future<Output = Result<String, Report<UpdateErr>>> + Send;}/// the service level trait for dealing with tauri app integrationpub trait NativeAppService: Send + Sync + 'static {- /// returns an `Option<BundleUpdate>` to denote that no errors occurred but there is no+ /// returns an `Option<BundleAction>` to denote that no errors occurred but there is no/// update availablefn get_bundle_update(&self,req: BundleUpdateRequest,- ) -> impl Future<Output = Result<Option<BundleUpdate>, Report<UpdateErr>>> + Send;+ ) -> impl Future<Output = Result<Option<BundleAction>, Report<UpdateErr>>> + Send;/// retrieve the verification payload for some platform Tfn verification_data<T: PlatformVerifier>(&self, req: T) -> T::VerifierPayload;diff --git a/rust/cloud-storage/native_app_service/src/domain/service.rs b/rust/cloud-storage/native_app_service/src/domain/service.rsindex 1c9adb5ccf..301201856b 100644--- a/rust/cloud-storage/native_app_service/src/domain/service.rs+++ b/rust/cloud-storage/native_app_service/src/domain/service.rs@@ -1,72 +1,86 @@use crate::domain::{- models::{BundleUpdate, BundleUpdateRequest, PlatformData, PlatformVerifier, UpdateErr},- ports::{GetJsBundleSemver, NativeAppService},+ models::{+ BundleAction, BundleClear, BundleNativeUpdateRequired, BundlePolicyAction, BundleUpdate,+ BundleUpdatePolicy, BundleUpdateRequest, PlatformData, PlatformVerifier, UpdateErr,+ },+ ports::{GetJsBundleManifest, NativeAppService},};use rootcause::Report;/// the concrete struct which implements [NativeAppService]pub struct NativeAppServiceImpl<T> {- /// the implementation of [GetJsBundleSemver]+ /// the implementation of [GetJsBundleManifest]pub bundle_fetcher: T,+ /// server-side compatibility and revocation rules+ pub bundle_policy: BundleUpdatePolicy,/// the platform data for various platformspub platform_data: PlatformData,}impl<T> NativeAppService for NativeAppServiceImpl<T>where- T: GetJsBundleSemver,+ T: GetJsBundleManifest,{#[tracing::instrument(err, skip(self))]async fn get_bundle_update(&self,req: BundleUpdateRequest,- ) -> Result<Option<BundleUpdate>, Report<UpdateErr>> {+ ) -> Result<Option<BundleAction>, Report<UpdateErr>> {let BundleUpdateRequest {- target: _,+ target,arch: _,- semver: cur_ver,+ current_bundle_build,+ native_build,} = req;- let most_recent = self.bundle_fetcher.get_app_semver().await?;- if needs_update(&most_recent, &cur_ver) {- let checksum = self- .bundle_fetcher- .get_app_bundle_checksum(&most_recent)- .await?;- return Ok(Some(BundleUpdate {- version: most_recent,- notes: None,- url: self.bundle_fetcher.get_app_bundle_path(),- checksum,- }));+ let manifest = self.bundle_fetcher.get_app_bundle_manifest().await?;++ if let Some(rule) = self.bundle_policy.rules.iter().find(|rule| {+ rule.action == BundlePolicyAction::Revoke+ && rule.matches(target, native_build, current_bundle_build)+ }) {+ return Ok(Some(BundleAction::Clear(BundleClear {+ reason: rule+ .reason+ .clone()+ .unwrap_or_else(|| "bundle_revoked".to_string()),+ })));+ }++ if manifest.bundle_build <= current_bundle_build {+ return Ok(None);}- Ok(None)+ if manifest.min_native_build > native_build {+ return Ok(Some(BundleAction::NativeUpdateRequired(+ BundleNativeUpdateRequired {+ bundle_build: manifest.bundle_build,+ min_native_build: manifest.min_native_build,+ },+ )));+ }++ if self.bundle_policy.rules.iter().any(|rule| {+ rule.action == BundlePolicyAction::Block+ && rule.matches(target, native_build, manifest.bundle_build)+ }) {+ return Ok(None);+ }++ let checksum = self+ .bundle_fetcher+ .get_app_bundle_checksum(manifest.bundle_build)+ .await?;+ Ok(Some(BundleAction::Update(BundleUpdate {+ bundle_build: manifest.bundle_build,+ min_native_build: manifest.min_native_build,+ notes: None,+ url: self.bundle_fetcher.get_app_bundle_path(),+ checksum,+ })))}fn verification_data<P: PlatformVerifier>(&self, req: P) -> P::VerifierPayload {req.get_payload(&self.platform_data)}}--/// Check whether the client should update to `latest` from `current`.-///-/// The `semver` crate's derived `Ord` includes build metadata in the-/// comparison, but for update purposes we follow the semver 2.0 spec:-/// compare by precedence (major.minor.patch.pre) only. When precedence-/// is equal, trigger an update if build metadata differs — each deploy-/// produces a unique build metadata tag (the short commit SHA).-pub(crate) fn needs_update(latest: &semver::Version, current: &semver::Version) -> bool {- let precedence = latest- .major- .cmp(¤t.major)- .then(latest.minor.cmp(¤t.minor))- .then(latest.patch.cmp(¤t.patch))- .then(latest.pre.cmp(¤t.pre));-- match precedence {- std::cmp::Ordering::Greater => true,- std::cmp::Ordering::Less => false,- std::cmp::Ordering::Equal => latest.build != current.build,- }-}diff --git a/rust/cloud-storage/native_app_service/src/inbound.rs b/rust/cloud-storage/native_app_service/src/inbound.rsindex 4997c41b94..901ef13c60 100644--- a/rust/cloud-storage/native_app_service/src/inbound.rs+++ b/rust/cloud-storage/native_app_service/src/inbound.rs@@ -4,12 +4,13 @@ use axum::Json;use axum::response::IntoResponse;use axum::{Router,- extract::{Path, State},+ extract::{Path, Query, State},routing::get,};+use serde::Deserialize;use crate::domain::models::{- AllTargets, Arch, BundleUpdate, BundleUpdateRequest, DesktopTarget, DesktopUpdate, IOSVerifier,+ AllTargets, Arch, BundleAction, BundleUpdateRequest, DesktopTarget, DesktopUpdate, IOSVerifier,};use crate::domain::ports::NativeAppService;@@ -35,7 +36,7 @@ pub fn native_app_router<S: NativeAppService, T>(state: RouterState<S>) -> Routeget(desktop_update_handler),).route(- "/update/bundle/{all_target}/{arch}/{current_version}",+ "/update/bundle/{all_target}/{arch}",get(bundle_update_handler),).route(@@ -54,14 +55,16 @@ async fn desktop_update_handler(async fn bundle_update_handler<S: NativeAppService>(State(s): State<RouterState<S>>,- Path((target, arch, semver)): Path<(AllTargets, Arch, semver::Version)>,-) -> UpdateResult<Json<BundleUpdate>> {+ Path((target, arch)): Path<(AllTargets, Arch)>,+ Query(query): Query<BundleUpdateQuery>,+) -> UpdateResult<Json<BundleAction>> {match s.inner.get_bundle_update(BundleUpdateRequest {target,arch,- semver,+ current_bundle_build: query.current_bundle_build,+ native_build: query.native_build,}).await{@@ -70,6 +73,12 @@ async fn bundle_update_handler<S: NativeAppService>(}}+#[derive(Debug, Deserialize)]+struct BundleUpdateQuery {+ current_bundle_build: u64,+ native_build: u64,+}+#[derive(Debug)]enum UpdateResult<T> {UpdateFound(T),diff --git a/rust/cloud-storage/native_app_service/src/outbound.rs b/rust/cloud-storage/native_app_service/src/outbound.rsindex 97722c77e6..daa52a0e83 100644--- a/rust/cloud-storage/native_app_service/src/outbound.rs+++ b/rust/cloud-storage/native_app_service/src/outbound.rs@@ -1,25 +1,48 @@use crate::domain::{- models::{BUNDLE_ARCHIVE_NAME, SEMVER_FILE_NAME, UpdateErr},- ports::GetJsBundleSemver,+ models::{+ BUNDLE_ARCHIVE_NAME, BUNDLE_MANIFEST_FILE_NAME, BundleManifest, BundleUpdatePolicy,+ UpdateErr,+ },+ ports::GetJsBundleManifest,};use futures::StreamExt;use rootcause::{Report, prelude::ResultExt};use sha2::{Digest, Sha256};-use std::str::FromStr;use tokio::sync::RwLock;use url::Url;+struct BundleChecksumCache {+ inner: RwLock<Option<(u64, String)>>,+}++impl BundleChecksumCache {+ fn new() -> Self {+ Self {+ inner: RwLock::new(None),+ }+ }++ async fn get(&self, bundle_build: u64) -> Option<String> {+ let (cached_build, cached_checksum) = self.inner.read().await.as_ref()?.clone();+ (cached_build == bundle_build).then_some(cached_checksum)+ }++ async fn set(&self, bundle_build: u64, checksum: String) {+ *self.inner.write().await = Some((bundle_build, checksum));+ }+}+/// unit struct to define the default behaviour of the service/// (not mocked service)pub struct DefaultBundleFetcher {/// the base url of the frontend apppub base_url: Url,- /// the file name of the semver file in the js app s3 bucket- pub semver_file_name: &'static str,+ /// the file name of the bundle manifest in the js app s3 bucket+ pub manifest_file_name: &'static str,/// the name of the bundle archive on the s3 bucketpub bundle_archive_name: &'static str,- /// cached (version, checksum) to avoid re-downloading the bundle- checksum_cache: RwLock<Option<(semver::Version, String)>>,+ /// cached (bundle build, checksum) to avoid re-downloading the bundle+ checksum_cache: BundleChecksumCache,}impl DefaultBundleFetcher {@@ -27,9 +50,9 @@ impl DefaultBundleFetcher {pub fn new(base_url: Url) -> Self {Self {base_url,- semver_file_name: SEMVER_FILE_NAME,+ manifest_file_name: BUNDLE_MANIFEST_FILE_NAME,bundle_archive_name: BUNDLE_ARCHIVE_NAME,- checksum_cache: RwLock::new(None),+ checksum_cache: BundleChecksumCache::new(),}}@@ -50,10 +73,10 @@ impl DefaultBundleFetcher {}}-impl GetJsBundleSemver for DefaultBundleFetcher {+impl GetJsBundleManifest for DefaultBundleFetcher {#[tracing::instrument(skip(self), ret, err)]- async fn get_app_semver(&self) -> Result<semver::Version, Report<UpdateErr>> {- let url = self.base_url.join(self.semver_file_name).unwrap();+ async fn get_app_bundle_manifest(&self) -> Result<BundleManifest, Report<UpdateErr>> {+ let url = self.base_url.join(self.manifest_file_name).unwrap();let res = reqwest::get(url).await.context(UpdateErr::Network)?@@ -62,8 +85,7 @@ impl GetJsBundleSemver for DefaultBundleFetcher {.text().await.context(UpdateErr::Network)?;- let cur_ver = semver::Version::from_str(res.trim()).context(UpdateErr::Semver)?;- Ok(cur_ver)+ serde_json::from_str(&res).context(UpdateErr::Manifest)}fn get_app_bundle_path(&self) -> Url {@@ -73,17 +95,49 @@ impl GetJsBundleSemver for DefaultBundleFetcher {#[tracing::instrument(skip(self), ret, err)]async fn get_app_bundle_checksum(&self,- version: &semver::Version,+ bundle_build: u64,) -> Result<String, Report<UpdateErr>> {- // return cached checksum if version matches- if let Some((cached_ver, cached_checksum)) = self.checksum_cache.read().await.as_ref()- && cached_ver == version- {- return Ok(cached_checksum.clone());+ // return cached checksum if bundle build matches+ if let Some(cached_checksum) = self.checksum_cache.get(bundle_build).await {+ return Ok(cached_checksum);}let checksum = self.compute_checksum().await?;- *self.checksum_cache.write().await = Some((version.clone(), checksum.clone()));+ self.checksum_cache+ .set(bundle_build, checksum.clone())+ .await;Ok(checksum)}}++impl BundleUpdatePolicy {+ /// Load bundle update policy from `BUNDLE_UPDATE_POLICY_JSON` or `BUNDLE_UPDATE_POLICY_FILE`.+ pub fn from_env() -> Result<Self, Report<UpdateErr>> {+ if let Ok(json) = std::env::var("BUNDLE_UPDATE_POLICY_JSON") {+ return serde_json::from_str(&json).context(UpdateErr::Policy);+ }+ if let Ok(path) = std::env::var("BUNDLE_UPDATE_POLICY_FILE") {+ let json = std::fs::read_to_string(path).context(UpdateErr::Policy)?;+ return serde_json::from_str(&json).context(UpdateErr::Policy);+ }+ Ok(Self::default())+ }+}++#[cfg(test)]+mod tests {+ use super::BundleChecksumCache;++ #[tokio::test]+ async fn checksum_cache_is_keyed_by_bundle_build() {+ let cache = BundleChecksumCache::new();++ cache.set(100, "checksum-100".to_string()).await;+ assert_eq!(cache.get(100).await.as_deref(), Some("checksum-100"));+ assert_eq!(cache.get(101).await, None);++ cache.set(101, "checksum-101".to_string()).await;+ assert_eq!(cache.get(100).await, None);+ assert_eq!(cache.get(101).await.as_deref(), Some("checksum-101"));+ }+}diff --git a/rust/cloud-storage/native_app_service/src/tests.rs b/rust/cloud-storage/native_app_service/src/tests.rsindex 8919457a07..4920d0e324 100644--- a/rust/cloud-storage/native_app_service/src/tests.rs+++ b/rust/cloud-storage/native_app_service/src/tests.rs@@ -2,19 +2,28 @@ use crate::{domain::{self,models::{- AllTargets, Arch, BundleUpdate, DesktopTarget, MobileTarget, PlatformData, UpdateErr,+ AllTargets, Arch, BundleAction, BundleManifest, BundlePolicyAction, BundlePolicyRule,+ BundleUpdatePolicy, DesktopTarget, MobileTarget, PlatformData, UpdateErr,},- ports::{GetJsBundleSemver, NativeAppService},- service::{self, NativeAppServiceImpl},+ ports::{GetJsBundleManifest, NativeAppService},+ service::NativeAppServiceImpl,},+ inbound::{RouterState, native_app_router},outbound::DefaultBundleFetcher,};+use axum::{+ body::Body,+ http::{Request, StatusCode},+};+use cool_asserts::assert_matches;use reqwest::Url;use rootcause::Report;--use cool_asserts::assert_matches;-use semver::Version;+use std::{+ sync::{Arc, Mutex},+ time::{SystemTime, UNIX_EPOCH},+};use strum::IntoEnumIterator;+use tower::ServiceExt;#[test]fn all_urls_work() {@@ -23,11 +32,57 @@ fn all_urls_work() {assert_eq!(url.as_str(), "https://macro.com/app/app-archive.zip");}-struct MockBundleFetcher;+struct MockBundleFetcher {+ manifest: BundleManifest,+}++impl MockBundleFetcher {+ fn new(bundle_build: u64, min_native_build: u64) -> Self {+ Self {+ manifest: BundleManifest {+ schema_version: 2,+ bundle_build,+ min_native_build,+ git_sha: Some("abc123".to_string()),+ app_version: "2.5.0".to_string(),+ },+ }+ }+}++static POLICY_ENV_LOCK: Mutex<()> = Mutex::new(());++struct PolicyEnvGuard {+ json: Option<String>,+ file: Option<String>,+}++impl PolicyEnvGuard {+ fn capture() -> Self {+ Self {+ json: std::env::var("BUNDLE_UPDATE_POLICY_JSON").ok(),+ file: std::env::var("BUNDLE_UPDATE_POLICY_FILE").ok(),+ }+ }+}++impl Drop for PolicyEnvGuard {+ fn drop(&mut self) {+ restore_env_var("BUNDLE_UPDATE_POLICY_JSON", self.json.as_deref());+ restore_env_var("BUNDLE_UPDATE_POLICY_FILE", self.file.as_deref());+ }+}-impl GetJsBundleSemver for MockBundleFetcher {- async fn get_app_semver(&self) -> Result<semver::Version, Report<UpdateErr>> {- Ok("1.1.1".parse().unwrap())+fn restore_env_var(name: &str, value: Option<&str>) {+ match value {+ Some(value) => unsafe { std::env::set_var(name, value) },+ None => unsafe { std::env::remove_var(name) },+ }+}++impl GetJsBundleManifest for MockBundleFetcher {+ async fn get_app_bundle_manifest(&self) -> Result<BundleManifest, Report<UpdateErr>> {+ Ok(self.manifest.clone())}fn get_app_bundle_path(&self) -> Url {@@ -36,7 +91,7 @@ impl GetJsBundleSemver for MockBundleFetcher {async fn get_app_bundle_checksum(&self,- _version: &semver::Version,+ _bundle_build: u64,) -> Result<String, Report<UpdateErr>> {Ok("abc123".to_string())}@@ -49,235 +104,298 @@ fn mock_platform_data() -> PlatformData {}}-#[tokio::test]-async fn it_should_not_downgrade_mobile() {- let semver: Version = "1.2.1".parse().unwrap();-- let service = NativeAppServiceImpl {- bundle_fetcher: MockBundleFetcher,+fn service(+ bundle_build: u64,+ min_native_build: u64,+ bundle_policy: BundleUpdatePolicy,+) -> NativeAppServiceImpl<MockBundleFetcher> {+ NativeAppServiceImpl {+ bundle_fetcher: MockBundleFetcher::new(bundle_build, min_native_build),+ bundle_policy,platform_data: mock_platform_data(),- };-- let iter = MobileTarget::iter().flat_map(move |target| {- let semver = semver.clone();- Arch::iter().map(move |arch| (AllTargets::Mobile(target), arch, semver.clone()))- });+ }+}- for (target, arch, semver) in iter {- assert_matches!(- service- .get_bundle_update(domain::models::BundleUpdateRequest {- target,- arch,- semver,- })- .await,- Ok(None)- );+fn request(+ target: AllTargets,+ arch: Arch,+ current_bundle_build: u64,+ native_build: u64,+) -> domain::models::BundleUpdateRequest {+ domain::models::BundleUpdateRequest {+ target,+ arch,+ current_bundle_build,+ native_build,}}#[tokio::test]-async fn it_should_upgrade_mobile() {- let semver: Version = "1.0.1".parse().unwrap();+async fn returns_update_when_deployed_bundle_is_newer() {+ let service = service(20, 0, BundleUpdatePolicy::default());- let service = NativeAppServiceImpl {- bundle_fetcher: MockBundleFetcher,- platform_data: mock_platform_data(),- };+ assert_matches!(+ service+ .get_bundle_update(request(+ AllTargets::Mobile(MobileTarget::Ios),+ Arch::Aarch64,+ 10,+ 100,+ ))+ .await,+ Ok(Some(BundleAction::Update(update))) => {+ assert_eq!(update.bundle_build, 20);+ assert_eq!(update.min_native_build, 0);+ assert_eq!(update.url.as_str(), "https://example.com/");+ assert_eq!(update.checksum, "abc123");+ }+ );+}- let iter = MobileTarget::iter().flat_map(move |target| {- let semver = semver.clone();- Arch::iter().map(move |arch| (AllTargets::Mobile(target), arch, semver.clone()))- });+#[tokio::test]+async fn returns_none_when_deployed_bundle_is_equal_or_older() {+ let service = service(20, 0, BundleUpdatePolicy::default());- for (target, arch, semver) in iter {+ for current_bundle_build in [20, 21] {assert_matches!(service- .get_bundle_update(domain::models::BundleUpdateRequest {- target,- arch,- semver,- })+ .get_bundle_update(request(+ AllTargets::Mobile(MobileTarget::Ios),+ Arch::Aarch64,+ current_bundle_build,+ 100,+ )).await,- Ok(Some(BundleUpdate { version, notes: _, url, checksum })) => {- assert_eq!(version.to_string(), "1.1.1");- assert_eq!(url.as_str(), "https://example.com/");- assert_eq!(checksum, "abc123");- }+ Ok(None));}}#[tokio::test]-async fn it_should_not_downgrade_desktop() {- let semver: Version = "1.2.1".parse().unwrap();+async fn returns_native_update_required_when_newer_bundle_requires_too_new_native_build() {+ let service = service(20, 200, BundleUpdatePolicy::default());- let service = NativeAppServiceImpl {- bundle_fetcher: MockBundleFetcher,- platform_data: mock_platform_data(),- };+ assert_matches!(+ service+ .get_bundle_update(request(+ AllTargets::Mobile(MobileTarget::Ios),+ Arch::Aarch64,+ 10,+ 199,+ ))+ .await,+ Ok(Some(BundleAction::NativeUpdateRequired(required))) => {+ assert_eq!(required.bundle_build, 20);+ assert_eq!(required.min_native_build, 200);+ }+ );+}- let iter = DesktopTarget::iter().flat_map(move |target| {- let semver = semver.clone();- Arch::iter().map(move |arch| (AllTargets::Desktop(target), arch, semver.clone()))- });+#[tokio::test]+async fn policy_blocks_updates_for_matching_target_native_and_bundle_ranges() {+ let service = service(+ 20,+ 0,+ BundleUpdatePolicy {+ rules: vec![BundlePolicyRule {+ action: BundlePolicyAction::Block,+ target: Some(AllTargets::Mobile(MobileTarget::Ios)),+ native_build_gte: None,+ native_build_lte: Some(142),+ bundle_build_gte: Some(20),+ bundle_build_lte: None,+ reason: Some("ios_142_breakage".to_string()),+ }],+ },+ );- for (target, arch, semver) in iter {- assert_matches!(- service- .get_bundle_update(domain::models::BundleUpdateRequest {- target,- arch,- semver,- })- .await,- Ok(None)- );- }+ assert_matches!(+ service+ .get_bundle_update(request(+ AllTargets::Mobile(MobileTarget::Ios),+ Arch::Aarch64,+ 10,+ 142,+ ))+ .await,+ Ok(None)+ );}#[tokio::test]-async fn it_should_upgrade_desktop() {- let semver: Version = "1.0.1".parse().unwrap();-- let service = NativeAppServiceImpl {- bundle_fetcher: MockBundleFetcher,- platform_data: mock_platform_data(),- };+async fn policy_returns_clear_when_current_active_bundle_is_revoked() {+ let service = service(+ 20,+ 0,+ BundleUpdatePolicy {+ rules: vec![BundlePolicyRule {+ action: BundlePolicyAction::Revoke,+ target: Some(AllTargets::Mobile(MobileTarget::Ios)),+ native_build_gte: None,+ native_build_lte: Some(142),+ bundle_build_gte: Some(15),+ bundle_build_lte: Some(15),+ reason: Some("bundle_revoked".to_string()),+ }],+ },+ );- let iter = DesktopTarget::iter().flat_map(move |target| {- let semver = semver.clone();- Arch::iter().map(move |arch| (AllTargets::Desktop(target), arch, semver.clone()))- });+ assert_matches!(+ service+ .get_bundle_update(request(+ AllTargets::Mobile(MobileTarget::Ios),+ Arch::Aarch64,+ 15,+ 142,+ ))+ .await,+ Ok(Some(BundleAction::Clear(clear))) => {+ assert_eq!(clear.reason, "bundle_revoked");+ }+ );+}- for (target, arch, semver) in iter {- assert_matches!(- service- .get_bundle_update(domain::models::BundleUpdateRequest {- target,- arch,- semver,- })- .await,- Ok(Some(BundleUpdate { version, notes: _, url, checksum })) => {- assert_eq!(version.to_string(), "1.1.1");- assert_eq!(url.as_str(), "https://example.com/");- assert_eq!(checksum, "abc123");- }- );+#[tokio::test]+async fn all_targets_can_receive_manifest_updates() {+ let service = service(20, 0, BundleUpdatePolicy::default());++ let mobile = MobileTarget::iter()+ .map(AllTargets::Mobile)+ .chain(DesktopTarget::iter().map(AllTargets::Desktop));++ for target in mobile {+ for arch in Arch::iter() {+ assert_matches!(+ service+ .get_bundle_update(request(target, arch, 10, 100))+ .await,+ Ok(Some(BundleAction::Update(update))) => {+ assert_eq!(update.bundle_build, 20);+ }+ );+ }}}-#[test]-fn needs_update_higher_version() {- let latest: Version = "2.0.0".parse().unwrap();- let current: Version = "1.0.0".parse().unwrap();- assert!(service::needs_update(&latest, ¤t));-}+#[tokio::test]+async fn route_returns_update_for_bundle_query_parameters() {+ let service = service(20, 0, BundleUpdatePolicy::default());+ let app = native_app_router::<_, ()>(RouterState {+ inner: Arc::new(service),+ });-#[test]-fn needs_update_same_version_no_metadata() {- let latest: Version = "1.0.0".parse().unwrap();- let current: Version = "1.0.0".parse().unwrap();- assert!(!service::needs_update(&latest, ¤t));+ let response = app+ .oneshot(+ Request::builder()+ .uri("/update/bundle/ios/aarch64?current_bundle_build=10&native_build=142")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);++ let body = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let body: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(body["action"], "update");+ assert_eq!(body["bundleBuild"], 20);+ assert_eq!(body["minNativeBuild"], 0);+ assert_eq!(body["checksum"], "abc123");}-#[test]-fn needs_update_same_version_different_build_metadata() {- let latest: Version = "1.0.0+abc1234".parse().unwrap();- let current: Version = "1.0.0+def5678".parse().unwrap();- assert!(service::needs_update(&latest, ¤t));-}+#[tokio::test]+async fn route_returns_204_when_no_bundle_action_is_needed() {+ let service = service(20, 0, BundleUpdatePolicy::default());+ let app = native_app_router::<_, ()>(RouterState {+ inner: Arc::new(service),+ });-#[test]-fn needs_update_same_version_same_build_metadata() {- let latest: Version = "1.0.0+abc1234".parse().unwrap();- let current: Version = "1.0.0+abc1234".parse().unwrap();- assert!(!service::needs_update(&latest, ¤t));+ let response = app+ .oneshot(+ Request::builder()+ .uri("/update/bundle/ios/aarch64?current_bundle_build=20&native_build=142")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::NO_CONTENT);}-#[test]-fn needs_update_latest_has_metadata_current_does_not() {- let latest: Version = "1.0.0+abc1234".parse().unwrap();- let current: Version = "1.0.0".parse().unwrap();- assert!(service::needs_update(&latest, ¤t));-}+#[tokio::test]+async fn route_returns_native_update_required_for_incompatible_newer_bundle() {+ let service = service(20, 200, BundleUpdatePolicy::default());+ let app = native_app_router::<_, ()>(RouterState {+ inner: Arc::new(service),+ });-#[test]-fn needs_update_build_metadata_order_does_not_matter() {- let a: Version = "1.0.0+aaaa".parse().unwrap();- let z: Version = "1.0.0+zzzz".parse().unwrap();- assert!(service::needs_update(&a, &z));- assert!(service::needs_update(&z, &a));+ let response = app+ .oneshot(+ Request::builder()+ .uri("/update/bundle/ios/aarch64?current_bundle_build=10&native_build=142")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);++ let body = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let body: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(body["action"], "native_update_required");+ assert_eq!(body["bundleBuild"], 20);+ assert_eq!(body["minNativeBuild"], 200);}#[test]-fn needs_update_should_not_downgrade() {- let latest: Version = "1.0.0+abc1234".parse().unwrap();- let current: Version = "2.0.0".parse().unwrap();- assert!(!service::needs_update(&latest, ¤t));+fn missing_policy_env_falls_back_to_default_policy() {+ with_policy_env(None, None, || {+ let policy = BundleUpdatePolicy::from_env().unwrap();+ assert!(policy.rules.is_empty());+ });}-struct MockBundleFetcherWithBuild;--impl GetJsBundleSemver for MockBundleFetcherWithBuild {- async fn get_app_semver(&self) -> Result<semver::Version, Report<UpdateErr>> {- Ok("1.1.1+abc1234".parse().unwrap())- }-- fn get_app_bundle_path(&self) -> Url {- "https://example.com".parse().unwrap()- }-- async fn get_app_bundle_checksum(- &self,- _version: &semver::Version,- ) -> Result<String, Report<UpdateErr>> {- Ok("abc123".to_string())- }+#[test]+fn malformed_policy_json_fails_to_load() {+ with_policy_env(Some("{not json"), None, || {+ assert!(BundleUpdatePolicy::from_env().is_err());+ });}-#[tokio::test]-async fn it_should_upgrade_when_build_metadata_differs() {- let semver: Version = "1.1.1+old5678".parse().unwrap();-- let service = NativeAppServiceImpl {- bundle_fetcher: MockBundleFetcherWithBuild,- platform_data: mock_platform_data(),- };-- assert_matches!(- service- .get_bundle_update(domain::models::BundleUpdateRequest {- target: AllTargets::Desktop(DesktopTarget::Darwin),- arch: Arch::Aarch64,- semver,- })- .await,- Ok(Some(BundleUpdate { version, .. })) => {- assert_eq!(version.to_string(), "1.1.1+abc1234");- }+#[test]+fn missing_policy_file_fails_to_load() {+ let missing_path = format!(+ "/tmp/macro-missing-bundle-policy-{}.json",+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos());+ with_policy_env(None, Some(&missing_path), || {+ assert!(BundleUpdatePolicy::from_env().is_err());+ });}-#[tokio::test]-async fn it_should_not_upgrade_when_build_metadata_matches() {- let semver: Version = "1.1.1+abc1234".parse().unwrap();-- let service = NativeAppServiceImpl {- bundle_fetcher: MockBundleFetcherWithBuild,- platform_data: mock_platform_data(),- };+fn with_policy_env(json: Option<&str>, file: Option<&str>, test: impl FnOnce()) {+ let _guard = POLICY_ENV_LOCK.lock().unwrap();+ let _env_guard = PolicyEnvGuard::capture();+ unsafe {+ std::env::remove_var("BUNDLE_UPDATE_POLICY_JSON");+ std::env::remove_var("BUNDLE_UPDATE_POLICY_FILE");+ if let Some(json) = json {+ std::env::set_var("BUNDLE_UPDATE_POLICY_JSON", json);+ }+ if let Some(file) = file {+ std::env::set_var("BUNDLE_UPDATE_POLICY_FILE", file);+ }+ }- assert_matches!(- service- .get_bundle_update(domain::models::BundleUpdateRequest {- target: AllTargets::Desktop(DesktopTarget::Darwin),- arch: Arch::Aarch64,- semver,- })- .await,- Ok(None)- );+ test();}diff --git a/rust/cloud-storage/tools/native_app_server/src/main.rs b/rust/cloud-storage/tools/native_app_server/src/main.rsindex 2ceeefaeb1..2c78799eb6 100644--- a/rust/cloud-storage/tools/native_app_server/src/main.rs+++ b/rust/cloud-storage/tools/native_app_server/src/main.rs@@ -3,8 +3,8 @@ use std::sync::Arc;use native_app_service::{domain::{- models::{PlatformData, UpdateErr},- ports::GetJsBundleSemver,+ models::{BundleManifest, BundleUpdatePolicy, PlatformData, UpdateErr},+ ports::GetJsBundleManifest,service::NativeAppServiceImpl,},inbound::{RouterState, native_app_router},@@ -15,7 +15,7 @@ use tokio::io::AsyncReadExt;use tower_http::services::ServeFile;use url::Url;-/// Bundle fetcher that always reports a very high version, forcing an update.+/// Bundle fetcher that always reports a very high bundle build, forcing an update./// The checksum is recomputed from the archive on disk each time it is/// requested, so rebuilding the archive doesn't require restarting the server.struct AlwaysUpdateFetcher {@@ -23,9 +23,15 @@ struct AlwaysUpdateFetcher {archive_path: PathBuf,}-impl GetJsBundleSemver for AlwaysUpdateFetcher {- async fn get_app_semver(&self) -> Result<semver::Version, Report<UpdateErr>> {- Ok(semver::Version::new(999, 0, 0))+impl GetJsBundleManifest for AlwaysUpdateFetcher {+ async fn get_app_bundle_manifest(&self) -> Result<BundleManifest, Report<UpdateErr>> {+ Ok(BundleManifest {+ schema_version: 2,+ bundle_build: 999_000_000_000,+ min_native_build: 0,+ git_sha: None,+ app_version: "999.0.0".to_string(),+ })}fn get_app_bundle_path(&self) -> Url {@@ -34,7 +40,7 @@ impl GetJsBundleSemver for AlwaysUpdateFetcher {async fn get_app_bundle_checksum(&self,- _version: &semver::Version,+ _bundle_build: u64,) -> Result<String, Report<UpdateErr>> {sha256_hex(&self.archive_path).await.map_err(|e| {tracing::error!(error=?e, path=?self.archive_path, "failed to hash bundle archive");@@ -74,6 +80,7 @@ async fn main() {bundle_url,archive_path: PathBuf::from(ARCHIVE_PATH),},+ bundle_policy: BundleUpdatePolicy::default(),platform_data: PlatformData {ios_development_team_id: String::new(),ios_app_bundle_id: String::new(),