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(whatsapp-linked): import history from the chat, without a phone prompt (#9271)

Wolf Mermelstein407ba326e693
diff --git a/apps/web/src/features/external-chat/context/external-chat-context.tsx b/apps/web/src/features/external-chat/context/external-chat-context.tsx
index cf2c2a531f..39dc21abe0 100644
--- a/apps/web/src/features/external-chat/context/external-chat-context.tsx
+++ b/apps/web/src/features/external-chat/context/external-chat-context.tsx
@@ -37,6 +37,8 @@ export type ExternalChatCapabilities = {
fileUrl: (fileId: string) => string;
markRead: (messageId: string) => Promise<unknown>;
stopSync: () => Promise<unknown>;
+ /** Asks the owner's phone for this chat's earlier messages. */
+ importHistory: () => Promise<unknown>;
};
const Context = createContext<ExternalChatCapabilities>();
export function ExternalChatContextProvider(
diff --git a/apps/web/src/features/external-chat/core/chat.ts b/apps/web/src/features/external-chat/core/chat.ts
index a0af95a9c6..c5500b87ce 100644
--- a/apps/web/src/features/external-chat/core/chat.ts
+++ b/apps/web/src/features/external-chat/core/chat.ts
@@ -226,15 +226,16 @@ export function backfillStatus(
viewerOwns: boolean
): string | undefined {
if (!backfill) return undefined;
- return match(backfill.state)
- .with(P.union('pending', 'running'), () => 'Importing history…')
- .with('waiting_for_phone', () =>
- viewerOwns
- ? 'Earlier messages not imported. Open WhatsApp on your phone, then import them.'
- : "Earlier messages wait for the owner's phone"
- )
- .with(P.union('waiting_for_message', 'done', 'partial'), () => undefined)
- .exhaustive();
+ return (
+ match(backfill.state)
+ .with(P.union('pending', 'running'), () => 'Importing history…')
+ // The owner gets the import bar with its button instead.
+ .with('waiting_for_phone', () =>
+ viewerOwns ? undefined : "Earlier messages wait for the owner's phone"
+ )
+ .with(P.union('waiting_for_message', 'done', 'partial'), () => undefined)
+ .exhaustive()
+ );
}
/** "Launch · Design", or "Launch · Announcements" for its announcement group. */
diff --git a/apps/web/src/features/external-chat/queries/capabilities.ts b/apps/web/src/features/external-chat/queries/capabilities.ts
index 63ca1d76ad..8e3a822258 100644
--- a/apps/web/src/features/external-chat/queries/capabilities.ts
+++ b/apps/web/src/features/external-chat/queries/capabilities.ts
@@ -175,5 +175,11 @@ export function createExternalChatCapabilities(
await chatOperation('stop_sync', chatId(), () => api.stopSync(chatId()));
invalidateExternalChat(chatId());
},
+ importHistory: async () => {
+ await chatOperation('import_history', chatId(), () =>
+ api.importHistory()
+ );
+ invalidateExternalChat(chatId());
+ },
};
}
diff --git a/apps/web/src/features/external-chat/queries/production-api.ts b/apps/web/src/features/external-chat/queries/production-api.ts
index 2a6e0b7845..74bc0f1596 100644
--- a/apps/web/src/features/external-chat/queries/production-api.ts
+++ b/apps/web/src/features/external-chat/queries/production-api.ts
@@ -8,6 +8,7 @@ import type { ExternalChatReplyContent } from '@service-storage/generated/schema
import type { ExternalChatRichContent } from '@service-storage/generated/schemas/externalChatRichContent';
import type { ExternalChatSendProgress } from '@service-storage/generated/schemas/externalChatSendProgress';
import type { WhatsAppErrorCode } from '@service-storage/whatsapp-errors';
+import { whatsappLinkedClient } from '@service-storage/whatsapp-linked';
import { err, ok } from 'neverthrow';
import { match, P } from 'ts-pattern';
import { phoneFromJid } from '../../whatsapp-linked/core/account';
@@ -328,4 +329,5 @@ export const externalChatApi: ExternalChatApi = {
},
markRead: (id, messageId) => throwOnErr(() => client.markRead(id, messageId)),
stopSync: (id) => throwOnErr(() => client.stopSync(id)),
+ importHistory: () => throwOnErr(() => whatsappLinkedClient.importHistory()),
};
diff --git a/apps/web/src/features/external-chat/tests/fake-capabilities.ts b/apps/web/src/features/external-chat/tests/fake-capabilities.ts
index 8514df9584..ef0ca50c53 100644
--- a/apps/web/src/features/external-chat/tests/fake-capabilities.ts
+++ b/apps/web/src/features/external-chat/tests/fake-capabilities.ts
@@ -97,6 +97,7 @@ export function createFakeChat(
fileUrl: (fileId: string) => `https://files.example.test/${fileId}`,
markRead: vi.fn(async (_messageId: string) => undefined),
stopSync: vi.fn(async () => undefined),
+ importHistory: vi.fn(async () => undefined),
} satisfies ExternalChatCapabilities;
return { capabilities, setChat, setMessages, setDelivery };
}
diff --git a/apps/web/src/features/external-chat/views/external-chat-view.test.tsx b/apps/web/src/features/external-chat/views/external-chat-view.test.tsx
index de475777ac..7ef9ab1a79 100644
--- a/apps/web/src/features/external-chat/views/external-chat-view.test.tsx
+++ b/apps/web/src/features/external-chat/views/external-chat-view.test.tsx
@@ -216,13 +216,18 @@ it('says while history imports and shows older messages as they land', () => {
backfill: { state: 'waiting_for_phone', imported: 1 },
});
fake.setMessages(messages);
- expect(screen.getByRole('status').textContent).toBe(
- 'Earlier messages not imported. Open WhatsApp on your phone, then import them.'
- );
+ expect(
+ screen.getByText('Open WhatsApp on your phone to import earlier messages.')
+ ).toBeTruthy();
const ids = [...document.querySelectorAll('[data-message-id]')].map((row) =>
row.getAttribute('data-message-id')
);
expect(ids).toEqual(['message-1', 'message-2']);
+ // The owner can always start the import here, prompt or not.
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Import earlier messages' })
+ );
+ expect(fake.capabilities.importHistory).toHaveBeenCalledOnce();
fake.setChat({ ...chat, backfill: { state: 'done', imported: 1 } });
expect(screen.queryByText(/Importing history|Waiting for/)).toBeNull();
@@ -266,6 +271,9 @@ it('tells a shared viewer whose phone the import waits for', () => {
).toHaveLength(2);
// Not "No messages yet" while history is still coming.
expect(screen.queryByText(/No messages yet/)).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'Import earlier messages' })
+ ).toBeNull();
});
it('plays stored images and voice notes inline, like Chat, and opens other files', () => {
diff --git a/apps/web/src/features/external-chat/views/external-chat-view.tsx b/apps/web/src/features/external-chat/views/external-chat-view.tsx
index 09ce549eae..abe79ac562 100644
--- a/apps/web/src/features/external-chat/views/external-chat-view.tsx
+++ b/apps/web/src/features/external-chat/views/external-chat-view.tsx
@@ -372,6 +372,21 @@ export function ExternalChatView(props: {
source.chat.data?.backfill,
source.chat.data?.accessLevel === 'owner'
);
+ /** The owner can start the import here; it is the one place it always is. */
+ const canImport = () =>
+ source.chat.data?.accessLevel === 'owner' &&
+ source.chat.data.backfill?.state === 'waiting_for_phone';
+ const [startingImport, setStartingImport] = createSignal(false);
+ const startImport = async () => {
+ setStartingImport(true);
+ try {
+ await source.importHistory();
+ } catch {
+ toast.failure("Couldn't start importing earlier messages. Try again.");
+ } finally {
+ setStartingImport(false);
+ }
+ };
const historyStart = () =>
source.hasOlder()
? undefined
@@ -521,6 +536,27 @@ export function ExternalChatView(props: {
<SidePanel.Toggle />
</div>
</ViewShell.TopBar>
+ {/* Always reachable, however far back the timeline is scrolled. */}
+ <Show when={canImport()}>
+ <div class="flex min-w-0 items-center gap-3 border-b border-edge-muted px-4 py-2 text-xs text-ink-muted">
+ <span class="min-w-0 flex-1">
+ Open WhatsApp on your phone to import earlier messages.
+ </span>
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ class="shrink-0"
+ aria-label="Import earlier messages"
+ disabled={startingImport()}
+ onClick={() =>
+ fireAndForget(startImport(), 'external-chat.import-history')
+ }
+ >
+ {startingImport() ? 'Starting…' : 'Import'}
+ </Button>
+ </div>
+ </Show>
{/* Members, sharing and syncing open in the generic floating side
panel over the timeline, like an email thread's details. */}
<div class="relative min-h-0 min-w-0 flex-1">
diff --git a/apps/web/src/features/whatsapp-linked/AGENTS.md b/apps/web/src/features/whatsapp-linked/AGENTS.md
index 574e5dacf7..be65379772 100644
--- a/apps/web/src/features/whatsapp-linked/AGENTS.md
+++ b/apps/web/src/features/whatsapp-linked/AGENTS.md
@@ -28,10 +28,12 @@ own shareable external chat (`POST /external-chats` with `provider:
`NewChatFailure`); the `startChat` capability looks it up
(`useLookUpWhatsappNumberMutation` polls `GET /whatsapp/lookups/{id}`),
then adds and opens the chat.
-- `components/history-import-prompt.tsx`: the app-wide bottom-right prompt
- (mounted lazily in `Layout.tsx`) to import earlier messages of the owner's
- chats waiting for their phone (`core/history-import.ts`); its **Import** is
- the only thing that asks the phone (`POST /whatsapp/history-import`).
+- `components/history-import-prompt.tsx`: the bottom-right prompt (mounted
+ lazily in `Layout.tsx`; not on phones, where it covers the composer) to
+ import earlier messages of the owner's chats waiting for their phone
+ (`core/history-import.ts`). It and the chat view's import bar
+ (`features/external-chat`) are the only things that ask the phone
+ (`POST /whatsapp/history-import`).
- `core/chat.ts`: chat sections, search matching and row wording.
## Scope
diff --git a/apps/web/src/features/whatsapp-linked/components/history-import-prompt.tsx b/apps/web/src/features/whatsapp-linked/components/history-import-prompt.tsx
index 5d14dff15b..d87227adc9 100644
--- a/apps/web/src/features/whatsapp-linked/components/history-import-prompt.tsx
+++ b/apps/web/src/features/whatsapp-linked/components/history-import-prompt.tsx
@@ -2,6 +2,7 @@ import { externalChatApi } from '@app/features/external-chat/queries/production-
import { toast } from '@core/component/Toast/Toast';
import { useKeyedPersistentToasts } from '@core/component/Toast/useKeyedPersistentToasts';
import { useUserId } from '@core/context/user';
+import { isMobile } from '@core/mobile/isMobile';
import { fireAndForget } from '@core/util/fireAndForget';
import { useExternalChatsQuery } from '@queries/external-chats';
import { useExternalChatListsSync } from '@queries/external-chats/sync';
@@ -16,8 +17,9 @@ import { historyPromptText, waitingForPhone } from '../core/history-import';
* the phone, and on iOS one it can't finish in the background shows a
* "syncing stopped" notification. One prompt covers all the owner's chats
* waiting for the phone. It leaves while they import and comes back if the
- * phone didn't answer. It is the only way to start an import, so a close
- * lasts for this session only.
+ * phone didn't answer; a close sticks until another chat needs it, since each
+ * chat also offers Import above its earliest message. Not on phones, where
+ * the prompt region covers the composer.
*/
export function WhatsAppHistoryImportPrompt() {
const userId = useUserId();
@@ -30,12 +32,13 @@ export function WhatsAppHistoryImportPrompt() {
);
useKeyedPersistentToasts({
- items: () => (waiting().length ? [waiting()] : []),
+ items: () => (!isMobile() && waiting().length ? [waiting()] : []),
key: (group) =>
group
.map((chat) => chat.id)
.sort()
.join(','),
+ persistKey: 'macro:whatsapp-history-prompt:dismissed',
itemsLoaded: () => chats.isSuccess && userId() !== undefined,
toast: (group) => ({
title: 'Import WhatsApp history',
diff --git a/apps/web/src/lib/queries/external-chats/index.ts b/apps/web/src/lib/queries/external-chats/index.ts
index 0db9d3e1bc..abf94ac8e0 100644
--- a/apps/web/src/lib/queries/external-chats/index.ts
+++ b/apps/web/src/lib/queries/external-chats/index.ts
@@ -36,6 +36,11 @@ export type ExternalChatApi = {
) => Promise<Result<{ uploadId: string; audio: boolean }, SendFailure>>;
markRead: (chatId: string, messageId: string) => Promise<unknown>;
stopSync: (chatId: string) => Promise<unknown>;
+ /**
+ * Asks the owner's phone for the earlier messages of their chats waiting
+ * for it (WhatsApp imports per account, not per chat).
+ */
+ importHistory: () => Promise<unknown>;
};
// DSS pushes `external_chat_changed` through the connection gateway (`./sync`);
diff --git a/apps/web/tests/functional/whatsapp-linked.spec.ts b/apps/web/tests/functional/whatsapp-linked.spec.ts
index 76bf595f11..1ca28f152d 100644
--- a/apps/web/tests/functional/whatsapp-linked.spec.ts
+++ b/apps/web/tests/functional/whatsapp-linked.spec.ts
@@ -771,11 +771,37 @@ for (const mobile of [false, true]) {
const crit = state.chats.find((chat) => chat.added?.id === CHAT_ID);
if (!crit?.added) throw new Error('missing the added group');
crit.added.backfill = { state: 'waiting_for_phone', imported: 0 };
+ state.backfill = { state: 'waiting_for_phone', imported: 0 };
const unexpected = await mount(page, state);
const prompt = page.getByRole('status', {
name: 'Import WhatsApp history',
});
+ if (mobile) {
+ // On phones the prompt region covers the composer, so there is none;
+ // the chat itself offers Import above its earliest message.
+ await expect(page.getByText('Launch War Room')).toBeVisible();
+ await expect(prompt).toHaveCount(0);
+ await page.goto(
+ `${test.info().project.use.baseURL}/tests/functional/whatsapp-linked/index.html?chat=${CHAT_ID}`
+ );
+ const importHere = page.getByRole('button', {
+ name: 'Import earlier messages',
+ });
+ await expect(importHere).toBeVisible();
+ await page.screenshot({
+ path: process.env.WHATSAPP_SCREENSHOT_DIR
+ ? join(
+ process.env.WHATSAPP_SCREENSHOT_DIR,
+ 'whatsapp-history-import-chat-mobile.png'
+ )
+ : test.info().outputPath('whatsapp-history-import-chat.png'),
+ });
+ await importHere.click();
+ await expect.poll(() => state.historyImports).toBe(1);
+ expect(unexpected).toEqual([]);
+ return;
+ }
await expect(prompt).toBeVisible();
await expect(
prompt.getByText(
@@ -1433,9 +1459,7 @@ test('history imported after adding shows up older, with the import state', asyn
state.backfill = { state: 'waiting_for_phone', imported: 0 };
const unexpected = await mount(page, state, `?chat=${CHAT_ID}`);
await expect(
- page.getByText(
- 'WhatsApp · Earlier messages not imported. Open WhatsApp on your phone, then import them.'
- )
+ page.getByRole('button', { name: 'Import earlier messages' })
).toBeVisible();
// The phone answers; the next read (push or fallback re-fetch) shows it.
state.backfill = { state: 'done', imported: 1 };
diff --git a/docs/agent-guide/external.md b/docs/agent-guide/external.md
index 8f4499d68b..5d481c0233 100644
--- a/docs/agent-guide/external.md
+++ b/docs/agent-guide/external.md
@@ -136,17 +136,16 @@ The owner may stop syncing (details → **Syncing**, groups and direct chats) wi
`DELETE /external-chats/<id>`; history remains readable.
After adding, earlier messages (up to 500 messages or 90 days) come from the
-owner's phone only when they press **Import** in the bottom-right prompt
-**Import WhatsApp history** ("Open WhatsApp on your phone and keep it open,
-then import …"), shown app-wide while any of their chats is
-`waiting_for_phone`; closing it hides it until the next load (it is the only
-way to start an import). **Import**
-posts `/whatsapp/history-import`. The detail's `backfill` drives the header's
-subtitle: **WhatsApp · Importing history…** while `pending`/`running`,
-**WhatsApp · Earlier messages not imported. Open WhatsApp on your phone, then
-import them.** (*Earlier messages wait for the owner's phone* for shared
-viewers) while `waiting_for_phone`; the same line shows above the oldest
-message. `waiting_for_message` (nobody has posted since adding, so nothing to
+owner's phone only when they press Import. While a chat is
+`waiting_for_phone`, its owner sees a bar under the chat header ("Open
+WhatsApp on your phone to import earlier messages." with **Import**), and on desktop and
+tablets a closable bottom-right prompt **Import WhatsApp history** with
+**Import** covers all their waiting chats (never on phones, where it would
+cover the composer; a close sticks until another chat needs it). Both post
+`/whatsapp/history-import`. The detail's `backfill` drives the header's
+subtitle: **WhatsApp · Importing history…** while `pending`/`running`, and
+*Earlier messages wait for the owner's phone* for shared viewers while
+`waiting_for_phone`; the same line shows above the oldest message. `waiting_for_message` (nobody has posted since adding, so nothing to
import from yet) shows nothing; the first message makes it importable. Imported
messages appear older than what is shown as each page lands (pushed as
`external_chat_changed`), without moving the viewer's scroll position. `done` is
diff --git a/docs/architecture/whatsapp-linked-devices.md b/docs/architecture/whatsapp-linked-devices.md
index 2c7a988bd8..41aaa89309 100644
--- a/docs/architecture/whatsapp-linked-devices.md
+++ b/docs/architecture/whatsapp-linked-devices.md
@@ -145,8 +145,9 @@ there is nothing earlier to import, and its first message arrives live. If a
chat update later brings a message from before the chat was added (the phone
had history after all), it becomes `waiting_for_phone`.
-The web shows the owner a closable bottom-right prompt while any of their
-chats is `waiting_for_phone` ("open WhatsApp on your phone … **Import**").
+The web shows the owner an import bar in each chat that is
+`waiting_for_phone`, and on desktop a closable bottom-right prompt covering all
+of them ("open WhatsApp on your phone … **Import**").
`POST /whatsapp/history-import` (the owner's own session) moves those chats
to `pending` and signals `whatsapp_history_requested`; the replica holding the
account then asks for the anchor message itself when it predates adoption (a