Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Android 05: harden offline account isolation and OTA recovery (#7303)

Peter Chinman5e80fcd92551
diff --git a/Cargo.lock b/Cargo.lock
index f8875618aa..fab57d3179 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -12852,13 +12852,16 @@ dependencies = [
"native_app_service",
"rootcause",
"semver",
+ "serde_json",
"sha2 0.10.9",
+ "tempfile",
"tokio",
"tower-http",
"tracing",
"tracing-subscriber",
"url",
"workspace-hack",
+ "zip 2.4.2",
]
[[package]]
diff --git a/apps/web/scripts/write-bundle-manifest.mjs b/apps/web/scripts/write-bundle-manifest.mjs
index 13f244fc63..ee115288ce 100644
--- a/apps/web/scripts/write-bundle-manifest.mjs
+++ b/apps/web/scripts/write-bundle-manifest.mjs
@@ -12,7 +12,9 @@ function parseBuildNumber(name, fallback) {
if (!/^\d+$/.test(value)) {
throw new Error(`${name} must be an unsigned integer, got ${JSON.stringify(value)}`);
}
- return Number(value);
+ const parsed = Number(value);
+ if (!Number.isSafeInteger(parsed)) throw new Error(`${name} exceeds safe integer range`);
+ return parsed;
}
function gitSha() {
@@ -27,10 +29,21 @@ function gitSha() {
}
}
+const androidMinimum = parseBuildNumber('MIN_NATIVE_BUILD_ANDROID', undefined);
+const iosMinimum = parseBuildNumber('MIN_NATIVE_BUILD_IOS', undefined);
+if ((androidMinimum === undefined) !== (iosMinimum === undefined)) {
+ throw new Error('Set both MIN_NATIVE_BUILD_ANDROID and MIN_NATIVE_BUILD_IOS');
+}
+const platformMinima = androidMinimum === undefined ? undefined : {
+ android: androidMinimum,
+ ios: iosMinimum,
+};
+
const manifest = {
- schemaVersion: 2,
+ schemaVersion: platformMinima ? 3 : 2,
bundleBuild: parseBuildNumber('BUNDLE_BUILD_NUMBER', Date.now()),
minNativeBuild: parseBuildNumber('MIN_NATIVE_BUILD', 0),
+ ...(platformMinima ? { minNativeBuilds: platformMinima } : {}),
gitSha: gitSha(),
appVersion: packageJson.version,
};
diff --git a/apps/web/scripts/write-bundle-manifest.test.mjs b/apps/web/scripts/write-bundle-manifest.test.mjs
new file mode 100644
index 0000000000..ae18486e2b
--- /dev/null
+++ b/apps/web/scripts/write-bundle-manifest.test.mjs
@@ -0,0 +1,34 @@
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, readFileSync, copyFileSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+
+function build(env) {
+ const dir = mkdtempSync(join(tmpdir(), 'macro-manifest-'));
+ try {
+ mkdirSync(join(dir, 'scripts'));
+ mkdirSync(join(dir, 'dist'));
+ copyFileSync(new URL('./write-bundle-manifest.mjs', import.meta.url), join(dir, 'scripts/build.mjs'));
+ writeFileSync(join(dir, 'package.json'), '{"version":"2.5.0"}');
+ writeFileSync(join(dir, 'dist/index.html'), '__MACRO_BUNDLE_BUILD__');
+ execFileSync(process.execPath, [join(dir, 'scripts/build.mjs')], { env: { PATH: process.env.PATH, BUNDLE_BUILD_NUMBER: '20', ...env }, stdio: 'pipe' });
+ return JSON.parse(readFileSync(join(dir, 'dist/bundle-manifest.json'), 'utf8'));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+test('independent mobile minima use a schema older updaters reject', () => {
+ const manifest = build({ MIN_NATIVE_BUILD_ANDROID: '2050001', MIN_NATIVE_BUILD_IOS: '184' });
+ assert.equal(manifest.schemaVersion, 3);
+ assert.deepEqual(manifest.minNativeBuilds, { android: 2050001, ios: 184 });
+});
+test('incomplete or unsafe minima fail the build', () => {
+ assert.throws(() => build({ MIN_NATIVE_BUILD_ANDROID: '2' }));
+ assert.throws(() => build({ MIN_NATIVE_BUILD_ANDROID: '9007199254740992', MIN_NATIVE_BUILD_IOS: '1' }));
+});
+test('legacy manifests retain schema 2', () => {
+ assert.equal(build({ MIN_NATIVE_BUILD: '5' }).schemaVersion, 2);
+});
diff --git a/apps/web/src/features/agents-view/primitives/composer-draft.test.ts b/apps/web/src/features/agents-view/primitives/composer-draft.test.ts
index b99394c344..63e50d3ac9 100644
--- a/apps/web/src/features/agents-view/primitives/composer-draft.test.ts
+++ b/apps/web/src/features/agents-view/primitives/composer-draft.test.ts
@@ -2,7 +2,7 @@
* @vitest-environment jsdom
*/
-import { createRoot } from 'solid-js';
+import { createRoot, createSignal } from 'solid-js';
import { beforeEach, describe, expect, it } from 'vitest';
import {
createPersistedComposerDraft,
@@ -11,24 +11,81 @@ import {
} from './composer-draft';
describe('createPersistedComposerDraft', () => {
+ it('never restores shared storage and follows a late or changed identity', () => {
+ localStorage.setItem(
+ NEW_CONVERSATION_DRAFT_KEY,
+ JSON.stringify('legacy secret')
+ );
+ createRoot((dispose) => {
+ const [identity, setIdentity] = createSignal<string>();
+ const draft = createPersistedComposerDraft(undefined, identity);
+ expect(draft.draft()).toBe('');
+ draft.setDraft('anonymous memory only');
+ expect(localStorage.getItem(`${NEW_CONVERSATION_DRAFT_KEY}:`)).toBeNull();
+ setIdentity('alice');
+ expect(draft.draft()).toBe('');
+ draft.setDraft('Alice private');
+ setIdentity('bob');
+ expect(draft.draft()).toBe('');
+ draft.setDraft('Bob private');
+ setIdentity(undefined);
+ expect(draft.draft()).toBe('');
+ setIdentity('alice');
+ expect(draft.draft()).toBe('Alice private');
+ dispose();
+ });
+ });
+ it('restores each account draft without exposing another account draft', () => {
+ createRoot((dispose) => {
+ const alice = createPersistedComposerDraft(
+ HOME_CONVERSATION_DRAFT_KEY,
+ () => 'alice'
+ );
+ alice.setDraft('Private Alice draft');
+ dispose();
+ });
+ createRoot((dispose) => {
+ const bob = createPersistedComposerDraft(
+ HOME_CONVERSATION_DRAFT_KEY,
+ () => 'bob'
+ );
+ expect(bob.draft()).toBe('');
+ bob.setDraft('Private Bob draft');
+ const alice = createPersistedComposerDraft(
+ HOME_CONVERSATION_DRAFT_KEY,
+ () => 'alice'
+ );
+ expect(alice.draft()).toBe('Private Alice draft');
+ expect(bob.draft()).toBe('Private Bob draft');
+ dispose();
+ });
+ });
it('keeps Home and Agents drafts independent when either is cleared', () => {
createRoot((dispose) => {
- const home = createPersistedComposerDraft(HOME_CONVERSATION_DRAFT_KEY);
- const agents = createPersistedComposerDraft();
+ const home = createPersistedComposerDraft(
+ HOME_CONVERSATION_DRAFT_KEY,
+ () => 'user'
+ );
+ const agents = createPersistedComposerDraft(undefined, () => 'user');
home.setDraft('Home prompt');
agents.setDraft('Agents prompt');
dispose();
});
createRoot((dispose) => {
- const home = createPersistedComposerDraft(HOME_CONVERSATION_DRAFT_KEY);
- const agents = createPersistedComposerDraft();
+ const home = createPersistedComposerDraft(
+ HOME_CONVERSATION_DRAFT_KEY,
+ () => 'user'
+ );
+ const agents = createPersistedComposerDraft(undefined, () => 'user');
expect(home.draft()).toBe('Home prompt');
expect(agents.draft()).toBe('Agents prompt');
home.setDraft('');
expect(agents.draft()).toBe('Agents prompt');
dispose();
});
- expect(localStorage.getItem(HOME_CONVERSATION_DRAFT_KEY)).toBeNull();
+ expect(
+ localStorage.getItem(`${HOME_CONVERSATION_DRAFT_KEY}:user`)
+ ).toBeNull();
});
beforeEach(() => {
localStorage.clear();
@@ -36,14 +93,14 @@ describe('createPersistedComposerDraft', () => {
it('rehydrates the persisted draft for the same key', () => {
createRoot((dispose) => {
- const draft = createPersistedComposerDraft();
+ const draft = createPersistedComposerDraft(undefined, () => 'user');
draft.setDraft('keep this prompt');
expect(draft.draft()).toBe('keep this prompt');
dispose();
});
createRoot((dispose) => {
- const draft = createPersistedComposerDraft();
+ const draft = createPersistedComposerDraft(undefined, () => 'user');
expect(draft.draft()).toBe('keep this prompt');
dispose();
});
@@ -51,16 +108,18 @@ describe('createPersistedComposerDraft', () => {
it('removes the persisted value when the draft becomes empty', () => {
createRoot((dispose) => {
- const draft = createPersistedComposerDraft();
+ const draft = createPersistedComposerDraft(undefined, () => 'user');
draft.setDraft('keep this prompt');
draft.setDraft('');
dispose();
});
- expect(localStorage.getItem(NEW_CONVERSATION_DRAFT_KEY)).toBeNull();
+ expect(
+ localStorage.getItem(`${NEW_CONVERSATION_DRAFT_KEY}:user`)
+ ).toBeNull();
createRoot((dispose) => {
- const draft = createPersistedComposerDraft();
+ const draft = createPersistedComposerDraft(undefined, () => 'user');
expect(draft.draft()).toBe('');
dispose();
});
diff --git a/apps/web/src/features/agents-view/primitives/composer-draft.ts b/apps/web/src/features/agents-view/primitives/composer-draft.ts
index 59a1ac9968..45377865c5 100644
--- a/apps/web/src/features/agents-view/primitives/composer-draft.ts
+++ b/apps/web/src/features/agents-view/primitives/composer-draft.ts
@@ -1,6 +1,6 @@
import { createPersistenceKey } from '@queries/persistence';
import { makePersisted } from '@solid-primitives/storage';
-import { createSignal } from 'solid-js';
+import { type Accessor, createMemo, createSignal } from 'solid-js';
/** Same localStorage projection channel composers use for unsent drafts. */
export const NEW_CONVERSATION_DRAFT_KEY = createPersistenceKey(
@@ -21,12 +21,20 @@ export const NEW_CONVERSATION_ATTACHMENTS_KEY = createPersistenceKey(
/** Keep a composer draft after the New conversation page remounts. */
export function createPersistedComposerDraft(
- name = NEW_CONVERSATION_DRAFT_KEY
+ name = NEW_CONVERSATION_DRAFT_KEY,
+ userId: Accessor<string | undefined> = () => undefined
) {
- const raw = createSignal<string | undefined>(undefined);
- const [persisted, setPersisted] = makePersisted(raw, { name });
+ const state = createMemo(() => {
+ const identity = userId();
+ const raw = createSignal<string | undefined>(undefined);
+ return identity
+ ? makePersisted(raw, {
+ name: `${name}:${encodeURIComponent(identity)}`,
+ })
+ : raw;
+ });
return {
- draft: () => persisted() ?? '',
- setDraft: (value: string) => setPersisted(value || undefined),
+ draft: () => state()[0]() ?? '',
+ setDraft: (value: string) => state()[1](value || undefined),
};
}
diff --git a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
index 81c00d4abf..69adefff1e 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
@@ -9,7 +9,7 @@ import {
waitFor,
within,
} from '@solidjs/testing-library';
-import type { JSX } from 'solid-js';
+import { createSignal, type JSX } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { AgentKind } from '../core/agent-kind';
import {
@@ -21,6 +21,7 @@ import { AgentPicker } from './AgentPicker';
import { NewChatPage } from './NewChatPage';
const mocks = vi.hoisted(() => ({
+ userId: () => 'user' as string | undefined,
touch: false,
freePlan: false,
modelsPending: false,
@@ -43,7 +44,9 @@ vi.mock('@channel/Input', async () => ({
...(await import('../../channel/Input/attachment-tracker')),
uploadInputAttachments: vi.fn(),
}));
-vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user' }));
+vi.mock('@core/context/user', () => ({
+ useUserId: () => () => mocks.userId(),
+}));
vi.mock('@core/constant/SettingsState', () => ({
useSettingsState: () => ({ openSettings: mocks.openSettings }),
}));
@@ -176,6 +179,7 @@ type ComposerProps = {
drawer: JSX.Element;
drawerOpen: boolean;
draft: string;
+ attachments: InputAttachmentData[];
onDraftChange: (draft: string) => void;
onSend: (prompt: string, attachments: InputAttachmentData[]) => void;
};
@@ -183,6 +187,9 @@ vi.mock('../components/ChatComposer', () => ({
ChatComposer: (props: ComposerProps) => (
<>
{props.selector}
+ <output data-testid="attachments">
+ {props.attachments.map((a) => a.name).join(',')}
+ </output>
<div data-testid="drawer" hidden={!props.drawerOpen}>
{props.drawer}
</div>
@@ -207,6 +214,7 @@ vi.mock('../components/ChatComposer', () => ({
beforeEach(() => {
localStorage.clear();
+ mocks.userId = () => 'user';
});
function page(
@@ -933,3 +941,30 @@ it('starts a conversation with an uploaded image and no text', () => {
})
);
});
+
+it('isolates drafts and attachment projections as identity arrives and changes', () => {
+ const [identity, setIdentity] = createSignal<string>();
+ mocks.userId = identity;
+ const base = 'attachment-tracker-agents-new-conversation-persist-v0';
+ const attachment = { id: 'private', name: 'alice-only.txt', kind: 'file' };
+ localStorage.setItem(`${base}:`, JSON.stringify([attachment]));
+ localStorage.setItem(`${base}:alice`, JSON.stringify([attachment]));
+ page();
+ expect(screen.getByTestId('attachments').textContent).toBe('');
+ fireEvent.input(screen.getByLabelText('Draft'), {
+ target: { value: 'anonymous' },
+ });
+ setIdentity('alice');
+ expect((screen.getByLabelText('Draft') as HTMLInputElement).value).toBe('');
+ expect(screen.getByTestId('attachments').textContent).toBe('alice-only.txt');
+ fireEvent.input(screen.getByLabelText('Draft'), {
+ target: { value: 'Alice private' },
+ });
+ setIdentity('bob');
+ expect((screen.getByLabelText('Draft') as HTMLInputElement).value).toBe('');
+ expect(screen.getByTestId('attachments').textContent).toBe('');
+ setIdentity('alice');
+ expect((screen.getByLabelText('Draft') as HTMLInputElement).value).toBe(
+ 'Alice private'
+ );
+});
diff --git a/apps/web/src/features/agents-view/views/NewChatPage.tsx b/apps/web/src/features/agents-view/views/NewChatPage.tsx
index 6111432c1d..bc12adb2e1 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.tsx
@@ -85,7 +85,7 @@ export function NewChatPage(props: {
const [repositoryPickerOpen, setRepositoryPickerOpen] = createSignal(false);
// A new conversation starts on Automatic until the caller picks a repository.
const [repoUrl, setRepoUrl] = createSignal<string | undefined>();
- const persistedDraft = createPersistedComposerDraft();
+ const persistedDraft = createPersistedComposerDraft(undefined, userId);
const draft = () => props.draft ?? persistedDraft.draft();
const setDraft = (text: string) =>
props.onDraftChange
@@ -194,16 +194,20 @@ export function NewChatPage(props: {
if (agent.harness === 'cursor') openSettings('Harness');
};
- const attachmentTracker = createInputAttachmentTracker({
- // Home supplies its own text draft; attachment persistence here is for Agents.
- persistenceKey: props.onDraftChange
- ? undefined
- : NEW_CONVERSATION_ATTACHMENTS_KEY,
+ const attachmentTracker = createMemo(() => {
+ const identity = userId();
+ return createInputAttachmentTracker({
+ // Home owns its attachments; unknown identities never read shared storage.
+ persistenceKey:
+ !props.onDraftChange && identity
+ ? `${NEW_CONVERSATION_ATTACHMENTS_KEY}:${encodeURIComponent(identity)}`
+ : undefined,
+ });
});
const attachFiles = (files: File[]) =>
void uploadInputAttachments({
files,
- tracker: attachmentTracker,
+ tracker: attachmentTracker(),
uploadFile: (file) =>
uploadFile(file, 'static', { hideProgressIndicator: true }),
});
@@ -214,7 +218,7 @@ export function NewChatPage(props: {
(!prompt.trim() && attachments.length === 0) ||
!persona ||
blocked() ||
- attachmentTracker.hasPending()
+ attachmentTracker().hasPending()
)
return;
recentAgents.remember(persona.id);
@@ -237,7 +241,7 @@ export function NewChatPage(props: {
: {}),
effortOverride: effortOverride(),
});
- attachmentTracker.clearAttachments();
+ attachmentTracker().clearAttachments();
// Macro's preferred model stays; coding-agent submenu picks are one-shot.
setModelOverride(undefined);
setEffortSelection(undefined);
@@ -312,10 +316,10 @@ export function NewChatPage(props: {
drawerOpen={coding()}
placeholder={coding() ? 'Describe what you want to build' : undefined}
onSend={send}
- attachments={attachmentTracker.attachments()}
+ attachments={attachmentTracker().attachments()}
onAttachFiles={attachFiles}
onRemoveAttachment={(attachment) =>
- attachmentTracker.removeAttachment(attachment.id)
+ attachmentTracker().removeAttachment(attachment.id)
}
/>
);
diff --git a/apps/web/src/features/home/home-agent-composer.tsx b/apps/web/src/features/home/home-agent-composer.tsx
index 5b17719b96..5f4de36b91 100644
--- a/apps/web/src/features/home/home-agent-composer.tsx
+++ b/apps/web/src/features/home/home-agent-composer.tsx
@@ -32,7 +32,8 @@ export function HomeAgentComposer(props: { autoFocus?: boolean }) {
const userId = useUserId();
useWarmAgentSessionQuery(userId);
const { draft, setDraft } = createPersistedComposerDraft(
- HOME_CONVERSATION_DRAFT_KEY
+ HOME_CONVERSATION_DRAFT_KEY,
+ userId
);
let focus: (() => void) | undefined;
let draftVersion = 0;
diff --git a/apps/web/src/lib/core/auth/clear-composer-storage.test.ts b/apps/web/src/lib/core/auth/clear-composer-storage.test.ts
new file mode 100644
index 0000000000..ba20085232
--- /dev/null
+++ b/apps/web/src/lib/core/auth/clear-composer-storage.test.ts
@@ -0,0 +1,18 @@
+import { beforeEach, expect, it } from 'vitest';
+import { clearComposerStorage } from './clear-composer-storage';
+
+beforeEach(() => localStorage.clear());
+
+it('clears scoped and legacy drafts and attachments while retaining preferences', () => {
+ const keys = [
+ 'input-value-home-agent-conversation-persist-v0:alice',
+ 'input-value-agents-new-conversation-persist-v0:bob',
+ 'input-value-channel-1',
+ 'attachment-tracker-agents-new-conversation-persist-v0:alice',
+ ];
+ for (const key of keys) localStorage.setItem(key, 'private draft');
+ localStorage.setItem('macro-selected-theme', 'dark');
+ clearComposerStorage();
+ for (const key of keys) expect(localStorage.getItem(key)).toBeNull();
+ expect(localStorage.getItem('macro-selected-theme')).toBe('dark');
+});
diff --git a/apps/web/src/lib/core/auth/clear-composer-storage.ts b/apps/web/src/lib/core/auth/clear-composer-storage.ts
new file mode 100644
index 0000000000..fb5c51651f
--- /dev/null
+++ b/apps/web/src/lib/core/auth/clear-composer-storage.ts
@@ -0,0 +1,12 @@
+/** Remove saved composer text and attachment references on explicit logout. */
+export function clearComposerStorage(): void {
+ for (let index = localStorage.length - 1; index >= 0; index--) {
+ const key = localStorage.key(index);
+ if (
+ key?.startsWith('input-value-') ||
+ key?.startsWith('attachment-tracker-')
+ ) {
+ localStorage.removeItem(key);
+ }
+ }
+}
diff --git a/apps/web/src/lib/core/auth/logout.test.ts b/apps/web/src/lib/core/auth/logout.test.ts
index e12ad89fba..2910ec4d08 100644
--- a/apps/web/src/lib/core/auth/logout.test.ts
+++ b/apps/web/src/lib/core/auth/logout.test.ts
@@ -9,6 +9,11 @@ const { client, navigate } = vi.hoisted(() => ({
navigate: vi.fn(),
}));
vi.mock('@queries/client', () => ({
+ queryPersistence: {
+ clear: async () => {
+ client.current?.clear();
+ },
+ },
get queryClient() {
return client.current;
},
diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.ts
index 046513a812..9ef68a63ed 100644
--- a/apps/web/src/lib/core/auth/logout.ts
+++ b/apps/web/src/lib/core/auth/logout.ts
@@ -5,17 +5,15 @@ import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { syncLoginStorage } from '@core/util/cookies';
import { clearPostLoginRedirect } from '@core/util/postLoginRedirect';
import { clearRegisteredCaches } from '@graphql-cache/lifecycle';
+import { rotateCacheScope } from '@graphql-cache/scope';
import { authKeys, type UserInfoData } from '@queries/auth/user-info';
import { clearTeamCalendarQueries } from '@queries/calendar/team-cache';
-import { queryClient } from '@queries/client';
-import { emailKeys } from '@queries/email/keys';
+import { queryClient, queryPersistence } from '@queries/client';
import {
clearLocalDrafts,
flushLocalDrafts,
listLocalDrafts,
} from '@queries/email/local-drafts';
-import { notificationKeys } from '@queries/notification/keys';
-import { propertiesKeys } from '@queries/properties/keys';
import { resetGraphqlSoupDoneSession } from '@queries/soup/graphql/done-session';
import { clearDocumentQueryCache } from '@queries/storage/document-cache';
import { clearOfflineDocumentContexts } from '@queries/storage/documentLoad/offline-context-runtime';
@@ -25,6 +23,7 @@ import { createCallback } from '@solid-primitives/rootless';
import { useNavigate } from '@solidjs/router';
import { confirmDialog } from '@ui';
import { getOwner } from 'solid-js';
+import { clearComposerStorage } from './clear-composer-storage';
import { unregisterPushRegistrationsForLogout } from './push-registration-lifecycle';
const unauthenticatedUserInfo: UserInfoData = {
@@ -51,22 +50,19 @@ export async function clearLocalAuthSession() {
const documentContextsCleared = clearOfflineDocumentContexts();
clearDocumentQueryCache(queryClient);
clearTeamCalendarQueries();
- queryClient.setQueryData(authKeys.userInfo.queryKey, unauthenticatedUserInfo);
- queryClient.removeQueries({ queryKey: emailKeys.links.queryKey });
- queryClient.removeQueries({ queryKey: notificationKeys._def });
- resetGraphqlSoupDoneSession();
- queryClient.removeQueries({ queryKey: propertiesKeys._def });
- // The billing position (usage, credits, overage settings) belongs to the
- // account that fetched it; never let it render for the next sign-in.
- queryClient.removeQueries({ queryKey: authKeys.aiBillingSummary.queryKey });
-
- // Queued mutations are user intent; never allow them to replay under a
- // subsequent account sharing this anonymous device cache scope.
- await Promise.all([
+ // Start every wipe before waiting, including stores not hydrated this session.
+ const results = await Promise.allSettled([
+ Promise.resolve().then(clearComposerStorage),
documentContextsCleared,
clearRegisteredCaches(),
+ queryPersistence.clear(),
clearLocalDrafts(),
]);
+ if (results.some((result) => result.status === 'rejected')) {
+ await rotateCacheScope();
+ }
+ resetGraphqlSoupDoneSession();
+ queryClient.setQueryData(authKeys.userInfo.queryKey, unauthenticatedUserInfo);
clearMcpAuthAttempts();
}
diff --git a/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.test.tsx b/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.test.tsx
new file mode 100644
index 0000000000..d206e898ce
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.test.tsx
@@ -0,0 +1,62 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { NativeAppUpdateRequiredDialog } from './NativeAppUpdateRequiredDialog';
+import { openNativeUpdateLink } from './native-update-link';
+
+vi.mock('@core/util/platform', () => ({
+ getNativeMobilePlatform: () => 'android',
+}));
+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => true }));
+vi.mock('@core/mobile/virtualKeyboard', () => ({
+ virtualKeyboardVisible: () => false,
+}));
+vi.mock('./native-update-link', () => ({ openNativeUpdateLink: vi.fn() }));
+vi.mock('@ui', async () => ({
+ ...(await import('@app/components/ui/components/Button')),
+ ...(await import('@app/components/ui/components/Dialog')),
+ ...(await import('@app/components/ui/components/Surface')),
+}));
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+it('keeps a mobile drawer dismissible after an unavailable store', async () => {
+ vi.stubGlobal('scrollTo', vi.fn());
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ vi.mocked(openNativeUpdateLink).mockResolvedValue(false);
+ const close = vi.fn();
+ render(() => {
+ const [open, setOpen] = createSignal(true);
+ return (
+ <NativeAppUpdateRequiredDialog
+ open={open()}
+ onClose={() => {
+ close();
+ setOpen(false);
+ }}
+ />
+ );
+ });
+ await fireEvent.click(screen.getByRole('button', { name: 'Update app' }));
+ await waitFor(() =>
+ expect(screen.getByRole('alert').textContent).toContain('Unable to open')
+ );
+ expect(openNativeUpdateLink).toHaveBeenCalledWith('android');
+ await fireEvent.click(screen.getByRole('button', { name: 'OK' }));
+ expect(close).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.tsx b/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.tsx
index 67388ffe59..8c3e599473 100644
--- a/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.tsx
+++ b/apps/web/src/lib/core/mobile/NativeAppUpdateRequiredDialog.tsx
@@ -1,5 +1,7 @@
+import { getNativeMobilePlatform } from '@core/util/platform';
import { Button, Dialog, Surface } from '@ui';
-import { Show } from 'solid-js';
+import { createSignal, Show } from 'solid-js';
+import { openNativeUpdateLink } from './native-update-link';
export function NativeAppUpdateRequiredDialog(props: {
open: boolean;
@@ -7,6 +9,15 @@ export function NativeAppUpdateRequiredDialog(props: {
description?: string;
onRestart?: () => void;
}) {
+ const platform = getNativeMobilePlatform();
+ const [linkFailed, setLinkFailed] = createSignal(false);
+ const [opening, setOpening] = createSignal(false);
+ async function openStore() {
+ if (!platform || opening()) return;
+ setOpening(true);
+ setLinkFailed(!(await openNativeUpdateLink(platform)));
+ setOpening(false);
+ }
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.';
@@ -30,7 +41,25 @@ export function NativeAppUpdateRequiredDialog(props: {
{props.description ?? description}
</Dialog.Description>
</div>
+ <p class="text-sm text-ink-extra-muted">
+ If the store is unavailable, close this dialog and try again later.
+ </p>
+ <Show when={linkFailed()}>
+ <p role="alert" class="text-sm text-ink">
+ Unable to open the store. Please try again later.
+ </p>
+ </Show>
<div class="flex justify-end gap-2">
+ <Show when={platform}>
+ <Button
+ variant="strong"
+ size="sm"
+ disabled={opening()}
+ onClick={() => void openStore()}
+ >
+ Update app
+ </Button>
+ </Show>
<Show when={props.onRestart}>
<Button
variant="accent"
@@ -40,9 +69,9 @@ export function NativeAppUpdateRequiredDialog(props: {
Restart to update
</Button>
</Show>
- <Dialog.CloseButton as={Button} variant="strong" size="sm">
+ <Button onClick={props.onClose} variant="strong" size="sm">
OK
- </Dialog.CloseButton>
+ </Button>
</div>
</div>
</Surface>
diff --git a/apps/web/src/lib/core/mobile/native-network-status.test.ts b/apps/web/src/lib/core/mobile/native-network-status.test.ts
new file mode 100644
index 0000000000..0538363bf7
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/native-network-status.test.ts
@@ -0,0 +1,61 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ receive: undefined as ((payload: { status: string }) => void) | undefined,
+}));
+vi.mock('@core/util/platform', () => ({
+ isPlatform: (platforms: string | string[]) => platforms.includes('android'),
+}));
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: mocks.invoke,
+ Channel: class {
+ constructor(receive: typeof mocks.receive) {
+ mocks.receive = receive;
+ }
+ },
+}));
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.resetModules();
+ vi.clearAllMocks();
+});
+
+describe('Android native reachability', () => {
+ it('starts the bridge and aborts offline work, then gives reconnect work a fresh signal', async () => {
+ mocks.invoke.mockResolvedValue(undefined);
+ const network = await import('./native-network-status');
+ const observed: string[] = [];
+ const unsubscribe = network.subscribeNativeNetworkStatus((status) =>
+ observed.push(status)
+ );
+ await network.initializeNativeNetworkStatus();
+ expect(mocks.invoke).toHaveBeenCalledWith(
+ 'plugin:network-status|watch_status',
+ expect.objectContaining({ channel: expect.anything() })
+ );
+ const initial = network.getNativeNetworkAbortSignal();
+ mocks.receive?.({ status: 'offline' });
+ expect(initial.aborted).toBe(true);
+ mocks.receive?.({ status: 'online' });
+ expect(network.getNativeNetworkAbortSignal().aborted).toBe(false);
+ expect(network.getNativeNetworkAbortSignal()).not.toBe(initial);
+ expect(observed).toEqual(['unknown', 'offline', 'online']);
+ unsubscribe();
+ });
+
+ it('leaves older Android binaries on browser connectivity when the command is absent', async () => {
+ vi.useFakeTimers();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.invoke.mockRejectedValue(new Error('unknown command'));
+ const network = await import('./native-network-status');
+ const initialized = network.initializeNativeNetworkStatus();
+ await vi.runAllTimersAsync();
+ await initialized;
+ expect(mocks.invoke).toHaveBeenCalledTimes(3);
+ expect(network.nativeNetworkStatus()).toBe('unknown');
+ expect(network.getNativeNetworkAbortSignal().aborted).toBe(false);
+ vi.restoreAllMocks();
+ });
+});
diff --git a/apps/web/src/lib/core/mobile/native-network-status.ts b/apps/web/src/lib/core/mobile/native-network-status.ts
index d52f152aa2..614a285745 100644
--- a/apps/web/src/lib/core/mobile/native-network-status.ts
+++ b/apps/web/src/lib/core/mobile/native-network-status.ts
@@ -49,10 +49,10 @@ function applyStatus(payload: NetworkStatusPayload): void {
for (const listener of listeners) listener(status);
}
-/** Current native reachability state. Remains `unknown` off iOS. */
+/** Current native reachability state. Remains `unknown` off native mobile. */
export { nativeNetworkStatus };
-/** Signal aborted whenever iOS reports that no network path is available. */
+/** Signal aborted whenever the native platform reports that no network path is available. */
export function getNativeNetworkAbortSignal(): AbortSignal {
return networkAbortController.signal;
}
@@ -66,9 +66,9 @@ export function subscribeNativeNetworkStatus(
return () => listeners.delete(listener);
}
-/** Starts the singleton iOS `NWPathMonitor` channel. */
+/** Starts the singleton native reachability channel. */
export function initializeNativeNetworkStatus(): Promise<void> {
- if (!isPlatform('ios')) return Promise.resolve();
+ if (!isPlatform(['ios', 'android'])) return Promise.resolve();
if (!initialization) initialization = startNativeMonitor();
return initialization;
}
@@ -85,7 +85,7 @@ async function startNativeMonitor(): Promise<void> {
statusChannel = undefined;
if (attempt === WATCH_START_ATTEMPTS) {
// Fail open: status stays 'unknown' and offline aborts never engage
- // this session, matching the browser-connectivity behavior off iOS.
+ // this session, matching the browser-connectivity behavior off native mobile.
initialization = undefined;
console.error('[network-status] failed to start native monitor', error);
return;
diff --git a/apps/web/src/lib/core/mobile/native-update-link.test.ts b/apps/web/src/lib/core/mobile/native-update-link.test.ts
new file mode 100644
index 0000000000..51b942de99
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/native-update-link.test.ts
@@ -0,0 +1,28 @@
+import { invoke } from '@tauri-apps/api/core';
+import { describe, expect, it, vi } from 'vitest';
+import { nativeUpdateLink, openNativeUpdateLink } from './native-update-link';
+
+vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() }));
+
+describe('native update destination', () => {
+ it('targets the production Android package using HTTPS', () => {
+ const url = new URL(nativeUpdateLink('android'));
+ expect(url.protocol).toBe('https:');
+ expect(url.hostname).toBe('play.google.com');
+ expect(url.searchParams.get('id')).toBe('com.macro.app.prod');
+ expect(nativeUpdateLink('ios')).toContain('id6743133649');
+ });
+
+ it('keeps opener failures recoverable', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(invoke)
+ .mockRejectedValueOnce(new Error('No handler'))
+ .mockResolvedValueOnce(undefined);
+ expect(await openNativeUpdateLink('android')).toBe(false);
+ expect(await openNativeUpdateLink('android')).toBe(true);
+ expect(invoke).toHaveBeenLastCalledWith('plugin:opener|open_url', {
+ url: nativeUpdateLink('android'),
+ });
+ vi.restoreAllMocks();
+ });
+});
diff --git a/apps/web/src/lib/core/mobile/native-update-link.ts b/apps/web/src/lib/core/mobile/native-update-link.ts
new file mode 100644
index 0000000000..dc027ba8e6
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/native-update-link.ts
@@ -0,0 +1,21 @@
+import { invoke } from '@tauri-apps/api/core';
+
+/** HTTPS works even when the Play Store app is absent. */
+export function nativeUpdateLink(platform: 'ios' | 'android'): string {
+ return platform === 'android'
+ ? 'https://play.google.com/store/apps/details?id=com.macro.app.prod'
+ : 'https://apps.apple.com/us/app/macro-app/id6743133649';
+}
+
+/** Keep the current app usable when the operating system cannot open the link. */
+export async function openNativeUpdateLink(
+ platform: 'ios' | 'android'
+): Promise<boolean> {
+ try {
+ await invoke('plugin:opener|open_url', { url: nativeUpdateLink(platform) });
+ return true;
+ } catch (error) {
+ console.error('[native-update] unable to open store', error);
+ return false;
+ }
+}
diff --git a/apps/web/src/lib/queries/client.ts b/apps/web/src/lib/queries/client.ts
index 5cd72ae6c4..981effb36f 100644
--- a/apps/web/src/lib/queries/client.ts
+++ b/apps/web/src/lib/queries/client.ts
@@ -32,8 +32,8 @@ export const queryClient = new QueryClient({
},
});
-if (isPlatform('ios')) {
- // Replace WKWebView's navigator.onLine integration with NWPathMonitor.
+if (isPlatform(['ios', 'android'])) {
+ // Use the native default network path on both mobile platforms.
onlineManager.setEventListener((setOnline) =>
subscribeNativeNetworkStatus((status) => {
if (status !== 'unknown') setOnline(status === 'online');
diff --git a/apps/web/src/lib/queries/persistence-scopes.ts b/apps/web/src/lib/queries/persistence-scopes.ts
index 3b3285f66a..eb1cafe4bb 100644
--- a/apps/web/src/lib/queries/persistence-scopes.ts
+++ b/apps/web/src/lib/queries/persistence-scopes.ts
@@ -1,5 +1,6 @@
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { hasLoginCookie } from '@core/util/cookies';
+import { getOrCreateCacheScope } from '@graphql-cache/scope';
import { partialMatchKey, type QueryKey } from '@tanstack/query-core';
import { authKeys } from './auth/keys';
import { hasCachedUserIdentity } from './auth/user-info-cache';
@@ -23,29 +24,35 @@ export function shouldPersistChannelQuery(queryKey: QueryKey): boolean {
export function createQueryPersistenceScopes(
buster: string
): readonly PersistScope[] {
+ // A failed durable logout wipe can rotate this shared scope before relaunch.
+ const accountScope = getOrCreateCacheScope();
+ const scopedKey = (name: string) =>
+ createPersistenceKey(`${name}-${accountScope}`, 1);
return [
{
store: createPerQueryIDBStore({
- dbName: createPersistenceKey('channels', 1),
+ dbName: scopedKey('channels'),
}),
maxAge: { value: 7, unit: 'd' },
buster,
shouldPersist: shouldPersistChannelQuery,
+ shouldRestore: hasLoginCookie,
},
{
store: createPerQueryIDBStore({
- dbName: createPersistenceKey('email-threads', 1),
+ dbName: scopedKey('email-threads'),
}),
maxAge: { value: 7, unit: 'd' },
buster,
shouldPersist: (queryKey) =>
partialMatchKey(queryKey, ['email', 'threadMessages']),
+ shouldRestore: hasLoginCookie,
},
...(isNativeMobilePlatform()
? [
{
store: createPerQueryIDBStore({
- dbName: createPersistenceKey('soup-list-queries', 1),
+ dbName: scopedKey('soup-list-queries'),
}),
maxAge: { value: 7, unit: 'd' },
buster,
@@ -55,7 +62,7 @@ export function createQueryPersistenceScopes(
} satisfies PersistScope,
{
store: createPerQueryIDBStore({
- dbName: createPersistenceKey('user-info', 1),
+ dbName: scopedKey('user-info'),
}),
buster,
shouldPersist: (queryKey: QueryKey) =>
diff --git a/apps/web/src/lib/queries/persistence.test.ts b/apps/web/src/lib/queries/persistence.test.ts
index 5c2f523483..bbd59bad02 100644
--- a/apps/web/src/lib/queries/persistence.test.ts
+++ b/apps/web/src/lib/queries/persistence.test.ts
@@ -6,7 +6,7 @@ import { channelKeys } from './channel/keys';
import { messageKeys } from './messages/keys';
import { type PersistScope, setupQueryPersistence } from './persistence';
import type {
- PerQueryPersistence,
+ ClearablePerQueryPersistence,
PersistedQueryEntry,
} from './persistence/per-query-idb';
import {
@@ -19,7 +19,7 @@ vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
}));
vi.mock('@core/util/cookies', () => ({ hasLoginCookie: () => true }));
-function createMockStore(): PerQueryPersistence & {
+function createMockStore(): ClearablePerQueryPersistence & {
entries: Map<string, PersistedQueryEntry>;
get: ReturnType<typeof vi.fn>;
set: ReturnType<typeof vi.fn>;
@@ -37,12 +37,15 @@ function createMockStore(): PerQueryPersistence & {
entries.delete(hash);
}),
flush: vi.fn(async () => {}),
+ clear: vi.fn(async () => {
+ entries.clear();
+ }),
};
}
function createScope(
prefix: readonly unknown[],
- store: PerQueryPersistence,
+ store: ClearablePerQueryPersistence,
overrides?: Partial<PersistScope>
): PersistScope {
return {
@@ -610,3 +613,61 @@ describe('setupQueryPersistence', () => {
expect(store.remove).toHaveBeenCalledWith('["channel","a"]');
});
});
+
+describe('account persistence reset', () => {
+ it('clears entries that were never hydrated and fences a pending old-account read', async () => {
+ const store = createMockStore();
+ const queryClient = new QueryClient();
+ const persistence = setupQueryPersistence({
+ queryClient,
+ scopes: [createScope(['private'], store)],
+ });
+ const entry: PersistedQueryEntry = {
+ queryHash: '["private","alice"]',
+ queryKey: ['private', 'alice'],
+ data: { owner: 'alice' },
+ dataUpdatedAt: Date.now(),
+ persistedAt: Date.now(),
+ buster: 'test',
+ };
+ store.entries.set(entry.queryHash, entry);
+ store.entries.set('["private","unhydrated"]', {
+ ...entry,
+ queryHash: '["private","unhydrated"]',
+ queryKey: ['private', 'unhydrated'],
+ });
+ let finishRead!: (entry: PersistedQueryEntry) => void;
+ store.get.mockImplementationOnce(
+ () =>
+ new Promise<PersistedQueryEntry>((resolve) => {
+ finishRead = resolve;
+ })
+ );
+ const restore = persistence.restoreQuery(entry.queryKey);
+ await persistence.clear();
+ queryClient.setQueryData(entry.queryKey, { owner: 'bob' });
+ finishRead(entry);
+ await restore;
+ expect(queryClient.getQueryData(entry.queryKey)).toEqual({ owner: 'bob' });
+ expect(store.entries.has('["private","unhydrated"]')).toBe(false);
+ persistence.dispose();
+ queryClient.clear();
+ });
+
+ it('attempts every durable wipe even when one store fails', async () => {
+ const failing = createMockStore();
+ failing.clear = vi.fn(async () => {
+ throw new Error('disk failure');
+ });
+ const other = createMockStore();
+ const queryClient = new QueryClient();
+ const persistence = setupQueryPersistence({
+ queryClient,
+ scopes: [createScope(['a'], failing), createScope(['b'], other)],
+ });
+ await expect(persistence.clear()).rejects.toThrow('disk failure');
+ expect(other.entries.size).toBe(0);
+ persistence.dispose();
+ queryClient.clear();
+ });
+});
diff --git a/apps/web/src/lib/queries/persistence.ts b/apps/web/src/lib/queries/persistence.ts
index a309309dbe..f37c02f206 100644
--- a/apps/web/src/lib/queries/persistence.ts
+++ b/apps/web/src/lib/queries/persistence.ts
@@ -4,7 +4,7 @@ import {
} from '@core/util/dateSearch/dateParser';
import type { Query, QueryClient, QueryKey } from '@tanstack/query-core';
import type {
- PerQueryPersistence,
+ ClearablePerQueryPersistence,
PersistedQueryEntry,
} from './persistence/per-query-idb';
@@ -19,7 +19,7 @@ export function createPersistenceKey(
}
export type PersistScope = Readonly<{
- store: PerQueryPersistence;
+ store: ClearablePerQueryPersistence;
/** Omit to retain same-buster entries regardless of their age. */
maxAge?: ParsedDuration;
buster: string;
@@ -32,6 +32,8 @@ export type PersistScope = Readonly<{
export type QueryPersistence = {
/** Restore this query without starting or waiting for its network request. */
restoreQuery: (queryKey: QueryKey) => Promise<void>;
+ /** Clear every durable scope and fence pending hydration on account changes. */
+ clear: () => Promise<void>;
/** Await pending local writes before restarting the native app. */
flush: () => Promise<void>;
dispose: () => void;
@@ -139,13 +141,16 @@ export function setupQueryPersistence(
}>
): QueryPersistence {
const { queryClient, scopes } = params;
- const restores = new WeakMap<Query, Promise<void>>();
+ let restores = new WeakMap<Query, Promise<void>>();
+ let generation = 0;
+ let clearing = false;
let disposed = false;
const findScope = (queryKey: QueryKey) =>
scopes.find((s) => s.shouldPersist(queryKey));
async function restoreFromStore(query: Query, scope: PersistScope) {
+ const capturedGeneration = generation;
try {
await handleRestore(
queryClient,
@@ -153,6 +158,8 @@ export function setupQueryPersistence(
query,
() =>
!disposed &&
+ !clearing &&
+ capturedGeneration === generation &&
queryClient.getQueryCache().get(query.queryHash) === query
);
} catch {
@@ -185,6 +192,8 @@ export function setupQueryPersistence(
const scope = findScope(query.queryKey);
if (!scope) return;
+ if (disposed || clearing) return;
+
if (type === 'added') {
void restore(query, scope);
} else if (type === 'updated') {
@@ -197,7 +206,7 @@ export function setupQueryPersistence(
return {
restoreQuery(queryKey) {
const scope = findScope(queryKey);
- if (disposed || !scope) return Promise.resolve();
+ if (disposed || clearing || !scope) return Promise.resolve();
// Building a missing query emits `added`, starting the same restore that
// an observer would start, without issuing a request or needing a queryFn.
const query = queryClient
@@ -205,6 +214,26 @@ export function setupQueryPersistence(
.build(queryClient, { queryKey });
return restore(query, scope);
},
+ async clear() {
+ generation += 1;
+ clearing = true;
+ restores = new WeakMap();
+ // Clear memory synchronously; removed-query events cannot race the reset.
+ queryClient.clear();
+ try {
+ const results = await Promise.allSettled(
+ scopes.map((scope) => scope.store.clear())
+ );
+ const failed = results.find((result) => result.status === 'rejected');
+ if (failed?.status === 'rejected') {
+ // Quarantine this session; logout rotates the disk namespace for restart.
+ disposed = true;
+ throw failed.reason;
+ }
+ } finally {
+ clearing = false;
+ }
+ },
flush: async () => {
await Promise.all(
scopes.map((scope) => scope.store.flush({ throwOnError: true }))
diff --git a/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts b/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts
index a202ceb612..43b7783307 100644
--- a/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts
+++ b/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts
@@ -81,6 +81,7 @@ vi.mock('../../client', async () => {
set: vi.fn(),
remove: vi.fn(),
flush: async () => {},
+ clear: async () => {},
},
},
],
diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lock
index 484000a4a5..6253155488 100644
--- a/apps/web/tauri/Cargo.lock
+++ b/apps/web/tauri/Cargo.lock
@@ -6948,6 +6948,7 @@ dependencies = [
name = "tauri-plugin-network-status"
version = "0.1.0"
dependencies = [
+ "serde",
"tauri",
"tauri-plugin",
]
diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service.rs
index 3ce1b68d17..3d98d63a4a 100644
--- a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service.rs
+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/asset_service.rs
@@ -146,6 +146,12 @@ where
});
}
+ // Entrypoints select the active generation. Serving a previous
+ // index would prevent the new document from acknowledging it.
+ if path == &BundleAssetPath::entrypoint() {
+ return Ok(BundleAssetResolution::NotFound);
+ }
+
match &routes.fallback {
Some(BundleSource::Ota { root, .. }) => {
Ok(match self.assets.read_asset(root, path).await? {
diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models.rs
index 14a1f6ad34..6e8f2cb269 100644
--- a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models.rs
+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models.rs
@@ -111,25 +111,52 @@ pub struct BundleManifest {
pub bundle_build: u64,
/// Minimum native app build that can safely run this bundle.
pub min_native_build: u64,
+ /// Independent mobile build minima for schema 3 bundles.
+ #[serde(default)]
+ pub min_native_builds: Option<MobileBuildMinima>,
/// Short git SHA used to build the bundle.
pub git_sha: Option<String>,
/// Application package version used for the bundle.
pub app_version: String,
}
+/// Independent native build requirements for a shared bundle.
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct MobileBuildMinima {
+ /// Android versionCode.
+ pub android: u64,
+ /// iOS CFBundleVersion.
+ pub ios: u64,
+}
+
impl BundleManifest {
+ /// Select a native minimum without comparing independent platform numbers.
+ pub fn minimum_for(&self, target: Target) -> Option<u64> {
+ match (self.schema_version, &self.min_native_builds, target) {
+ (2, None, Target::Android) => None,
+ (2, None, _) => Some(self.min_native_build),
+ (3, Some(builds), Target::Android) => Some(builds.android),
+ (3, Some(builds), Target::Ios) => Some(builds.ios),
+ _ => None,
+ }
+ }
+
/// Read and validate a bundle manifest from disk.
pub async fn read(path: &Path, fs: &impl FsRepo) -> Option<Self> {
- let manifest = fs
+ let mut manifest = fs
.read_to_string(path)
.await
.ok()
.and_then(|s| serde_json::from_str::<Self>(&s).ok())?;
- if manifest.schema_version == 2 {
- Some(manifest)
+ let target = if cfg!(target_os = "android") {
+ Target::Android
+ } else if cfg!(target_os = "ios") {
+ Target::Ios
} else {
- None
- }
+ Target::Linux
+ };
+ manifest.min_native_build = manifest.minimum_for(target)?;
+ Some(manifest)
}
}
@@ -522,3 +549,7 @@ pub enum UpdateStatus {
/// The update has been applied successfully.
Completed(CompletedStatus),
}
+
+#[cfg(test)]
+#[path = "models/test.rs"]
+mod platform_test;
diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models/test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models/test.rs
new file mode 100644
index 0000000000..5ec26b0031
--- /dev/null
+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/models/test.rs
@@ -0,0 +1,23 @@
+use super::{BundleManifest, Target};
+
+fn manifest(schema: u8, minima: &str) -> BundleManifest {
+ serde_json::from_str(&format!(
+ r#"{{"schemaVersion":{schema},"bundleBuild":20,"minNativeBuild":0,"minNativeBuilds":{minima},"appVersion":"2.5.0"}}"#
+ )).unwrap()
+}
+
+#[test]
+fn platform_minima_are_independent_and_never_fall_back_to_legacy_zero() {
+ let bundle = manifest(3, r#"{"android":2050001,"ios":184}"#);
+ assert_eq!(bundle.minimum_for(Target::Android), Some(2_050_001));
+ assert_eq!(bundle.minimum_for(Target::Ios), Some(184));
+ assert_eq!(bundle.minimum_for(Target::Linux), None);
+ assert_eq!(manifest(3, "null").minimum_for(Target::Android), None);
+ assert_eq!(manifest(4, "null").minimum_for(Target::Android), None);
+ assert_eq!(
+ manifest(2, r#"{"android":9,"ios":2}"#).minimum_for(Target::Android),
+ None
+ );
+ assert_eq!(manifest(2, "null").minimum_for(Target::Android), None);
+ assert_eq!(manifest(2, "null").minimum_for(Target::Ios), Some(0));
+}
diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service.rs
index b29a4d2255..225550cfad 100644
--- a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service.rs
+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service.rs
@@ -301,6 +301,12 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery, S: TaskSpawner> Worker<U, Fs, Q,
.parent()
.unwrap_or(&unzip_status.zip_filename)
.to_path_buf();
+ // Keep the completion record outside the extracted archive.
+ // A retry must invalidate it before writing any assets.
+ self.fs_repo
+ .remove_file(&archive_target.with_extension("complete"))
+ .await
+ .context(UpdateError::Unzip)?;
let update_dir = archive_target.parent().map(Path::to_path_buf);
let (req, rx) = UnzipRequest::new(unzip_status.zip_filename, archive_target);
@@ -327,6 +333,13 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery, S: TaskSpawner> Worker<U, Fs, Q,
)
.await
.context(UpdateError::Unzip)?;
+ self.fs_repo
+ .write(
+ &bundle_dir.with_extension("complete"),
+ unzip_status.expected_bundle_build.to_string().as_bytes(),
+ )
+ .await
+ .context(UpdateError::Unzip)?;
if let Some(update_dir) = update_dir {
let marker = update_dir.join(PENDING_BUNDLE_ROOT_FILE);
if let Err(e) =
@@ -407,6 +420,12 @@ pub(crate) fn next_bundle_index(names: &[String]) -> u64 {
.map_or(0, |m| m + 1)
}
+async fn extraction_is_complete(fs: &impl FsRepo, bundle_dir: &Path, build: u64) -> bool {
+ fs.read_to_string(&bundle_dir.with_extension("complete"))
+ .await
+ .is_ok_and(|value| value == build.to_string())
+}
+
/// Search existing numeric bundle directories for one whose manifest matches
/// `bundle_build` and is compatible with this native app.
async fn find_cached_bundle(
@@ -429,7 +448,10 @@ async fn find_cached_bundle(
tracing::debug!("find_cached_bundle: no valid manifest in {dir:?}");
continue;
};
- if manifest.bundle_build == bundle_build && manifest.min_native_build <= native_build {
+ if manifest.bundle_build == bundle_build
+ && manifest.min_native_build <= native_build
+ && extraction_is_complete(fs, &dir, bundle_build).await
+ {
let entrypoint = dir.join(ENTRYPOINT_NAME);
if fs.read_to_string(&entrypoint).await.is_ok() {
tracing::debug!("find_cached_bundle: hit reusing {entrypoint:?}");
@@ -766,7 +788,8 @@ impl<Fs: FsRepo> Service<Fs> {
else {
continue;
};
- if manifest.bundle_build < self.embedded_bundle_build
+ if !extraction_is_complete(&self.fs_repo, &bundle_dir, manifest.bundle_build).await
+ || manifest.bundle_build < self.embedded_bundle_build
|| manifest.min_native_build > native_build
|| self
.fs_repo
@@ -804,7 +827,9 @@ impl<Fs: FsRepo> Service<Fs> {
};
let entrypoint = bundle_dir.join(ENTRYPOINT_NAME);
- let usable = manifest.bundle_build >= self.embedded_bundle_build
+ let usable = extraction_is_complete(&self.fs_repo, &bundle_dir, manifest.bundle_build)
+ .await
+ && 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 {
@@ -900,7 +925,8 @@ impl<Fs: FsRepo> Service<Fs> {
let Some(manifest) = self.bundle_root.manifest(&self.fs_repo).await else {
return false;
};
- manifest.bundle_build >= self.embedded_bundle_build
+ extraction_is_complete(&self.fs_repo, path, manifest.bundle_build).await
+ && manifest.bundle_build >= self.embedded_bundle_build
&& manifest.min_native_build <= native_build
}
}
@@ -982,6 +1008,8 @@ impl<Fs: FsRepo> Service<Fs> {
}
}
+#[cfg(test)]
+mod interruption_test;
#[cfg(test)]
mod network_test;
#[cfg(test)]
@@ -1053,7 +1081,7 @@ mod tests {
}
impl FakeFs {
- fn write_file(&self, path: impl Into<PathBuf>, contents: impl Into<String>) {
+ pub(super) 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);
@@ -1323,6 +1351,7 @@ mod tests {
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.with_extension("complete"), bundle_build.to_string());
fs.write_file(
dir.join("bundle-manifest.json"),
manifest_json(bundle_build, min_native_build),
diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/interruption_test.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/interruption_test.rs
new file mode 100644
index 0000000000..73bffee83f
--- /dev/null
+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/domain/service/interruption_test.rs
@@ -0,0 +1,39 @@
+use super::{
+ FsRepo, UpdateStatus, find_cached_bundle,
+ tests::{
+ FakeFs, cache_dir, seed_bundle, seed_persisted_bundle_root, service_with_status_and_fs,
+ },
+};
+
+#[tokio::test]
+async fn process_death_during_extraction_never_restores_or_reuses_partial_assets() {
+ let fs = FakeFs::default();
+ let cache = cache_dir();
+ let dir = seed_bundle(&fs, &cache, "1", 20, 0);
+ // Manifest and entrypoint can arrive before the JavaScript/assets.
+ fs.remove_file(&dir.with_extension("complete"))
+ .await
+ .unwrap();
+ assert!(find_cached_bundle(&fs, &cache, 20, 0).await.is_none());
+ let (mut service, _rx) = service_with_status_and_fs(UpdateStatus::Idle, fs.clone());
+ assert!(!service.load_bundle_root(&cache, 0).await);
+ assert!(service.bundle_root_path().is_none());
+}
+
+#[tokio::test]
+async fn torn_completion_record_and_evicted_entrypoint_fall_back_to_embedded() {
+ for missing_entrypoint in [false, true] {
+ let fs = FakeFs::default();
+ let cache = cache_dir();
+ let dir = seed_bundle(&fs, &cache, "1", 20, 0);
+ seed_persisted_bundle_root(&fs, &cache, &dir);
+ if missing_entrypoint {
+ fs.remove_file(&dir.join("index.html")).await.unwrap();
+ } else {
+ fs.write_file(dir.with_extension("complete"), "2");
+ }
+ let (mut service, _rx) = service_with_status_and_fs(UpdateStatus::Idle, fs.clone());
+ assert!(!service.load_bundle_root(&cache, 0).await);
+ assert!(service.bundle_root_path().is_none());
+ }
+}
diff --git a/apps/web/tauri/network_status_plugin/Cargo.toml b/apps/web/tauri/network_status_plugin/Cargo.toml
index 00da9dbada..94502adc28 100644
--- a/apps/web/tauri/network_status_plugin/Cargo.toml
+++ b/apps/web/tauri/network_status_plugin/Cargo.toml
@@ -12,3 +12,6 @@ tauri = { workspace = true }
[target.'cfg(target_os = "ios")'.dependencies]
tauri = { workspace = true, features = ["wry"] }
+
+[target.'cfg(target_os = "android")'.dependencies]
+serde = { version = "1", features = ["derive"] }
diff --git a/apps/web/tauri/network_status_plugin/android/build.gradle.kts b/apps/web/tauri/network_status_plugin/android/build.gradle.kts
new file mode 100644
index 0000000000..61ed110885
--- /dev/null
+++ b/apps/web/tauri/network_status_plugin/android/build.gradle.kts
@@ -0,0 +1,18 @@
+plugins {
+ id("com.android.library")
+ id("org.jetbrains.kotlin.android")
+}
+android {
+ namespace = "com.macro.network"
+ compileSdk = 36
+ defaultConfig { minSdk = 24 }
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_1_8
+ targetCompatibility = JavaVersion.VERSION_1_8
+ }
+ kotlinOptions { jvmTarget = "1.8" }
+}
+dependencies {
+ implementation(project(":tauri-android"))
+ implementation("androidx.appcompat:appcompat:1.7.0")
+}
diff --git a/apps/web/tauri/network_status_plugin/android/src/main/AndroidManifest.xml b/apps/web/tauri/network_status_plugin/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..d7546021b5
--- /dev/null
+++ b/apps/web/tauri/network_status_plugin/android/src/main/AndroidManifest.xml
@@ -0,0 +1,3 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+</manifest>
diff --git a/apps/web/tauri/network_status_plugin/android/src/main/java/com/macro/network/NetworkStatusPlugin.kt b/apps/web/tauri/network_status_plugin/android/src/main/java/com/macro/network/NetworkStatusPlugin.kt
new file mode 100644
index 0000000000..4b780df12c
--- /dev/null
+++ b/apps/web/tauri/network_status_plugin/android/src/main/java/com/macro/network/NetworkStatusPlugin.kt
@@ -0,0 +1,61 @@
+package com.macro.network
+
+import android.app.Activity
+import android.net.ConnectivityManager
+import android.net.Network
+import android.net.NetworkCapabilities
+import android.webkit.WebView
+import androidx.appcompat.app.AppCompatActivity
+import app.tauri.annotation.Command
+import app.tauri.annotation.InvokeArg
+import app.tauri.annotation.TauriPlugin
+import app.tauri.plugin.Channel
+import app.tauri.plugin.Invoke
+import app.tauri.plugin.JSObject
+import app.tauri.plugin.Plugin
+
+@InvokeArg
+internal class WatchStatusArgs { lateinit var channel: Channel }
+
+@TauriPlugin
+class NetworkStatusPlugin(private val activity: Activity) : Plugin(activity) {
+ private val connectivity = activity.getSystemService(ConnectivityManager::class.java)
+ private var channel: Channel? = null
+ private var registered = false
+ private val callback = object : ConnectivityManager.NetworkCallback() {
+ override fun onAvailable(network: Network) = publish()
+ override fun onLost(network: Network) = publish()
+ override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) = publish()
+ }
+
+ override fun load(webView: WebView) {
+ // API 24 default-network callbacks follow Wi-Fi/cellular handoffs.
+ connectivity.registerDefaultNetworkCallback(callback)
+ registered = true
+ }
+
+ @Command
+ fun watchStatus(invoke: Invoke) {
+ channel = invoke.parseArgs(WatchStatusArgs::class.java).channel
+ publish()
+ invoke.resolve()
+ }
+
+ override fun onResume(activity: AppCompatActivity) = publish()
+
+ override fun onDestroy(activity: AppCompatActivity) {
+ if (registered) connectivity.unregisterNetworkCallback(callback)
+ registered = false
+ channel = null
+ }
+
+ private fun publish() {
+ // Serialize callback and lifecycle delivery on the WebView thread.
+ activity.runOnUiThread {
+ val capabilities = connectivity.getNetworkCapabilities(connectivity.activeNetwork)
+ val online = capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true &&
+ capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+ channel?.send(JSObject().apply { put("status", if (online) "online" else "offline") })
+ }
+ }
+}
diff --git a/apps/web/tauri/network_status_plugin/build.rs b/apps/web/tauri/network_status_plugin/build.rs
index 66c7d07027..df5c7de932 100644
--- a/apps/web/tauri/network_status_plugin/build.rs
+++ b/apps/web/tauri/network_status_plugin/build.rs
@@ -1,6 +1,7 @@
fn main() {
tauri_plugin::Builder::new(&["watch_status"])
.ios_path("ios")
+ .android_path("android")
.try_build()
.unwrap();
}
diff --git a/apps/web/tauri/network_status_plugin/src/android.rs b/apps/web/tauri/network_status_plugin/src/android.rs
new file mode 100644
index 0000000000..26485a254e
--- /dev/null
+++ b/apps/web/tauri/network_status_plugin/src/android.rs
@@ -0,0 +1,21 @@
+use serde::Serialize;
+use tauri::{AppHandle, Manager, Runtime, ipc::Channel, plugin::PluginHandle};
+
+pub(crate) struct NetworkStatus<R: Runtime>(pub PluginHandle<R>);
+
+#[derive(Serialize)]
+struct WatchStatusArgs {
+ channel: Channel,
+}
+
+#[tauri::command]
+pub(crate) async fn watch_status<R: Runtime>(
+ app: AppHandle<R>,
+ channel: Channel,
+) -> Result<(), String> {
+ app.state::<NetworkStatus<R>>()
+ .0
+ .run_mobile_plugin_async("watchStatus", WatchStatusArgs { channel })
+ .await
+ .map_err(|error| error.to_string())
+}
diff --git a/apps/web/tauri/network_status_plugin/src/lib.rs b/apps/web/tauri/network_status_plugin/src/lib.rs
index 040201b320..46333ac1f2 100644
--- a/apps/web/tauri/network_status_plugin/src/lib.rs
+++ b/apps/web/tauri/network_status_plugin/src/lib.rs
@@ -1,19 +1,28 @@
-//! Tauri plugin exposing native iOS network-path status.
+//! Tauri plugin exposing native mobile network-path status.
#![deny(missing_docs)]
#[cfg(target_os = "ios")]
tauri::ios_plugin_binding!(init_plugin_network_status);
-/// Builds the `network-status` Tauri plugin.
-///
-/// On iOS this registers a Swift `NWPathMonitor` adapter. Other targets keep
-/// the plugin inert and continue using their existing browser connectivity
-/// integration.
+#[cfg(target_os = "android")]
+mod android;
+
+/// Builds the native mobile `network-status` Tauri plugin.
pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
- tauri::plugin::Builder::new("network-status")
+ let builder = tauri::plugin::Builder::new("network-status");
+ #[cfg(target_os = "android")]
+ let builder = builder.invoke_handler(tauri::generate_handler![android::watch_status]);
+ builder
.setup(|_app, _api| {
#[cfg(target_os = "ios")]
_api.register_ios_plugin(init_plugin_network_status)?;
+ #[cfg(target_os = "android")]
+ {
+ use tauri::Manager;
+ let handle =
+ _api.register_android_plugin("com.macro.network", "NetworkStatusPlugin")?;
+ _app.manage(android::NetworkStatus(handle));
+ }
Ok(())
})
.build()
diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.toml
index c6508e1a29..4934bff208 100644
--- a/apps/web/tauri/src-tauri/Cargo.toml
+++ b/apps/web/tauri/src-tauri/Cargo.toml
@@ -101,6 +101,7 @@ rustls-platform-verifier = "0.6"
tauri-plugin-android-auth = { path = "../android_auth_plugin" }
tauri-plugin-android-mobile = { path = "../android_mobile_plugin" }
tauri-plugin-android-push = { path = "../android_push_plugin" }
+tauri-plugin-network-status = { path = "../network_status_plugin" }
[target.'cfg(target_os = "ios")'.dependencies]
tauri-plugin-auth = { git = "https://github.com/macro-inc/tauri-plugins", rev = "6ddd6600e20436388f169e936b610fe93944b7b0" }
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index 96dcceb03d..25f138fed9 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -160,9 +160,29 @@ for compatible additions, queued work, and rollback behavior.
GraphQL hydration checkpoints require the native
`graphql_cache_current_storage_generation` command. When shipping this frontend
-through the bundle updater, set `MIN_NATIVE_BUILD` to the first native build that
-includes that command. Older binaries must receive a native update before this
-bundle; they cannot validate a saved hydration cursor against the cache database.
+through the bundle updater, set `MIN_NATIVE_BUILD_ANDROID` to the first Android
+versionCode that implements the command and `MIN_NATIVE_BUILD_IOS` to the first
+iOS CFBundleVersion that implements it. Set both together: build numbers are
+independent. The schema 3 manifest carries `minNativeBuilds: { android, ios }`;
+the endpoint returns the requesting platform's minimum in its existing response.
+The updater checks that minimum during extraction, restore, and application.
+Old schema 2 updaters reject schema 3 and continue using their existing bundle.
+Android cannot receive legacy schema 2 updates because their shared minimum
+cannot establish Android compatibility. `MIN_NATIVE_BUILD` remains supported
+for iOS/desktop-only schema 2 releases.
+
+Every new native command used by shared JS must raise the corresponding
+platform minimum to a binary that implements it. Optional reachability falls
+back to browser connectivity if an older native binary lacks the command.
+Deploy the updated native_app_service before publishing schema 3 archives;
+an old server returns the legacy minimum and the client rejects the mismatch.
+Never lower a minimum to force an incompatible update to apply.
+
+Extraction writes a sibling `<directory>.complete` record only after checksum,
+extraction, manifest, and entrypoint validation succeed. Directories without a
+matching completion record cannot be reused or restored. Previously cached OTA
+bundles lack this record and fall back to embedded assets on the first native
+upgrade; a compatible update can then be downloaded again.
Durable email-draft recovery additionally requires
`graphql_cache_inspect_mutations` and queued `client_metadata` support. Set
diff --git a/apps/web/tauri/src-tauri/capabilities/android.json b/apps/web/tauri/src-tauri/capabilities/android.json
index 0201053f4d..01b3c9a3db 100644
--- a/apps/web/tauri/src-tauri/capabilities/android.json
+++ b/apps/web/tauri/src-tauri/capabilities/android.json
@@ -9,6 +9,7 @@
"permissions": [
"android-auth:allow-authenticate",
"android-mobile:default",
- "android-push:default"
+ "android-push:default",
+ "network-status:allow-watch-status"
]
}
diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml
index f8e612805b..aa7a1fe2dd 100644
--- a/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml
+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml
@@ -10,6 +10,9 @@
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<application
+ android:allowBackup="false"
+ android:fullBackupContent="false"
+ android:dataExtractionRules="@xml/data_extraction_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.app"
diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/res/xml/data_extraction_rules.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 0000000000..3d9e205811
--- /dev/null
+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<data-extraction-rules>
+ <cloud-backup>
+ <exclude domain="root" path="." />
+ <exclude domain="device_root" path="." />
+ <exclude domain="device_file" path="." />
+ <exclude domain="device_database" path="." />
+ <exclude domain="device_sharedpref" path="." />
+ <exclude domain="file" path="." />
+ <exclude domain="database" path="." />
+ <exclude domain="sharedpref" path="." />
+ <exclude domain="external" path="." />
+ </cloud-backup>
+ <device-transfer>
+ <exclude domain="root" path="." />
+ <exclude domain="device_root" path="." />
+ <exclude domain="device_file" path="." />
+ <exclude domain="device_database" path="." />
+ <exclude domain="device_sharedpref" path="." />
+ <exclude domain="file" path="." />
+ <exclude domain="database" path="." />
+ <exclude domain="sharedpref" path="." />
+ <exclude domain="external" path="." />
+ </device-transfer>
+</data-extraction-rules>
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 955d8f9183..dd29a82120 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -183,7 +183,8 @@ pub fn run() {
builder = builder
.plugin(tauri_plugin_android_auth::init())
.plugin(tauri_plugin_android_mobile::init())
- .plugin(tauri_plugin_android_push::init());
+ .plugin(tauri_plugin_android_push::init())
+ .plugin(tauri_plugin_network_status::init());
}
// register the rest of the common plugins
diff --git a/crates/native_app_service/src/domain/models.rs b/crates/native_app_service/src/domain/models.rs
index a62074d4bf..9f47e9fe05 100644
--- a/crates/native_app_service/src/domain/models.rs
+++ b/crates/native_app_service/src/domain/models.rs
@@ -77,12 +77,37 @@ pub struct BundleManifest {
pub bundle_build: u64,
/// Minimum native app build that can safely run this bundle.
pub min_native_build: u64,
+ /// Platform-specific native minima. Schema 3 requires both mobile platforms.
+ #[serde(default)]
+ pub min_native_builds: Option<MobileBuildMinima>,
/// Short git SHA used to build the bundle.
pub git_sha: Option<String>,
/// Application package version used for the bundle.
pub app_version: String,
}
+/// Native build numbers are independent across mobile platforms.
+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
+pub struct MobileBuildMinima {
+ /// Minimum Android versionCode.
+ pub android: u64,
+ /// Minimum iOS CFBundleVersion.
+ pub ios: u64,
+}
+
+impl BundleManifest {
+ /// Select the minimum for the requesting platform, rejecting unknown schemas.
+ pub fn minimum_for(&self, target: AllTargets) -> Option<u64> {
+ match (self.schema_version, &self.min_native_builds, target) {
+ (2, None, AllTargets::Mobile(MobileTarget::Android)) => None,
+ (2, None, _) => Some(self.min_native_build),
+ (3, Some(builds), AllTargets::Mobile(MobileTarget::Android)) => Some(builds.android),
+ (3, Some(builds), AllTargets::Mobile(MobileTarget::Ios)) => Some(builds.ios),
+ _ => None,
+ }
+ }
+}
+
/// Action returned by the bundle update endpoint.
#[derive(Debug, Serialize)]
#[serde(tag = "action", rename_all = "lowercase")]
diff --git a/crates/native_app_service/src/domain/service.rs b/crates/native_app_service/src/domain/service.rs
index 301201856b..ce804787f9 100644
--- a/crates/native_app_service/src/domain/service.rs
+++ b/crates/native_app_service/src/domain/service.rs
@@ -51,11 +51,15 @@ where
return Ok(None);
}
- if manifest.min_native_build > native_build {
+ let Some(min_native_build) = manifest.minimum_for(target) else {
+ return Ok(None);
+ };
+
+ if min_native_build > native_build {
return Ok(Some(BundleAction::NativeUpdateRequired(
BundleNativeUpdateRequired {
bundle_build: manifest.bundle_build,
- min_native_build: manifest.min_native_build,
+ min_native_build,
},
)));
}
@@ -73,7 +77,7 @@ where
.await?;
Ok(Some(BundleAction::Update(BundleUpdate {
bundle_build: manifest.bundle_build,
- min_native_build: manifest.min_native_build,
+ min_native_build,
notes: None,
url: self.bundle_fetcher.get_app_bundle_path(),
checksum,
diff --git a/crates/native_app_service/src/tests.rs b/crates/native_app_service/src/tests.rs
index 4920d0e324..daff620994 100644
--- a/crates/native_app_service/src/tests.rs
+++ b/crates/native_app_service/src/tests.rs
@@ -41,6 +41,7 @@ impl MockBundleFetcher {
Self {
manifest: BundleManifest {
schema_version: 2,
+ min_native_builds: None,
bundle_build,
min_native_build,
git_sha: Some("abc123".to_string()),
@@ -256,7 +257,7 @@ async fn policy_returns_clear_when_current_active_bundle_is_revoked() {
}
#[tokio::test]
-async fn all_targets_can_receive_manifest_updates() {
+async fn legacy_manifests_only_update_platforms_with_legacy_numbering() {
let service = service(20, 0, BundleUpdatePolicy::default());
let mobile = MobileTarget::iter()
@@ -264,6 +265,15 @@ async fn all_targets_can_receive_manifest_updates() {
.chain(DesktopTarget::iter().map(AllTargets::Desktop));
for target in mobile {
+ if target == AllTargets::Mobile(MobileTarget::Android) {
+ assert_matches!(
+ service
+ .get_bundle_update(request(target, Arch::Aarch64, 10, 100))
+ .await,
+ Ok(None)
+ );
+ continue;
+ }
for arch in Arch::iter() {
assert_matches!(
service
@@ -399,3 +409,63 @@ fn with_policy_env(json: Option<&str>, file: Option<&str>, test: impl FnOnce())
test();
}
+
+#[tokio::test]
+async fn shared_bundle_uses_independent_mobile_build_minima() {
+ let mut service = service(20, 0, BundleUpdatePolicy::default());
+ service.bundle_fetcher.manifest.schema_version = 3;
+ service.bundle_fetcher.manifest.min_native_builds = Some(domain::models::MobileBuildMinima {
+ android: 2_050_001,
+ ios: 184,
+ });
+ for (target, build, minimum) in [
+ (MobileTarget::Android, 2_050_000, 2_050_001),
+ (MobileTarget::Ios, 183, 184),
+ ] {
+ assert_matches!(
+ service.get_bundle_update(request(AllTargets::Mobile(target), Arch::Aarch64, 10, build)).await,
+ Ok(Some(BundleAction::NativeUpdateRequired(required))) => {
+ assert_eq!(required.min_native_build, minimum);
+ }
+ );
+ assert_matches!(
+ service.get_bundle_update(request(AllTargets::Mobile(target), Arch::Aarch64, 10, minimum)).await,
+ Ok(Some(BundleAction::Update(update))) => {
+ assert_eq!(update.min_native_build, minimum);
+ }
+ );
+ }
+}
+
+#[tokio::test]
+async fn ambiguous_or_unknown_manifest_cannot_offer_an_update() {
+ let mut service = service(20, 0, BundleUpdatePolicy::default());
+ for schema in [3, 4] {
+ service.bundle_fetcher.manifest.schema_version = schema;
+ assert_matches!(
+ service
+ .get_bundle_update(request(
+ AllTargets::Mobile(MobileTarget::Android),
+ Arch::Aarch64,
+ 10,
+ 2_050_000
+ ))
+ .await,
+ Ok(None)
+ );
+ }
+ service.bundle_fetcher.manifest.schema_version = 2;
+ service.bundle_fetcher.manifest.min_native_builds =
+ Some(domain::models::MobileBuildMinima { android: 9, ios: 2 });
+ assert_matches!(
+ service
+ .get_bundle_update(request(
+ AllTargets::Mobile(MobileTarget::Android),
+ Arch::Aarch64,
+ 10,
+ 2_050_000
+ ))
+ .await,
+ Ok(None)
+ );
+}
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 91c9c62d4a..196f365388 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -812,6 +812,13 @@ Home does not bind Delete or Backspace to deleting list items. These keys remain
available to the open editor (for example, clearing a selected spreadsheet range).
Use the item menu to delete an item from Home.
+Home and Agents unsent composer storage follows the current account identity.
+Before identity is available, it uses memory only and does not restore legacy
+shared drafts or attachment projections. Logout
+clears composer drafts and attachment projections, including legacy keys. When
+checking Android draft recovery, verify the actual editor text after process
+death; storage unit tests alone do not establish lifecycle recovery.
+
`C A` (Create → Agent) opens the Agents new-conversation page and focuses its
message input; `C Shift+A` requests a new split. It does not open a modal or
create a session before the user sends. Repeating it focuses the existing draft.
@@ -884,3 +891,12 @@ retry errors inline. See [Email reminders](reminders.md).
Action dialogs share `ActionDialogShell` presentation slots: the same capped selection badges for single and multiple items, compact heading and copy, prominent fields, and an attached footer. Rename, delete, move, and shared confirmations use this layout. Bulk rename keeps bubble tabs and one first-item preview.
The Move to folder picker uses the Drive sidebar’s folder rows: neutral icons, trailing expand/collapse buttons, and indented branch guides. Click a folder to select it; use the chevron to expand it. Search and arrow-key navigation remain available.
+
+### Native update-required dialog
+
+When newer frontend JS requires a newer native app, the mobile shell offers
+**Update app** and **OK**. Update app uses the native opener; Android targets the
+HTTPS Play listing for `com.macro.app.prod`, allowing a browser when the Store app
+is absent. An opener failure displays an inline error and the dialog stays
+dismissible. A missing listing is handled in the external store/browser: return
+to Macro, dismiss, and retry later. Task 07 verifies the live listing.
diff --git a/docs/ANDROID_DEVELOPMENT.md b/docs/ANDROID_DEVELOPMENT.md
index 4140109797..ac1f5aec59 100644
--- a/docs/ANDROID_DEVELOPMENT.md
+++ b/docs/ANDROID_DEVELOPMENT.md
@@ -460,3 +460,124 @@ Publication procedure for the hosting owner:
route result. If rollback is needed, restore the saved JSON and metadata with
a conditional write against the published ETag, then invalidate the same URL.
Reconcile concurrent edits before restoring anything.
+
+## Offline and OTA qualification (Task 05)
+
+Use a dedicated installation. Local APK upgrades need the same package and
+signing key and an increasing versionCode. A local test key may sign a
+release-optimized APK; preserve it outside the checkout for local upgrades and
+never use it for Play uploads. To build an emulator APK, run
+`cargo tauri android build --target x86_64 --apk --ci` from
+`apps/web/tauri/src-tauri` inside the Android Nix shell. ARM64 uses the launcher
+above. Keep OTA enabled for update acceptance; `--no-default-features` qualifies
+only embedded behavior. Shared OTA builds need both `MIN_NATIVE_BUILD_ANDROID`
+and `MIN_NATIVE_BUILD_IOS`; see the
+[native compatibility contract](../apps/web/tauri/src-tauri/README.md).
+
+Android ConnectivityManager reports the validated default network and takes a
+fresh snapshot on resume. Captive/unvalidated networks count as offline. Older
+native binaries lacking the command retain browser connectivity. Neither signal
+proves a particular backend is reachable. The activity unregisters its monitor
+on destruction.
+
+Android backup is disabled. API 31+ cloud-backup/device-transfer rules exclude
+normal and device-protected private storage, databases, preferences, and external
+app files, including credentials, WebView cookies, cache, drafts, and staging.
+An app upgrade still preserves app-private data. Logout clears all query stores,
+including unhydrated entries, fences pending hydration, and clears the native
+normalized cache/queue. Failed wipes quarantine the disk namespace. The new query
+namespace deliberately discards legacy read caches on the first upgrade.
+
+Record device/API/WebView, APK certificate/versionCode, embedded/active bundle
+build, and these results for locally installed release builds:
+
+| Case | Required evidence |
+| --- | --- |
+| Acknowledged edit, queued/optimistic mutation, cached document/list, durable draft/upload workflows | Background/resume and process kill/relaunch preserve state; reconnect drains queued work without duplication |
+| Airplane mode, Wi-Fi/cellular transition, captive network | Correct native status; cached reads; session refresh; websocket subscriptions recover |
+| Missed websocket events | Replay deduplicates retained events; gaps resynchronize |
+| Logout and second-account login, including offline logout | No prior-account records, drafts, staged files, or queued writes appear or replay |
+| Local native upgrade signed with the same key | Data survives and build detection returns installed versionCode |
+| Higher Android minimum in a newer iOS/shared bundle; legacy/unknown metadata | Older Android stays functional and rejects incompatible JS |
+| Kill during download/extraction; truncated archive; cache eviction | Partial assets are never selected; failures retain working embedded/active assets |
+| Revocation, apply on resume, unavailable store handler/listing | Embedded fallback; correct generation acknowledgment; dismissible update dialog |
+| Lower-end physical hardware | Cold/warm launch and hydration times, large lists/documents, peak PSS, background CPU/battery and Doze |
+
+Background then use `adb shell am kill com.macro.app.prod` and verify the PID
+has disappeared for normal process death. Force-stop/relaunch is a separate case.
+Use `adb shell am start -W -n com.macro.app.prod/.MainActivity` for launch timings,
+`adb shell dumpsys meminfo com.macro.app.prod` for PSS, and Perfetto/Android Studio
+for rendering/CPU/battery evidence. A VM emulator cannot qualify physical battery,
+cellular handoffs, OEM memory pressure, or lower-end hardware. Do not reset shared
+device statistics or account data. Keep evidence free of credentials/content.
+
+Task 07 owns live Play listing verification and a real Play-delivered update.
+Task 05 retains offline/account isolation and shared-JS/older-native acceptance,
+using local release installations and local version upgrades. No Play Console is
+required.
+
+Local evidence recorded on 2026-09-30 uses an isolated API 36 x86_64 emulator
+with 2 GB RAM, production frontend, OTA enabled, and a local test signing key.
+Release versionCodes 2005000, 2005001, and 2005002 installed successfully.
+The final 2005001 → 2005002 upgrade preserved a committed native cache record and
+a WebView storage value; native build detection returned 2005002. Airplane mode
+reported offline then online; disabling Wi-Fi retained emulator cellular
+connectivity. Acknowledged native records and optimistic queued mutations
+survived background process death. The recovered queue allowed only one lease
+at a time; changing a synthetic account identity cleared the records and queue.
+The update-required dialog rendered and its explicit OK button dismissed it on
+Android; a mobile component regression covers unavailable-store failure.
+
+Signed-out launch was 837 ms initially and 186 ms after process death, with
+approximately 137 MiB app PSS after relaunch. A synthetic 5,000-document native
+cache write took 2.39 s; five cached reads took 15–21 ms, with approximately
+173 MiB app PSS afterward. These measure native cache/IPC, not document/list
+rendering or signed-in hydration. Immediate WebView writes need a disk flush:
+an immediate replacement-install test lost its sentinel; backgrounding for
+10 seconds before replacement preserved it. Acknowledged native database writes
+survived process death and upgrade independently of that WebView flush.
+
+Automated coverage includes platform-specific OTA minima and legacy rejection,
+interrupted extraction and missing completion markers, eviction/revocation and
+embedded fallback, cache/queue reopen, logout hydration fencing and durable
+query-store wiping, draft/upload persistence, session refresh, websocket
+reconnect/replay, native reachability, and store-link failure recovery.
+Additional installed-release evidence on 2026-10-01 uses two dedicated signed-in
+accounts and local signed upgrades through versionCode 2005005. Both accounts'
+acknowledged document edits and offline edits survived background process death
+and reopening the cached document. A fresh authenticated sync client confirmed
+account A's queued edit reached the server. A server-acknowledged peer edit made
+while the Android client was offline appeared exactly once after reconnect.
+Real offline logout followed by the second account's email-code login exposed
+neither the first account's draft nor its cached test document. A fresh
+authenticated sync client also confirmed account B's queued edit reached the
+server. Online logout of account B removed its session and composer storage.
+
+The Home Ask AI composer's unsent text and a file selected there while offline
+both disappeared after process death. Loss of these unsent Home inputs is an
+accepted behavior for Task 05, not an acceptance blocker. The original selected
+file remains on the device. This exception does not cover acknowledged document
+edits, durable drafts elsewhere, or committed upload workflows. Existing
+persisted Home/Agents composer and attachment projections use account-specific
+keys, and logout clears both legacy and scoped keys.
+
+A loopback-only controlled OTA feed exercised the installed release with real
+production assets. Dropped downloads, truncated archives, bad checksums, legacy
+and unknown schemas, and incompatible Android minima were rejected. Rejected
+updates retained an existing active bundle. Killing the process during Unzipping
+retained the previous complete bundle; retry completed. Resume applied a valid
+bundle with an Android-compatible minimum and a much newer iOS minimum.
+Background process death during download retained embedded assets, and retry
+completed. Revocation recovered to embedded assets. These tests found an embedded-entrypoint
+routing bug that could load the previous OTA index after rollback; the resolver
+now selects the embedded index, with regression coverage and installed-release
+rollback verification. The local-feed APK is a test artifact: its feed override
+must be omitted from a distributed release.
+
+Actual Android OS cache eviction is not qualified: the API 36 emulator's
+`pm clear --cache-only com.macro.app.prod` command hung and did not remove the
+active OTA cache. Missing-assets/eviction recovery remains covered by updater
+unit tests. Expired-session refresh, all pending-upload and queued-write logout
+paths, actual large-document rendering/hydration, and physical memory-pressure,
+battery, and cellular testing remain necessary for full Task 05 acceptance.
+Play verification remains Task 07.
diff --git a/tooling/native_app_server/Cargo.toml b/tooling/native_app_server/Cargo.toml
index 9be19d0e84..89210bb3f7 100644
--- a/tooling/native_app_server/Cargo.toml
+++ b/tooling/native_app_server/Cargo.toml
@@ -10,6 +10,7 @@ macro_env_var = { path = "../../crates/macro_env_var" }
native_app_service = { path = "../../crates/native_app_service" }
rootcause = { workspace = true }
semver = { workspace = true }
+serde_json = { workspace = true }
sha2 = { workspace = true }
tokio = { workspace = true }
tower-http = { workspace = true, features = ["fs"] }
@@ -17,3 +18,7 @@ tracing = { workspace = true }
tracing-subscriber = { workspace = true }
url = { workspace = true }
workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }
+zip = { workspace = true }
+
+[dev-dependencies]
+tempfile = { workspace = true }
diff --git a/tooling/native_app_server/src/main.rs b/tooling/native_app_server/src/main.rs
index 29418da7e7..1f31cc57fe 100644
--- a/tooling/native_app_server/src/main.rs
+++ b/tooling/native_app_server/src/main.rs
@@ -16,23 +16,20 @@ use tokio::io::AsyncReadExt;
use tower_http::services::ServeFile;
use url::Url;
-/// Bundle fetcher that always reports a very high bundle build, forcing an update.
+/// Bundle fetcher that reads compatibility metadata from the served archive.
/// 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 {
+struct ArchiveBundleFetcher {
bundle_url: Url,
archive_path: PathBuf,
}
-impl GetJsBundleManifest for AlwaysUpdateFetcher {
+impl GetJsBundleManifest for ArchiveBundleFetcher {
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(),
- })
+ let archive_path = self.archive_path.clone();
+ tokio::task::spawn_blocking(move || read_archive_manifest(&archive_path))
+ .await
+ .map_err(|e| report!(e).context(UpdateErr::Network))?
}
fn get_app_bundle_path(&self) -> Url {
@@ -50,6 +47,16 @@ impl GetJsBundleManifest for AlwaysUpdateFetcher {
}
}
+fn read_archive_manifest(path: &Path) -> Result<BundleManifest, Report<UpdateErr>> {
+ let file = std::fs::File::open(path).map_err(|e| report!(e).context(UpdateErr::Network))?;
+ let mut archive =
+ zip::ZipArchive::new(file).map_err(|e| report!(e).context(UpdateErr::Network))?;
+ let manifest = archive
+ .by_name("bundle-manifest.json")
+ .map_err(|e| report!(e).context(UpdateErr::Network))?;
+ serde_json::from_reader(manifest).map_err(|e| report!(e).context(UpdateErr::Network))
+}
+
async fn sha256_hex(path: &Path) -> std::io::Result<String> {
let mut file = tokio::fs::File::open(path).await?;
let mut hasher = Sha256::new();
@@ -82,7 +89,7 @@ async fn main() {
.expect("BUNDLE_URL must be a valid URL");
let service = NativeAppServiceImpl {
- bundle_fetcher: AlwaysUpdateFetcher {
+ bundle_fetcher: ArchiveBundleFetcher {
bundle_url,
archive_path: PathBuf::from(ARCHIVE_PATH),
},
@@ -105,3 +112,6 @@ async fn main() {
let listener = tokio::net::TcpListener::bind(ADDR).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
+
+#[cfg(test)]
+mod test;
diff --git a/tooling/native_app_server/src/test.rs b/tooling/native_app_server/src/test.rs
new file mode 100644
index 0000000000..2f2db8683f
--- /dev/null
+++ b/tooling/native_app_server/src/test.rs
@@ -0,0 +1,46 @@
+use std::io::Write;
+
+use native_app_service::domain::models::{AllTargets, MobileTarget};
+use zip::write::SimpleFileOptions;
+
+use super::read_archive_manifest;
+
+fn archive(schema: u64, minima: &str) -> tempfile::NamedTempFile {
+ let file = tempfile::NamedTempFile::new().unwrap();
+ let mut zip = zip::ZipWriter::new(file.reopen().unwrap());
+ zip.start_file("bundle-manifest.json", SimpleFileOptions::default())
+ .unwrap();
+ write!(zip, r#"{{"schemaVersion":{schema},"bundleBuild":123,"minNativeBuild":7,{minima}"appVersion":"2.5.0"}}"#).unwrap();
+ zip.finish().unwrap();
+ file
+}
+
+#[test]
+fn served_metadata_matches_archive_platform_minima_and_build() {
+ let file = archive(3, r#""minNativeBuilds":{"android":42,"ios":99},"#);
+ let manifest = read_archive_manifest(file.path()).unwrap();
+ assert_eq!(manifest.schema_version, 3);
+ assert_eq!(manifest.bundle_build, 123);
+ assert_eq!(
+ manifest.minimum_for(AllTargets::Mobile(MobileTarget::Android)),
+ Some(42)
+ );
+ assert_eq!(
+ manifest.minimum_for(AllTargets::Mobile(MobileTarget::Ios)),
+ Some(99)
+ );
+}
+
+#[test]
+fn legacy_archive_remains_legacy_and_android_rejects_it() {
+ let file = archive(2, "");
+ let manifest = read_archive_manifest(file.path()).unwrap();
+ assert_eq!(
+ manifest.minimum_for(AllTargets::Mobile(MobileTarget::Android)),
+ None
+ );
+ assert_eq!(
+ manifest.minimum_for(AllTargets::Mobile(MobileTarget::Ios)),
+ Some(7)
+ );
+}