Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(mobile): offer to download a waiting update off Wi-Fi (#9900)
Peter Chinman3bedbcc132ee
diff --git a/apps/web/src/lib/i18n/locales/en/mobile.ts b/apps/web/src/lib/i18n/locales/en/mobile.tsindex ce23b36aeb..162a7c5210 100644--- a/apps/web/src/lib/i18n/locales/en/mobile.ts+++ b/apps/web/src/lib/i18n/locales/en/mobile.ts@@ -33,4 +33,24 @@ export default {// Picker sheetdone: 'Done',++ // App update waiting for Wi-Fi+ updateOffWifiTitle: 'Update available',+ updateOffWifiDescription:+ 'A new update to Macro is available. Updates download automatically on Wi-Fi. Download it now? This may use mobile data.',+ updateNotNow: 'Not now',+ updateDownload: 'Download',+ updateDownloadingTitle: 'Downloading update',+ updateStartingDownload: 'Starting download…',+ updateDownloadProgress: 'Downloading… {{progress}}%',+ updateInstallProgress: 'Installing… {{progress}}%',+ updateHide: 'Hide',+ updateReadyTitle: 'Update ready',+ updateReadyDescription: 'Restart Macro to use the new version.',+ updateLater: 'Later',+ updateRestart: 'Restart',+ updateFailedTitle: "Couldn't download the update",+ updateFailedDescription:+ 'Try again later. Macro downloads updates automatically on Wi-Fi.',+ updateOk: 'OK',};diff --git a/apps/web/src/lib/tauri/TauriProvider.tsx b/apps/web/src/lib/tauri/TauriProvider.tsxindex daf51539da..5ce872eb5e 100644--- a/apps/web/src/lib/tauri/TauriProvider.tsx+++ b/apps/web/src/lib/tauri/TauriProvider.tsx@@ -36,6 +36,10 @@ import {import { useTauriNavigationEffect } from './navigation';import { MaybePushNotificationRegistration } from './PushNotification';import { ShareTargetProvider } from './ShareTargetProvider';+import {+ createWaitingForWifiPrompt,+ WaitingForWifiUpdateDialog,+} from './WaitingForWifiUpdateDialog';export type BundleUpdateStatus =| { status: 'Idle' }@@ -89,6 +93,11 @@ function TauriProvider(props: { children: JSX.Element }) {useAndroidBack();const [bundleUpdateStatus, setBundleUpdateStatus] =createSignal<BundleUpdateStatus>({ status: 'Idle' });+ const waitingForWifiPrompt = createWaitingForWifiPrompt(bundleUpdateStatus);+ function receiveBundleUpdateStatus(status: BundleUpdateStatus) {+ setBundleUpdateStatus(status);+ waitingForWifiPrompt.observe(status);+ }const [nativeAppUpdateRequiredDialogOpen,setNativeAppUpdateRequiredDialogOpen,@@ -114,6 +123,8 @@ function TauriProvider(props: { children: JSX.Element }) {hasShownNativeAppUpdateRequiredDialog = true;if (reason !== undefined) hasShownNativeUpdateReason = true;+ // The App Store prompt wins over the offer to download a bundle off Wi-Fi.+ waitingForWifiPrompt.yieldToNativeUpdate();setNativeAppUpdateRequiredDialogOpen(true);});@@ -132,7 +143,7 @@ function TauriProvider(props: { children: JSX.Element }) {const unlistenPromise = listen<BundleUpdateStatus>('bundle-update-status',(ev) => {- setBundleUpdateStatus(ev.payload);+ receiveBundleUpdateStatus(ev.payload);});if (LOADED_BUNDLE_BUILD !== undefined) {@@ -146,7 +157,7 @@ function TauriProvider(props: { children: JSX.Element }) {// Fetch current status since events emitted before the listener registered are missedinvoke<BundleUpdateStatus>('get_bundle_update_status').then((status) => {- setBundleUpdateStatus(status);+ receiveBundleUpdateStatus(status);}).catch((error) => Telemetry.error(error, { surface: 'bundle-update' }));onCleanup(() => {@@ -200,6 +211,10 @@ function TauriProvider(props: { children: JSX.Element }) {</div></Surface></Dialog>+ <WaitingForWifiUpdateDialog+ prompt={waitingForWifiPrompt}+ status={bundleUpdateStatus()}+ /><NativeAppUpdateRequiredDialogopen={nativeAppUpdateRequiredDialogOpen()}onClose={() => setNativeAppUpdateRequiredDialogOpen(false)}diff --git a/apps/web/src/lib/tauri/WaitingForWifiUpdateDialog.test.tsx b/apps/web/src/lib/tauri/WaitingForWifiUpdateDialog.test.tsxnew file mode 100644index 0000000000..d9fd210aac--- /dev/null+++ b/apps/web/src/lib/tauri/WaitingForWifiUpdateDialog.test.tsx@@ -0,0 +1,241 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { invoke } from '@tauri-apps/api/core';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { BundleUpdateStatus } from './TauriProvider';+import {+ createWaitingForWifiPrompt,+ nextWaitingForWifiPromptPhase,+ WAITING_FOR_WIFI_PHASES,+ type WaitingForWifiPrompt,+ WaitingForWifiUpdateDialog,+ WIFI_OFFER_SNOOZE_MS,+} from './WaitingForWifiUpdateDialog';++vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() }));+vi.mock('@macro-inc/observability', () => ({+ Telemetry: { error: vi.fn() },+}));+// The phone drawer never finishes its transitions in jsdom; the desktop+// dialog marks itself closed, so closing is observable.+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));+vi.mock('@core/mobile/virtualKeyboard', () => ({+ virtualKeyboardVisible: () => false,+}));+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')),+}));++const WAITING: BundleUpdateStatus = { status: 'WaitingForWifi' };++beforeEach(() => {+ vi.stubGlobal('scrollTo', vi.fn());+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ vi.mocked(invoke).mockResolvedValue(undefined);+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.mocked(invoke).mockReset();+ vi.useRealTimers();+ localStorage.clear();+});++describe('nextWaitingForWifiPromptPhase', () => {+ it('offers a Wi-Fi wait only when allowed', () => {+ expect(nextWaitingForWifiPromptPhase('closed', WAITING, true)).toBe(+ 'offer'+ );+ expect(nextWaitingForWifiPromptPhase('closed', WAITING, false)).toBe(+ 'closed'+ );+ });++ it('gives way to a required native update or a revoked bundle', () => {+ for (const phase of WAITING_FOR_WIFI_PHASES) {+ for (const status of [+ {+ status: 'NativeUpdateRequired',+ data: { bundleBuild: 2, minNativeBuild: 199 },+ },+ { status: 'ClearRequired', data: { reason: 'bundle_revoked' } },+ ] satisfies BundleUpdateStatus[]) {+ expect(nextWaitingForWifiPromptPhase(phase, status, true)).toBe(+ 'closed'+ );+ }+ }+ });++ it('withdraws the offer when the download starts on its own', () => {+ expect(+ nextWaitingForWifiPromptPhase(+ 'offer',+ { status: 'Downloading', data: { progress: 0 } },+ true+ )+ ).toBe('closed');+ });++ it('follows an approved download through a restarted check', () => {+ for (const status of [+ { status: 'Idle' },+ { status: 'CheckingForUpdate' },+ { status: 'Unzipping', data: { progress: 50 } },+ ] satisfies BundleUpdateStatus[]) {+ expect(nextWaitingForWifiPromptPhase('downloading', status, true)).toBe(+ 'downloading'+ );+ }+ expect(+ nextWaitingForWifiPromptPhase(+ 'downloading',+ { status: 'Completed' },+ true+ )+ ).toBe('ready');+ expect(+ nextWaitingForWifiPromptPhase(+ 'downloading',+ { status: 'Error', data: { message: 'offline' } },+ true+ )+ ).toBe('failed');+ });++ it('follows a download that starts after a refused grant', () => {+ expect(+ nextWaitingForWifiPromptPhase(+ 'failed',+ { status: 'Downloading', data: { progress: 5 } },+ true+ )+ ).toBe('downloading');+ expect(nextWaitingForWifiPromptPhase('failed', WAITING, true)).toBe(+ 'failed'+ );+ });+});++/** A dialog stays mounted while it animates out; Kobalte marks it closed. */+function promptOpen() {+ const dialog = screen.queryByRole('dialog');+ return dialog !== null && !dialog.hasAttribute('data-closed');+}++/** Mount the prompt as a fresh page load would. */+function renderPrompt() {+ const [status, setStatus] = createSignal<BundleUpdateStatus>({+ status: 'Idle',+ });+ let prompt: WaitingForWifiPrompt | undefined;+ render(() => {+ prompt = createWaitingForWifiPrompt(status);+ return <WaitingForWifiUpdateDialog prompt={prompt} status={status()} />;+ });+ if (!prompt) throw new Error('prompt did not mount');+ const mounted = prompt;+ return {+ prompt: mounted,+ report(next: BundleUpdateStatus) {+ setStatus(next);+ mounted.observe(next);+ },+ };+}++function relaunch() {+ cleanup();+ return renderPrompt();+}++it('downloads off Wi-Fi and restarts into the update', async () => {+ const { report } = renderPrompt();+ report(WAITING);++ await fireEvent.click(+ await screen.findByRole('button', { name: 'Download' })+ );+ expect(invoke).toHaveBeenCalledWith('grant_bundle_update', {+ approved: true,+ });++ report({ status: 'Downloading', data: { progress: 42.4 } });+ expect(await screen.findByText('Downloading… 42%')).toBeTruthy();++ report({ status: 'Completed' });+ await fireEvent.click(await screen.findByRole('button', { name: 'Restart' }));+ expect(invoke).toHaveBeenCalledWith('perform_update');+ await waitFor(() => expect(promptOpen()).toBe(false));+});++it('leaves the Wi-Fi wait running and does not ask again', async () => {+ const { report } = renderPrompt();+ report(WAITING);++ await fireEvent.click(await screen.findByRole('button', { name: 'Not now' }));+ await waitFor(() => expect(promptOpen()).toBe(false));++ report({ status: 'Idle' });+ report(WAITING);+ expect(promptOpen()).toBe(false);+ expect(invoke).not.toHaveBeenCalled();+});++it('reports a grant the updater refused while still waiting', async () => {+ vi.mocked(invoke).mockRejectedValue('No pending bundle update to approve');+ const { report } = renderPrompt();+ report(WAITING);++ await fireEvent.click(+ await screen.findByRole('button', { name: 'Download' })+ );+ expect(await screen.findByText("Couldn't download the update")).toBeTruthy();+});++it('holds off the offer for a day after Not now, across relaunches', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-11-05T12:00:00Z'));+ renderPrompt().report(WAITING);+ await fireEvent.click(await screen.findByRole('button', { name: 'Not now' }));++ relaunch().report(WAITING);+ expect(promptOpen()).toBe(false);++ vi.setSystemTime(Date.now() + WIFI_OFFER_SNOOZE_MS);+ relaunch().report(WAITING);+ expect(await screen.findByRole('button', { name: 'Not now' })).toBeTruthy();+});++it('gives way to the App Store prompt for the rest of the page', async () => {+ const { prompt, report } = renderPrompt();+ report(WAITING);+ await screen.findByRole('button', { name: 'Download' });++ prompt.yieldToNativeUpdate();+ await waitFor(() => expect(promptOpen()).toBe(false));++ report({ status: 'Idle' });+ report(WAITING);+ expect(promptOpen()).toBe(false);++ // Giving way is not turning the offer down: the next launch asks again.+ relaunch().report(WAITING);+ expect(await screen.findByRole('button', { name: 'Download' })).toBeTruthy();+});diff --git a/apps/web/src/lib/tauri/WaitingForWifiUpdateDialog.tsx b/apps/web/src/lib/tauri/WaitingForWifiUpdateDialog.tsxnew file mode 100644index 0000000000..9f176575c8--- /dev/null+++ b/apps/web/src/lib/tauri/WaitingForWifiUpdateDialog.tsx@@ -0,0 +1,326 @@+import { t } from '@app/lib/i18n';+import { makePersistedState } from '@app/lib/persistence';+import { fireAndForget } from '@core/util/fireAndForget';+import { Telemetry } from '@macro-inc/observability';+import { invoke } from '@tauri-apps/api/core';+import { Button, Dialog, Surface } from '@ui';+import { ResultAsync } from 'neverthrow';+import {+ type Accessor,+ createMemo,+ createSignal,+ type JSX,+ Match,+ Switch,+} from 'solid-js';+import { match } from 'ts-pattern';+import { z } from 'zod';+import type { BundleUpdateStatus } from './TauriProvider';++/** Device-wide: the update waiting for Wi-Fi belongs to the install. */+const SNOOZE_STORAGE_KEY = 'macro:bundle-update:wifi-offer-snoozed-until';+/** How long "Not now" holds off the offer, across relaunches. */+export const WIFI_OFFER_SNOOZE_MS = 24 * 60 * 60 * 1000;+const SNOOZED_UNTIL_SCHEMA = z.coerce.number().int().nonnegative();++export const WAITING_FOR_WIFI_PHASES = [+ 'closed',+ 'offer',+ 'downloading',+ 'ready',+ 'failed',+] as const;++export type WaitingForWifiPromptPhase =+ (typeof WAITING_FOR_WIFI_PHASES)[number];++export type WaitingForWifiPrompt = ReturnType<+ typeof createWaitingForWifiPrompt+>;++/**+ * Where the prompt goes when the bundle updater reports `status`.+ *+ * The offer opens when the updater waits for Wi-Fi and `mayOffer` allows it,+ * and closes if that wait ends some other way (Wi-Fi arrived and the download+ * started on its own). After the person approves, the prompt follows the+ * download to `ready` or `failed`; the updater passes through `Idle` and+ * `CheckingForUpdate` when a resume restarts its check, so those keep it open,+ * and a download that starts after a failure is followed again. A required+ * native update or a revoked bundle closes it from any phase, because the+ * App Store prompt takes over and no downloaded bundle can apply.+ */+export function nextWaitingForWifiPromptPhase(+ phase: WaitingForWifiPromptPhase,+ status: BundleUpdateStatus,+ mayOffer: boolean+): WaitingForWifiPromptPhase {+ if (+ status.status === 'NativeUpdateRequired' ||+ status.status === 'ClearRequired'+ ) {+ return 'closed';+ }+ return match(phase)+ .with('closed', () =>+ status.status === 'WaitingForWifi' && mayOffer ? 'offer' : phase+ )+ .with('offer', () =>+ status.status === 'WaitingForWifi' ? phase : 'closed'+ )+ .with('downloading', () =>+ match(status.status)+ .returnType<WaitingForWifiPromptPhase>()+ .with('Completed', () => 'ready')+ .with('Error', () => 'failed')+ .with('NoUpdateNeeded', () => 'closed')+ .with(+ 'Idle',+ 'CheckingForUpdate',+ 'UpdateFound',+ 'WaitingForWifi',+ 'Downloading',+ 'Unzipping',+ () => phase+ )+ // The native updater ships separately and may add statuses.+ .exhaustive(() => phase)+ )+ .with('failed', () =>+ // A refused grant can race a download that Wi-Fi started; follow it.+ match(status.status)+ .returnType<WaitingForWifiPromptPhase>()+ .with('Downloading', 'Unzipping', () => 'downloading')+ .with('Completed', () => 'ready')+ .otherwise(() => phase)+ )+ .with('ready', () => phase)+ .exhaustive();+}++/**+ * Offers to download a bundle update that is waiting for Wi-Fi.+ *+ * Mobile builds download bundle updates only on Wi-Fi or Ethernet, so someone+ * on cellular, or behind a VPN the OS doesn't report as Wi-Fi, stays on their+ * current bundle until they join one, even when that bundle is broken. The+ * offer opens at most once per page load. Declining it leaves the native+ * Wi-Fi wait running and holds off the offer for a day, across relaunches;+ * approving it starts the download over the current connection.+ *+ * Feed it every status the updater reports with `observe`, and call+ * `yieldToNativeUpdate` when the App Store prompt opens.+ */+export function createWaitingForWifiPrompt(+ status: Accessor<BundleUpdateStatus>+) {+ const [phase, setPhase] = createSignal<WaitingForWifiPromptPhase>('closed');+ const [snoozedUntil, setSnoozedUntil] = createSnooze();+ let canOffer = true;++ const mayOffer = () => canOffer && (snoozedUntil() ?? 0) <= Date.now();++ function observe(next: BundleUpdateStatus) {+ const nextPhase = nextWaitingForWifiPromptPhase(phase(), next, mayOffer());+ if (nextPhase === 'offer') canOffer = false;+ setPhase(nextPhase);+ }++ /** Hide the prompt; turning down the offer also snoozes it. */+ function close() {+ if (phase() === 'offer') setSnoozedUntil(Date.now() + WIFI_OFFER_SNOOZE_MS);+ setPhase('closed');+ }++ /**+ * The app needs a newer native build: that prompt wins, and a bundle+ * download can't help, so close this one and stop offering for this page.+ */+ function yieldToNativeUpdate() {+ canOffer = false;+ setPhase('closed');+ }++ async function download() {+ setPhase('downloading');+ const granted = await ResultAsync.fromPromise(+ invoke('grant_bundle_update', { approved: true }),+ (error: unknown) => error+ );+ if (granted.isOk()) return;+ Telemetry.error(granted.error, { surface: 'bundle-update' });+ // A download that started on its own (Wi-Fi arrived) also rejects the+ // grant; only a wait that is still pending means nothing will happen.+ if (status().status === 'WaitingForWifi') setPhase('failed');+ }++ async function restart() {+ const applied = await ResultAsync.fromPromise(+ invoke<boolean>('perform_update'),+ (error: unknown) => error+ );+ if (applied.isErr()) {+ Telemetry.error(applied.error, { surface: 'bundle-update' });+ }+ // The webview reloads when the update applies; anything else (a reload+ // hold, or the update already applied) leaves nothing to wait for.+ close();+ }++ return { phase, observe, close, yieldToNativeUpdate, download, restart };+}++function createSnooze() {+ return makePersistedState(createSignal<number | undefined>(), {+ storages: {+ restore: () => {+ try {+ const stored = localStorage.getItem(SNOOZE_STORAGE_KEY);+ if (stored === null) return undefined;+ const parsed = SNOOZED_UNTIL_SCHEMA.safeParse(stored);+ return parsed.success ? parsed.data : undefined;+ } catch {+ return undefined;+ }+ },+ write: (value) => {+ try {+ if (value === undefined) localStorage.removeItem(SNOOZE_STORAGE_KEY);+ else localStorage.setItem(SNOOZE_STORAGE_KEY, String(value));+ } catch {+ // Storage may be unavailable; the offer then waits for a relaunch.+ }+ },+ },+ });+}++function downloadProgress(status: BundleUpdateStatus): string {+ if (status.status === 'Downloading') {+ return t('mobile.updateDownloadProgress', {+ progress: Math.round(status.data.progress),+ });+ }+ if (status.status === 'Unzipping') {+ return t('mobile.updateInstallProgress', {+ progress: Math.round(status.data.progress),+ });+ }+ return t('mobile.updateStartingDownload');+}++export function WaitingForWifiUpdateDialog(props: {+ prompt: WaitingForWifiPrompt;+ status: BundleUpdateStatus;+}) {+ const runDownload = () =>+ fireAndForget(props.prompt.download(), 'bundle-update');+ const runRestart = () =>+ fireAndForget(props.prompt.restart(), 'bundle-update');+ // Keep the last content while the sheet animates closed.+ const shown = createMemo<WaitingForWifiPromptPhase>((last) => {+ const phase = props.prompt.phase();+ return phase === 'closed' ? last : phase;+ }, 'offer');++ return (+ <Dialog+ open={props.prompt.phase() !== 'closed'}+ onOpenChange={(open) => {+ if (!open) props.prompt.close();+ }}+ class="w-[90%] max-w-120"+ position="center"+ >+ <Surface depth={2}>+ <div class="flex flex-col gap-4 px-4 py-5">+ <Switch>+ <Match when={shown() === 'offer'}>+ <PromptBody+ title={t('mobile.updateOffWifiTitle')}+ description={t('mobile.updateOffWifiDescription')}+ />+ <PromptActions>+ <Button+ variant="secondary"+ size="sm"+ onClick={props.prompt.close}+ >+ {t('mobile.updateNotNow')}+ </Button>+ <Button variant="primary" size="sm" onClick={runDownload}>+ {t('mobile.updateDownload')}+ </Button>+ </PromptActions>+ </Match>+ <Match when={shown() === 'downloading'}>+ <PromptBody+ title={t('mobile.updateDownloadingTitle')}+ description={downloadProgress(props.status)}+ />+ <PromptActions>+ <Button+ variant="secondary"+ size="sm"+ onClick={props.prompt.close}+ >+ {t('mobile.updateHide')}+ </Button>+ </PromptActions>+ </Match>+ <Match when={shown() === 'ready'}>+ <PromptBody+ title={t('mobile.updateReadyTitle')}+ description={t('mobile.updateReadyDescription')}+ />+ <PromptActions>+ <Button+ variant="secondary"+ size="sm"+ onClick={props.prompt.close}+ >+ {t('mobile.updateLater')}+ </Button>+ <Button variant="primary" size="sm" onClick={runRestart}>+ {t('mobile.updateRestart')}+ </Button>+ </PromptActions>+ </Match>+ <Match when={shown() === 'failed'}>+ <PromptBody+ title={t('mobile.updateFailedTitle')}+ description={t('mobile.updateFailedDescription')}+ />+ <PromptActions>+ <Button+ variant="secondary"+ size="sm"+ onClick={props.prompt.close}+ >+ {t('mobile.updateOk')}+ </Button>+ </PromptActions>+ </Match>+ </Switch>+ </div>+ </Surface>+ </Dialog>+ );+}++function PromptBody(props: { title: string; description: string }) {+ return (+ <div class="flex flex-col gap-2">+ <Dialog.Title class="text-lg font-semibold text-ink">+ {props.title}+ </Dialog.Title>+ <Dialog.Description class="text-sm leading-5 text-ink-extra-muted">+ {props.description}+ </Dialog.Description>+ </div>+ );+}++function PromptActions(props: { children: JSX.Element }) {+ return <div class="flex justify-end gap-2">{props.children}</div>;+}