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.

fix(web): recover from native and lazy-chunk build skew (#8217)

teob44c5f2ac5b2
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index ef55138bd6..16ee087083 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -682,6 +682,20 @@ on focus/reconnect; route existing subscriptions to billing management. Keep
known management access through refetch failures, but hide unconfirmed trials.
Reset rejected checkout offers before refetching eligibility.
+## Native commands
+
+Over-the-air bundles reach native apps older than the commands they call.
+`native-commands.json` lists every Tauri command the web code invokes directly,
+through a wrapper such as the cache host's `request`, or by `addPluginListener`.
+`src/lib/tauri/native-commands.test.ts` reads the calls with the TypeScript
+parser and fails when one is missing from that list, is not registered by the
+app (`generate_handler!` or an in-repo plugin's `build.rs`), or names its
+command with a value it cannot read: use a string literal, a constant, or a
+parameter typed as a union of literals. Commands that published plugins' own
+JavaScript packages call are not covered. Before adding a command to the list,
+raise `min-native-build.json` to the first build with it, or handle
+`Command … not found` in the caller (see the src-tauri README).
+
## Desktop release builds: generated WASM
Keep `nix/tauri-desktop.nix` in sync with generated WASM dependencies: desktop
diff --git a/apps/web/native-commands.json b/apps/web/native-commands.json
new file mode 100644
index 0000000000..bed3bec453
--- /dev/null
+++ b/apps/web/native-commands.json
@@ -0,0 +1,117 @@
+{
+ "commands": [
+ "ack_bundle_update_reload",
+ "check_for_update",
+ "clear_shared_files",
+ "close_linux_notification",
+ "flush_launch_deep_link",
+ "get_bundle_debug_info",
+ "get_bundle_update_status",
+ "get_macos_notification_permission",
+ "get_native_update_status",
+ "get_pending_share_filenames",
+ "grant_bundle_update",
+ "graphql_cache_calendar_commit",
+ "graphql_cache_calendar_range",
+ "graphql_cache_claim_next_mutation",
+ "graphql_cache_clear",
+ "graphql_cache_commit_optimistic_write",
+ "graphql_cache_current_revision",
+ "graphql_cache_current_storage_generation",
+ "graphql_cache_defer_optimistic_write",
+ "graphql_cache_delete_records",
+ "graphql_cache_enqueue_optimistic_mutation",
+ "graphql_cache_entity_filter",
+ "graphql_cache_hydrate",
+ "graphql_cache_init_with_schema",
+ "graphql_cache_inspect_mutations",
+ "graphql_cache_inspect_query",
+ "graphql_cache_inspect_query_variants",
+ "graphql_cache_invalidate",
+ "graphql_cache_read",
+ "graphql_cache_read_records_by_keys",
+ "graphql_cache_rollback_optimistic_write",
+ "graphql_cache_search",
+ "graphql_cache_teardown",
+ "graphql_cache_watch",
+ "graphql_cache_write",
+ "is_ipad",
+ "macrod_detect_agents",
+ "macrod_inspect",
+ "macrod_start",
+ "macrod_status",
+ "macrod_stop",
+ "macrod_support",
+ "perform_update",
+ "plugin:android-auth|authenticate",
+ "plugin:android-mobile|appendExport",
+ "plugin:android-mobile|beginExport",
+ "plugin:android-mobile|clearShares",
+ "plugin:android-mobile|discardExport",
+ "plugin:android-mobile|finishExport",
+ "plugin:android-mobile|getInsets",
+ "plugin:android-mobile|getPendingShares",
+ "plugin:android-mobile|register_listener",
+ "plugin:android-mobile|stageClipboardImage",
+ "plugin:android-push|acknowledge",
+ "plugin:android-push|check_permissions",
+ "plugin:android-push|configure",
+ "plugin:android-push|register",
+ "plugin:android-push|request_permissions",
+ "plugin:android-push|unwatch",
+ "plugin:android-push|watch",
+ "plugin:auth|authenticate",
+ "plugin:call-kit|abort_join",
+ "plugin:call-kit|can_use_full_screen_intent",
+ "plugin:call-kit|configure_tracing",
+ "plugin:call-kit|end_active_call",
+ "plugin:call-kit|get_active_call_state",
+ "plugin:call-kit|get_pending_answered_call",
+ "plugin:call-kit|get_voip_token",
+ "plugin:call-kit|open_full_screen_intent_settings",
+ "plugin:call-kit|prepare_join",
+ "plugin:call-kit|register_listener",
+ "plugin:call-kit|set_call_drawer_channel_title",
+ "plugin:call-kit|set_call_drawer_theme",
+ "plugin:call-kit|set_participant_display_name",
+ "plugin:call-kit|set_video_overlay_mode",
+ "plugin:call-kit|start_outgoing_call",
+ "plugin:call-kit|watch_call_answered",
+ "plugin:call-kit|watch_call_ended",
+ "plugin:call-kit|watch_connection_state",
+ "plugin:call-kit|watch_drawer_opened",
+ "plugin:call-kit|watch_participant_identities",
+ "plugin:edit-menu|set_native_menu_suppressed",
+ "plugin:file-export|appendExport",
+ "plugin:file-export|available",
+ "plugin:file-export|beginExport",
+ "plugin:file-export|discardExport",
+ "plugin:file-export|finishExport",
+ "plugin:network-status|watch_status",
+ "plugin:notifications|acknowledge_notification",
+ "plugin:notifications|check_permissions",
+ "plugin:notifications|clear_pending_notification",
+ "plugin:notifications|configure_recipient",
+ "plugin:notifications|get_pending_notification",
+ "plugin:notifications|release_notification_cover",
+ "plugin:notifications|unwatch_notifications",
+ "plugin:notifications|watch_notifications",
+ "plugin:opener|open_url",
+ "plugin:pasteboard|read_pasteboard_text",
+ "plugin:pasteboard|stage_pasteboard_image",
+ "plugin:photo-library|pick_photo_library_images",
+ "plugin:websocket|connect",
+ "plugin:websocket|recover",
+ "plugin:websocket|send",
+ "pop_shared_files",
+ "read_desktop_diagnostics",
+ "read_shared_file_text",
+ "record_frontend_diagnostic",
+ "request_macos_notification_permission",
+ "restart_native_update",
+ "send_linux_notification",
+ "send_macos_notification",
+ "upload_staged_file_to_presigned_url",
+ "whatsapp_passkey_authenticate"
+ ]
+}
diff --git a/apps/web/src/index.tsx b/apps/web/src/index.tsx
index 8bce11c741..a7789d54c2 100644
--- a/apps/web/src/index.tsx
+++ b/apps/web/src/index.tsx
@@ -10,7 +10,7 @@ import { initializeLexical } from '@core/component/LexicalMarkdown/init';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { getPlatform, isTauri } from '@core/util/platform';
import { platformFetch } from '@core/util/platformFetch';
-import { promptReloadForFailedLoad } from '@core/util/reloadForNewerBuild';
+import { recoverFromFailedLoad } from '@core/util/reloadForNewerBuild';
import { Telemetry } from '@macro-inc/observability';
import { initMonochromeIcons } from '@ui/utils/monochromeIcons';
import { ErrorBoundary, render } from 'solid-js/web';
@@ -135,11 +135,12 @@ async function main() {
// during `vite dev` (but not dev builds), don't inject analytics/observability
if (!import.meta.hot) {
- // this event is emitted when dynamically loading a module fails
- // for example when you're using the app and a new version is deployed
- // The rail's update button offers the reload (a toast on touch layouts).
+ // this event is emitted when dynamically loading a module or its CSS
+ // fails, for example when you're using the app and a new version is
+ // deployed. Reloads once, or offers the reload on the rail's update button
+ // (a toast on touch layouts).
window.addEventListener('vite:preloadError', () => {
- promptReloadForFailedLoad();
+ recoverFromFailedLoad();
});
}
diff --git a/apps/web/src/lib/core/mobile/nativeUpdateRequired.test.ts b/apps/web/src/lib/core/mobile/nativeUpdateRequired.test.ts
new file mode 100644
index 0000000000..e4d7d9e00c
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/nativeUpdateRequired.test.ts
@@ -0,0 +1,21 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import {
+ nativeUpdateRequired,
+ requireNativeUpdate,
+ resetNativeUpdateRequiredForTests,
+} from './nativeUpdateRequired';
+
+describe('requireNativeUpdate', () => {
+ beforeEach(() => {
+ resetNativeUpdateRequiredForTests();
+ });
+
+ it('keeps the first reason, so the request is shown once', () => {
+ expect(nativeUpdateRequired()).toBeUndefined();
+
+ requireNativeUpdate('Update Macro to use the local cache.');
+ requireNativeUpdate('Update Macro to sync drafts.');
+
+ expect(nativeUpdateRequired()).toBe('Update Macro to use the local cache.');
+ });
+});
diff --git a/apps/web/src/lib/core/mobile/nativeUpdateRequired.ts b/apps/web/src/lib/core/mobile/nativeUpdateRequired.ts
new file mode 100644
index 0000000000..398df6e3dc
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/nativeUpdateRequired.ts
@@ -0,0 +1,20 @@
+import { createSignal } from 'solid-js';
+
+const [nativeUpdateRequired, setNativeUpdateRequired] = createSignal<string>();
+
+/** Why this web bundle needs a newer native app, once something found out. */
+export { nativeUpdateRequired };
+
+/**
+ * This web bundle needs a native command the installed app lacks, which
+ * happens when an over-the-air bundle outruns the app. The app shell asks the
+ * user to update; the first reason wins, so the request is shown once.
+ */
+export function requireNativeUpdate(reason: string): void {
+ if (nativeUpdateRequired() === undefined) setNativeUpdateRequired(reason);
+}
+
+/** Test seam: forget the request. */
+export function resetNativeUpdateRequiredForTests(): void {
+ setNativeUpdateRequired(undefined);
+}
diff --git a/apps/web/src/lib/core/util/reloadForNewerBuild.test.ts b/apps/web/src/lib/core/util/reloadForNewerBuild.test.ts
index 32a12954e1..f3152b6da4 100644
--- a/apps/web/src/lib/core/util/reloadForNewerBuild.test.ts
+++ b/apps/web/src/lib/core/util/reloadForNewerBuild.test.ts
@@ -9,7 +9,9 @@ import {
holdAutomaticReload,
pendingWebUpdate,
promptReloadForFailedLoad,
+ type ReloadOnce,
type ReloadPage,
+ recoverFromFailedLoad,
reloadForNewerBuild,
resetReloadForNewerBuildForTests,
} from './reloadForNewerBuild';
@@ -153,3 +155,137 @@ describe('promptReloadForFailedLoad', () => {
expect(pendingWebUpdate()?.reload).toBeTypeOf('function');
});
});
+
+describe('recoverFromFailedLoad', () => {
+ beforeEach(() => {
+ resetReloadForNewerBuildForTests();
+ sessionStorage.clear();
+ });
+
+ const reloadOnce = (): ReloadOnce & { claimed: Set<string> } => {
+ const claimed = new Set<string>();
+ return {
+ claimed,
+ claim(build) {
+ if (claimed.has(build)) return false;
+ claimed.add(build);
+ return true;
+ },
+ };
+ };
+
+ it('reloads the visible tab right away, once per build', () => {
+ const once = reloadOnce();
+ const { page, prompts } = fakePage({ hidden: false, offline: false });
+
+ recoverFromFailedLoad(page, once, 'build-a');
+ expect(page.reload).toHaveBeenCalledExactlyOnceWith('failed_load_recovery');
+ expect(prompts).toHaveLength(0);
+
+ // The reload landed on the same build again, for example from a stale
+ // cache: offer the reload instead of looping.
+ recoverFromFailedLoad(page, once, 'build-a');
+ expect(page.reload).toHaveBeenCalledOnce();
+ expect(prompts).toHaveLength(1);
+
+ resetReloadForNewerBuildForTests();
+ recoverFromFailedLoad(page, once, 'build-b');
+ expect(page.reload).toHaveBeenCalledTimes(2);
+ });
+
+ it('only offers the reload while offline, holding work, or writing text', () => {
+ const offline = fakePage({ hidden: false, offline: true });
+ const once = reloadOnce();
+ recoverFromFailedLoad(offline.page, once, 'build-a');
+ expect(offline.page.reload).not.toHaveBeenCalled();
+ expect(offline.prompts).toHaveLength(1);
+
+ resetReloadForNewerBuildForTests();
+ const release = holdAutomaticReload();
+ const held = fakePage({ hidden: false, offline: false });
+ recoverFromFailedLoad(held.page, once, 'build-a');
+ expect(held.page.reload).not.toHaveBeenCalled();
+ release();
+
+ resetReloadForNewerBuildForTests();
+ const writing = fakePage({
+ hidden: false,
+ offline: false,
+ editingText: true,
+ });
+ recoverFromFailedLoad(writing.page, once, 'build-a');
+ expect(writing.page.reload).not.toHaveBeenCalled();
+
+ // None of those spent the one automatic reload.
+ expect(once.claimed.size).toBe(0);
+ });
+
+ it('reloads a hidden tab by itself at most once per build', () => {
+ const once = reloadOnce();
+ const first = fakePage({ hidden: true, offline: false });
+ recoverFromFailedLoad(first.page, once, 'build-a');
+ expect(first.page.reload).toHaveBeenCalledExactlyOnceWith(
+ 'failed_load_recovery'
+ );
+
+ // The reload landed on the same build, still hidden: offer the reload
+ // without reloading again, now or when the tab is hidden later.
+ resetReloadForNewerBuildForTests();
+ const again = fakePage({ hidden: true, offline: false });
+ recoverFromFailedLoad(again.page, once, 'build-a');
+ again.hide();
+ expect(again.page.reload).not.toHaveBeenCalled();
+ expect(again.prompts).toHaveLength(1);
+ });
+
+ it('spends the allowance when an offered reload runs by itself later', () => {
+ const once = reloadOnce();
+ const offline = fakePage({ hidden: true, offline: true });
+ recoverFromFailedLoad(offline.page, once, 'build-a');
+ expect(offline.page.reload).not.toHaveBeenCalled();
+
+ offline.goOnline();
+ expect(offline.page.reload).toHaveBeenCalledExactlyOnceWith(
+ 'cache_replaced_automatic'
+ );
+ expect(once.claimed).toEqual(new Set(['build-a']));
+ });
+
+ it('remembers the reload in session storage and never reloads without it', () => {
+ const first = fakePage({ hidden: false, offline: false });
+ recoverFromFailedLoad(first.page, undefined, 'build-a');
+ expect(first.page.reload).toHaveBeenCalledOnce();
+
+ resetReloadForNewerBuildForTests();
+ const again = fakePage({ hidden: false, offline: false });
+ recoverFromFailedLoad(again.page, undefined, 'build-a');
+ expect(again.page.reload).not.toHaveBeenCalled();
+ expect(again.prompts).toHaveLength(1);
+
+ // Another build reloaded since: build-a still never reloads again, so two
+ // stale builds served in turn cannot reload each other.
+ resetReloadForNewerBuildForTests();
+ const next = fakePage({ hidden: false, offline: false });
+ recoverFromFailedLoad(next.page, undefined, 'build-c');
+ expect(next.page.reload).toHaveBeenCalledOnce();
+ resetReloadForNewerBuildForTests();
+ const back = fakePage({ hidden: false, offline: false });
+ recoverFromFailedLoad(back.page, undefined, 'build-a');
+ expect(back.page.reload).not.toHaveBeenCalled();
+
+ resetReloadForNewerBuildForTests();
+ const unavailable = vi
+ .spyOn(Storage.prototype, 'getItem')
+ .mockImplementation(() => {
+ throw new DOMException('denied', 'SecurityError');
+ });
+ try {
+ const noStorage = fakePage({ hidden: false, offline: false });
+ recoverFromFailedLoad(noStorage.page, undefined, 'build-b');
+ expect(noStorage.page.reload).not.toHaveBeenCalled();
+ expect(noStorage.prompts).toHaveLength(1);
+ } finally {
+ unavailable.mockRestore();
+ }
+ });
+});
diff --git a/apps/web/src/lib/core/util/reloadForNewerBuild.ts b/apps/web/src/lib/core/util/reloadForNewerBuild.ts
index 937b51016b..2d74081279 100644
--- a/apps/web/src/lib/core/util/reloadForNewerBuild.ts
+++ b/apps/web/src/lib/core/util/reloadForNewerBuild.ts
@@ -126,8 +126,10 @@ export function reloadForNewerBuild(
* the offer again even if it was dismissed, since something the user opened
* just failed.
*/
-export function promptReloadForFailedLoad(): void {
- reloadForNewerBuild();
+export function promptReloadForFailedLoad(
+ page: ReloadPage = browserPage
+): void {
+ reloadForNewerBuild(page);
const current = pendingWebUpdate();
setPendingWebUpdate({
reload: () => reloadApp('failed_load_recovery'),
@@ -136,6 +138,72 @@ export function promptReloadForFailedLoad(): void {
});
}
+/** Allows one automatic reload per build; replaced in tests. */
+export interface ReloadOnce {
+ /** Records a reload of `build`; false when it already reloaded this session
+ * or the reload cannot be recorded, so a reload can never loop. */
+ claim(build: string): boolean;
+}
+
+const FAILED_LOAD_RELOAD_KEY = 'macro:failed-load-reload';
+
+/** Records every build this tab session reloaded for, so two stale builds
+ * served in turn cannot reload each other in a loop. */
+const sessionReloadOnce: ReloadOnce = {
+ claim(build) {
+ try {
+ const saved: unknown = JSON.parse(
+ sessionStorage.getItem(FAILED_LOAD_RELOAD_KEY) ?? '[]'
+ );
+ const builds = Array.isArray(saved) ? saved : [];
+ if (builds.includes(build)) return false;
+ sessionStorage.setItem(
+ FAILED_LOAD_RELOAD_KEY,
+ JSON.stringify([...builds, build])
+ );
+ return true;
+ } catch {
+ return false;
+ }
+ },
+};
+
+const currentBuild = `${import.meta.env.__APP_VERSION__ ?? 'dev'}@${
+ import.meta.env.__APP_BUILD_TIME__ ?? 0
+}`;
+
+/**
+ * A lazy chunk or its CSS failed to load, usually because a deploy removed this
+ * build's files. Reloads into the deployed build right away when the reload
+ * loses nothing: the device is online, nothing holds the tab, and no text is
+ * being written. Otherwise it offers the reload, which reloads a hidden tab by
+ * itself. Either automatic reload happens once per build per tab session, so a
+ * stale cache serving this build again cannot loop.
+ */
+export function recoverFromFailedLoad(
+ page: ReloadPage = browserPage,
+ reloadOnce: ReloadOnce = sessionReloadOnce,
+ build: string = currentBuild
+): void {
+ if (
+ !page.isOffline() &&
+ holds.size === 0 &&
+ !page.isEditingText() &&
+ reloadOnce.claim(build)
+ ) {
+ page.reload('failed_load_recovery');
+ return;
+ }
+ promptReloadForFailedLoad({
+ ...page,
+ reload(reason) {
+ if (reason !== 'cache_replaced_automatic' || reloadOnce.claim(build)) {
+ page.reload(reason);
+ }
+ },
+ });
+}
+
/** Test seam: forget the scheduled reload and every hold. */
export function resetReloadForNewerBuildForTests(): void {
scheduled = false;
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index f3263d7dee..32cd5639ce 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -180,6 +180,32 @@ describe('createTauriCacheHost', () => {
host.dispose();
});
+ it('asks for an app update instead of running an older compiled-in schema', async () => {
+ const onInitializationError = vi.fn();
+ invokeMock.mockImplementation(async (command: string) => {
+ if (command === 'graphql_cache_init_with_schema')
+ throw 'Command graphql_cache_init_with_schema not found';
+ return null;
+ });
+ const host = createTauriCacheHost({
+ scope: 'pre-sdl-native',
+ onInitializationError,
+ });
+ await vi.waitFor(() =>
+ expect(onInitializationError).toHaveBeenCalledOnce()
+ );
+ expect(onInitializationError).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'NativeCacheUpgradeRequiredError',
+ message: expect.stringContaining('use the local cache'),
+ })
+ );
+ expect(invokeMock.mock.calls.map(([command]) => command)).toEqual([
+ 'graphql_cache_init_with_schema',
+ ]);
+ host.dispose();
+ });
+
it('projects selected records by explicit key', async () => {
const records = [
{
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
index 297e6d3c0a..f05a177a3a 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -105,12 +105,21 @@ const CALENDAR_RANGE_COMMAND = 'graphql_cache_calendar_range';
const CALENDAR_COMMIT_COMMAND = 'graphql_cache_calendar_commit';
const INSPECT_MUTATIONS_COMMAND = 'graphql_cache_inspect_mutations';
-/** An OTA bundle cannot safely replay drafts using an older native queue API. */
+const INIT_COMMAND = 'graphql_cache_init_with_schema';
+
+const DRAFTS_NEED_UPDATE =
+ 'Update Macro to sync drafts saved on this device. Your queued drafts are preserved until the app is updated.';
+const CACHE_NEEDS_UPDATE =
+ 'Update Macro to use the local cache on this device. Until the app is updated, drafts saved here do not sync, and queued drafts are preserved.';
+
+/**
+ * The installed native app is older than this OTA bundle and lacks a cache
+ * command it needs. OTA updates cannot add Rust commands, so only an app
+ * update helps; the bundle runs uncached until then.
+ */
export class NativeCacheUpgradeRequiredError extends Error {
- constructor() {
- super(
- 'Update Macro to sync drafts saved on this device. Your queued drafts are preserved until the app is updated.'
- );
+ constructor(message: string = DRAFTS_NEED_UPDATE) {
+ super(message);
this.name = 'NativeCacheUpgradeRequiredError';
}
}
@@ -256,20 +265,27 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
const { default: schemaSdl } = await import(
'../../../../../../static_assets/schema.graphql?raw'
);
- await request<void>('graphql_cache_init_with_schema', {
- scope: options.scope,
- hotCapacity: options.hotCapacity,
- schemaSdl,
- });
+ // An app from before runtime SDL loading has no such command. Its own
+ // `graphql_cache_init` would run its compiled-in schema, which can lack
+ // fields this bundle reads, so the bundle stays uncached instead.
+ try {
+ await request<void>(INIT_COMMAND, {
+ scope: options.scope,
+ hotCapacity: options.hotCapacity,
+ schemaSdl,
+ });
+ } catch (error) {
+ if (isMissingCommand(error, INIT_COMMAND)) {
+ throw new NativeCacheUpgradeRequiredError(CACHE_NEEDS_UPDATE);
+ }
+ throw error;
+ }
// Probe before any enqueue/claim. Older binaries silently ignore new
// metadata arguments, so waiting until a draft fails would lose correlation.
try {
await request<MutationInspection[]>(INSPECT_MUTATIONS_COMMAND, {});
} catch (error) {
- if (
- error instanceof Error &&
- error.message === `Command ${INSPECT_MUTATIONS_COMMAND} not found`
- ) {
+ if (isMissingCommand(error, INSPECT_MUTATIONS_COMMAND)) {
throw new NativeCacheUpgradeRequiredError();
}
throw error;
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
index 21b6b3cfef..3d6a6bd089 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
@@ -1421,14 +1421,13 @@ describe('GraphQL Soup browser cache session gate', () => {
const { NativeCacheUpgradeRequiredError } = await import(
'@graphql-cache/host/tauri-host'
);
+ const { nativeUpdateRequired, resetNativeUpdateRequiredForTests } =
+ await import('@core/mobile/nativeUpdateRequired');
+ resetNativeUpdateRequiredForTests();
const cached = soup.getGraphqlSoupClient();
mocks.failInitialization(new NativeCacheUpgradeRequiredError());
- expect(mocks.toastFailure).toHaveBeenCalledWith(
- 'Macro update required',
- expect.objectContaining({
- subtext: expect.stringContaining('queued drafts are preserved'),
- })
- );
+ expect(nativeUpdateRequired()).toContain('queued drafts are preserved');
+ expect(mocks.toastFailure).not.toHaveBeenCalled();
expect(soup.graphqlCacheEnabled()).toBe(false);
expect(soup.getGraphqlSoupClient()).not.toBe(cached);
expect(mocks.host.dispose).toHaveBeenCalledOnce();
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
index 1b987c0db3..e6eee43490 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
@@ -5,6 +5,7 @@ import {
isFeatureEnabled,
} from '@core/constant/featureFlags';
import { SERVER_HOSTS } from '@core/constant/servers';
+import { requireNativeUpdate } from '@core/mobile/nativeUpdateRequired';
import { hasLoginCookie } from '@core/util/cookies';
import { fetchToken } from '@core/util/fetchWithToken';
import { fireAndForget } from '@core/util/fireAndForget';
@@ -759,19 +760,16 @@ export function getGraphqlSoupClient(): Client {
}
reportCacheError(error, 'initialization');
fallbackAfterInitializationFailure(error);
- toast.failure(
- error instanceof NativeCacheUpgradeRequiredError
- ? 'Macro update required'
- : 'Local cache unavailable',
- {
+ if (error instanceof NativeCacheUpgradeRequiredError) {
+ requireNativeUpdate(error.message);
+ } else {
+ toast.failure('Local cache unavailable', {
subtext:
- error instanceof NativeCacheUpgradeRequiredError
- ? error.message
- : cacheRecovery.state() === 'unavailable'
- ? 'Drafts remain on this device. Reconnect or retry draft synchronization.'
- : 'Queued changes are preserved. Update or reload Macro to recover local storage.',
- }
- );
+ cacheRecovery.state() === 'unavailable'
+ ? 'Drafts remain on this device. Reconnect or retry draft synchronization.'
+ : 'Queued changes are preserved. Update or reload Macro to recover local storage.',
+ });
+ }
console.warn(
'graphql cache async init failed; using uncached client',
error
diff --git a/apps/web/src/lib/tauri/TauriProvider.tsx b/apps/web/src/lib/tauri/TauriProvider.tsx
index b229607fb9..99383da517 100644
--- a/apps/web/src/lib/tauri/TauriProvider.tsx
+++ b/apps/web/src/lib/tauri/TauriProvider.tsx
@@ -3,6 +3,7 @@ import { useCallKitSetup } from '@channel/Call/use-callkit';
import { useAndroidBack } from '@core/mobile/androidBack';
import { useAndroidWindowInsets } from '@core/mobile/androidWindowInsets';
import { NativeAppUpdateRequiredDialog } from '@core/mobile/NativeAppUpdateRequiredDialog';
+import { nativeUpdateRequired } from '@core/mobile/nativeUpdateRequired';
import { fireAndForget } from '@core/util/fireAndForget';
import { isPlatform, isTauri } from '@core/util/platform';
import { Telemetry } from '@macro-inc/observability';
@@ -89,6 +90,7 @@ function TauriProvider(props: { children: JSX.Element }) {
setNativeAppUpdateRequiredDialogOpen,
] = createSignal(false);
let hasShownNativeAppUpdateRequiredDialog = false;
+ let hasShownNativeUpdateReason = false;
function performBundleUpdate() {
invoke<boolean>('perform_update').catch((e) =>
@@ -97,14 +99,17 @@ function TauriProvider(props: { children: JSX.Element }) {
}
createEffect(() => {
- if (
- hasShownNativeAppUpdateRequiredDialog ||
- !shouldShowNativeAppUpdateRequiredDialog(bundleUpdateStatus())
- ) {
- return;
- }
+ const reason = nativeUpdateRequired();
+ // A missing cache command opens the dialog once with its reason, even
+ // after the bundle updater's request was dismissed: it replaces a toast.
+ const showReason = reason !== undefined && !hasShownNativeUpdateReason;
+ const showBundle =
+ !hasShownNativeAppUpdateRequiredDialog &&
+ shouldShowNativeAppUpdateRequiredDialog(bundleUpdateStatus());
+ if (!showReason && !showBundle) return;
hasShownNativeAppUpdateRequiredDialog = true;
+ if (reason !== undefined) hasShownNativeUpdateReason = true;
setNativeAppUpdateRequiredDialogOpen(true);
});
@@ -192,9 +197,10 @@ function TauriProvider(props: { children: JSX.Element }) {
open={nativeAppUpdateRequiredDialogOpen()}
onClose={() => setNativeAppUpdateRequiredDialogOpen(false)}
description={
- isPlatform('desktop') && nativeUpdates.status().status !== 'Disabled'
+ nativeUpdateRequired() ??
+ (isPlatform('desktop') && nativeUpdates.status().status !== 'Disabled'
? nativeUpdateDescription(nativeUpdates.status())
- : undefined
+ : undefined)
}
onRestart={
nativeUpdates.status().status === 'Ready'
diff --git a/apps/web/src/lib/tauri/native-commands.test.ts b/apps/web/src/lib/tauri/native-commands.test.ts
new file mode 100644
index 0000000000..bf127faaab
--- /dev/null
+++ b/apps/web/src/lib/tauri/native-commands.test.ts
@@ -0,0 +1,392 @@
+import { readdirSync, readFileSync } from 'node:fs';
+import { dirname, join, relative, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import ts from 'typescript';
+import { describe, expect, it } from 'vitest';
+import nativeCommands from '../../../native-commands.json';
+
+const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
+const repositoryRoot = resolve(webRoot, '../..');
+const tauriRoot = resolve(webRoot, 'tauri');
+const SOURCE_ROOTS = ['apps/web/src', 'packages'];
+const TAURI_CORE = '@tauri-apps/api/core';
+// Stands for a wrapper's command parameter while reading its invoke call.
+const PARAMETER = '\u0000';
+
+function sourceFiles(dir: string): string[] {
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ return entry.name === 'node_modules' || entry.name === 'dist'
+ ? []
+ : sourceFiles(path);
+ }
+ return /\.tsx?$/.test(entry.name) &&
+ !/\.(test|spec)\.tsx?$/.test(entry.name) &&
+ !entry.name.endsWith('.d.ts')
+ ? [path]
+ : [];
+ });
+}
+
+function walk(node: ts.Node, visit: (node: ts.Node) => void): void {
+ visit(node);
+ node.forEachChild((child) => walk(child, visit));
+}
+
+/** The named functions around `node`, innermost first. */
+function enclosingFunctions(
+ node: ts.Node
+): Array<{ name: string; declaration: ts.SignatureDeclaration }> {
+ const functions: Array<{
+ name: string;
+ declaration: ts.SignatureDeclaration;
+ }> = [];
+ for (let at = node.parent; at; at = at.parent) {
+ if (!ts.isFunctionLike(at)) continue;
+ const declared =
+ ts.isFunctionDeclaration(at) && at.name
+ ? at.name
+ : ts.isVariableDeclaration(at.parent)
+ ? at.parent.name
+ : undefined;
+ if (declared && ts.isIdentifier(declared)) {
+ functions.push({ name: declared.text, declaration: at });
+ }
+ }
+ return functions;
+}
+
+/** String values of a parameter type that is a union of string literals. */
+function literalUnionValues(
+ type: ts.TypeNode | undefined
+): string[] | undefined {
+ const members = type && ts.isUnionTypeNode(type) ? type.types : [type];
+ const values = members.map((member) =>
+ member && ts.isLiteralTypeNode(member) && ts.isStringLiteral(member.literal)
+ ? member.literal.text
+ : undefined
+ );
+ return values.every((value) => value !== undefined) ? values : undefined;
+}
+
+/** The variable named `name` declared directly in a block or file. */
+function localDeclaration(
+ container: ts.Node,
+ name: string
+): ts.VariableDeclaration | undefined {
+ if (!ts.isSourceFile(container) && !ts.isBlock(container)) return undefined;
+ for (const statement of container.statements) {
+ if (!ts.isVariableStatement(statement)) continue;
+ const declaration = statement.declarationList.declarations.find(
+ (d) => ts.isIdentifier(d.name) && d.name.text === name
+ );
+ if (declaration) return declaration;
+ }
+ return undefined;
+}
+
+/**
+ * Values of the binding an identifier refers to, found by scope: a `const`
+ * string, a parameter typed as a literal union, or the command parameter of
+ * the wrapper being read. Anything else, a `let` included, is unreadable.
+ */
+function bindingValues(
+ name: ts.Identifier,
+ wrapper?: ts.SignatureDeclaration
+): string[] | undefined {
+ for (let at = name.parent; at; at = at.parent) {
+ if (ts.isFunctionLike(at)) {
+ const parameter = at.parameters.find(
+ (p) => ts.isIdentifier(p.name) && p.name.text === name.text
+ );
+ if (parameter) {
+ return at === wrapper && parameter === at.parameters[0]
+ ? [PARAMETER]
+ : literalUnionValues(parameter.type);
+ }
+ }
+ const declaration = localDeclaration(at, name.text);
+ if (declaration) {
+ const constant =
+ ts.isVariableDeclarationList(declaration.parent) &&
+ (declaration.parent.flags & ts.NodeFlags.Const) !== 0;
+ return constant &&
+ declaration.initializer &&
+ ts.isStringLiteralLike(declaration.initializer)
+ ? [declaration.initializer.text]
+ : undefined;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Every value a command expression can have, or undefined when it is computed
+ * from something this scan cannot read. Reads string literals, conditionals,
+ * templates, and the bindings `bindingValues` reads.
+ */
+function commandValues(
+ node: ts.Expression,
+ wrapper?: ts.SignatureDeclaration
+): string[] | undefined {
+ if (ts.isStringLiteralLike(node)) return [node.text];
+ if (ts.isParenthesizedExpression(node)) {
+ return commandValues(node.expression, wrapper);
+ }
+ if (ts.isConditionalExpression(node)) {
+ const whenTrue = commandValues(node.whenTrue, wrapper);
+ const whenFalse = commandValues(node.whenFalse, wrapper);
+ return whenTrue && whenFalse ? [...whenTrue, ...whenFalse] : undefined;
+ }
+ if (ts.isIdentifier(node)) return bindingValues(node, wrapper);
+ if (ts.isTemplateExpression(node)) {
+ let values = [node.head.text];
+ for (const span of node.templateSpans) {
+ const parts = commandValues(span.expression, wrapper);
+ if (!parts) return undefined;
+ values = values.flatMap((value) =>
+ parts.map((part) => value + part + span.literal.text)
+ );
+ }
+ return values;
+ }
+ return undefined;
+}
+
+type NamedCall = {
+ call: ts.CallExpression;
+ callee: string;
+ command: ts.Expression;
+};
+type TauriImports = { invokes: Set<string>; pluginListeners: Set<string> };
+
+/** Local names a file gives `invoke` and `addPluginListener`. */
+function tauriImports(source: ts.SourceFile): TauriImports {
+ const imports: TauriImports = {
+ invokes: new Set(),
+ pluginListeners: new Set(),
+ };
+ for (const statement of source.statements) {
+ if (
+ !ts.isImportDeclaration(statement) ||
+ !ts.isStringLiteral(statement.moduleSpecifier) ||
+ statement.moduleSpecifier.text !== TAURI_CORE
+ ) {
+ continue;
+ }
+ const bindings = statement.importClause?.namedBindings;
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
+ for (const element of bindings.elements) {
+ const imported = (element.propertyName ?? element.name).text;
+ if (imported === 'invoke') imports.invokes.add(element.name.text);
+ if (imported === 'addPluginListener') {
+ imports.pluginListeners.add(element.name.text);
+ }
+ }
+ }
+ return imports;
+}
+
+/** Calls of a plain name with at least one argument. */
+function namedCalls(source: ts.SourceFile): NamedCall[] {
+ const calls: NamedCall[] = [];
+ walk(source, (node) => {
+ const [command] = ts.isCallExpression(node) ? node.arguments : [];
+ if (
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ command
+ ) {
+ calls.push({ call: node, callee: node.expression.text, command });
+ }
+ });
+ return calls;
+}
+
+/**
+ * Functions that pass their first parameter to `invoke` (the cache host's
+ * `request`), with the commands they build from it, and those invoke calls.
+ */
+function findWrappers(calls: NamedCall[], invokes: Set<string>) {
+ const wrappers = new Map<string, string[]>();
+ const wrapped = new Set<ts.CallExpression>();
+ for (const { call, callee, command } of calls) {
+ if (!invokes.has(callee) || commandValues(command)) continue;
+ for (const wrapper of enclosingFunctions(call)) {
+ const shapes = commandValues(command, wrapper.declaration);
+ if (!shapes?.every((shape) => shape.includes(PARAMETER))) continue;
+ wrappers.set(wrapper.name, shapes);
+ wrapped.add(call);
+ break;
+ }
+ }
+ return { wrappers, wrapped };
+}
+
+/**
+ * The native commands one call names: none for a call that is not IPC, or
+ * undefined when it is IPC and its command cannot be read.
+ */
+function callCommands(
+ { callee, command }: NamedCall,
+ imports: TauriImports,
+ wrappers: Map<string, string[]>
+): string[] | undefined {
+ if (imports.pluginListeners.has(callee)) {
+ return commandValues(command)?.map(
+ (plugin) => `plugin:${plugin}|register_listener`
+ );
+ }
+ const shapes = imports.invokes.has(callee)
+ ? [PARAMETER]
+ : wrappers.get(callee);
+ if (!shapes) return [];
+ const values = commandValues(command);
+ return values?.flatMap((value) =>
+ shapes.map((shape) => shape.replace(PARAMETER, value))
+ );
+}
+
+/**
+ * Every native command the shipped web code calls, by the file calling it,
+ * and the calls whose command this scan cannot read. A function that passes
+ * its first parameter to `invoke` is a wrapper, and its callers name the
+ * command.
+ */
+function scanInvokedCommands(): {
+ commands: Map<string, string>;
+ unreadable: string[];
+} {
+ const commands = new Map<string, string>();
+ const unreadable: string[] = [];
+ for (const root of SOURCE_ROOTS) {
+ for (const file of sourceFiles(resolve(repositoryRoot, root))) {
+ const text = readFileSync(file, 'utf8');
+ if (!text.includes(TAURI_CORE)) continue;
+ const source = ts.createSourceFile(
+ file,
+ text,
+ ts.ScriptTarget.Latest,
+ true
+ );
+ const path = relative(repositoryRoot, file);
+ const imports = tauriImports(source);
+ const calls = namedCalls(source);
+ const { wrappers, wrapped } = findWrappers(calls, imports.invokes);
+ for (const named of calls) {
+ if (wrapped.has(named.call)) continue;
+ const names = callCommands(named, imports, wrappers);
+ if (!names) {
+ const { line } = source.getLineAndCharacterOfPosition(
+ named.call.getStart()
+ );
+ unreadable.push(
+ `${path}:${line + 1} ${named.call.getText().split('\n')[0]}`
+ );
+ continue;
+ }
+ for (const name of names)
+ if (!commands.has(name)) commands.set(name, path);
+ }
+ }
+ }
+ return { commands, unreadable };
+}
+
+/** Commands the app registers itself, in `generate_handler!`. */
+function appCommands(): Set<string> {
+ const lib = readFileSync(resolve(tauriRoot, 'src-tauri/src/lib.rs'), 'utf8');
+ const handler =
+ /\.invoke_handler\(tauri::generate_handler!\[([\s\S]*?)\]\)/.exec(lib)?.[1];
+ if (!handler) throw new Error('generate_handler! not found in lib.rs');
+ return new Set(
+ handler
+ .split(',')
+ .map((entry) => entry.replace(/#\[[^\]]*\]/g, '').trim())
+ .filter(Boolean)
+ .map((path) => path.split('::').at(-1) ?? path)
+ );
+}
+
+/**
+ * The commands a plugin's `build.rs` passes to `tauri_plugin::Builder::new`,
+ * inline or through a `const` array.
+ */
+function buildScriptCommands(build: string): Set<string> {
+ const argument =
+ /tauri_plugin::Builder::new\(\s*(&\[[\s\S]*?\]|[A-Z_]+)\s*\)/.exec(
+ build
+ )?.[1];
+ const list = argument?.startsWith('&[')
+ ? argument
+ : argument &&
+ new RegExp(`const ${argument}: &\\[&str\\] = (&\\[[\\s\\S]*?\\]);`).exec(
+ build
+ )?.[1];
+ return new Set(
+ [...(list ?? '').matchAll(/"([A-Za-z0-9_]+)"/g)].map((m) => m[1] ?? '')
+ );
+}
+
+/** Commands of the in-repo plugins, by plugin name, from their `build.rs`. */
+function repoPluginCommands(): Map<string, Set<string>> {
+ const plugins = new Map<string, Set<string>>();
+ for (const entry of readdirSync(tauriRoot, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue;
+ let lib: string;
+ let build: string;
+ try {
+ lib = readFileSync(resolve(tauriRoot, entry.name, 'src/lib.rs'), 'utf8');
+ build = readFileSync(resolve(tauriRoot, entry.name, 'build.rs'), 'utf8');
+ } catch {
+ continue;
+ }
+ const name = /Builder::new\("([a-z0-9-]+)"\)/.exec(lib)?.[1];
+ if (!name) continue;
+ plugins.set(name, buildScriptCommands(build));
+ }
+ return plugins;
+}
+
+describe('native commands', () => {
+ const { commands: invoked, unreadable } = scanInvokedCommands();
+
+ it('names every native command with a value this test can read', () => {
+ // Pass the command as a string literal, a constant, or a parameter typed
+ // as a union of literals, so the checks below can see it.
+ expect(unreadable).toEqual([]);
+ });
+
+ it('lists every command the web bundle calls in native-commands.json', () => {
+ // An over-the-air bundle can reach native builds older than the command.
+ // Before adding one here, raise min-native-build.json to the first build
+ // with it, or handle `Command … not found` (see apps/web/AGENTS.md).
+ expect([...invoked.keys()].sort()).toEqual(nativeCommands.commands);
+ expect(nativeCommands.commands.length).toBeGreaterThan(50);
+ });
+
+ it('calls only commands the native app registers', () => {
+ const app = appCommands();
+ const plugins = repoPluginCommands();
+ const lib = readFileSync(
+ resolve(tauriRoot, 'src-tauri/src/lib.rs'),
+ 'utf8'
+ );
+ const unregistered = [...invoked].flatMap(([command, file]) => {
+ const plugin = /^plugin:([a-z0-9-]+)\|([A-Za-z0-9_]+)$/.exec(command);
+ if (!plugin) return app.has(command) ? [] : [`${command} (${file})`];
+ const [, name = '', pluginCommand = ''] = plugin;
+ const repoPlugin = plugins.get(name);
+ if (repoPlugin) {
+ return repoPlugin.has(pluginCommand) ? [] : [`${command} (${file})`];
+ }
+ // A published plugin: the app must at least install it.
+ const crate = `tauri_plugin_${name.replaceAll('-', '_')}`;
+ return new RegExp(`\\b${crate}::(init|Builder)\\b`).test(lib)
+ ? []
+ : [`${command} (${file})`];
+ });
+ expect(unregistered).toEqual([]);
+ });
+});
diff --git a/crates/client/README.md b/crates/client/README.md
index 1708af141d..cb1e5e3996 100644
--- a/crates/client/README.md
+++ b/crates/client/README.md
@@ -31,7 +31,8 @@ intermediate JSON asset. Browser workers configure SDL through
Native startup calls `graphql_cache_init_with_schema`. This requires one native
release; set the OTA bundle's `MIN_NATIVE_BUILD` to the first build containing that
command. Older native binaries cannot accept runtime SDL. The frontend does
-not fall back to the old initialization command.
+not fall back to the old initialization command; it runs uncached and asks for
+an app update instead.
An engine owns a validated schema snapshot; there is no mutable global schema.
Compatible additions are merged under the native engine lock, including when an
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index 9e408502fe..930d42035a 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -760,8 +760,8 @@ local copy rather than recreating the sent message. The REST compose path keeps
its existing behavior.
Native draft recovery requires a full app update containing queue inspection and
-durable mutation metadata support. An older app receiving an OTA bundle shows
-**Macro update required** and uses the existing uncached fallback. Its old queue
+durable mutation metadata support. An older app receiving an OTA bundle opens
+the update-required dialog once and uses the existing uncached fallback. Its old queue
must remain intact, with no new claims or queued writes, until the native update.
When the cache becomes unavailable, draft saves and discards must not bypass its
preserved queue through GraphQL or REST fallback. Local editing stays durable;
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 169b685b2e..f3ccd80c67 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -36,6 +36,14 @@ must load through the webview, not native HTTP. A `vite:preloadError` with
`scheme tauri not supported` indicates an asset-routing failure; reloading the
same bundle does not resolve it.
+A `vite:preloadError` (a lazy chunk or its CSS failed, usually after a deploy)
+reloads the tab right away, once per build per tab session, when it is online,
+holds no call or upload, and has no text being typed. Otherwise, and on a second
+failure in the same build, the rail's update button (a toast on touch layouts)
+offers the reload; the offer reloads a hidden tab by itself only if that build's
+one automatic reload is unspent. A failed route chunk can still end on the
+root error screen, which hides the offer.
+
## External links in the native app
Desktop external links open in the system browser, whether activated by a normal
@@ -1571,7 +1579,11 @@ Every move, from the picker or a drop, ends in a **Moved to folder** or **Moved
### 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
+**Update app** and **OK**. It opens once per launch, either when the bundle
+updater reports a native floor, or when the OTA bundle finds the app lacks a
+GraphQL cache command (`graphql_cache_init_with_schema` or
+`graphql_cache_inspect_mutations`); the cache case explains what needs the
+update and the app runs uncached until then. Update app uses the native opener; Android targets the
HTTPS Play listing for `com.macro.workspace.mobile`, 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