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(mobile): route Android system Back through the active split view (#7332)

Peter Chinman878d493b1c88
diff --git a/apps/web/src/components/app/split-layout/back-interceptor.ts b/apps/web/src/components/app/split-layout/back-interceptor.ts
index 002604a1f4..22a4cb769a 100644
--- a/apps/web/src/components/app/split-layout/back-interceptor.ts
+++ b/apps/web/src/components/app/split-layout/back-interceptor.ts
@@ -18,3 +18,19 @@ export function useSplitBackInterceptor(fn: SplitBackInterceptor) {
setInterceptor(() => fn);
onCleanup(() => setInterceptor(null));
}
+
+/**
+ * Resolves one committed Back press — the split header's button or Android's
+ * system Back — so both route through the active view's interceptor instead of
+ * navigating straight away. Returns false when nothing consumed the press,
+ * which leaves Android's Back to the system.
+ */
+export function runSplitBack(navigation: {
+ canGoBack: () => boolean;
+ goBack: () => void;
+}): boolean {
+ if (!navigation.canGoBack()) return false;
+ if (interceptor()?.()) return true;
+ navigation.goBack();
+ return true;
+}
diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
index ba46c99b45..7e64711301 100644
--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
@@ -33,7 +33,7 @@ import {
} from 'solid-js';
import { Portal } from 'solid-js/web';
import { match, P } from 'ts-pattern';
-import { splitBackInterceptor } from '../back-interceptor';
+import { runSplitBack } from '../back-interceptor';
import { SplitLayoutContext, SplitPanelContext } from '../context';
import type { SplitContent } from '../layoutManager';
import {
@@ -132,18 +132,21 @@ function SplitBackButton() {
!context.handle.canGoBack() &&
!hasAgentsBackFallback(context.handle.content())
}
- onClick={() => {
- if (splitBackInterceptor()?.()) return;
- if (
- !context.handle.canGoBack() &&
- hasAgentsBackFallback(context.handle.content())
- ) {
- context.handle.replace({
- next: { type: 'component', id: 'agents' },
- mergeHistory: true,
- });
- } else context.handle.goBack();
- }}
+ onClick={() =>
+ runSplitBack({
+ canGoBack: () =>
+ context.handle.canGoBack() ||
+ hasAgentsBackFallback(context.handle.content()),
+ goBack: () => {
+ if (!context.handle.canGoBack()) {
+ context.handle.replace({
+ next: { type: 'component', id: 'agents' },
+ mergeHistory: true,
+ });
+ } else context.handle.goBack();
+ },
+ })
+ }
>
<CaretLeft />
</Button>
diff --git a/apps/web/src/components/app/split-layout/mobile/MobileSplitContainer.tsx b/apps/web/src/components/app/split-layout/mobile/MobileSplitContainer.tsx
index 54d8fc377e..6a7637e98b 100644
--- a/apps/web/src/components/app/split-layout/mobile/MobileSplitContainer.tsx
+++ b/apps/web/src/components/app/split-layout/mobile/MobileSplitContainer.tsx
@@ -8,6 +8,7 @@ import {
Show,
Suspense,
} from 'solid-js';
+import { runSplitBack } from '../back-interceptor';
import { SplitPanel } from '../components/SplitPanel';
import type {
SplitHandle,
@@ -55,11 +56,12 @@ function createPaneSlots(stack: MobilePaneStack): Accessor<Slots> {
export function MobileSplitContainer(props: MobileSplitContainerProps) {
const { splitManager, stack } = props;
- useAndroidBackNavigation(() => {
- if (!stack.canGoBack()) return false;
- stack.goBack();
- return true;
- });
+ useAndroidBackNavigation(() =>
+ runSplitBack({
+ canGoBack: stack.canGoBack,
+ goBack: stack.goBack,
+ })
+ );
const motion = createMobileSplitMotion({ stack });
const slots = createPaneSlots(stack);
diff --git a/apps/web/src/components/app/split-layout/tests/mobile-split-back.test.tsx b/apps/web/src/components/app/split-layout/tests/mobile-split-back.test.tsx
new file mode 100644
index 0000000000..f7a09597e3
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/tests/mobile-split-back.test.tsx
@@ -0,0 +1,126 @@
+import { render } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+// The container only wires Android's system Back on the native Android app.
+vi.mock(import('@core/util/platform'), async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ isPlatform: (target: Parameters<typeof actual.isPlatform>[0]) =>
+ Array.isArray(target) ? target.includes('android') : target === 'android',
+ };
+});
+
+// Back routing needs no panel content, and the real panel pulls in the whole app.
+vi.mock('../components/SplitPanel', () => ({ SplitPanel: () => null }));
+
+import { useSplitBackInterceptor } from '../back-interceptor';
+import type { SplitId, SplitState } from '../layoutManager';
+import type { MobilePaneStack } from '../mobile/createMobilePaneStack';
+import { MobileSplitContainer } from '../mobile/MobileSplitContainer';
+
+function stubPaneStack(
+ overrides: Partial<MobilePaneStack> = {}
+): MobilePaneStack {
+ return {
+ front: () => undefined,
+ behind: () => undefined,
+ canGoBack: () => true,
+ completeGoBack: () => {},
+ setAnimatedTrigger: () => {},
+ setForwardTrigger: () => {},
+ goBack: () => {},
+ ...overrides,
+ };
+}
+
+function mountContainer(stack: MobilePaneStack) {
+ return render(() => (
+ <MobileSplitContainer
+ splitManager={{ getSplit: () => undefined }}
+ stack={stack}
+ splits={() => [] as ReadonlyArray<SplitState>}
+ panelRefs={new Map<SplitId, HTMLDivElement>()}
+ />
+ ));
+}
+
+function pressBack() {
+ return window.dispatchEvent(
+ new Event('android-navigate-back', { cancelable: true })
+ );
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('Android system Back in the mobile split container', () => {
+ it('navigates back when no view claims the press', () => {
+ const goBack = vi.fn();
+ const { unmount } = mountContainer(stubPaneStack({ goBack }));
+
+ expect(pressBack()).toBe(false);
+ expect(goBack).toHaveBeenCalledOnce();
+ unmount();
+ });
+
+ it('lets the active view claim it, so a dirty draft keeps its composer', () => {
+ const goBack = vi.fn();
+ const confirmDraft = vi.fn(() => true);
+ const { unmount } = render(() => {
+ useSplitBackInterceptor(confirmDraft);
+ return (
+ <MobileSplitContainer
+ splitManager={{ getSplit: () => undefined }}
+ stack={stubPaneStack({ goBack })}
+ splits={() => [] as ReadonlyArray<SplitState>}
+ panelRefs={new Map<SplitId, HTMLDivElement>()}
+ />
+ );
+ });
+
+ expect(pressBack()).toBe(false);
+ expect(confirmDraft).toHaveBeenCalledOnce();
+ expect(goBack).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it('navigates back when the view declines the press', () => {
+ const goBack = vi.fn();
+ const { unmount } = render(() => {
+ useSplitBackInterceptor(() => false);
+ return (
+ <MobileSplitContainer
+ splitManager={{ getSplit: () => undefined }}
+ stack={stubPaneStack({ goBack })}
+ splits={() => [] as ReadonlyArray<SplitState>}
+ panelRefs={new Map<SplitId, HTMLDivElement>()}
+ />
+ );
+ });
+
+ expect(pressBack()).toBe(false);
+ expect(goBack).toHaveBeenCalledOnce();
+ unmount();
+ });
+
+ it('leaves root Back to Android without consulting the view', () => {
+ const interceptor = vi.fn(() => true);
+ const { unmount } = render(() => {
+ useSplitBackInterceptor(interceptor);
+ return (
+ <MobileSplitContainer
+ splitManager={{ getSplit: () => undefined }}
+ stack={stubPaneStack({ canGoBack: () => false })}
+ splits={() => [] as ReadonlyArray<SplitState>}
+ panelRefs={new Map<SplitId, HTMLDivElement>()}
+ />
+ );
+ });
+
+ expect(pressBack()).toBe(true);
+ expect(interceptor).not.toHaveBeenCalled();
+ unmount();
+ });
+});
diff --git a/apps/web/src/features/email-compose/browser-test/android-back-fixture.tsx b/apps/web/src/features/email-compose/browser-test/android-back-fixture.tsx
new file mode 100644
index 0000000000..303a42507b
--- /dev/null
+++ b/apps/web/src/features/email-compose/browser-test/android-back-fixture.tsx
@@ -0,0 +1,183 @@
+import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
+import { useSplitBackInterceptor } from '@components/app/split-layout/back-interceptor';
+import type {
+ SplitId,
+ SplitState,
+} from '@components/app/split-layout/layoutManager';
+import type { MobilePaneStack } from '@components/app/split-layout/mobile/createMobilePaneStack';
+import { MobileSplitContainer } from '@components/app/split-layout/mobile/MobileSplitContainer';
+import { useAndroidBack } from '@core/mobile/androidBack';
+import { createSignal, Show } from 'solid-js';
+import { createEmailComposer } from '../primitives/email-composer';
+import { createEmailEditor, setEmailEditorText } from '../tests/editor';
+
+/** Only the Back role matters here; the container never mounts a panel. */
+function stubPaneStack(goBack: () => void): MobilePaneStack {
+ return {
+ front: () => undefined,
+ behind: () => undefined,
+ canGoBack: () => true,
+ completeGoBack: () => {},
+ setAnimatedTrigger: () => {},
+ setForwardTrigger: () => {},
+ goBack,
+ };
+}
+
+/** Real composer controller with injected transports, as the draft fixtures use. */
+function MobileComposePanel(props: { onLeave: () => void }) {
+ const editor = createEmailEditor();
+ const state = createEmailComposer({
+ drafts: {
+ saveDraft: async (input) => ({
+ draftId: input.clientHandles?.draftId ?? 'draft',
+ threadId: input.clientHandles?.threadId ?? 'thread',
+ inboxId: 'inbox',
+ }),
+ deleteDraft: async () => {},
+ restoreDraft: async () => {},
+ },
+ attachmentStorage: {
+ uploadAttachments: async () => {},
+ addForwardedAttachments: async () => {},
+ removeAttachment: async () => {},
+ removeForwardedAttachment: async () => {},
+ },
+ delivery: {
+ sendMessage: async () => ({ inboxId: 'inbox' }),
+ unschedule: async () => {},
+ schedule: async () => {},
+ archive: async () => {},
+ undoSend: async () => {},
+ },
+ draftLifecycle: {
+ observe: () => ({
+ state: () => undefined,
+ refresh: async () => undefined,
+ }),
+ },
+ notices: {
+ feedback: {
+ success: () => undefined,
+ failure: () => undefined,
+ alert: () => undefined,
+ dismiss: () => {},
+ },
+ blockingNotice: async () => {},
+ reportError: () => {},
+ },
+ accounts: {
+ inboxes: () => [
+ { id: 'inbox', email_address: '[email protected]', settings: {} },
+ ],
+ loading: () => false,
+ failed: () => false,
+ primaryId: () => 'inbox',
+ },
+ connectivity: { looksOffline: () => false },
+ viewerEmail: () => '[email protected]',
+ hasPaidAccess: () => true,
+ recipients: () => [],
+ recipientName: (id) => id,
+ initialTo: ['[email protected]'],
+ });
+ state.context.captureEditor(editor);
+ state.context.onContentChange('');
+
+ const [draftBackMenuOpen, setDraftBackMenuOpen] = createSignal(false);
+ // Mirrors the mobile branch of views/email-compose.tsx.
+ useSplitBackInterceptor(() => {
+ if (!state.context.hasDraft() || !state.draftDirty()) return false;
+ setDraftBackMenuOpen(true);
+ return true;
+ });
+
+ return (
+ <section aria-label="Compose email" class="p-3">
+ <p class="text-sm text-ink-muted">To [email protected]</p>
+ <label class="mt-2 block text-sm">
+ Message
+ <textarea
+ aria-label="Message"
+ class="mt-1 block w-full border border-edge-muted bg-transparent p-2 outline-none"
+ onInput={(event) => {
+ const text = event.currentTarget.value;
+ setEmailEditorText(editor, text);
+ state.context.onContentChange(text);
+ }}
+ />
+ </label>
+ <output class="sr-only" data-testid="draft-dirty">
+ {String(state.context.hasDraft() && state.draftDirty())}
+ </output>
+ <MobileDrawer
+ side="bottom"
+ open={draftBackMenuOpen()}
+ onOpenChange={setDraftBackMenuOpen}
+ preventScroll={false}
+ preventScrollbarShift={false}
+ >
+ <MobileDrawer.Portal>
+ <MobileDrawer.Overlay />
+ <MobileDrawer.Content aria-label="Draft options">
+ <MobileDrawer.Handle />
+ <MobileDrawer.Section class="mb-3">
+ <button
+ type="button"
+ class="w-full bg-surface px-3 py-3.5 text-center text-sm font-medium text-failure not-last:mb-px"
+ onClick={() => {
+ setDraftBackMenuOpen(false);
+ props.onLeave();
+ }}
+ >
+ Delete Draft
+ </button>
+ <button
+ type="button"
+ class="w-full bg-surface px-3 py-3.5 text-center text-sm font-medium"
+ onClick={() => {
+ setDraftBackMenuOpen(false);
+ props.onLeave();
+ }}
+ >
+ Save Draft
+ </button>
+ </MobileDrawer.Section>
+ </MobileDrawer.Content>
+ </MobileDrawer.Portal>
+ </MobileDrawer>
+ </section>
+ );
+}
+
+/**
+ * Android's system Back, as `MobilePlugin.kt` dispatches it, driven through the
+ * real `useAndroidBack` bridge and the real mobile split container.
+ */
+export function AndroidBackFixture() {
+ const [composerOpen, setComposerOpen] = createSignal(true);
+ const [navigatedBack, setNavigatedBack] = createSignal(0);
+ useAndroidBack();
+ return (
+ <main class="min-h-screen bg-surface text-ink">
+ <MobileSplitContainer
+ splitManager={{ getSplit: () => undefined }}
+ stack={stubPaneStack(() => {
+ setNavigatedBack((count) => count + 1);
+ setComposerOpen(false);
+ })}
+ splits={() => [] as ReadonlyArray<SplitState>}
+ panelRefs={new Map<SplitId, HTMLDivElement>()}
+ />
+ <Show
+ when={composerOpen()}
+ fallback={<p class="p-3 text-sm">Back at the mail list</p>}
+ >
+ <MobileComposePanel onLeave={() => setComposerOpen(false)} />
+ </Show>
+ <output class="sr-only" data-testid="navigated-back">
+ {navigatedBack()}
+ </output>
+ </main>
+ );
+}
diff --git a/apps/web/src/features/email-compose/browser-test/android-back.browser.e2e.ts b/apps/web/src/features/email-compose/browser-test/android-back.browser.e2e.ts
new file mode 100644
index 0000000000..011abeccc0
--- /dev/null
+++ b/apps/web/src/features/email-compose/browser-test/android-back.browser.e2e.ts
@@ -0,0 +1,57 @@
+import { expect, type Page, test } from '@playwright/test';
+
+/** `MobilePlugin.kt` dispatches exactly this once the IME is already hidden. */
+async function pressSystemBack(page: Page) {
+ await page.evaluate(() =>
+ window.dispatchEvent(new Event('android-back', { cancelable: true }))
+ );
+}
+
+test.use({ viewport: { width: 390, height: 720 } });
+
+test('system Back on a dirty draft asks before leaving the composer', async ({
+ page,
+}) => {
+ page.on('pageerror', (error) => {
+ throw error;
+ });
+ await page.goto('/?android-back');
+ const composer = page.getByRole('region', { name: 'Compose email' });
+ await expect(composer).toBeVisible();
+
+ await page.getByRole('textbox', { name: 'Message' }).fill('Half-written');
+ await expect(page.getByTestId('draft-dirty')).toHaveText('true');
+
+ await pressSystemBack(page);
+ const options = page.getByRole('dialog', { name: 'Draft options' });
+ const saveDraft = options.getByRole('button', { name: 'Save Draft' });
+ // The sheet slides in, so wait for both choices to settle on screen.
+ await expect(options).not.toHaveAttribute('data-transitioning');
+ await expect(
+ options.getByRole('button', { name: 'Delete Draft' })
+ ).toBeInViewport();
+ await expect(saveDraft).toBeInViewport({ ratio: 1 });
+ await expect(page.getByTestId('navigated-back')).toHaveText('0');
+ await expect(composer).toBeVisible();
+ await page.screenshot({ path: test.info().outputPath('draft-options.png') });
+
+ await saveDraft.click();
+ await expect(composer).toHaveCount(0);
+});
+
+test('system Back leaves an untouched composer immediately', async ({
+ page,
+}) => {
+ page.on('pageerror', (error) => {
+ throw error;
+ });
+ await page.goto('/?android-back');
+ await expect(page.getByTestId('draft-dirty')).toHaveText('false');
+
+ await pressSystemBack(page);
+ await expect(page.getByRole('dialog', { name: 'Draft options' })).toHaveCount(
+ 0
+ );
+ await expect(page.getByTestId('navigated-back')).toHaveText('1');
+ await expect(page.getByText('Back at the mail list')).toBeVisible();
+});
diff --git a/apps/web/src/features/email-compose/browser-test/fixture.tsx b/apps/web/src/features/email-compose/browser-test/fixture.tsx
index efd16f92eb..31777affb2 100644
--- a/apps/web/src/features/email-compose/browser-test/fixture.tsx
+++ b/apps/web/src/features/email-compose/browser-test/fixture.tsx
@@ -17,6 +17,7 @@ import {
EmailScheduleSummary,
} from '../components/email-schedule-summary';
import type { EmailScheduleState } from '../primitives/email-send-schedule';
+import { AndroidBackFixture } from './android-back-fixture';
import { DraftOwnerFixture } from './draft-owner-fixture';
import { DraftRecoveryFixture } from './draft-recovery-fixture';
import { SenderFixture } from './sender-fixture';
@@ -341,6 +342,8 @@ render(
<DraftOwnerFixture />
) : new URLSearchParams(location.search).has('recovery') ? (
<DraftRecoveryFixture />
+ ) : new URLSearchParams(location.search).has('android-back') ? (
+ <AndroidBackFixture />
) : (
<Fixture />
),
diff --git a/apps/web/src/features/email-compose/browser-test/index.html b/apps/web/src/features/email-compose/browser-test/index.html
index a50f0f8dbd..fa928d4393 100644
--- a/apps/web/src/features/email-compose/browser-test/index.html
+++ b/apps/web/src/features/email-compose/browser-test/index.html
@@ -7,6 +7,17 @@
</head>
<body>
<div id="root"></div>
+ <script>
+ // Platform detection caches on first read, so the Android Back fixture
+ // needs the Tauri Android globals in place before any module runs.
+ if (new URLSearchParams(location.search).has('android-back')) {
+ window.__TAURI_INTERNALS__ = {};
+ window.__TAURI_OS_PLUGIN_INTERNALS__ = {
+ os_type: 'android',
+ platform: 'android',
+ };
+ }
+ </script>
<script type="module" src="/fixture.tsx"></script>
</body>
</html>
diff --git a/apps/web/src/features/email-compose/browser-test/split-panel-stub.tsx b/apps/web/src/features/email-compose/browser-test/split-panel-stub.tsx
new file mode 100644
index 0000000000..e83a2ffe6e
--- /dev/null
+++ b/apps/web/src/features/email-compose/browser-test/split-panel-stub.tsx
@@ -0,0 +1,4 @@
+/** Stands in for the split panel, which the Android Back fixture never mounts. */
+export function SplitPanel() {
+ return null;
+}
diff --git a/apps/web/src/features/email-compose/browser-test/vite.config.ts b/apps/web/src/features/email-compose/browser-test/vite.config.ts
index d533aeefbf..0bf9221676 100644
--- a/apps/web/src/features/email-compose/browser-test/vite.config.ts
+++ b/apps/web/src/features/email-compose/browser-test/vite.config.ts
@@ -11,10 +11,28 @@ const workspaceDirectory = fileURLToPath(
new URL('../../../../../../', import.meta.url)
);
+/**
+ * Back routing needs no panel content, and the real panel mounts most of the
+ * app, so the Android Back fixture gets an empty one.
+ */
+const stubSplitPanel = {
+ name: 'email-compose-fixture-stub-split-panel',
+ enforce: 'pre' as const,
+ resolveId(source: string, importer?: string) {
+ if (
+ source.endsWith('/components/SplitPanel') &&
+ importer?.endsWith('MobileSplitContainer.tsx')
+ ) {
+ return fileURLToPath(new URL('./split-panel-stub.tsx', import.meta.url));
+ }
+ },
+};
+
export default defineConfig({
root: directory,
cacheDir: `${directory}/.vite`,
plugins: [
+ stubSplitPanel,
{
name: 'sender-fixture-context',
enforce: 'pre',
@@ -28,6 +46,7 @@ export default defineConfig({
);
},
},
+
solidPlugin(),
solidSvg({ defaultAsComponent: true }),
tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
@@ -35,23 +54,27 @@ export default defineConfig({
],
resolve: {
dedupe: ['solid-js'],
- alias: {
- '@ui': fileURLToPath(new URL('./ui-shim.ts', import.meta.url)),
- ...Object.fromEntries(
- [
- '@core/component/UserIcon',
- '@core/component/inboxIcon',
- '@queries/email/mail-accounts',
- '@app/lib/analytics/posthog',
- '@core/email-link',
- '@app/components/view-shell',
- ].map((name) => [
- name,
- fileURLToPath(new URL('./sender-adapters.tsx', import.meta.url)),
- ])
- ),
- 'loro-crdt': 'loro-crdt/base64',
- },
+ // Exact matches only: `@ui/…` subpaths resolve to the real components.
+ alias: [
+ {
+ find: /^@ui$/,
+ replacement: fileURLToPath(new URL('./ui-shim.ts', import.meta.url)),
+ },
+ ...[
+ '@core/component/UserIcon',
+ '@core/component/inboxIcon',
+ '@queries/email/mail-accounts',
+ '@app/lib/analytics/posthog',
+ '@core/email-link',
+ '@app/components/view-shell',
+ ].map((name) => ({
+ find: name,
+ replacement: fileURLToPath(
+ new URL('./sender-adapters.tsx', import.meta.url)
+ ),
+ })),
+ { find: /^loro-crdt$/, replacement: 'loro-crdt/base64' },
+ ],
},
server: {
host: '127.0.0.1',
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index ea29bd26df..858f79f2e9 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -51,9 +51,12 @@ Switching tabs or navigating an in-app route is not a back/forward-cache restore
## Android system navigation and sharing
In the Android app, Back first hides the keyboard, then dismisses the active
-menu/drawer, then returns through mobile pane history. Root Back backgrounds the
-app. Check that a canceled predictive Back gesture leaves the current screen and
-draft untouched. After changing orientation or window size, focused inputs and
+menu/drawer, then offers the press to the active view, then returns through
+mobile pane history. Root Back backgrounds the app. A view that claims Back gets
+it before history: in the mobile email composer, Back on an edited draft opens
+**Draft options** with **Delete Draft** and **Save Draft** rather than leaving,
+exactly as the pane's back button does. Check that a canceled predictive Back
+gesture leaves the current screen and draft untouched. After changing orientation or window size, focused inputs and
sheet actions should stay above the keyboard without an extra blank keyboard-sized
gap. Font-size and display-size changes should retain the active draft and update
safe areas. Also change display size with the keyboard hidden: bottom composers