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.

feat(whatsapp): open WhatsApp groups in External as channel chats (#8726)

Wolf Mermelsteinfd971940b6c0
diff --git a/Cargo.lock.rej b/Cargo.lock.rej
deleted file mode 100644
index ff24efdfe8..0000000000
--- a/Cargo.lock.rej
+++ /dev/null
@@ -1,9 +0,0 @@
-diff a/Cargo.lock b/Cargo.lock (rejected hunks)
-@@ -21645,6 +21645,7 @@ dependencies = [
- "macro_db_migrator",
- "macro_entrypoint",
- "macro_env",
-+ "macro_env_var",
- "macro_service_urls",
- "rootcause",
- "rustls",
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index a463c0d0c9..283a727e10 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -232,7 +232,7 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.
- Compose multiselect filters with `Dropdown.MultiSelectItem` and the shared
searchable filters; follow [multiselect dropdowns](../../docs/agent-guide/ui-conventions.md#multiselect-dropdowns)
for checkbox, row, Only, keyboard, and touch behavior.
-- Keep adopted WhatsApp groups on `/whatsapp-group/:id` with their own queries; sharing controls viewing and the viewer's own WhatsApp membership controls sending. Never route them through channel context or services.
+- Keep adopted WhatsApp groups in External at `/external/whatsapp/:id` (`/whatsapp-group/:id` redirects) with their own queries; sharing controls viewing and the viewer's own WhatsApp membership controls sending. Never route them through channel context or services.
- All API/network calls live in service-clients.
- Open projects through `openProject` (`features/projects/open-project.ts`): it
retargets an already-open project split to the section or comment in place.
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 355eef4535..24013a46c6 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -2,6 +2,7 @@ import { parseAgentsRoute } from '@app/features/agents-view/core/route';
import { useSpreadsheetAccess } from '@app/features/block-spreadsheet/primitives/use-spreadsheet-access';
import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
import type { CalendarEvent } from '@app/features/calendar/types';
+import { whatsappGroupContent } from '@app/features/external-view/hosted-content';
import { HomeRouteView } from '@app/features/home/route-views';
import { parseProjectRoute } from '@app/features/projects/core/route';
import { parseWhatsAppGroupComponentId } from '@app/features/whatsapp-group/core/route';
@@ -102,10 +103,6 @@ const ProjectView = lazyNamed(
() => import('@app/features/projects/project-view'),
'ProjectView'
);
-const WhatsAppGroup = lazyNamed(
- () => import('@app/features/whatsapp-group/whatsapp-group-entry'),
- 'WhatsAppGroupEntry'
-);
const ExternalRouteView = lazyNamed(
() => import('@app/features/external-view/route-views'),
'ExternalRouteView'
@@ -210,14 +207,10 @@ export function resolveComponent(
const registration = REGISTRY.get(name);
if (!registration) {
const groupId = parseWhatsAppGroupComponentId(name);
- if (groupId) {
- const group = REGISTRY.get('whatsapp-group');
- if (group)
- return {
- element: () => group.factory({ groupId }),
- initialMeta: resolveInitialMeta('whatsapp-group', group.initialMeta),
- };
- }
+ if (groupId)
+ return {
+ element: () => <RedirectSplit to={whatsappGroupContent(groupId)} />,
+ };
if (parseProjectRoute(name)) {
const base = REGISTRY.get('initiative-view');
if (base)
@@ -507,17 +500,6 @@ registerComponent(
() => <BookingLinksRouteView />,
() => composableLayout()
);
-registerComponent(
- 'whatsapp-group',
- withAuth((params) =>
- typeof params.groupId === 'string' ? (
- <WhatsAppGroup groupId={params.groupId} />
- ) : (
- <NotFound />
- )
- ),
- { splitPanelLayout: 'composable' }
-);
registerComponent(
'external',
() => <ExternalRouteView />,
diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts
index 483caf61e0..dd2329219b 100644
--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts
+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts
@@ -1,6 +1,8 @@
import { createRoutesManifest, type SplitRoutes } from '@app/lib/split-router';
import {
appRoute,
+ externalRoute,
+ externalWhatsappGroupRoute,
homeSplitRoute,
legacyContentRoute,
notFoundRoute,
@@ -33,6 +35,7 @@ const routes = createRoutesManifest({
...appRoute,
children: [
homeSplitRoute,
+ { ...externalRoute, children: [externalWhatsappGroupRoute] },
whatsappGroupRoute,
legacyContentRoute,
notFoundRoute,
@@ -70,15 +73,20 @@ describe('resolveContentLocation', () => {
});
});
-it('round-trips WhatsApp group components through their own route without a block', () => {
- const content = {
- type: 'component' as const,
+it('restores a saved WhatsApp group component inside External', () => {
+ const location = resolveContentLocation(routes, {
+ type: 'component',
id: 'whatsapp-group:019a061e-0000-7000-8000-000000000001',
- };
- const location = resolveContentLocation(routes, content);
- expect(location.route.matches.at(-1)).toEqual({
- id: 'whatsapp-group',
- params: { groupId: '019a061e-0000-7000-8000-000000000001' },
});
- expect(splitContentFromLocation(location)).toEqual(content);
+ expect(location.route.matches.slice(1)).toEqual([
+ { id: 'view-external', params: {} },
+ {
+ id: 'external-whatsapp-group',
+ params: { groupId: '019a061e-0000-7000-8000-000000000001' },
+ },
+ ]);
+ expect(splitContentFromLocation(location)).toEqual({
+ type: 'component',
+ id: 'external',
+ });
});
diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
index a678c59cce..f4ded5436a 100644
--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
@@ -21,10 +21,7 @@ import {
routineIdFromContent,
routineLocation,
} from '@app/features/routines/routine-navigation';
-import {
- parseWhatsAppGroupComponentId,
- whatsappGroupComponentId,
-} from '@app/features/whatsapp-group/core/route';
+import { parseWhatsAppGroupComponentId } from '@app/features/whatsapp-group/core/route';
import {
canonicalRoute,
decodePane,
@@ -298,7 +295,10 @@ export function splitLocationFromContent(
const groupId = parseWhatsAppGroupComponentId(content.id);
if (groupId)
return {
- route: paneRoute({ id: 'whatsapp-group', params: { groupId } }),
+ route: paneRoute(
+ { id: 'view-external', params: {} },
+ { id: 'external-whatsapp-group', params: { groupId } }
+ ),
};
const viewId = `view-${content.id}`;
if (routes.byId.has(viewId)) {
@@ -417,12 +417,9 @@ export function splitContentFromLocation(
throw new Error('Invalid routine detail split route');
}
- if (root.id === 'whatsapp-group') {
- const { groupId } = routeParams(location.route);
- if (typeof groupId === 'string')
- return { type: 'component', id: whatsappGroupComponentId(groupId) };
- throw new Error('Invalid WhatsApp group split route');
- }
+ // The retired route only redirects; its pane belongs to External.
+ if (root.id === 'whatsapp-group')
+ return { type: 'component', id: 'external' };
if (root.id.startsWith('view-'))
return { type: 'component', id: root.id.slice('view-'.length) };
if (root.id === 'drive') return { type: 'component', id: 'documents' };
diff --git a/apps/web/src/components/app/split-layout/tests/fixtures.ts b/apps/web/src/components/app/split-layout/tests/fixtures.ts
index eb2364d333..d219b024bc 100644
--- a/apps/web/src/components/app/split-layout/tests/fixtures.ts
+++ b/apps/web/src/components/app/split-layout/tests/fixtures.ts
@@ -11,6 +11,8 @@ import {
appRoute,
channelDetailRoute,
channelsSplitRoute,
+ externalRoute,
+ externalWhatsappGroupRoute,
homeSplitRoute,
legacyContentRoute,
notFoundRoute,
@@ -35,6 +37,7 @@ const routes: SplitRoutes = {
children: [
homeSplitRoute,
whatsappGroupRoute,
+ { ...externalRoute, children: [externalWhatsappGroupRoute] },
{ ...channelsSplitRoute, children: [channelDetailRoute] },
legacyContentRoute,
notFoundRoute,
diff --git a/apps/web/src/features/channel/Input/ChannelInput.tsx b/apps/web/src/features/channel/Input/ChannelInput.tsx
index 16fe4c8056..f8c001be70 100644
--- a/apps/web/src/features/channel/Input/ChannelInput.tsx
+++ b/apps/web/src/features/channel/Input/ChannelInput.tsx
@@ -92,10 +92,47 @@ import { isReplyInput } from './types';
import { uploadInputAttachments } from './upload-attachments';
import { clearComposer as clearComposerPreservingFocus } from './utils/clear-composer';
import { entityToDocumentMentionInfo } from './utils/entity-mention';
+import type { UploadResult } from './utils/file-helpers';
import { applyInlineFormat, applyNodeFormat } from './utils/formatting';
import { $selectTrailingParagraph } from './utils/select-trailing-paragraph';
import { hasSendableInputContent } from './utils/sendable-content';
+/**
+ * What the composer offers beyond text, formatting and file attachments.
+ * Hosts that carry only those, such as a WhatsApp group, switch the rest off.
+ */
+export type ChannelInputFeatures = {
+ /** `@` mentions of people, agents and Macro items, including Ask Macro. */
+ mentions: boolean;
+ /** Creating Macro items from the composer: tasks, documents, polls, forms. */
+ createItems: boolean;
+ gifs: boolean;
+ /** Blocks plain-text hosts can't carry: headings, checklists, tables, math, embeds. */
+ richBlocks: boolean;
+};
+
+const ALL_FEATURES: ChannelInputFeatures = {
+ mentions: true,
+ createItems: true,
+ gifs: true,
+ richBlocks: true,
+};
+
+/** Slash actions behind each switchable feature. */
+const CREATE_ITEM_ACTION_IDS = [
+ 'task',
+ 'document',
+ 'database',
+ 'database-query',
+];
+const RICH_BLOCK_ACTION_IDS = [
+ 'heading1',
+ 'heading2',
+ 'heading3',
+ 'list-check',
+ 'table',
+];
+
export type ChannelInputProps = InputCallbacks & {
input: InputData;
parent?: MessageParent;
@@ -127,6 +164,12 @@ export type ChannelInputProps = InputCallbacks & {
* Defaults to `false`.
*/
collapsible?: boolean;
+ /** Defaults to every feature; calls are offered through `onStartCall`. */
+ features?: Partial<ChannelInputFeatures>;
+ /** Uploads one picked or dropped file. Defaults to Macro's chat upload. */
+ uploadAttachment?: (file: File) => Promise<UploadResult>;
+ /** File picker filter. Defaults to the media and documents channels accept. */
+ fileAccept?: string;
/**
* Drop the composer's own card chrome (rounding, background, shadow) and sit
* flat on whatever surface hosts it. For composers that already live inside a
@@ -204,6 +247,10 @@ function DefaultActions(props: {
}
export function ChannelInput(props: ChannelInputProps) {
+ const features = (): ChannelInputFeatures => ({
+ ...ALL_FEATURES,
+ ...props.features,
+ });
const [layout, setLayout] = createSignal<HTMLDivElement>();
const [scrollContainer, setScrollContainer] = createSignal<HTMLElement>();
let clearComposer = () => {};
@@ -230,6 +277,7 @@ export function ChannelInput(props: ChannelInputProps) {
files,
tracker: attachmentTracker,
uploadFile: (file) =>
+ props.uploadAttachment?.(file) ??
uploadFile(file, chatRuleset, { hideProgressIndicator: true }),
});
},
@@ -316,11 +364,19 @@ export function ChannelInput(props: ChannelInputProps) {
]);
const groupMentions = !props.parent || props.parent.type === 'channel';
+ // The editor is configured once, at mount.
+ const initialFeatures = features();
const markdownEditor = createConfiguredChannelMarkdownEditor({
groupMentions,
namespace: props.markdownNamespace ?? 'channel-input-markdown',
resolveAppLink: useMacroMentionLinkResolver(),
- enableMentions: true,
+ enableMentions: initialFeatures.mentions,
+ composerActions: initialFeatures.createItems,
+ ignoreActionIds: [
+ ...(initialFeatures.createItems ? [] : CREATE_ITEM_ACTION_IDS),
+ ...(initialFeatures.richBlocks ? [] : RICH_BLOCK_ACTION_IDS),
+ ...(initialFeatures.gifs ? [] : ['gif']),
+ ],
users: mentionUsers,
scrollContainer,
onMentionCreate: (mention) => {
@@ -426,7 +482,7 @@ export function ChannelInput(props: ChannelInputProps) {
// The picker opens at the caret, so the editor takes focus first.
const gif = (): ComposerAddMenuGroup['items'] => {
const action = slashAction('gif');
- if (!action) return [];
+ if (!action || !features().gifs) return [];
return [
{
id: 'gif',
@@ -440,20 +496,25 @@ export function ChannelInput(props: ChannelInputProps) {
},
];
};
- const macro = macroUser();
+ const macro = features().mentions ? macroUser() : undefined;
const startCall = props.onStartCall;
const callInProgress = !!props.callInProgress;
return [
{
items: [
- {
- id: 'mention',
- label: 'Mention',
- icon: <AtIcon class="size-3.5" />,
- hint: '@',
- onSelect: () => runInEditor(openMentionTypeahead, { focus: true }),
- focusesEditor: true,
- },
+ ...(features().mentions
+ ? [
+ {
+ id: 'mention',
+ label: 'Mention',
+ icon: <AtIcon class="size-3.5" />,
+ hint: '@',
+ onSelect: () =>
+ runInEditor(openMentionTypeahead, { focus: true }),
+ focusesEditor: true,
+ },
+ ]
+ : []),
{
id: 'attach',
label: 'Attach files',
@@ -465,28 +526,30 @@ export function ChannelInput(props: ChannelInputProps) {
},
{
label: 'Create',
- items: [
- ...create(
- 'task',
- 'New task',
- <EntityIcon targetType="task" size="xs" />
- ),
- ...create(
- 'poll',
- 'New poll',
- <ChartBarIcon class="size-3.5 text-violet" />
- ),
- ...create(
- 'form',
- 'New form',
- <EntityIcon targetType="form" size="xs" />
- ),
- ...create(
- 'document',
- 'New document',
- <EntityIcon targetType="md" size="xs" />
- ),
- ],
+ items: !features().createItems
+ ? []
+ : [
+ ...create(
+ 'task',
+ 'New task',
+ <EntityIcon targetType="task" size="xs" />
+ ),
+ ...create(
+ 'poll',
+ 'New poll',
+ <ChartBarIcon class="size-3.5 text-violet" />
+ ),
+ ...create(
+ 'form',
+ 'New form',
+ <EntityIcon targetType="form" size="xs" />
+ ),
+ ...create(
+ 'document',
+ 'New document',
+ <EntityIcon targetType="md" size="xs" />
+ ),
+ ],
},
{
items: [
@@ -769,7 +832,7 @@ export function ChannelInput(props: ChannelInputProps) {
type="file"
class="hidden"
multiple
- accept={CHANNEL_FILE_PICKER_ACCEPT}
+ accept={props.fileAccept ?? CHANNEL_FILE_PICKER_ACCEPT}
onChange={collapsedInput.onFilePickerChange}
data-collapsed-input-file-picker
/>
diff --git a/apps/web/src/features/channel/Input/configured-markdown-editor.ts b/apps/web/src/features/channel/Input/configured-markdown-editor.ts
index 743267ab22..368387ee58 100644
--- a/apps/web/src/features/channel/Input/configured-markdown-editor.ts
+++ b/apps/web/src/features/channel/Input/configured-markdown-editor.ts
@@ -26,9 +26,14 @@ export function channelComposerActions(sendMessage?: () => void): Action[] {
*/
export function createConfiguredChannelMarkdownEditor({
sendMessage,
+ composerActions = true,
...options
-}: MessageEditorOptions & { sendMessage?: () => void }) {
- const actions = channelComposerActions(sendMessage);
+}: MessageEditorOptions & {
+ sendMessage?: () => void;
+ /** Offer the channel's own `/poll` and `/form`. */
+ composerActions?: boolean;
+}) {
+ const actions = composerActions ? channelComposerActions(sendMessage) : [];
return createConfiguredMessageEditor({
groupMentions: true,
floatingFormatMenu: true,
diff --git a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx b/apps/web/src/features/channel/Input/tests/input-slots.test.tsx
index d3a63c9e2a..f5aac691d0 100644
--- a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx
+++ b/apps/web/src/features/channel/Input/tests/input-slots.test.tsx
@@ -26,6 +26,7 @@ const editorMocks = vi.hoisted(() => ({
onEnter: undefined as (() => boolean) | undefined,
inlineMenuOpen: false,
onEscape: undefined as ((event?: KeyboardEvent) => boolean) | undefined,
+ ignoredActions: [] as string[],
}));
vi.mock(
@@ -276,7 +277,10 @@ vi.mock(
return builder;
},
withEmojis: () => builder,
- withActions: () => builder,
+ withActions: (options?: { ignoreActionIds?: string[] }) => {
+ editorMocks.ignoredActions.push(...(options?.ignoreActionIds ?? []));
+ return builder;
+ },
withLinks: () => builder,
withHistory: () => builder,
withCode: () => builder,
@@ -408,6 +412,7 @@ describe('Input slots', () => {
editorMocks.inlineMenuOpen = false;
editorMocks.onEscape = undefined;
editorMocks.mentionUsers = undefined;
+ editorMocks.ignoredActions = [];
vi.mocked(isMobile).mockReturnValue(false);
});
@@ -711,6 +716,29 @@ describe('Input slots', () => {
expect(onSend.mock.calls[0]?.[0]?.value).toBe('reply');
});
+ it('offers only text, formatting and files when a host switches features off', async () => {
+ const user = userEvent.setup();
+ render(() => (
+ <ChannelInput
+ input={baseInput}
+ features={{
+ mentions: false,
+ createItems: false,
+ gifs: false,
+ richBlocks: false,
+ }}
+ />
+ ));
+ expect(editorMocks.mentionUsers).toBeUndefined();
+ expect(editorMocks.ignoredActions).toEqual(
+ expect.arrayContaining(['task', 'document', 'gif', 'table', 'heading1'])
+ );
+ await user.click(screen.getByRole('button', { name: 'Add' }));
+ expect(
+ screen.getAllByRole('menuitem').map((item) => item.textContent)
+ ).toEqual(['Attach files']);
+ });
+
it('omits the reply action for channel mode', () => {
render(() => <ChannelInput input={baseInput} />);
diff --git a/apps/web/src/features/channel/Input/tests/message-payload.test.ts b/apps/web/src/features/channel/Input/tests/message-payload.test.ts
index 2a25013a02..2ed65e1579 100644
--- a/apps/web/src/features/channel/Input/tests/message-payload.test.ts
+++ b/apps/web/src/features/channel/Input/tests/message-payload.test.ts
@@ -23,6 +23,23 @@ vi.mock('@service-connection/websocket', () => ({
}));
describe('authored group references', () => {
+ it('sends a mentioned WhatsApp group so posting shares it with the channel', () => {
+ const result = buildPostMessageRequest({
+ snapshot: snap([
+ {
+ itemType: 'whatsapp_group',
+ itemId: '01a16445-9fdc-7bb1-80b4-8935a1243c98',
+ },
+ ]),
+ });
+ expect(result.mentions).toEqual([
+ {
+ entity_type: 'whatsapp_group',
+ entity_id: '01a16445-9fdc-7bb1-80b4-8935a1243c98',
+ },
+ ]);
+ });
+
it('sends routine references with the same wire type as headless extraction, including saved mentions', () => {
const blockNames = ['routine', 'automation'];
const snapshot = snap(
diff --git a/apps/web/src/features/channel/Input/upload-attachments.ts b/apps/web/src/features/channel/Input/upload-attachments.ts
index d672a7d89a..74d17f104f 100644
--- a/apps/web/src/features/channel/Input/upload-attachments.ts
+++ b/apps/web/src/features/channel/Input/upload-attachments.ts
@@ -103,7 +103,7 @@ export async function uploadInputAttachments(options: {
if (result.failed) {
options.tracker.removeAttachment(pendingId);
- toast.failure(`Failed to upload ${file.name}`);
+ toast.failure(result.reason ?? `Failed to upload ${file.name}`);
continue;
}
diff --git a/apps/web/src/features/channel/Input/utils/file-helpers.ts b/apps/web/src/features/channel/Input/utils/file-helpers.ts
index 6178139689..a7e5436904 100644
--- a/apps/web/src/features/channel/Input/utils/file-helpers.ts
+++ b/apps/web/src/features/channel/Input/utils/file-helpers.ts
@@ -8,6 +8,15 @@ import type { InputAttachmentData, InputAttachmentKind } from '../types';
export type UploadFailedResult = {
failed: true;
+ /** Shown instead of the generic failure, when the uploader knows why. */
+ reason?: string;
+};
+
+/** A file the host stored for its own send, such as a WhatsApp group upload. */
+export type UploadStagedSuccessResult = {
+ failed: false;
+ destination: 'staged';
+ id: string;
};
export type UploadStaticSuccessResult = {
@@ -27,6 +36,7 @@ export type UploadDocumentSuccessResult = {
export type UploadResult =
| UploadFailedResult
| UploadStaticSuccessResult
+ | UploadStagedSuccessResult
| UploadDocumentSuccessResult
| {
failed: false;
@@ -75,7 +85,7 @@ export function buildUploadedAttachment(
pendingKind: InputAttachmentKind,
result: UploadSuccess
): InputAttachmentData | undefined {
- if (result.destination === 'static') {
+ if (result.destination === 'static' || result.destination === 'staged') {
// A static upload keeps the kind the file was classified as: channels
// only send media here, but the agent composer sends every file, and a
// PDF stored as a static file is still a document chip.
diff --git a/apps/web/src/features/channel/Message/ChannelMessage.tsx b/apps/web/src/features/channel/Message/ChannelMessage.tsx
index 0560a68245..8e802ceab7 100644
--- a/apps/web/src/features/channel/Message/ChannelMessage.tsx
+++ b/apps/web/src/features/channel/Message/ChannelMessage.tsx
@@ -12,9 +12,21 @@ import type { ChannelMessageListMeta } from './list-meta';
import { Message } from './Message';
import { MaybeSwipeToReplyRow } from './SwipeToReplyRow';
+/**
+ * Where a message lives. A WhatsApp group renders through these rows but keeps
+ * its own storage, so it never reaches the stored-message editor.
+ */
+export type ChannelMessageParent =
+ | MessageParent
+ | { type: 'whatsapp_group'; id: string };
+
+function storedParent(parent: ChannelMessageParent): MessageParent | undefined {
+ return parent.type === 'whatsapp_group' ? undefined : parent;
+}
+
type ChannelMessageProps = {
renderContent?: (content: JSX.Element) => JSX.Element;
- parent: MessageParent;
+ parent: ChannelMessageParent;
inputMode?: 'inline' | 'unified';
message: MessageData;
actions?: MessageActions;
@@ -43,26 +55,28 @@ function isEditingMessage(
function MessageContentSlot(props: {
renderContent?: (content: JSX.Element) => JSX.Element;
- parent: MessageParent;
+ parent: ChannelMessageParent;
inputMode?: 'inline' | 'unified';
messageEditor?: MessageEditor;
class?: string;
}) {
const message = useMessage();
const isEditing = () => isEditingMessage(props.messageEditor, message().id);
+ const inlineEditing = () => {
+ const parent = storedParent(props.parent);
+ const messageEditor = props.messageEditor;
+ if (!isEditing() || props.inputMode === 'unified') return;
+ return parent && messageEditor ? { parent, messageEditor } : undefined;
+ };
const content = (
<Switch>
- <Match
- when={
- isEditing() && props.inputMode !== 'unified' && props.messageEditor
- }
- >
- {(messageEditor) => (
+ <Match when={inlineEditing()}>
+ {(editing) => (
<MessageEditorContent
- parent={props.parent}
+ parent={editing().parent}
message={message()}
- messageEditor={messageEditor()}
+ messageEditor={editing().messageEditor}
class={props.class}
/>
)}
@@ -119,7 +133,7 @@ function DeletedMessageLayout() {
function RegularMessageLayout(props: {
renderContent?: (content: JSX.Element) => JSX.Element;
- parent: MessageParent;
+ parent: ChannelMessageParent;
inputMode?: 'inline' | 'unified';
messageEditor?: MessageEditor;
hideTriggeredBy?: boolean;
@@ -135,7 +149,12 @@ function RegularMessageLayout(props: {
<Message.AgentBadge />
<Message.Timestamp
class="shrink-0"
- format={props.parent.type === 'channel' ? 'time' : 'dateAndTime'}
+ format={
+ props.parent.type === 'channel' ||
+ props.parent.type === 'whatsapp_group'
+ ? 'time'
+ : 'dateAndTime'
+ }
/>
<Message.EditedIndicator class="shrink-0" />
<Message.AgentSessionLink class="ml-auto" />
@@ -165,7 +184,7 @@ function RegularMessageLayout(props: {
function GroupedMessageLayout(props: {
renderContent?: (content: JSX.Element) => JSX.Element;
- parent: MessageParent;
+ parent: ChannelMessageParent;
inputMode?: 'inline' | 'unified';
messageEditor?: MessageEditor;
}) {
diff --git a/apps/web/src/features/channel/Message/ReactionChip.tsx b/apps/web/src/features/channel/Message/ReactionChip.tsx
index fc6f298fd0..f8e7ce04ec 100644
--- a/apps/web/src/features/channel/Message/ReactionChip.tsx
+++ b/apps/web/src/features/channel/Message/ReactionChip.tsx
@@ -1,5 +1,6 @@
import { touchHandler } from '@core/directive/touchHandler';
import { idToDisplayName } from '@core/user';
+import { tryMacroId } from '@core/user/macroId';
import { Popover } from '@kobalte/core/popover';
import { Button, cn, HoverCard } from '@ui';
import { createSignal, type JSX, Show } from 'solid-js';
@@ -25,14 +26,23 @@ export function formatReactorNames(
): string {
if (userIds.length === 0) return '';
+ // Reactors outside Macro, such as WhatsApp participants, have no name here.
+ const isNamed = (id: string) =>
+ id === currentUserId || tryMacroId(id) !== undefined;
const ordered = [
...userIds.filter((id) => id === currentUserId),
- ...userIds.filter((id) => id !== currentUserId),
+ ...userIds.filter((id) => id !== currentUserId && isNamed(id)),
];
+ const others = userIds.filter((id) => !isNamed(id)).length;
- const names = ordered.map((id) =>
- id === currentUserId ? 'You' : idToDisplayName(id)
- );
+ const names = [
+ ...ordered.map((id) =>
+ id === currentUserId ? 'You' : idToDisplayName(id)
+ ),
+ ...(others === 0
+ ? []
+ : [others === 1 ? '1 other person' : `${others} other people`]),
+ ];
if (names.length === 1) return names[0]!;
if (names.length === 2) return `${names[0]} and ${names[1]}`;
diff --git a/apps/web/src/features/channel/Message/SenderIcon.tsx b/apps/web/src/features/channel/Message/SenderIcon.tsx
index 27133cb3f9..0deb3badfc 100644
--- a/apps/web/src/features/channel/Message/SenderIcon.tsx
+++ b/apps/web/src/features/channel/Message/SenderIcon.tsx
@@ -24,6 +24,14 @@ export function SenderIcon(props: SenderIconProps) {
return sender;
};
+ // Someone outside Macro, such as a WhatsApp participant, has no principal.
+ const externalAuthor = () => {
+ const name = message().imported_author?.name?.trim();
+ return !message().sender_id && name
+ ? { name, avatar_url: null }
+ : undefined;
+ };
+
return (
<div
class={cn('shrink-0 size-(--user-icon-width)', props.class, {
@@ -36,7 +44,7 @@ export function SenderIcon(props: SenderIconProps) {
when={
message().guest_name
? { name: message().guest_name, avatar_url: null }
- : botSender()
+ : (externalAuthor() ?? botSender())
}
fallback={<UserIcon id={message().sender_id} size="fill" />}
>
diff --git a/apps/web/src/features/channel/Message/tests/reactions.test.tsx b/apps/web/src/features/channel/Message/tests/reactions.test.tsx
index 13af487a02..a1189c41f1 100644
--- a/apps/web/src/features/channel/Message/tests/reactions.test.tsx
+++ b/apps/web/src/features/channel/Message/tests/reactions.test.tsx
@@ -159,6 +159,18 @@ describe('formatReactorNames', () => {
});
+ it('counts reactors outside Macro instead of naming them', () => {
+ expect(
+ formatReactorNames(
+ ['whatsapp-reactor:1', 'user-1', 'whatsapp-reactor:2'],
+ 'user-1'
+ )
+ ).toBe('You and 2 other people');
+ expect(formatReactorNames(['whatsapp-reactor:1'], 'user-1')).toBe(
+ '1 other person'
+ );
+ });
+
it('puts current user first regardless of input order', () => {
expect(
formatReactorNames(['macro|[email protected]', 'user-1'], 'user-1')
diff --git a/apps/web/src/features/external-view/components/in-macro-section.test.tsx b/apps/web/src/features/external-view/components/in-macro-section.test.tsx
new file mode 100644
index 0000000000..4eaca027ba
--- /dev/null
+++ b/apps/web/src/features/external-view/components/in-macro-section.test.tsx
@@ -0,0 +1,65 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from '@solidjs/testing-library';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { InMacroSection } from './in-macro-section';
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe = vi.fn();
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+ }
+ );
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+it('lists readable groups with unread counts and marks read-only ones', () => {
+ const onOpenGroup = vi.fn();
+ render(() => (
+ <InMacroSection
+ groups={[
+ {
+ id: 'group-design',
+ name: 'Design Crit',
+ unreadCount: 3,
+ canSend: true,
+ },
+ {
+ id: 'group-family',
+ name: 'Ana, Ben, +2',
+ unreadCount: 0,
+ canSend: false,
+ },
+ ]}
+ isPending={false}
+ isError={false}
+ activeGroupId="group-family"
+ open
+ onOpenChange={vi.fn()}
+ onOpenGroup={onOpenGroup}
+ onRetry={vi.fn()}
+ />
+ ));
+ const nav = within(
+ screen.getByRole('navigation', { name: 'WhatsApp groups in Macro' })
+ );
+ const design = nav.getByRole('button', { name: /Design Crit/ });
+ expect(within(design).getByLabelText('3 unread messages')).toBeTruthy();
+ expect(within(design).queryByText('Read-only')).toBeNull();
+ const family = nav.getByRole('button', { name: /Ana, Ben, \+2/ });
+ expect(family.getAttribute('aria-current')).toBe('page');
+ expect(within(family).getByText('Read-only')).toBeTruthy();
+
+ fireEvent.click(design);
+ expect(onOpenGroup).toHaveBeenCalledWith('group-design');
+});
diff --git a/apps/web/src/features/external-view/components/in-macro-section.tsx b/apps/web/src/features/external-view/components/in-macro-section.tsx
new file mode 100644
index 0000000000..d89140b441
--- /dev/null
+++ b/apps/web/src/features/external-view/components/in-macro-section.tsx
@@ -0,0 +1,117 @@
+import { CollapsibleSection, ViewSidebar } from '@app/components/view-shell';
+import type { GroupSummary } from '@app/features/whatsapp-group/core/group';
+import { Button } from '@ui';
+import { For, Match, Show, Switch } from 'solid-js';
+
+function UnreadCount(props: { count: number }) {
+ return (
+ <Show when={props.count > 0}>
+ <span
+ aria-label={`${props.count} unread messages`}
+ class="flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full bg-accent px-1 text-xs font-medium leading-none tabular-nums text-accent-contrast"
+ >
+ {props.count}
+ </span>
+ </Show>
+ );
+}
+
+function GroupRow(props: {
+ group: GroupSummary;
+ active: boolean;
+ onOpen: () => void;
+}) {
+ return (
+ <ViewSidebar.Item
+ active={props.active}
+ title={props.group.name}
+ onClick={props.onOpen}
+ >
+ <span
+ class="min-w-0 flex-1 truncate"
+ classList={{ 'font-medium text-ink': props.group.unreadCount > 0 }}
+ >
+ {props.group.name}
+ </span>
+ <Show when={!props.group.canSend}>
+ <span
+ class="shrink-0 text-xs text-ink-extra-muted"
+ title="You can read this group. Your WhatsApp isn't in it, so you can't send."
+ >
+ Read-only
+ </span>
+ </Show>
+ <UnreadCount count={props.group.unreadCount} />
+ </ViewSidebar.Item>
+ );
+}
+
+/** WhatsApp groups this viewer can read in Macro: their own and shared ones. */
+export function InMacroSection(props: {
+ groups: GroupSummary[] | undefined;
+ isPending: boolean;
+ isError: boolean;
+ activeGroupId: string | undefined;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onOpenGroup: (groupId: string) => void;
+ onRetry: () => void;
+}) {
+ const unread = () =>
+ (props.groups ?? []).reduce((sum, group) => sum + group.unreadCount, 0);
+ return (
+ <CollapsibleSection.Root
+ open={props.open}
+ onOpenChange={props.onOpenChange}
+ >
+ <CollapsibleSection.Header>
+ <CollapsibleSection.Trigger class="flex-1">
+ <span class="min-w-0 truncate">In Macro</span>
+ <CollapsibleSection.Indicator />
+ <Show when={!props.open}>
+ <UnreadCount count={unread()} />
+ </Show>
+ </CollapsibleSection.Trigger>
+ </CollapsibleSection.Header>
+ <CollapsibleSection.Content>
+ <Switch>
+ <Match when={props.groups}>
+ {(groups) => (
+ <ViewSidebar.Nav aria-label="WhatsApp groups in Macro">
+ <For
+ each={groups()}
+ fallback={
+ <p class="px-3 py-2 text-sm text-ink-extra-muted">
+ No WhatsApp groups in Macro yet
+ </p>
+ }
+ >
+ {(group) => (
+ <GroupRow
+ group={group}
+ active={group.id === props.activeGroupId}
+ onOpen={() => props.onOpenGroup(group.id)}
+ />
+ )}
+ </For>
+ </ViewSidebar.Nav>
+ )}
+ </Match>
+ <Match when={props.isPending}>
+ <p role="status" class="px-3 py-2 text-sm text-ink-extra-muted">
+ Loading groups…
+ </p>
+ </Match>
+ <Match when={props.isError}>
+ <div class="flex items-center gap-2 px-3 py-2 text-sm text-ink-muted">
+ <span role="alert">Couldn't load your groups.</span>
+ <Button size="sm" variant="ghost" onClick={props.onRetry}>
+ Try again
+ </Button>
+ </div>
+ </Match>
+ </Switch>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ );
+}
diff --git a/apps/web/src/features/external-view/external-view.tsx b/apps/web/src/features/external-view/external-view.tsx
index b553c7a48e..abfe40f29f 100644
--- a/apps/web/src/features/external-view/external-view.tsx
+++ b/apps/web/src/features/external-view/external-view.tsx
@@ -1,15 +1,27 @@
import { ViewShell, ViewSidebar } from '@app/components/view-shell';
+import { SplitRouter, useNavigate, useParams } from '@app/lib/split-router';
+import { externalRoute, externalWhatsappGroupRoute } from '@app/routes/routes';
import { useSplitDisplayName } from '@components/app/split-layout/layoutUtils';
import { SplitPanel } from '@components/app/split-panel';
+import { useUserId } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { fireAndForget } from '@core/util/fireAndForget';
import WhatsappIcon from '@phosphor/whatsapp-logo.svg';
+import { queryReadyGate } from '@queries/gate';
+import { useWhatsappGroupsQuery } from '@queries/whatsapp-groups';
+import { useWhatsappGroupListsSync } from '@queries/whatsapp-groups/sync';
+import { traceWhatsappLoad } from '@queries/whatsapp-linked/operation';
import { useSearchParams } from '@solidjs/router';
+import { createSignal, Show } from 'solid-js';
import { z } from 'zod';
+import { whatsappGroupApi } from '../whatsapp-group/queries/production-api';
import { WhatsAppLinked } from '../whatsapp-linked/whatsapp-linked';
+import { InMacroSection } from './components/in-macro-section';
/**
* External: accounts on outside messaging apps that bring conversations into
- * Macro. WhatsApp is the only one today, so the list has one entry.
+ * Macro. WhatsApp is the only one today. Groups in Macro open in the main pane
+ * at `/external/whatsapp/:groupId`; on touch the list drills into the group.
*/
export function ExternalView() {
useSplitDisplayName(() => 'External');
@@ -18,6 +30,72 @@ export function ExternalView() {
const handedOffPairing = z.uuid().safeParse(search.whatsappPairing).data;
if (search.whatsappPairing !== undefined)
setSearch({ whatsappPairing: undefined }, { replace: true });
+
+ useWhatsappGroupListsSync();
+ const userId = useUserId();
+ const groups = useWhatsappGroupsQuery(whatsappGroupApi, () => userId() ?? '');
+ const inMacro = () => (queryReadyGate(groups) ? groups.data : undefined);
+ traceWhatsappLoad('groups.load', () => {
+ if (groups.isError) return { outcome: 'error' };
+ const list = inMacro();
+ if (!list) return;
+ return {
+ outcome: 'success',
+ attrs: {
+ 'whatsapp.groups.count': list.length,
+ 'whatsapp.groups.unread': list.filter((group) => group.unreadCount)
+ .length,
+ },
+ };
+ });
+
+ const params = useParams<{ groupId?: string }>();
+ const navigate = useNavigate();
+ const openGroup = (groupId: string) =>
+ fireAndForget(
+ navigate({ route: externalWhatsappGroupRoute, params: { groupId } }),
+ 'external-view'
+ );
+ const openWhatsApp = () =>
+ fireAndForget(
+ navigate({ route: externalRoute, params: {} }),
+ 'external-view'
+ );
+ const [inMacroOpen, setInMacroOpen] = createSignal(true);
+ const inMacroSection = () => (
+ <InMacroSection
+ groups={inMacro()}
+ isPending={groups.isPending}
+ isError={groups.isError}
+ activeGroupId={params.groupId}
+ open={inMacroOpen()}
+ onOpenChange={setInMacroOpen}
+ onOpenGroup={openGroup}
+ onRetry={() => fireAndForget(groups.refetch(), 'external-view')}
+ />
+ );
+
+ const whatsappPage = () => (
+ <>
+ <ViewShell.TopBar>
+ <h1 class="min-w-0 flex-1 truncate px-1 text-sm font-semibold tracking-[-0.03em] text-ink">
+ WhatsApp
+ </h1>
+ </ViewShell.TopBar>
+ <ViewShell.Content class="overflow-y-auto px-4 py-4 mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)">
+ {/* The top bar is desktop chrome; touch layouts title the page here. */}
+ <h1 class="hidden px-1 pb-3 text-lg font-semibold text-ink touch:block">
+ WhatsApp
+ </h1>
+ {/* Touch has no sidebar: the groups in Macro lead the page. */}
+ <Show when={isTouchDevice()}>
+ <div class="pb-4">{inMacroSection()}</div>
+ </Show>
+ <WhatsAppLinked resumePairingId={handedOffPairing} />
+ </ViewShell.Content>
+ </>
+ );
+
return (
<SplitPanel.Root>
<SplitPanel.Body>
@@ -36,29 +114,23 @@ export function ExternalView() {
</ViewSidebar.Header>
<ViewSidebar.Content>
<ViewSidebar.Nav aria-label="External apps">
- <ViewSidebar.Item active aria-current="page" title="WhatsApp">
+ <ViewSidebar.Item
+ active={!params.groupId}
+ title="WhatsApp"
+ onClick={openWhatsApp}
+ >
<ViewSidebar.Icon>
<WhatsappIcon class="size-4" />
</ViewSidebar.Icon>
<span class="truncate">WhatsApp</span>
</ViewSidebar.Item>
</ViewSidebar.Nav>
+ {inMacroSection()}
</ViewSidebar.Content>
</ViewSidebar.Root>
</ViewShell.Aside>
<ViewShell.Main>
- <ViewShell.TopBar>
- <h1 class="min-w-0 flex-1 truncate px-1 text-sm font-semibold tracking-[-0.03em] text-ink">
- WhatsApp
- </h1>
- </ViewShell.TopBar>
- <ViewShell.Content class="overflow-y-auto px-4 py-4 mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)">
- {/* The top bar is desktop chrome; touch layouts title the page here. */}
- <h1 class="hidden px-1 pb-3 text-lg font-semibold text-ink touch:block">
- WhatsApp
- </h1>
- <WhatsAppLinked resumePairingId={handedOffPairing} />
- </ViewShell.Content>
+ <SplitRouter.Outlet fallback={whatsappPage} />
</ViewShell.Main>
</ViewShell.Root>
</SplitPanel.Body>
diff --git a/apps/web/src/features/external-view/hosted-content.ts b/apps/web/src/features/external-view/hosted-content.ts
new file mode 100644
index 0000000000..01da948cc6
--- /dev/null
+++ b/apps/web/src/features/external-view/hosted-content.ts
@@ -0,0 +1,16 @@
+import { paneRoute } from '@app/routes/app-route';
+import type { SplitContent } from '@components/app/split-layout/layoutManager';
+
+/** A WhatsApp group opens in External's main pane, sharing External's identity. */
+export function whatsappGroupContent(groupId: string): SplitContent {
+ return {
+ type: 'component',
+ id: 'external',
+ entryMetadata: {
+ route: paneRoute(
+ { id: 'view-external', params: {} },
+ { id: 'external-whatsapp-group', params: { groupId } }
+ ),
+ },
+ };
+}
diff --git a/apps/web/src/features/external-view/route-views.tsx b/apps/web/src/features/external-view/route-views.tsx
index a32481aaef..0e7d9be771 100644
--- a/apps/web/src/features/external-view/route-views.tsx
+++ b/apps/web/src/features/external-view/route-views.tsx
@@ -1,11 +1,19 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { useNavigate } from '@app/lib/split-router';
-import { homeSplitRoute } from '@app/routes/routes';
+import { useNavigate, useRouteParams } from '@app/lib/split-router';
+import {
+ externalRoute,
+ externalWhatsappGroupRoute,
+ homeSplitRoute,
+} from '@app/routes/routes';
import {
usePageViewTracking,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
import { enableWhatsappLinked } from '@core/constant/featureFlags';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { fireAndForget } from '@core/util/fireAndForget';
+import CaretLeftIcon from '@phosphor/caret-left.svg';
+import { Button } from '@ui';
import { lazy, onMount, Show } from 'solid-js';
import { ExternalViewSkeleton } from './external-view-skeleton';
@@ -42,3 +50,42 @@ export const ExternalRouteView = withAuth(() => {
</Show>
);
}, ExternalViewSkeleton);
+
+const WhatsAppGroupEntry = lazy(async () => ({
+ default: (await import('../whatsapp-group/whatsapp-group-entry'))
+ .WhatsAppGroupEntry,
+}));
+
+/** Touch drills into a group full-screen; Back returns to External's list. */
+function BackToExternal() {
+ const navigate = useNavigate();
+ return (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Back to WhatsApp"
+ tooltip="Back to WhatsApp"
+ class="shrink-0"
+ onClick={() =>
+ fireAndForget(
+ navigate({ route: externalRoute, params: {} }),
+ 'external-view'
+ )
+ }
+ >
+ <CaretLeftIcon />
+ </Button>
+ );
+}
+
+/** `/external/whatsapp/:groupId`: a group in External's main pane. */
+export function ExternalWhatsAppGroupRouteView() {
+ const params = useRouteParams(externalWhatsappGroupRoute);
+ usePageViewTracking('whatsapp-group');
+ return (
+ <WhatsAppGroupEntry
+ groupId={params.groupId}
+ leading={isTouchDevice() ? <BackToExternal /> : undefined}
+ />
+ );
+}
diff --git a/apps/web/src/features/notifications/notification-navigation.ts b/apps/web/src/features/notifications/notification-navigation.ts
index 93c085e7c7..bc05bbbdb1 100644
--- a/apps/web/src/features/notifications/notification-navigation.ts
+++ b/apps/web/src/features/notifications/notification-navigation.ts
@@ -9,7 +9,7 @@ import {
import { prefetchChannelTarget } from '@channel/queries/prefetch-channel-target';
import { contentReference } from '@components/app/split-layout/content-reference';
import type {
- OpenSplitResult,
+ SplitContent,
SplitHandle,
SplitManager,
} from '@components/app/split-layout/layoutManager';
@@ -36,8 +36,8 @@ import type { PushNotificationNavigation } from '@service-notification/generated
import { errAsync, ResultAsync } from 'neverthrow';
import { match, P } from 'ts-pattern';
import { shareEntity } from '../access-requests/core/types';
+import { whatsappGroupContent } from '../external-view/hosted-content';
import { projectRouteId } from '../projects/core/route';
-import { whatsappGroupComponentId } from '../whatsapp-group/core/route';
import {
getDocumentCommentLocation,
type NotificationEntityOverride,
@@ -68,16 +68,16 @@ async function goToLocationInSplit(
}
/** Opens or activates the requested content from the source split. */
-function openSplitIfNotOpen(
+type OpenOptions = {
+ newSplit?: boolean;
+ sourceHandle?: SplitHandle;
+ onApplied?: VoidFunction;
+};
+
+function openContent(
layoutManager: SplitManager,
- type: BlockName | BlockAlias | 'component',
- id: string,
- options: {
- newSplit?: boolean;
- params?: Record<string, unknown>;
- sourceHandle?: SplitHandle;
- onApplied?: VoidFunction;
- } = {}
+ content: SplitContent,
+ options: OpenOptions
) {
let onApplied = options.onApplied;
const reportApplied = () => {
@@ -85,25 +85,38 @@ function openSplitIfNotOpen(
onApplied = undefined;
callback?.();
};
- const reportImmediateResult = (result: OpenSplitResult | undefined) => {
- if (!result) return;
- if (result.status === 'opened' || result.status === 'reused') {
- reportApplied();
- }
- };
+ const result = layoutManager.openWithSplit(content, {
+ activate: true,
+ referredFrom: null,
+ preferNewSplit: options.newSplit,
+ handle: options.sourceHandle,
+ ...(options.onApplied ? { onApplied: reportApplied } : {}),
+ });
+ if (result?.status === 'opened' || result?.status === 'reused')
+ reportApplied();
+}
+
+/** Groups open in External's main pane; the group's route claim reuses an open one. */
+function openWhatsAppGroup(
+ layoutManager: SplitManager,
+ groupId: string,
+ options: OpenOptions
+) {
+ openContent(layoutManager, whatsappGroupContent(groupId), options);
+}
+
+function openSplitIfNotOpen(
+ layoutManager: SplitManager,
+ type: BlockName | BlockAlias | 'component',
+ id: string,
+ options: OpenOptions & { params?: Record<string, unknown> } = {}
+) {
const existing = layoutManager.getSplitByContent(type, id);
if (existing) {
existing.activate();
- reportApplied();
+ options.onApplied?.();
} else {
- const result = layoutManager.openWithSplit(contentReference(type, id), {
- activate: true,
- referredFrom: null,
- preferNewSplit: options.newSplit,
- handle: options.sourceHandle,
- ...(options.onApplied ? { onApplied: reportApplied } : {}),
- });
- reportImmediateResult(result);
+ openContent(layoutManager, contentReference(type, id), options);
}
if (options.params && type !== 'component') {
goToLocationInSplit(layoutManager, type, id, options.params).catch(
@@ -231,12 +244,11 @@ function getSupportedHandler(
.with('whatsapp_group_message', () => {
if (!isFeatureEnabled(enableWhatsappLinked)) return null;
return async (lm: SplitManager, newSplit: boolean = false) =>
- openSplitIfNotOpen(
- lm,
- 'component',
- whatsappGroupComponentId(notification.entity_id),
- { newSplit, sourceHandle, onApplied }
- );
+ openWhatsAppGroup(lm, notification.entity_id, {
+ newSplit,
+ sourceHandle,
+ onApplied,
+ });
})
.with('new_email', () => {
const meta = notification.notification_metadata;
@@ -373,21 +385,24 @@ function getSupportedHandler(
});
};
span.setAttr('access_requests.outcome', 'navigation_requested');
- openSplitIfNotOpen(
- lm,
- block === 'initiative' || block === 'whatsapp_group'
- ? 'component'
- : block,
- block === 'whatsapp_group'
- ? whatsappGroupComponentId(target.entityId)
- : block === 'initiative'
+ if (block === 'whatsapp_group')
+ openWhatsAppGroup(lm, target.entityId, {
+ newSplit,
+ sourceHandle,
+ onApplied: applied,
+ });
+ else
+ openSplitIfNotOpen(
+ lm,
+ block === 'initiative' ? 'component' : block,
+ block === 'initiative'
? projectRouteId({
id: target.entityId,
section: 'overview',
})
: target.entityId,
- { newSplit, sourceHandle, onApplied: applied }
- );
+ { newSplit, sourceHandle, onApplied: applied }
+ );
} catch {
span.setAttr('access_requests.outcome', 'error');
span.error('Access-request notification could not be opened');
diff --git a/apps/web/src/features/notifications/tests/channel-notification-navigation.test.ts b/apps/web/src/features/notifications/tests/channel-notification-navigation.test.ts
index 634eee5fcb..507af8e585 100644
--- a/apps/web/src/features/notifications/tests/channel-notification-navigation.test.ts
+++ b/apps/web/src/features/notifications/tests/channel-notification-navigation.test.ts
@@ -239,7 +239,7 @@ it.each(['split', 'closed'] as const)(
}
);
-it('opens a WhatsApp notification in its own component without a channel block', async () => {
+it('opens a WhatsApp notification in External without a channel block', async () => {
vi.mocked(isFeatureEnabled).mockImplementation(
(flag) => flag === enableWhatsappLinked
);
@@ -256,10 +256,22 @@ it('opens a WhatsApp notification in its own component without a channel block',
layout
);
expect(open).toHaveBeenCalledWith(
- expect.objectContaining({
+ {
type: 'component',
- id: 'whatsapp-group:11111111-1111-4111-8111-111111111111',
- }),
+ id: 'external',
+ entryMetadata: {
+ route: {
+ matches: [
+ expect.anything(),
+ { id: 'view-external', params: {} },
+ {
+ id: 'external-whatsapp-group',
+ params: { groupId: '11111111-1111-4111-8111-111111111111' },
+ },
+ ],
+ },
+ },
+ },
expect.anything()
);
expect(createBlockInstance).not.toHaveBeenCalled();
diff --git a/apps/web/src/features/whatsapp-group/AGENTS.md b/apps/web/src/features/whatsapp-group/AGENTS.md
index e4a380fab7..ba2c8794cc 100644
--- a/apps/web/src/features/whatsapp-group/AGENTS.md
+++ b/apps/web/src/features/whatsapp-group/AGENTS.md
@@ -2,31 +2,40 @@
## Scope
-Owns the shareable WhatsApp conversation at `/whatsapp-group/:groupId`.
-It has independent message storage and queries. Reuse `channel/Message` only
-for presentation; never use channel queries, services, membership or context.
-Pairing and account management belong to `features/whatsapp-linked`.
+Owns the shareable WhatsApp conversation, opened inside External at
+`/external/whatsapp/:groupId`. It has independent message storage and
+queries. It renders with the channel components (`ChannelMessage`,
+`ChannelInput` with Macro-only features off) but never uses channel queries,
+services, membership or context. Pairing, account management and the External
+lists belong to `features/whatsapp-linked` and `features/external-view`.
## Map
-- `core/`: feature vocabulary, sending identity and edit eligibility.
+- `core/`: feature vocabulary, sending identity, edit eligibility, the
+ Markdown ↔ WhatsApp formatting converters and the `MessageData` mapping.
- `context/`: source and action contracts; no production imports.
-- `primitives/conversation.ts`: drafts, quotes, uploads and deliberate sends.
+- `primitives/conversation.ts`: optimistic sends, idempotency keys, quiet
+ retries, reply/edit targets, uploads and read state.
- `components/`: supplied values and callbacks only.
-- `views/`: conversation composition and read lifecycle.
-- `queries/`: generated wire decoding and production source construction.
-- `whatsapp-group.tsx`: app host, attachments and generic ShareModal.
+- `views/`: conversation composition, scroll and read lifecycle.
+- `queries/`: generated wire decoding, write-failure classification and
+ production source construction (spans live here).
+- `whatsapp-group.tsx`: app host and generic ShareModal.
- `whatsapp-group-entry.tsx`: flag gate for routed and restored panes.
-- Generic sharing uses direct people grants and view-only link/team controls;
- never forward groups into a channel to establish access.
-- `lib/queries/whatsapp-groups`: isolated query keys and server mutations.
+- `lib/queries/whatsapp-groups`: isolated query keys, reads and the
+ `whatsapp_changed` gateway sync (`sync.ts`).
## Gotchas
- Viewing follows ordinary entity sharing. WhatsApp membership controls sending.
- Every write uses the viewer's own connected WhatsApp account.
-- Never retry an unknown send automatically; it may already have arrived.
-- Preserve drafts during polling and after ambiguous failures.
+- A draft keeps one idempotency key until DSS records it; unknown outcomes
+ retry quietly with that key, so a resend can never arrive twice.
+- Refusals (`{code,message}` from DSS) remove the pending row, toast the
+ reason and restore the draft only if the composer is empty.
+- Row actions are getters: `ChannelMessage` reads them once per row.
+- Reads do not poll; DSS pushes `whatsapp_changed`, with one fallback
+ re-fetch 3 s after opening. Only in-flight sends poll their progress.
- Use backend limits for text, files, edits and deletes.
- Keep phone numbers and message bodies out of telemetry.
- Soup/search registration is deferred; External is the list entry point.
@@ -34,5 +43,6 @@ Pairing and account management belong to `features/whatsapp-linked`.
## Checks
- `bunx vitest run --project app src/features/whatsapp-group src/features/whatsapp-linked`
+- `bunx vitest run src/features/channel` (shared rows and composer)
- `bun run test:functional -- 'whatsapp-linked.spec.ts$'`
- `bun run check`
diff --git a/apps/web/src/features/whatsapp-group/components/group-composer.tsx b/apps/web/src/features/whatsapp-group/components/group-composer.tsx
deleted file mode 100644
index 8a80b86a54..0000000000
--- a/apps/web/src/features/whatsapp-group/components/group-composer.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-import { usePreserveFocusOnButtonTaps } from '@core/mobile/usePreserveFocusOnButtonTaps';
-import { useTouchOutsideToDismissKeyboard } from '@core/mobile/useTouchOutsideToDismissKeyboard';
-import { Button } from '@ui';
-import { For, Show } from 'solid-js';
-import { DeliveryStatus } from '../../whatsapp-linked/components/delivery-status';
-import type { PendingSend } from '../core/group';
-
-export function GroupComposer(props: {
- canSend: boolean;
- editing: boolean;
- note: string;
- draft: string;
- busy: boolean;
- fileName?: string;
- target?: { name: string; body: string };
- error?: string;
- pending: PendingSend[];
- onDraft: (value: string) => void;
- onFile: (file: File | undefined) => void;
- onCancelTarget: () => void;
- onSubmit: () => void;
- onConnect: () => void;
-}) {
- let container: HTMLDivElement | undefined;
- usePreserveFocusOnButtonTaps(() => container);
- useTouchOutsideToDismissKeyboard(() => container);
- return (
- <div
- ref={container}
- class="shrink-0 border-t border-edge-muted bg-panel px-3 pt-3 pb-4 touch:pb-[max(1rem,var(--mobile-content-inset-bottom,var(--safe-bottom,0px)))] sm:px-6"
- >
- <For each={props.pending}>
- {(send) => (
- <div class="mb-2 rounded-md border border-edge-muted p-2 ph-no-capture">
- <p class="text-sm break-words">{send.preview}</p>
- <DeliveryStatus state={send.state} errorCode={send.errorCode} />
- </div>
- )}
- </For>
- <Show when={props.target}>
- {(target) => (
- <div class="mb-2 flex min-w-0 items-center gap-2 border-l-2 border-accent pl-3 text-xs">
- <div class="min-w-0 flex-1">
- <strong>{target().name}</strong>
- <p class="truncate">{target().body}</p>
- </div>
- <Button variant="ghost" size="sm" onClick={props.onCancelTarget}>
- Cancel
- </Button>
- </div>
- )}
- </Show>
- <div class="mb-2 flex flex-wrap items-center justify-between gap-2 text-xs text-ink-muted">
- <span>{props.note}</span>
- <Show when={props.note === 'Connect your WhatsApp to reply'}>
- <Button variant="ghost" size="sm" onClick={props.onConnect}>
- Connect WhatsApp
- </Button>
- </Show>
- </div>
- <Show when={props.canSend}>
- <form
- class="flex flex-col gap-2 rounded-xl border border-edge-muted p-2"
- onSubmit={(event) => {
- event.preventDefault();
- props.onSubmit();
- }}
- >
- <textarea
- aria-label="Message WhatsApp group"
- placeholder="Message this group…"
- class="min-h-16 max-h-40 w-full resize-y bg-transparent px-2 py-1 text-base outline-none ph-no-capture"
- value={props.draft}
- disabled={props.busy}
- onInput={(event) => props.onDraft(event.currentTarget.value)}
- />
- <div class="flex items-center gap-2">
- <Show when={!props.editing}>
- <label class="rounded-md px-2 py-2 text-sm not-touch:hover:bg-hover">
- <span>Attach file</span>
- <input
- aria-label="Attach file"
- class="sr-only"
- type="file"
- disabled={props.busy}
- onChange={(event) => {
- props.onFile(event.currentTarget.files?.[0]);
- event.currentTarget.value = '';
- }}
- />
- </label>
- </Show>
- <Show when={props.fileName}>
- <span class="min-w-0 flex-1 truncate text-xs">
- {props.fileName}
- </span>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- disabled={props.busy}
- onClick={() => props.onFile(undefined)}
- >
- Remove file
- </Button>
- </Show>
- <Button
- type="submit"
- variant="strong"
- size="sm"
- class="ml-auto"
- disabled={props.busy || (!props.draft.trim() && !props.fileName)}
- >
- {props.busy ? 'Sending…' : 'Send'}
- </Button>
- </div>
- </form>
- </Show>
- <Show when={props.error}>
- <p role="alert" class="mt-2 text-xs text-failure-ink">
- {props.error}
- </p>
- </Show>
- </div>
- );
-}
diff --git a/apps/web/src/features/whatsapp-group/components/group-message.tsx b/apps/web/src/features/whatsapp-group/components/group-message.tsx
deleted file mode 100644
index 53d4c4df20..0000000000
--- a/apps/web/src/features/whatsapp-group/components/group-message.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-import { DateDivider } from '@channel/Message/DateDivider';
-import { Layout } from '@channel/Message/Layout';
-import { NewDivider } from '@channel/Message/NewDivider';
-import { Root } from '@channel/Message/Root';
-import { Slot } from '@channel/Message/Slot';
-import type { MessageData } from '@core/messages/types';
-import { Avatar, Button, Dropdown } from '@ui';
-import { For, type JSX, Show } from 'solid-js';
-import { DeliveryStatus } from '../../whatsapp-linked/components/delivery-status';
-import { InboundAttachmentPlaceholder } from '../../whatsapp-linked/components/inbound-attachment';
-import { groupInitials } from '../../whatsapp-linked/core/group';
-import type { GroupMessage } from '../core/group';
-
-export function GroupMessageRow(props: {
- message: GroupMessage;
- index: number;
- previousSentAt?: string;
- firstUnread: boolean;
- reply?: GroupMessage;
- canSend: boolean;
- busy: boolean;
- canEdit: boolean;
- canDelete: boolean;
- canReact: boolean;
- onReply: () => void;
- onEdit: () => void;
- onDelete: () => void;
- onReact: (emoji: string) => void;
- onRead: () => void;
- onOpenReply: (messageId: string) => void;
- renderAttachment: (documentId: string) => JSX.Element;
-}) {
- const messageData = (): MessageData => ({
- id: props.message.id,
- content: props.message.body,
- sender_id: props.message.sender.userId ?? '',
- imported_author: { name: props.message.sender.name },
- created_at: props.message.sentAt,
- updated_at: props.message.sentAt,
- attachments: [],
- reactions: [],
- });
- const meta = () => ({
- index: props.index,
- previousTopLevelCreatedAt: props.previousSentAt,
- isFirstNewMessage: props.firstUnread,
- isNewMessage: props.firstUnread,
- });
- return (
- <>
- <DateDivider createdAt={props.message.sentAt} listMeta={meta()} />
- <NewDivider
- createdAt={props.message.sentAt}
- listMeta={meta()}
- onDismiss={props.onRead}
- />
- <Root
- message={messageData()}
- class="py-3"
- actions={{
- onReply: props.onReply,
- onEdit: props.canEdit ? props.onEdit : undefined,
- onDelete: props.canDelete ? props.onDelete : undefined,
- }}
- >
- <Layout>
- <Slot placement="icon">
- <Avatar size="md">
- <Avatar.Fallback>
- {groupInitials(props.message.sender.name)}
- </Avatar.Fallback>
- </Avatar>
- </Slot>
- <Slot
- placement="header"
- class="flex flex-wrap items-baseline gap-x-2 text-sm"
- >
- <span class="font-medium">{props.message.sender.name}</span>
- <time
- class="text-xs text-ink-muted"
- dateTime={props.message.sentAt}
- >
- {new Intl.DateTimeFormat(undefined, {
- hour: 'numeric',
- minute: '2-digit',
- }).format(new Date(props.message.sentAt))}
- </time>
- <Show when={props.message.edited}>
- <span class="text-xs text-ink-muted">edited</span>
- </Show>
- </Slot>
- <Slot placement="content" class="ph-no-capture">
- <Show when={!props.message.deleted && props.message.replyTo}>
- {(id) => (
- <button
- type="button"
- class="mb-2 block max-w-full truncate border-l-2 border-accent py-1 pl-3 text-left text-xs text-ink-muted"
- onClick={() => props.onOpenReply(id())}
- >
- {props.reply
- ? `${props.reply.sender.name}: ${props.reply.deleted ? 'Deleted message' : props.reply.body || 'Attachment'}`
- : 'View quoted message'}
- </button>
- )}
- </Show>
- <p class="whitespace-pre-wrap break-words text-sm leading-6">
- {props.message.deleted
- ? 'This message was deleted.'
- : props.message.body}
- </p>
- <Show when={!props.message.deleted}>
- <div class="flex flex-wrap gap-2">
- <For each={props.message.attachments}>
- {(attachment) => (
- <Show
- when={
- attachment.state === 'ready' && attachment.documentId
- }
- fallback={
- <InboundAttachmentPlaceholder attachment={attachment} />
- }
- >
- {(id) => props.renderAttachment(id())}
- </Show>
- )}
- </For>
- </div>
- </Show>
- </Slot>
- <Slot placement="footer">
- <Show when={!props.message.deleted}>
- <div class="mt-1 flex flex-wrap items-center gap-1">
- <For each={props.message.reactions}>
- {(reaction) => (
- <Button
- variant={reaction.mine ? 'outline' : 'ghost'}
- size="sm"
- aria-label={`${reaction.emoji} ${reaction.count}${reaction.mine ? ', your reaction' : ''}`}
- disabled={!props.canReact || props.busy}
- onClick={() =>
- props.onReact(reaction.mine ? '' : reaction.emoji)
- }
- >
- {reaction.emoji} {reaction.count}
- </Button>
- )}
- </For>
- <Show when={props.canSend}>
- <Button
- variant="ghost"
- size="sm"
- disabled={props.busy}
- onClick={props.onReply}
- >
- Reply
- </Button>
- <Show when={props.canReact}>
- <Dropdown>
- <Dropdown.Trigger
- variant="ghost"
- size="sm"
- aria-label="React to message"
- disabled={props.busy}
- >
- React
- </Dropdown.Trigger>
- <Dropdown.Content>
- <For each={['👍', '❤️', '😂', '🎉', '🙏', '👀']}>
- {(emoji) => (
- <Dropdown.Item
- onSelect={() => props.onReact(emoji)}
- >
- {emoji}
- </Dropdown.Item>
- )}
- </For>
- </Dropdown.Content>
- </Dropdown>
- </Show>
- <Show when={props.canEdit}>
- <Button
- variant="ghost"
- size="sm"
- disabled={props.busy}
- onClick={props.onEdit}
- >
- Edit
- </Button>
- </Show>
- <Show when={props.canDelete}>
- <Button
- variant="ghost"
- size="sm"
- disabled={props.busy}
- onClick={props.onDelete}
- >
- Delete
- </Button>
- </Show>
- </Show>
- </div>
- <Show when={props.message.delivery}>
- {(state) => <DeliveryStatus state={state()} />}
- </Show>
- </Show>
- </Slot>
- </Layout>
- </Root>
- </>
- );
-}
diff --git a/apps/web/src/features/whatsapp-linked/components/inbound-attachment.tsx b/apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx
similarity index 100%
rename from apps/web/src/features/whatsapp-linked/components/inbound-attachment.tsx
rename to apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx
diff --git a/apps/web/src/features/whatsapp-group/components/inbound-media.tsx b/apps/web/src/features/whatsapp-group/components/inbound-media.tsx
new file mode 100644
index 0000000000..0ea82fb2c2
--- /dev/null
+++ b/apps/web/src/features/whatsapp-group/components/inbound-media.tsx
@@ -0,0 +1,65 @@
+import type { MediaItem } from '@channel/Media/media-items';
+import { MediaPreview } from '@channel/Message/MediaPreview';
+import { For, Show } from 'solid-js';
+
+/** An imported image, video or voice note with its resolved file URL. */
+export type InboundMediaFile = {
+ id: string;
+ kind: 'image' | 'video' | 'audio';
+ fileName: string;
+ /** Undefined while the URL resolves. */
+ url: string | undefined;
+};
+
+/**
+ * WhatsApp media inline, like Chat: images and video in Chat's media grid
+ * (click opens the viewer), audio in a player.
+ */
+export function InboundMedia(props: { files: InboundMediaFile[] }) {
+ const visual = (): MediaItem[] =>
+ props.files.flatMap((file) =>
+ file.kind !== 'audio' && file.url
+ ? [{ id: file.id, src: file.url, fullSrc: file.url, kind: file.kind }]
+ : []
+ );
+ const loading = () =>
+ props.files.some((file) => file.kind !== 'audio' && !file.url);
+ return (
+ <div class="mt-1 flex flex-col gap-2" data-whatsapp-inline-media>
+ <Show when={visual().length > 0}>
+ <MediaPreview items={visual()} />
+ </Show>
+ <Show when={loading()}>
+ <div
+ role="status"
+ aria-label="Loading media"
+ class="h-48 w-64 max-w-full skeleton-shimmer rounded-2xl bg-skeleton"
+ />
+ </Show>
+ <For each={props.files.filter((file) => file.kind === 'audio')}>
+ {(file) => (
+ <Show
+ when={file.url}
+ fallback={
+ <div
+ role="status"
+ aria-label={`Loading ${file.fileName}`}
+ class="h-10 w-72 max-w-full skeleton-shimmer rounded-full bg-skeleton"
+ />
+ }
+ >
+ {(url) => (
+ <audio
+ controls
+ preload="metadata"
+ src={url()}
+ aria-label={file.fileName}
+ class="h-10 w-72 max-w-full"
+ />
+ )}
+ </Show>
+ )}
+ </For>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx b/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx
index e9201c3706..5ebacd0cf4 100644
--- a/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx
+++ b/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx
@@ -1,3 +1,4 @@
+import type { Result } from 'neverthrow';
import {
type Accessor,
createContext,
@@ -9,19 +10,30 @@ import type {
GroupDetail,
GroupMessage,
GroupSend,
- PendingSend,
+ SendFailure,
+ SendProgress,
} from '../core/group';
/** One mounted group's independent data and writes. */
export type WhatsAppGroupCapabilities = {
group: SourceRead<GroupDetail>;
+ /** Messages DSS stored, oldest first. */
timeline: SourceRead<GroupMessage[]>;
- sends: SourceRead<PendingSend[]>;
hasOlder: Accessor<boolean>;
loadingOlder: Accessor<boolean>;
loadOlder: () => Promise<unknown>;
- send: (request: GroupSend, idempotencyKey: string) => Promise<unknown>;
- upload: (file: File) => Promise<{ uploadId: string; audio: boolean }>;
+ /** Records one write; DSS dedupes a retry that reuses its key. */
+ send: (
+ request: GroupSend,
+ idempotencyKey: string
+ ) => Promise<Result<SendProgress, SendFailure>>;
+ /** Progress of the recorded sends the page is waiting on. */
+ delivery: (sendIds: Accessor<string[]>) => SourceRead<SendProgress[]>;
+ upload: (
+ file: File
+ ) => Promise<Result<{ uploadId: string; audio: boolean }, SendFailure>>;
+ /** A short-lived URL for an imported file's bytes, to play it inline. */
+ fileUrl: (documentId: Accessor<string>) => SourceRead<string>;
markRead: (messageId: string) => Promise<unknown>;
stopSync: () => Promise<unknown>;
};
diff --git a/apps/web/src/features/whatsapp-group/core/attachments.test.ts b/apps/web/src/features/whatsapp-group/core/attachments.test.ts
new file mode 100644
index 0000000000..7ffe94b349
--- /dev/null
+++ b/apps/web/src/features/whatsapp-group/core/attachments.test.ts
@@ -0,0 +1,26 @@
+import { expect, it } from 'vitest';
+import { attachmentProblem } from './attachments';
+
+const MB = 1024 * 1024;
+const limits = {
+ attachmentTypes: ['image/jpeg', 'video/mp4', 'application/pdf'],
+ attachmentBytes: 32 * MB,
+};
+
+it('explains a refused file by type, then by size', () => {
+ expect(
+ attachmentProblem({ name: 'a.gif', type: 'image/gif', size: 1 }, limits)
+ ).toBe("WhatsApp doesn't accept a.gif's file type.");
+ expect(
+ attachmentProblem(
+ { name: 'b.mp4', type: 'video/mp4', size: 33 * MB },
+ limits
+ )
+ ).toBe("b.mp4 is larger than WhatsApp's 32 MB limit.");
+ expect(
+ attachmentProblem(
+ { name: 'c.pdf', type: 'application/pdf', size: MB },
+ limits
+ )
+ ).toBeUndefined();
+});
diff --git a/apps/web/src/features/whatsapp-group/core/attachments.ts b/apps/web/src/features/whatsapp-group/core/attachments.ts
new file mode 100644
index 0000000000..c0787035f9
--- /dev/null
+++ b/apps/web/src/features/whatsapp-group/core/attachments.ts
@@ -0,0 +1,31 @@
+/** An imported WhatsApp file on a group message, as DSS reports it. */
+export type InboundAttachment = {
+ ordinal: number;
+ state: 'loading' | 'ready' | 'unavailable' | 'unsupported';
+ fileName: string;
+ mime: string;
+ /** The Macro document holding the file, once ready. */
+ documentId: string | undefined;
+};
+
+/** How a ready file plays inline, like Chat's media; undefined for a file chip. */
+export function inlineMediaKind(
+ attachment: InboundAttachment
+): 'image' | 'video' | 'audio' | undefined {
+ if (attachment.state !== 'ready' || !attachment.documentId) return undefined;
+ const type = attachment.mime.split('/')[0];
+ if (type === 'image' || type === 'video' || type === 'audio') return type;
+ return undefined;
+}
+
+/** Why a file can't go to this WhatsApp group, by DSS's limits; undefined when it can. */
+export function attachmentProblem(
+ file: { name: string; type: string; size: number },
+ limits: { attachmentTypes: string[]; attachmentBytes: number }
+): string | undefined {
+ if (!limits.attachmentTypes.includes(file.type))
+ return `WhatsApp doesn't accept ${file.name}'s file type.`;
+ if (file.size > limits.attachmentBytes)
+ return `${file.name} is larger than WhatsApp's ${Math.floor(limits.attachmentBytes / (1024 * 1024))} MB limit.`;
+ return undefined;
+}
diff --git a/apps/web/src/features/whatsapp-group/core/formatting.test.ts b/apps/web/src/features/whatsapp-group/core/formatting.test.ts
new file mode 100644
index 0000000000..aa8827ab02
--- /dev/null
+++ b/apps/web/src/features/whatsapp-group/core/formatting.test.ts
@@ -0,0 +1,188 @@
+import { createHeadlessEditor } from '@lexical/headless';
+import {
+ $convertFromMarkdownString,
+ $convertToMarkdownString,
+} from '@lexical/markdown';
+import { SupportedNodeTypes } from '@macro-inc/lexical-core/node-list';
+import { ALL_TRANSFORMERS } from '@macro-inc/lexical-core/transformers';
+import {
+ $getRoot,
+ $isElementNode,
+ $isTextNode,
+ type LexicalNode,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+import { markdownToWhatsApp, whatsappToMarkdown } from './formatting';
+
+describe('composer Markdown to WhatsApp', () => {
+ it('rewrites inline formatting to WhatsApp markers', () => {
+ expect(
+ markdownToWhatsApp('**bold** *italic* _also_ ~~gone~~ `x = 1`')
+ ).toBe('*bold* _italic_ _also_ ~gone~ `x = 1`');
+ });
+ it('keeps nested formatting', () => {
+ expect(markdownToWhatsApp('**bold and *italic***')).toBe(
+ '*bold and _italic_*'
+ );
+ });
+ it('unescapes literal characters and spells out links', () => {
+ expect(markdownToWhatsApp('2 \\* 3 \\_ok\\_')).toBe('2 * 3 _ok_');
+ expect(markdownToWhatsApp('see [the doc](https://a.example/x)')).toBe(
+ 'see the doc (https://a.example/x)'
+ );
+ expect(
+ markdownToWhatsApp(
+ '[https://a.example](https://a.example) <https://b.example>'
+ )
+ ).toBe('https://a.example https://b.example');
+ });
+ it('sends fenced code as monospace without converting inside it', () => {
+ expect(
+ markdownToWhatsApp('before\n```ts\nconst **a** = 1;\n```\nafter')
+ ).toBe('before\n```const **a** = 1;```\nafter');
+ });
+ it('keeps lists and quotes, bolds headings', () => {
+ expect(markdownToWhatsApp('# Plan\n* one\n1. two\n> quoted')).toBe(
+ '*Plan*\n- one\n1. two\n> quoted'
+ );
+ });
+});
+
+/**
+ * What the shared renderer makes of `markdown`: its text, and each node as
+ * `type:text`, with text formats (`text[bold]:x`).
+ */
+function rendered(markdown: string): { text: string; nodes: string[] } {
+ const editor = createHeadlessEditor({ nodes: SupportedNodeTypes });
+ editor.update(() => $convertFromMarkdownString(markdown, ALL_TRANSFORMERS), {
+ discrete: true,
+ });
+ return editor.getEditorState().read(() => {
+ const nodes: string[] = [];
+ const walk = (node: LexicalNode) => {
+ if ($isTextNode(node)) {
+ const formats = (['bold', 'italic', 'strikethrough', 'code'] as const)
+ .filter((format) => node.hasFormat(format))
+ .join(',');
+ nodes.push(
+ `text${formats ? `[${formats}]` : ''}:${node.getTextContent()}`
+ );
+ return;
+ }
+ if (node.getType() !== 'paragraph' && node.getType() !== 'root')
+ nodes.push(`${node.getType()}:${node.getTextContent()}`);
+ if ($isElementNode(node)) node.getChildren().forEach(walk);
+ };
+ walk($getRoot());
+ return { text: $getRoot().getTextContent(), nodes };
+ });
+}
+
+describe('WhatsApp to Markdown for display', () => {
+ it('renders WhatsApp markers as formatting', () => {
+ expect(
+ rendered(whatsappToMarkdown('*bold* _italic_ ~strike~')).nodes
+ ).toEqual([
+ 'text[bold]:bold',
+ 'text: ',
+ 'text[italic]:italic',
+ 'text: ',
+ 'text[strikethrough]:strike',
+ ]);
+ });
+
+ it('shows Macro tags a sender typed as text, never as chips', () => {
+ const body =
+ 'hi <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> ' +
+ '<m-document-mention>{"documentId":"d1","documentName":"Payroll","blockName":"md"}</m-document-mention>';
+ expect(rendered(whatsappToMarkdown(body))).toEqual({
+ text: body,
+ nodes: [`text:${body}`],
+ });
+ });
+
+ it('shows Markdown a sender typed as text: links, headings, maths, citations', () => {
+ expect(
+ rendered(whatsappToMarkdown('[Macro login](javascript:alert(1))'))
+ ).toEqual({
+ text: '[Macro login](javascript:alert(1))',
+ nodes: ['text:[Macro login](javascript:alert(1))'],
+ });
+ for (const body of [
+ '# Urgent',
+ '---',
+ '| a | b |',
+ 'x $$y$$ [[cite]] <br> <u>z</u>',
+ 'C:\\temp\\new',
+ 'a literal &#60; stays',
+ ])
+ expect(rendered(whatsappToMarkdown(body))).toEqual({
+ text: body,
+ nodes: [`text:${body}`],
+ });
+ });
+
+ it('keeps markers inside words literal, and code as code', () => {
+ expect(
+ rendered(whatsappToMarkdown('snake_case_name 2*3*4 `x = f(1)`')).nodes
+ ).toEqual(['text:snake_case_name 2*3*4 ', 'text[code]:x = f(1)']);
+ });
+
+ it('shows code that could hold a tag as plain text', () => {
+ const body =
+ '`<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]","displayName":"x` `"}</m-user-mention>`';
+ expect(rendered(whatsappToMarkdown(body))).toEqual({
+ text: body,
+ nodes: [`text:${body}`],
+ });
+ });
+
+ it('turns triple-backtick monospace into a code block', () => {
+ const { nodes } = rendered(whatsappToMarkdown('look ```a *b* c``` done'));
+ expect(nodes).toContain('code:a *b* c');
+ });
+
+ it('renders WhatsApp bullets, numbers and quotes', () => {
+ expect(rendered(whatsappToMarkdown('* one\n- two\n> said')).nodes).toEqual([
+ 'list:one\n\ntwo',
+ 'listitem:one',
+ 'text:one',
+ 'listitem:two',
+ 'text:two',
+ 'quote:said',
+ 'text:said',
+ ]);
+ });
+
+ it('links bare http(s) URLs only, leaving trailing punctuation outside', () => {
+ expect(
+ rendered(
+ whatsappToMarkdown(
+ 'see https://example.com/a_b_c. or www.macro.com! javascript:alert(1)'
+ )
+ ).nodes
+ ).toEqual([
+ 'text:see ',
+ 'link:https://example.com/a_b_c',
+ 'text:https://example.com/a_b_c',
+ 'text:. or ',
+ 'link:www.macro.com',
+ 'text:www.macro.com',
+ 'text:! javascript:alert(1)',
+ ]);
+ });
+
+ it('round-trips an edited message back to the same WhatsApp text', () => {
+ const body = '*hi* _there_ ~x~ a < b & # c $d$ `e`';
+ const editor = createHeadlessEditor({ nodes: SupportedNodeTypes });
+ editor.update(
+ () =>
+ $convertFromMarkdownString(whatsappToMarkdown(body), ALL_TRANSFORMERS),
+ { discrete: true }
+ );
+ const exported = editor
+ .getEditorState()
+ .read(() => $convertToMarkdownString(ALL_TRANSFORMERS));
+ expect(markdownToWhatsApp(exported)).toBe(body);
+ });
+});
diff --git a/apps/web/src/features/whatsapp-group/core/formatting.ts b/apps/web/src/features/whatsapp-group/core/formatting.ts
new file mode 100644
index 0000000000..5c388a89d7
--- /dev/null
+++ b/apps/web/src/features/whatsapp-group/core/formatting.ts
@@ -0,0 +1,167 @@
+/**
+ * WhatsApp formats with single markers (`*bold*`, `_italic_`, `~strike~`,
+ * `` `code` ``, ```` ```monospace``` ````); the composer and the message
+ * renderer speak Markdown. These convert at the send and display edges.
+ */
+
+const FENCE = /^```/;
+
+/** Markdown inline syntax the composer writes, one alternative per group. */
+const MARKDOWN_INLINE =
+ /(`+)([^`]|[^`][\s\S]*?[^`])\1|\\([\\`*_{}[\]()#+\-.!~>|<])|\*\*((?:[^*]|\*[^*\s](?:[^*]*?[^*\s])?\*)+?)\*\*|__([\s\S]+?)__|\*([^*\s](?:[\s\S]*?[^*\s])?)\*|_([^_\s](?:[\s\S]*?[^_\s])?)_|~~([\s\S]+?)~~|\[([^\]]+)\]\(([^)\s]+)\)|<(https?:\/\/[^>\s]+)>/g;
+
+function markdownInline(text: string): string {
+ return text.replace(
+ MARKDOWN_INLINE,
+ (
+ _match,
+ _ticks: string | undefined,
+ code: string | undefined,
+ escaped: string | undefined,
+ starBold: string | undefined,
+ underscoreBold: string | undefined,
+ starItalic: string | undefined,
+ underscoreItalic: string | undefined,
+ strike: string | undefined,
+ linkText: string | undefined,
+ linkUrl: string | undefined,
+ autolink: string | undefined
+ ) => {
+ if (code !== undefined) return `\`${code}\``;
+ if (escaped !== undefined) return escaped;
+ const bold = starBold ?? underscoreBold;
+ if (bold !== undefined) return `*${markdownInline(bold)}*`;
+ const italic = starItalic ?? underscoreItalic;
+ if (italic !== undefined) return `_${markdownInline(italic)}_`;
+ if (strike !== undefined) return `~${markdownInline(strike)}~`;
+ if (linkText !== undefined && linkUrl !== undefined)
+ return linkText === linkUrl
+ ? linkUrl
+ : `${markdownInline(linkText)} (${linkUrl})`;
+ return autolink ?? '';
+ }
+ );
+}
+
+function markdownLine(line: string): string {
+ const heading = /^#{1,6}\s+(.*)$/.exec(line);
+ if (heading) return `*${markdownInline(heading[1] ?? '')}*`;
+ return markdownInline(line.replace(/^(\s*)[*+]\s+/, '$1- '));
+}
+
+/** Composer Markdown to the text WhatsApp sends and formats. */
+export function markdownToWhatsApp(markdown: string): string {
+ const out: string[] = [];
+ let code: string[] | undefined;
+ for (const line of markdown.split('\n')) {
+ if (FENCE.test(line)) {
+ if (code) {
+ out.push(`\`\`\`${code.join('\n')}\`\`\``);
+ code = undefined;
+ } else code = [];
+ continue;
+ }
+ if (code) code.push(line);
+ else out.push(markdownLine(line));
+ }
+ // An unterminated fence still sends its lines as monospace.
+ if (code) out.push(`\`\`\`${code.join('\n')}\`\`\``);
+ return out.join('\n').trim();
+}
+
+/** WhatsApp's markers, bounded by a non-word character or the line edge. */
+const WHATSAPP_INLINE =
+ /(`[^`\n]+`)|((?:https?:\/\/|www\.)[^\s<>]*[^\s<>.,;:!?'")\]*_~])|(^|[^\p{L}\p{N}*_~])([*_~])(?!\s)([^\n]*?[^\s*_~]|[^\s*_~])\4(?![\p{L}\p{N}*_~])/gu;
+
+/** ASCII punctuation, except `@`. */
+const PUNCTUATION = /[!-/:-?[-`{-~]/g;
+
+/**
+ * Received text as literal Markdown text: every punctuation mark becomes a
+ * numeric character reference, which the Markdown importer decodes back to
+ * the character after it has looked for syntax. No sender-written Markdown,
+ * HTML or Macro tag (`<m-user-mention>`, `[[…]]`, `$$…$$`) can take effect.
+ */
+function literal(text: string): string {
+ return text.replace(
+ PUNCTUATION,
+ (character) => `&#${character.charCodeAt(0)};`
+ );
+}
+
+/** A bare URL as a Markdown link, so it renders like Chat's links (with their preview). */
+function urlLink(url: string): string {
+ const href = (url.startsWith('www.') ? `https://${url}` : url)
+ .replace(/\(/g, '%28')
+ .replace(/\)/g, '%29');
+ return `[${literal(url)}](${href})`;
+}
+const MARKDOWN_FOR: Record<string, string> = { '*': '**', _: '*', '~': '~~' };
+
+function plainText(text: string): string {
+ return literal(text);
+}
+
+/**
+ * Characters a code span may hold. The importer neither decodes nor
+ * transforms inside a code span, so it must hold nothing a Macro tag, link,
+ * citation or equation could start with.
+ */
+const SAFE_CODE = /^[\p{L}\p{N}\s.,;?'"()+\-=/#%@^{}|]+$/u;
+
+/**
+ * `` `code` `` as a code span when that is safe and will form (not beside
+ * another span's backtick); otherwise as literal text.
+ */
+function inlineCode(code: string, before: string, after: string | undefined) {
+ const content = code.slice(1, -1);
+ if (SAFE_CODE.test(content) && !before.endsWith('`') && after !== '`')
+ return code;
+ return literal(code);
+}
+
+function whatsappInline(text: string): string {
+ let out = '';
+ let last = 0;
+ for (const found of text.matchAll(WHATSAPP_INLINE)) {
+ const [whole, code, url, before = '', marker = '', inner = ''] = found;
+ out += plainText(text.slice(last, found.index));
+ last = found.index + whole.length;
+ if (code !== undefined) out += inlineCode(code, out, text[last]);
+ else if (url !== undefined) out += urlLink(url);
+ else {
+ const markdown = MARKDOWN_FOR[marker] ?? '';
+ out += `${plainText(before)}${markdown}${whatsappInline(inner)}${markdown}`;
+ }
+ }
+ return out + plainText(text.slice(last));
+}
+
+/** WhatsApp's line formats: `- ` / `* ` bullets, `1. ` numbers and `> ` quotes. */
+const WHATSAPP_LINE = /^(?:([-*]) |(\d{1,9})\. |> ?)/;
+
+function whatsappLine(line: string): string {
+ const block = WHATSAPP_LINE.exec(line);
+ if (!block) return whatsappInline(line);
+ const rest = whatsappInline(line.slice(block[0].length));
+ if (block[1]) return `- ${rest}`;
+ if (block[2]) return `${block[2]}. ${rest}`;
+ return `> ${rest}`;
+}
+
+/**
+ * A received WhatsApp body as Markdown for the shared message renderer.
+ * Only what this function writes is Markdown: WhatsApp's own formatting and
+ * links for bare http(s) URLs. Everything else is literal text.
+ */
+export function whatsappToMarkdown(text: string): string {
+ return text
+ .split(/(```[\s\S]*?```)/)
+ .map((part) =>
+ part.startsWith('```') && part.endsWith('```') && part.length >= 6
+ ? `\n\`\`\`\n${part.slice(3, -3).replace(/^\n|\n$/g, '')}\n\`\`\`\n`
+ : part.split('\n').map(whatsappLine).join('\n')
+ )
+ .join('')
+ .trim();
+}
diff --git a/apps/web/src/features/whatsapp-group/core/group.ts b/apps/web/src/features/whatsapp-group/core/group.ts
index 02c62cf78e..70a0b17e2b 100644
--- a/apps/web/src/features/whatsapp-group/core/group.ts
+++ b/apps/web/src/features/whatsapp-group/core/group.ts
@@ -1,11 +1,13 @@
-import type { InboundAttachment } from '../../whatsapp-linked/core/attachments';
-import type { DeliveryState } from '../../whatsapp-linked/core/delivery';
+import { match, P } from 'ts-pattern';
+import type { InboundAttachment } from './attachments';
/** Feature vocabulary; transport decoding lives in queries/. */
export type GroupSummary = {
id: string;
name: string;
unreadCount: number;
+ /** False for viewers who can only read. */
+ canSend: boolean;
};
export type GroupDetail = {
id: string;
@@ -22,6 +24,7 @@ export type GroupDetail = {
textBytes: number;
attachmentBytes: number;
attachmentTypes: string[];
+ maxAttachments: number;
editSeconds: number;
mutations: ('reaction' | 'edit' | 'delete')[];
};
@@ -36,15 +39,10 @@ export type GroupMessage = {
replyTo?: string;
reactions: { emoji: string; count: number; mine: boolean }[];
attachments: InboundAttachment[];
- delivery?: DeliveryState;
+ /** Sent from this page and not yet in WhatsApp; never openable. */
+ pending?: boolean;
};
export type MessagePage = { messages: GroupMessage[]; before?: string };
-export type PendingSend = {
- id: string;
- preview: string;
- state: DeliveryState;
- errorCode?: string;
-};
export type GroupSend =
| { kind: 'text'; text: string; replyTo?: string }
| { kind: 'media'; uploadId: string; caption?: string; replyTo?: string }
@@ -52,6 +50,31 @@ export type GroupSend =
| { kind: 'edit'; messageId: string; text: string }
| { kind: 'delete'; messageId: string };
+/** A recorded send, as DSS reports its progress. */
+export type SendProgress = {
+ id: string;
+ state:
+ | 'pending'
+ | 'sending'
+ | 'unknown'
+ | 'accepted'
+ | 'sent'
+ | 'delivered'
+ | 'read'
+ | 'failed';
+ messageId?: string;
+ errorCode?: string;
+};
+
+/**
+ * Why a write did not go through. `refused` was never recorded, so the same
+ * draft can be sent again; `unknown` may have been recorded, so a retry reuses
+ * its idempotency key.
+ */
+export type SendFailure =
+ | { kind: 'refused'; reason: string }
+ | { kind: 'unknown' };
+
/** Both identity and the current backend limit are required for message changes. */
export function canChangeMessage(
message: GroupMessage,
@@ -64,6 +87,7 @@ export function canChangeMessage(
return (
!!userId &&
group.canSend &&
+ !message.pending &&
group.limits.mutations.includes(operation) &&
!message.deleted &&
message.sender.userId === userId &&
@@ -77,15 +101,62 @@ export function composerNote(group: GroupDetail): string {
return group.phone
? `Sending as ${group.phone}`
: 'Sending from your WhatsApp';
- if (group.sendReason === 'no_account' || group.sendReason === 'disconnected')
- return 'Connect your WhatsApp to reply';
- if (group.sendReason === 'not_member' || group.sendReason === 'not_observing')
- return "Your WhatsApp isn't in this group";
- if (group.sendReason === 'not_allowed_in_group')
- return "Your WhatsApp can't post in this group";
- if (group.sendReason === 'refreshing')
- return 'Refreshing this group from WhatsApp…';
- if (group.sendReason === 'group_unavailable')
- return 'This group is no longer syncing';
- return 'Sending to WhatsApp is unavailable right now';
+ return match(group.sendReason)
+ .with(
+ P.union('no_account', 'disconnected'),
+ () => 'Connect your WhatsApp to reply'
+ )
+ .with(
+ P.union('not_member', 'not_observing'),
+ () => "Your WhatsApp isn't in this group"
+ )
+ .with(
+ 'not_allowed_in_group',
+ () => "Your WhatsApp can't post in this group"
+ )
+ .with('group_unavailable', () => 'This group is no longer syncing')
+ .with('sending_disabled', () => 'Sending to WhatsApp is turned off')
+ .otherwise(() => 'Sending to WhatsApp is unavailable right now');
+}
+
+/** A send's outcome after DSS recorded it. */
+export function recordedOutcome(
+ progress: SendProgress
+): 'waiting' | 'accepted' | { failed: string } {
+ return match(progress.state)
+ .with(P.union('pending', 'sending'), () => 'waiting' as const)
+ .with(
+ P.union('accepted', 'sent', 'delivered', 'read'),
+ () => 'accepted' as const
+ )
+ .with(P.union('failed', 'unknown'), () => ({
+ failed: deliveryFailure(progress),
+ }))
+ .exhaustive();
+}
+
+/** Known delivery failures in plain words; never a provider response. */
+function deliveryFailure(progress: SendProgress): string {
+ // DSS never resends an unknown outcome; resending the restored draft reuses
+ // its key, so it cannot arrive twice.
+ if (progress.state === 'unknown')
+ return "WhatsApp didn't confirm this message.";
+ return match(progress.errorCode ?? '')
+ .with(
+ 'send_expired',
+ () => "WhatsApp wasn't reachable for 10 minutes, so this wasn't sent."
+ )
+ .with(
+ 'group_detached',
+ () => 'This chat stopped syncing before the message was sent.'
+ )
+ .with(
+ 'target_unavailable',
+ () => 'The message you replied to or changed is no longer in WhatsApp.'
+ )
+ .with(
+ 'disconnected',
+ () => 'Your WhatsApp disconnected before this was sent.'
+ )
+ .otherwise(() => "WhatsApp didn't accept this message.");
}
diff --git a/apps/web/src/features/whatsapp-group/core/message-data.ts b/apps/web/src/features/whatsapp-group/core/message-data.ts
new file mode 100644
index 0000000000..458f1b0b0c
--- /dev/null
+++ b/apps/web/src/features/whatsapp-group/core/message-data.ts
@@ -0,0 +1,63 @@
+import type { MessageData } from '@core/messages/types';
+import { inlineMediaKind } from './attachments';
+import { whatsappToMarkdown } from './formatting';
+import type { GroupMessage } from './group';
+
+/**
+ * A group message in the shape the shared channel rows render. Senders show
+ * their WhatsApp name; Macro users keep their Macro avatar.
+ */
+export function groupMessageData(
+ message: GroupMessage,
+ viewerId: string | undefined
+): MessageData {
+ return {
+ id: message.id,
+ content: message.deleted ? '' : whatsappToMarkdown(message.body),
+ sender_id: message.sender.userId ?? '',
+ // WhatsApp's name for everyone, Macro users included: a Macro profile
+ // without a name would otherwise show its email.
+ imported_author: message.sender.name.trim()
+ ? { name: message.sender.name }
+ : null,
+ created_at: message.sentAt,
+ updated_at: message.sentAt,
+ edited_at: message.edited ? message.sentAt : null,
+ deleted_at: message.deleted ? message.sentAt : null,
+ // Images, video and audio play inline (the view renders them); other
+ // files show as document chips.
+ attachments: message.attachments.flatMap((attachment) =>
+ attachment.state === 'ready' &&
+ attachment.documentId &&
+ !inlineMediaKind(attachment)
+ ? [
+ {
+ id: `${message.id}:${attachment.ordinal}`,
+ entity_id: attachment.documentId,
+ entity_type: 'document',
+ created_at: message.sentAt,
+ },
+ ]
+ : []
+ ),
+ // WhatsApp reports counts, not reactors; others stay unnamed.
+ reactions: message.reactions.map((reaction) => {
+ const mine = reaction.mine && viewerId ? [viewerId] : [];
+ return {
+ emoji: reaction.emoji,
+ users: [
+ ...mine,
+ ...Array.from(
+ { length: Math.max(0, reaction.count - mine.length) },
+ (_, index) => `whatsapp-reactor:${index}`
+ ),
+ ],
+ };
+ }),
+ };
+}
+
+/** Consecutive messages from one person group like a channel's. */
+export function senderKey(message: GroupMessage): string {
+ return message.sender.userId ?? `whatsapp:${message.sender.name}`;
+}
diff --git a/apps/web/src/features/whatsapp-group/core/route.ts b/apps/web/src/features/whatsapp-group/core/route.ts
index d2d779d7d5..82ee77cb2d 100644
--- a/apps/web/src/features/whatsapp-group/core/route.ts
+++ b/apps/web/src/features/whatsapp-group/core/route.ts
@@ -1,10 +1,10 @@
import { z } from 'zod';
const prefix = 'whatsapp-group:';
-/** The split manager stores native, block-free entities as component identities. */
-export function whatsappGroupComponentId(groupId: string): string {
- return `${prefix}${groupId}`;
-}
+/**
+ * Groups once opened as their own `whatsapp-group:<id>` split component;
+ * restored layouts still carry that identity and now open in External.
+ */
export function parseWhatsAppGroupComponentId(
componentId: string
): string | undefined {
diff --git a/apps/web/src/features/whatsapp-group/primitives/conversation.test.ts b/apps/web/src/features/whatsapp-group/primitives/conversation.test.ts
index e1742bac10..666773759e 100644
--- a/apps/web/src/features/whatsapp-group/primitives/conversation.test.ts
+++ b/apps/web/src/features/whatsapp-group/primitives/conversation.test.ts
@@ -1,152 +1,258 @@
-import { createRoot, createSignal } from 'solid-js';
-import { describe, expect, it } from 'vitest';
+import { err, ok } from 'neverthrow';
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
import { createFakeGroup, group, messages } from '../tests/fake-capabilities';
import { createConversation } from './conversation';
-describe('WhatsApp conversation draft', () => {
- it('keeps a draft and reply through polling and clears only after sending', async () => {
- const state = createRoot((dispose) => {
- const fake = createFakeGroup();
- return {
- fake,
- conversation: createConversation(
- fake.capabilities,
- () => group.ownerId
- ),
- dispose,
- };
- });
- state.conversation.setDraft('Reply from my own WhatsApp');
+function mountConversation(fake = createFakeGroup()) {
+ const notify = vi.fn();
+ const restore = vi.fn();
+ return createRoot((dispose) => ({
+ fake,
+ notify,
+ restore,
+ dispose,
+ conversation: createConversation(fake.capabilities, () => group.ownerId, {
+ notify,
+ restore,
+ retryDelays: [0, 0],
+ }),
+ }));
+}
+
+describe('sending to a WhatsApp group', () => {
+ it('shows the message at once and replaces it with the stored one', async () => {
+ const state = mountConversation();
state.conversation.reply(messages[0]);
- state.fake.setMessages([...messages]);
- expect(state.conversation.draft()).toBe('Reply from my own WhatsApp');
- await state.conversation.submit();
+ const delivery = state.conversation.submit({
+ markdown: 'On **it**',
+ attachments: [],
+ });
+ expect(delivery.isOk()).toBe(true);
+ const pending = state.conversation.rows().at(-1);
+ expect(pending).toMatchObject({
+ body: 'On *it*',
+ pending: true,
+ replyTo: 'message-1',
+ sender: { userId: group.ownerId },
+ });
+ expect(state.conversation.target()).toBeUndefined();
+ await delivery._unsafeUnwrap();
+ const key = state.fake.capabilities.send.mock.calls[0]?.[1];
expect(state.fake.capabilities.send).toHaveBeenCalledWith(
+ { kind: 'text', text: 'On *it*', replyTo: 'message-1' },
+ key
+ );
+ state.fake.setDelivery([
+ { id: `send-${key}`, state: 'accepted', messageId: 'message-3' },
+ ]);
+ expect(state.conversation.rows().at(-1)?.pending).toBe(true);
+ state.fake.setMessages([
+ ...messages,
{
- kind: 'text',
- text: 'Reply from my own WhatsApp',
+ id: 'message-3',
+ sender: { name: 'Me', userId: group.ownerId },
+ body: 'On *it*',
+ sentAt: new Date().toISOString(),
+ edited: false,
+ deleted: false,
replyTo: 'message-1',
+ reactions: [],
+ attachments: [],
},
- expect.any(String)
- );
- expect(state.conversation.draft()).toBe('');
- expect(state.conversation.quote()).toBeUndefined();
+ ]);
+ expect(state.conversation.rows().map((row) => row.id)).toEqual([
+ 'message-1',
+ 'message-2',
+ 'message-3',
+ ]);
+ expect(state.notify).not.toHaveBeenCalled();
state.dispose();
});
- it('keeps the draft after an ambiguous failure and never automatically retries', async () => {
- const state = createRoot((dispose) => {
- const fake = createFakeGroup();
- fake.capabilities.send.mockRejectedValueOnce(
- new Error('Connection lost')
- );
- return {
- fake,
- conversation: createConversation(
- fake.capabilities,
- () => group.ownerId
- ),
- dispose,
- };
+
+ it('removes a refused message, says why and gives the draft back', async () => {
+ const state = mountConversation();
+ state.fake.capabilities.send.mockResolvedValueOnce(
+ err({
+ kind: 'refused',
+ reason: "Your WhatsApp can't send to this group.",
+ })
+ );
+ state.conversation.reply(messages[0]);
+ const draft = { markdown: 'Hello', attachments: [] };
+ await state.conversation.submit(draft)._unsafeUnwrap();
+ expect(state.conversation.rows().some((row) => row.pending)).toBe(false);
+ expect(state.notify).toHaveBeenCalledWith(
+ "Your WhatsApp can't send to this group."
+ );
+ expect(state.restore).toHaveBeenCalledWith(draft, {
+ kind: 'reply',
+ message: messages[0],
});
- state.conversation.setDraft('Please check before resending');
- await state.conversation.submit();
- state.fake.setMessages([...messages]);
- expect(state.fake.capabilities.send).toHaveBeenCalledOnce();
- expect(state.conversation.draft()).toBe('Please check before resending');
- expect(state.conversation.error()).toContain('Check WhatsApp');
state.dispose();
});
- it('blocks sends without the viewers own connected membership and oversized files', async () => {
- const state = createRoot((dispose) => {
- const fake = createFakeGroup({ group: { ...group, canSend: false } });
- return {
- fake,
- conversation: createConversation(
- fake.capabilities,
- () => group.ownerId
- ),
- dispose,
- };
+
+ it('retries an unknown outcome quietly with the same key', async () => {
+ const state = mountConversation();
+ state.fake.capabilities.send
+ .mockResolvedValueOnce(err({ kind: 'unknown' }))
+ .mockResolvedValueOnce(err({ kind: 'unknown' }));
+ await state.conversation
+ .submit({ markdown: 'Hello', attachments: [] })
+ ._unsafeUnwrap();
+ const keys = state.fake.capabilities.send.mock.calls.map((call) => call[1]);
+ expect(keys).toHaveLength(3);
+ expect(new Set(keys).size).toBe(1);
+ expect(state.notify).not.toHaveBeenCalled();
+ expect(state.conversation.rows().at(-1)?.pending).toBe(true);
+ state.dispose();
+ });
+
+ it('after retries fail, restores the draft and resends it under the same key', async () => {
+ const state = mountConversation();
+ state.fake.capabilities.send.mockResolvedValue(err({ kind: 'unknown' }));
+ const draft = { markdown: 'Hello', attachments: [] };
+ await state.conversation.submit(draft)._unsafeUnwrap();
+ expect(state.notify).toHaveBeenCalledWith(
+ "Couldn't reach WhatsApp. Check your connection and try again."
+ );
+ expect(state.restore).toHaveBeenCalledWith(draft, undefined);
+ expect(state.conversation.rows().some((row) => row.pending)).toBe(false);
+ state.fake.capabilities.send.mockResolvedValue(
+ ok({ id: 'send-1', state: 'pending' })
+ );
+ await state.conversation
+ .submit({ markdown: 'Hello', attachments: [] })
+ ._unsafeUnwrap();
+ const keys = state.fake.capabilities.send.mock.calls.map((call) => call[1]);
+ expect(new Set(keys).size).toBe(1);
+ state.dispose();
+ });
+
+ it('reports a send WhatsApp rejected after recording it', async () => {
+ const state = mountConversation();
+ const draft = { markdown: 'Hello', attachments: [] };
+ await state.conversation.submit(draft)._unsafeUnwrap();
+ const key = state.fake.capabilities.send.mock.calls[0]?.[1];
+ state.fake.setDelivery([
+ { id: `send-${key}`, state: 'failed', errorCode: 'send_expired' },
+ ]);
+ expect(state.notify).toHaveBeenCalledWith(
+ "WhatsApp wasn't reachable for 10 minutes, so this wasn't sent."
+ );
+ expect(state.restore).toHaveBeenCalledWith(draft, undefined);
+ expect(state.conversation.rows().some((row) => row.pending)).toBe(false);
+ state.dispose();
+ });
+
+ it('keeps a draft WhatsApp could not take, without sending', () => {
+ const state = mountConversation(
+ createFakeGroup({
+ group: { ...group, limits: { ...group.limits, textBytes: 4 } },
+ })
+ );
+ const delivery = state.conversation.submit({
+ markdown: 'Too long',
+ attachments: [],
});
- state.conversation.setDraft('Cannot send');
- await state.conversation.submit();
+ expect(delivery._unsafeUnwrapErr()).toBe(
+ 'This message is too long for WhatsApp.'
+ );
expect(state.fake.capabilities.send).not.toHaveBeenCalled();
- state.fake.setGroup(group);
- state.conversation.setFile(
- new File(['test'], 'program.exe', { type: 'application/octet-stream' })
+ state.dispose();
+ });
+
+ it('sends a caption with a file, and after an audio file on its own', async () => {
+ const state = mountConversation();
+ state.fake.capabilities.upload.mockResolvedValueOnce(
+ ok({ uploadId: 'voice-1', audio: true })
);
- await state.conversation.submit();
- expect(state.fake.capabilities.upload).not.toHaveBeenCalled();
- expect(state.conversation.error()).toContain('not supported');
+ await state.conversation.upload(
+ new File(['a'], 'note.ogg', { type: 'audio/ogg' })
+ );
+ await state.conversation
+ .submit({
+ markdown: 'Listen',
+ attachments: [{ id: 'voice-1', name: 'note.ogg' }],
+ })
+ ._unsafeUnwrap();
+ await state.conversation
+ .submit({
+ markdown: 'Plan',
+ attachments: [{ id: 'upload-2', name: 'plan.pdf' }],
+ })
+ ._unsafeUnwrap();
+ expect(
+ state.fake.capabilities.send.mock.calls.map((call) => call[0])
+ ).toEqual([
+ {
+ kind: 'media',
+ uploadId: 'voice-1',
+ caption: undefined,
+ replyTo: undefined,
+ },
+ { kind: 'text', text: 'Listen' },
+ {
+ kind: 'media',
+ uploadId: 'upload-2',
+ caption: 'Plan',
+ replyTo: undefined,
+ },
+ ]);
state.dispose();
});
-});
-it('rechecks the mutation window after a delete confirmation waits', async () => {
- const state = createRoot((dispose) => {
- const fake = createFakeGroup();
- const conversation = createConversation(
- fake.capabilities,
- () => group.ownerId
- );
- fake.setGroup({ ...group, limits: { ...group.limits, editSeconds: 0 } });
- return { fake, conversation, dispose };
+ it('refuses files outside the group limits before uploading', async () => {
+ const state = mountConversation();
+ const result = await state.conversation.upload(
+ new File(['a'], 'clip.gif', { type: 'image/gif' })
+ );
+ expect(result._unsafeUnwrapErr()).toBe(
+ "WhatsApp doesn't accept clip.gif's file type."
+ );
+ expect(state.fake.capabilities.upload).not.toHaveBeenCalled();
+ state.dispose();
});
- await state.conversation.mutate({ kind: 'delete', messageId: 'message-2' });
- expect(state.fake.capabilities.send).not.toHaveBeenCalled();
- expect(state.conversation.error()).toContain('no longer be changed');
- state.dispose();
-});
-it('never silently discards a file selected during an edit', async () => {
- const state = createRoot((dispose) => {
- const fake = createFakeGroup();
- return {
- fake,
- conversation: createConversation(fake.capabilities, () => group.ownerId),
- dispose,
- };
+ it('toggles the viewer reaction and reports a refusal', async () => {
+ const state = mountConversation();
+ await state.conversation.react(messages[0], '👍');
+ expect(state.fake.capabilities.send).toHaveBeenLastCalledWith(
+ { kind: 'reaction', messageId: 'message-1', emoji: '' },
+ expect.any(String)
+ );
+ state.fake.capabilities.send.mockResolvedValueOnce(
+ err({ kind: 'refused', reason: 'Sending to WhatsApp is turned off.' })
+ );
+ await state.conversation.react(messages[0], '🎉');
+ expect(state.notify).toHaveBeenCalledWith(
+ 'Sending to WhatsApp is turned off.'
+ );
+ state.dispose();
});
- state.conversation.edit(messages[1]);
- state.conversation.setFile(
- new File(['test'], 'design.pdf', { type: 'application/pdf' })
- );
- await state.conversation.submit();
- expect(state.fake.capabilities.send).not.toHaveBeenCalled();
- expect(state.conversation.file()?.name).toBe('design.pdf');
- expect(state.conversation.error()).toContain('Attachments cannot be changed');
- state.dispose();
});
-it('does not send a staged attachment after the signed-in identity changes', async () => {
- let finishUpload!: (value: { uploadId: string; audio: boolean }) => void;
- const state = createRoot((dispose) => {
- const fake = createFakeGroup();
- const [userId, setUserId] = createSignal(group.ownerId);
- fake.capabilities.upload.mockImplementation(
+describe('reading a WhatsApp group', () => {
+ it('marks the newest message read once however often scrolling asks, and again after a failure', async () => {
+ const state = mountConversation();
+ let fail!: (error: Error) => void;
+ state.fake.capabilities.markRead.mockImplementationOnce(
() =>
- new Promise((resolve) => {
- finishUpload = resolve;
+ new Promise((_resolve, reject) => {
+ fail = reject;
})
);
- return {
- fake,
- setUserId,
- conversation: createConversation(fake.capabilities, userId),
- dispose,
- };
+ const first = state.conversation.markRead();
+ const second = state.conversation.markRead();
+ expect(state.fake.capabilities.markRead).toHaveBeenCalledOnce();
+ await second;
+
+ fail(new Error('offline'));
+ await expect(first).rejects.toThrow('offline');
+ await state.conversation.markRead();
+ expect(state.fake.capabilities.markRead).toHaveBeenCalledTimes(2);
+ await state.conversation.markRead();
+ expect(state.fake.capabilities.markRead).toHaveBeenCalledTimes(2);
+ state.dispose();
});
- state.conversation.setDraft('Keep this caption');
- state.conversation.setFile(
- new File(['test'], 'design.pdf', { type: 'application/pdf' })
- );
- const sending = state.conversation.submit();
- state.setUserId('macro|[email protected]');
- finishUpload({ uploadId: 'staged-upload', audio: false });
- await sending;
- expect(state.fake.capabilities.send).not.toHaveBeenCalled();
- expect(state.conversation.draft()).toBe('Keep this caption');
- expect(state.conversation.file()?.name).toBe('design.pdf');
- expect(state.conversation.busy()).toBe(false);
- state.dispose();
});
diff --git a/apps/web/src/features/whatsapp-group/primitives/conversation.ts b/apps/web/src/features/whatsapp-group/primitives/conversation.ts
index 71351a97ed..62d228c06a 100644
--- a/apps/web/src/features/whatsapp-group/primitives/conversation.ts
+++ b/apps/web/src/features/whatsapp-group/primitives/conversation.ts
@@ -1,25 +1,81 @@
-import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';
+import { sleep } from '@core/util/sleep';
+import { Telemetry } from '@macro-inc/observability';
+import { err, ok, type Result } from 'neverthrow';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
+import { v5 as uuidv5 } from 'uuid';
import type { WhatsAppGroupCapabilities } from '../context/whatsapp-group-context';
+import { attachmentProblem } from '../core/attachments';
+import { markdownToWhatsApp } from '../core/formatting';
import {
canChangeMessage,
+ composerNote,
type GroupMessage,
type GroupSend,
+ recordedOutcome,
+ type SendFailure,
} from '../core/group';
-/** Drafts survive background refresh; failed and unknown sends are never retried. */
+/** What the composer hands over: its Markdown and the files it staged. */
+export type Draft = {
+ markdown: string;
+ attachments: { id: string; name: string }[];
+};
+
+/** The message a reply quotes or an edit replaces. */
+export type ConversationTarget =
+ | { kind: 'reply'; message: GroupMessage }
+ | { kind: 'edit'; message: GroupMessage };
+
+/** One WhatsApp message of a send; a draft with files sends one per file. */
+type PendingPart = {
+ /** Idempotency key, and the pending row's id. */
+ key: string;
+ draft: Draft;
+ target: ConversationTarget | undefined;
+ sendId?: string;
+ row: GroupMessage;
+};
+
+/** Quiet retries of an unknown outcome, reusing its idempotency key. */
+const RETRY_DELAYS_MS = [1000, 2000, 4000];
+
+const UNKNOWN_SEND =
+ "Couldn't reach WhatsApp. Check your connection and try again.";
+
+export type ConversationHost = {
+ /** Tells the person why a write did not go through. */
+ notify: (message: string) => void;
+ /** Puts a draft that was not sent back in the composer. */
+ restore: (draft: Draft, target: ConversationTarget | undefined) => void;
+ retryDelays?: number[];
+};
+
+/**
+ * Sends appear at once and are replaced by the stored message; refusals and
+ * failures remove them and restore the draft. A draft keeps one idempotency
+ * key until it is recorded, so a retry after an unknown outcome can never
+ * arrive twice.
+ */
export function createConversation(
source: WhatsAppGroupCapabilities,
- userId: Accessor<string | undefined>
+ userId: Accessor<string | undefined>,
+ host: ConversationHost
) {
- const [draft, setDraft] = createSignal('');
- const [quote, setQuote] = createSignal<GroupMessage>();
- const [editing, setEditing] = createSignal<GroupMessage>();
- const [file, setFile] = createSignal<File>();
- const [busy, setBusy] = createSignal(false);
- const [error, setError] = createSignal<string>();
+ const retryDelays = host.retryDelays ?? RETRY_DELAYS_MS;
+ const [target, setTarget] = createSignal<ConversationTarget>();
+ const [pending, setPending] = createSignal<PendingPart[]>([]);
const [initialRead, setInitialRead] = createSignal<string>();
const [initialUnreadCount, setInitialUnreadCount] = createSignal(0);
const [readCaptured, setReadCaptured] = createSignal(false);
+ const draftKeys = new Map<string, string>();
+ const audioUploads = new Set<string>();
let marked: string | undefined;
let disposed = false;
onCleanup(() => {
@@ -34,148 +90,303 @@ export function createConversation(
setReadCaptured(true);
}
});
- const markRead = async () => {
- const id = source.timeline.data?.at(-1)?.id;
- if (!id || id === marked || document.visibilityState === 'hidden') return;
- try {
- await source.markRead(id);
- if (!disposed) marked = id;
- } catch {
- if (!disposed) setError("Couldn't mark these messages as read.");
- }
+
+ const sendIds = createMemo(
+ () => pending().flatMap((part) => (part.sendId ? [part.sendId] : [])),
+ [],
+ { equals: (a, b) => a.join() === b.join() }
+ );
+ const delivery = source.delivery(sendIds);
+ const progressBySend = createMemo(
+ () => new Map((delivery.data ?? []).map((send) => [send.id, send]))
+ );
+ const storedIds = createMemo(
+ () => new Set((source.timeline.data ?? []).map((message) => message.id))
+ );
+ /** Accepted sends whose stored message has arrived replace their row. */
+ const arrived = (part: PendingPart) => {
+ const progress = part.sendId && progressBySend().get(part.sendId);
+ return (
+ !!progress &&
+ recordedOutcome(progress) === 'accepted' &&
+ (!progress.messageId || storedIds().has(progress.messageId))
+ );
};
- const submit = async () => {
- const group = source.group.data;
- const senderId = userId();
- if (!group?.canSend || busy() || (!draft().trim() && !file())) return;
- if (
- new TextEncoder().encode(draft().trim()).length > group.limits.textBytes
- ) {
- setError('This message is too long for WhatsApp.');
- return;
- }
- const selected = file();
- if (
- selected &&
- (selected.size > group.limits.attachmentBytes ||
- !group.limits.attachmentTypes.includes(selected.type))
- ) {
- setError('This file type or size is not supported by WhatsApp.');
- return;
- }
- const text = draft().trim();
- if (selected?.type.startsWith('audio/') && text) {
- setError('Send audio without a caption. Your text is kept below.');
- return;
- }
- const replyTo = quote()?.id;
- const edit = editing();
- if (edit && selected) {
- setError('Attachments cannot be changed while editing a message.');
- return;
- }
- if (edit && !canChangeMessage(edit, userId(), group, Date.now(), 'edit')) {
- setError('This message can no longer be edited.');
- return;
+ const rows = () => [
+ ...(source.timeline.data ?? []),
+ ...pending()
+ .filter((part) => !arrived(part))
+ .map((part) => part.row),
+ ];
+
+ const drop = (keys: string[]) =>
+ setPending((parts) => parts.filter((part) => !keys.includes(part.key)));
+
+ // Outcomes after DSS recorded a send arrive with its progress.
+ createEffect(
+ on(
+ () => [progressBySend(), storedIds()] as const,
+ ([progress]) => {
+ for (const part of pending()) {
+ const send = part.sendId && progress.get(part.sendId);
+ if (!send) continue;
+ const outcome = recordedOutcome(send);
+ if (outcome === 'waiting') continue;
+ if (outcome === 'accepted') {
+ if (arrived(part)) drop([part.key]);
+ else source.timeline.refetch();
+ continue;
+ }
+ drop([part.key]);
+ host.notify(outcome.failed);
+ // A failed send may be retried as a new one; an unknown one keeps
+ // its key so resending the restored draft cannot duplicate it.
+ if (send.state === 'failed')
+ draftKeys.delete(fingerprint(part.draft, part.target));
+ if (!disposed) host.restore(part.draft, part.target);
+ }
+ }
+ )
+ );
+
+ /** One write, retried quietly while its outcome is unknown. */
+ const write = async (
+ request: GroupSend,
+ key: string
+ ): Promise<Result<{ sendId: string }, SendFailure>> => {
+ for (let attempt = 0; ; attempt++) {
+ const result = await source.send(request, key);
+ if (result.isOk()) return ok({ sendId: result.value.id });
+ const delay = retryDelays[attempt];
+ if (result.error.kind === 'refused' || delay === undefined)
+ return err(result.error);
+ await sleep(delay);
}
- setBusy(true);
- setError(undefined);
- try {
- let request: GroupSend;
- if (edit) request = { kind: 'edit', messageId: edit.id, text };
- else if (selected) {
- const uploaded = await source.upload(selected);
- if (disposed) return;
- if (uploaded.audio && text) {
- setError('Send audio without a caption. Your text is kept below.');
- return;
+ };
+
+ const deliver = (
+ parts: { request: GroupSend; key: string }[],
+ draft: Draft,
+ sentTarget: ConversationTarget | undefined,
+ draftFingerprint: string
+ ) =>
+ Telemetry.span('whatsapp.group.send', async (span) => {
+ span.setAttr('whatsapp.send.parts', parts.length);
+ let recorded = 0;
+ for (const [index, part] of parts.entries()) {
+ const result = await write(part.request, part.key);
+ if (result.isOk()) {
+ recorded++;
+ setPending((current) =>
+ current.map((item) =>
+ item.key === part.key
+ ? { ...item, sendId: result.value.sendId }
+ : item
+ )
+ );
+ continue;
}
- request = {
- kind: 'media',
- uploadId: uploaded.uploadId,
- caption: text || undefined,
- replyTo,
- };
- } else request = { kind: 'text', text, replyTo };
- if (disposed || userId() !== senderId || !source.group.data?.canSend)
- return;
- await source.send(request, crypto.randomUUID());
- if (disposed) return;
- setDraft('');
- setFile(undefined);
- setQuote(undefined);
- setEditing(undefined);
- } catch {
- if (!disposed)
- setError(
- "Couldn't confirm this send. Check WhatsApp and pending messages before trying again."
+ drop(parts.slice(index).map((item) => item.key));
+ span.setAttr('whatsapp.outcome', result.error.kind);
+ if (result.error.kind === 'refused') draftKeys.delete(draftFingerprint);
+ host.notify(
+ result.error.kind === 'refused' ? result.error.reason : UNKNOWN_SEND
);
- } finally {
- if (!disposed) setBusy(false);
- }
+ // Once part of a draft went out, restoring all of it would resend that part.
+ if (recorded === 0 && !disposed) host.restore(draft, sentTarget);
+ return;
+ }
+ draftKeys.delete(draftFingerprint);
+ span.setAttr('whatsapp.outcome', 'recorded');
+ });
+
+ /** Splits a draft into WhatsApp messages; a caption rides on the first non-audio file. */
+ const partsOf = (
+ draft: Draft,
+ text: string,
+ sentTarget: ConversationTarget | undefined
+ ): GroupSend[] => {
+ if (sentTarget?.kind === 'edit')
+ return [{ kind: 'edit', messageId: sentTarget.message.id, text }];
+ const replyTo =
+ sentTarget?.kind === 'reply' ? sentTarget.message.id : undefined;
+ if (draft.attachments.length === 0)
+ return [{ kind: 'text', text, replyTo }];
+ const captioned = draft.attachments.find(
+ (file) => !audioUploads.has(file.id)
+ );
+ const media = draft.attachments.map(
+ (file, index): GroupSend => ({
+ kind: 'media',
+ uploadId: file.id,
+ caption: file === captioned && text ? text : undefined,
+ replyTo: index === 0 ? replyTo : undefined,
+ })
+ );
+ // WhatsApp refuses captions on audio, so the text follows on its own.
+ return text && !captioned ? [...media, { kind: 'text', text }] : media;
};
- const mutate = async (request: GroupSend) => {
+
+ /**
+ * Sends a draft, or says why it can't go (the composer keeps it). The
+ * returned delivery reports its outcome through `host`, never by rejecting.
+ */
+ const submit = (draft: Draft): Result<Promise<void>, string> => {
const group = source.group.data;
- if (!group?.canSend || busy()) return;
- if (
- request.kind === 'reaction' &&
- !group.limits.mutations.includes('reaction')
- )
- return;
- if (request.kind === 'delete' || request.kind === 'edit') {
- const message = source.timeline.data?.find(
- (item) => item.id === request.messageId
- );
+ const senderId = userId();
+ if (!group || !senderId) return err('This group is still loading.');
+ if (!group.canSend) return err(composerNote(group));
+ const text = markdownToWhatsApp(draft.markdown);
+ const sentTarget = target();
+ if (new TextEncoder().encode(text).length > group.limits.textBytes)
+ return err('This message is too long for WhatsApp.');
+ if (sentTarget?.kind === 'edit') {
+ if (draft.attachments.length > 0)
+ return err("Files can't be added while editing a message.");
+ if (!text) return err('Write the edited message, or delete it instead.');
if (
- !message ||
- !canChangeMessage(message, userId(), group, Date.now(), request.kind)
- ) {
- setError('This message can no longer be changed.');
- return;
- }
+ !canChangeMessage(
+ sentTarget.message,
+ senderId,
+ group,
+ Date.now(),
+ 'edit'
+ )
+ )
+ return err('This message can no longer be edited.');
}
- setBusy(true);
- setError(undefined);
+ const requests = partsOf(draft, text, sentTarget);
+ if (requests.length === 0) return err('Write a message first.');
+ const draftFingerprint = fingerprint(draft, sentTarget);
+ const key = draftKeys.get(draftFingerprint) ?? crypto.randomUUID();
+ draftKeys.set(draftFingerprint, key);
+ const parts = requests.map((request, index) => ({
+ request,
+ key: requests.length === 1 ? key : uuidv5(String(index), key),
+ }));
+ const sentAt = new Date().toISOString();
+ setPending((current) => [
+ ...current,
+ ...parts.flatMap(({ request, key: partKey }): PendingPart[] =>
+ request.kind === 'text' || request.kind === 'media'
+ ? [
+ {
+ key: partKey,
+ draft,
+ target: sentTarget,
+ row: {
+ id: partKey,
+ sender: { name: '', userId: senderId },
+ body:
+ request.kind === 'text'
+ ? request.text
+ : (request.caption ?? ''),
+ sentAt,
+ edited: false,
+ deleted: false,
+ replyTo: request.replyTo,
+ reactions: [],
+ attachments:
+ request.kind === 'media'
+ ? draft.attachments
+ .filter((file) => file.id === request.uploadId)
+ .map((file, ordinal) => ({
+ ordinal,
+ state: 'loading' as const,
+ fileName: file.name,
+ mime: '',
+ documentId: undefined,
+ }))
+ : [],
+ pending: true,
+ },
+ },
+ ]
+ : []
+ ),
+ ]);
+ setTarget(undefined);
+ return ok(deliver(parts, draft, sentTarget, draftFingerprint));
+ };
+
+ /** Reactions and deletes: no draft to restore, just the reason. */
+ const change = async (request: GroupSend) => {
+ const result = await Telemetry.span('whatsapp.group.change', (span) => {
+ span.setAttr('whatsapp.send.kind', request.kind);
+ return write(request, crypto.randomUUID());
+ });
+ if (result.isErr())
+ host.notify(
+ result.error.kind === 'refused'
+ ? result.error.reason
+ : "Couldn't reach WhatsApp. Try again."
+ );
+ };
+
+ // Scrolling calls this many times a second: claim the id before the
+ // request so only one goes out, and give it back if the request fails.
+ const markRead = async () => {
+ const id = source.timeline.data?.at(-1)?.id;
+ if (!id || id === marked || document.visibilityState === 'hidden') return;
+ const previous = marked;
+ marked = id;
try {
- await source.send(request, crypto.randomUUID());
- } catch {
- if (!disposed)
- setError(
- "Couldn't confirm this change. Check WhatsApp before trying again."
- );
- } finally {
- if (!disposed) setBusy(false);
+ await source.markRead(id);
+ } catch (error) {
+ if (!disposed && marked === id) marked = previous;
+ throw error;
}
};
+
return {
- draft,
- setDraft,
- quote,
- editing,
- file,
- setFile,
- busy,
- error,
+ rows,
+ target,
initialRead,
initialUnreadCount,
markRead,
submit,
- mutate,
- reply: (message: GroupMessage) => {
- setQuote(message);
- setEditing(undefined);
+ reply: (message: GroupMessage) => setTarget({ kind: 'reply', message }),
+ edit: (message: GroupMessage) => setTarget({ kind: 'edit', message }),
+ cancelTarget: () => setTarget(undefined),
+ /** Toggles the viewer's one WhatsApp reaction on a message. */
+ react: (message: GroupMessage, emoji: string) => {
+ const mine = message.reactions.find((reaction) => reaction.mine);
+ return change({
+ kind: 'reaction',
+ messageId: message.id,
+ emoji: mine?.emoji === emoji ? '' : emoji,
+ });
},
- edit: (message: GroupMessage) => {
- setEditing(message);
- setQuote(undefined);
- setDraft(message.body);
- setFile(undefined);
- },
- cancelTarget: () => {
- if (editing()) setDraft('');
- setEditing(undefined);
- setQuote(undefined);
+ remove: (messageId: string) => change({ kind: 'delete', messageId }),
+ /** Stages one file for a later send, or says why it can't go. */
+ upload: async (
+ file: File
+ ): Promise<Result<{ uploadId: string }, string>> => {
+ const group = source.group.data;
+ if (!group?.canSend)
+ return err(
+ group ? composerNote(group) : 'This group is still loading.'
+ );
+ const problem = attachmentProblem(file, group.limits);
+ if (problem) return err(problem);
+ const result = await source.upload(file);
+ if (result.isErr())
+ return err(
+ result.error.kind === 'refused'
+ ? result.error.reason
+ : `Couldn't upload ${file.name}. Try again.`
+ );
+ if (result.value.audio) audioUploads.add(result.value.uploadId);
+ return ok({ uploadId: result.value.uploadId });
},
};
}
-export type Conversation = ReturnType<typeof createConversation>;
+
+function fingerprint(draft: Draft, target: ConversationTarget | undefined) {
+ return JSON.stringify([
+ draft.markdown,
+ draft.attachments.map((file) => file.id),
+ target?.kind,
+ target?.message.id,
+ ]);
+}
diff --git a/apps/web/src/features/whatsapp-group/queries/capabilities.ts b/apps/web/src/features/whatsapp-group/queries/capabilities.ts
index 287720ff38..a4aa4c0f04 100644
--- a/apps/web/src/features/whatsapp-group/queries/capabilities.ts
+++ b/apps/web/src/features/whatsapp-group/queries/capabilities.ts
@@ -1,13 +1,19 @@
import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
import { queryReadyGate } from '@queries/gate';
+import { useBinaryDocumentQuery } from '@queries/storage/binary-document';
import {
+ invalidateWhatsappGroupList,
invalidateWhatsappGroups,
+ refreshWhatsappGroupTimeline,
+ useWhatsappGroupDeliveryQuery,
useWhatsappGroupQueries,
type WhatsAppGroupApi,
} from '@queries/whatsapp-groups';
+import { useWhatsappGroupSync } from '@queries/whatsapp-groups/sync';
import { whatsappOperation } from '@queries/whatsapp-linked/operation';
import type { UseQueryResult } from '@tanstack/solid-query';
-import { type Accessor, createEffect } from 'solid-js';
+import { type Accessor, createEffect, on, onCleanup } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import type { SourceRead } from '../../whatsapp-linked/context/whatsapp-linked-context';
import type { WhatsAppGroupCapabilities } from '../context/whatsapp-group-context';
@@ -27,6 +33,36 @@ function sourceRead<T>(query: UseQueryResult<T>): SourceRead<T> {
refetch: () => fireAndForget(query.refetch(), 'whatsapp-group.refresh'),
};
}
+
+/** `whatsapp.group.open`: from mount until the roster and first page show. */
+function traceOpen(
+ groupId: Accessor<string>,
+ queries: ReturnType<typeof useWhatsappGroupQueries>
+) {
+ const span = Telemetry.span('whatsapp.group.open');
+ span.setAttr('whatsapp.group.id', groupId());
+ let ended = false;
+ const end = (outcome: string) => {
+ if (ended) return;
+ ended = true;
+ span.setAttr('whatsapp.outcome', outcome);
+ span.end();
+ };
+ createEffect(() => {
+ if (queries.group.isError || queries.messages.isError) {
+ span.error('WhatsApp group failed to load');
+ end('error');
+ } else if (queries.group.isSuccess && queries.messages.isSuccess) {
+ span.setAttr(
+ 'whatsapp.group.messages',
+ queries.messages.data.pages[0]?.messages.length ?? 0
+ );
+ end('success');
+ }
+ });
+ onCleanup(() => end('closed'));
+}
+
/** Mounted sources own row reconciliation; cached query callbacks own only resolved IDs. */
export function createWhatsAppGroupCapabilities(
api: WhatsAppGroupApi,
@@ -34,24 +70,31 @@ export function createWhatsAppGroupCapabilities(
groupId: Accessor<string>
): WhatsAppGroupCapabilities {
const queries = useWhatsappGroupQueries(api, userId, groupId);
+ useWhatsappGroupSync(userId, groupId);
+ traceOpen(groupId, queries);
const [rows, setRows] = createStore<GroupMessage[]>([]);
- createEffect(() => {
- if (!queryReadyGate(queries.messages)) return;
- const byId = new Map<string, GroupMessage>();
- for (const page of [...queries.messages.data.pages].reverse()) {
- for (const message of page.messages) byId.set(message.id, message);
- }
- setRows(
- reconcile(
- [...byId.values()].sort(
- (a, b) =>
- Date.parse(a.sentAt) - Date.parse(b.sentAt) ||
- a.id.localeCompare(b.id)
- ),
- { key: 'id' }
- )
- );
- });
+ createEffect(
+ on(
+ () => queryReadyGate(queries.messages) && queries.messages.data.pages,
+ (pages) => {
+ if (!pages) return;
+ const byId = new Map<string, GroupMessage>();
+ for (const page of [...pages].reverse()) {
+ for (const message of page.messages) byId.set(message.id, message);
+ }
+ setRows(
+ reconcile(
+ [...byId.values()].sort(
+ (a, b) =>
+ Date.parse(a.sentAt) - Date.parse(b.sentAt) ||
+ a.id.localeCompare(b.id)
+ ),
+ { key: 'id' }
+ )
+ );
+ }
+ )
+ );
return {
group: sourceRead(queries.group),
timeline: {
@@ -67,30 +110,49 @@ export function createWhatsAppGroupCapabilities(
refetch: () =>
fireAndForget(queries.messages.refetch(), 'whatsapp-group.refresh'),
},
- sends: sourceRead(queries.sends),
hasOlder: () => queries.messages.hasNextPage,
loadingOlder: () => queries.messages.isFetchingNextPage,
loadOlder: () => queries.messages.fetchNextPage(),
send: (request, idempotencyKey) =>
- queries.send.mutateAsync({
- userId: userId(),
- groupId: groupId(),
- request,
- idempotencyKey,
+ Telemetry.span('whatsapp.group.send.attempt', async (span) => {
+ span.setAttr('whatsapp.group.id', groupId());
+ span.setAttr('whatsapp.send.kind', request.kind);
+ const result = await api.send(groupId(), request, idempotencyKey);
+ if (result.isOk()) {
+ span.setAttr('whatsapp.send.id', result.value.id);
+ span.setAttr('whatsapp.outcome', 'recorded');
+ fireAndForget(
+ refreshWhatsappGroupTimeline(userId(), groupId()),
+ 'whatsapp-group.send'
+ );
+ } else {
+ span.setAttr('whatsapp.outcome', result.error.kind);
+ if (result.error.kind === 'refused')
+ span.error('WhatsApp refused the send');
+ }
+ return result;
}),
+ delivery: (sendIds) =>
+ sourceRead(useWhatsappGroupDeliveryQuery(api, userId, groupId, sendIds)),
upload: (file) =>
- whatsappOperation(
- 'group.upload',
- () => api.upload(groupId(), file),
- groupId()
- ),
+ Telemetry.span('whatsapp.group.upload', async (span) => {
+ span.setAttr('whatsapp.group.id', groupId());
+ span.setAttr('whatsapp.upload.size', file.size);
+ const result = await api.upload(groupId(), file);
+ span.setAttr(
+ 'whatsapp.outcome',
+ result.isOk() ? 'success' : result.error.kind
+ );
+ return result;
+ }),
+ fileUrl: (documentId) => sourceRead(useBinaryDocumentQuery(documentId)),
markRead: async (messageId) => {
await whatsappOperation(
'group.read',
() => api.markRead(groupId(), messageId),
groupId()
);
- await invalidateWhatsappGroups();
+ await invalidateWhatsappGroupList();
},
stopSync: async () => {
await whatsappOperation(
diff --git a/apps/web/src/features/whatsapp-group/queries/production-api.test.ts b/apps/web/src/features/whatsapp-group/queries/production-api.test.ts
index 03b47d72ab..92d4959ee4 100644
--- a/apps/web/src/features/whatsapp-group/queries/production-api.test.ts
+++ b/apps/web/src/features/whatsapp-group/queries/production-api.test.ts
@@ -2,7 +2,7 @@ import type {
WhatsAppGroupDetail,
WhatsAppGroupMessages,
} from '@service-storage/generated/schemas';
-import { ok } from 'neverthrow';
+import { err, ok } from 'neverthrow';
import { beforeEach, expect, it, vi } from 'vitest';
import { whatsappGroupApi } from './production-api';
@@ -10,7 +10,7 @@ const client = vi.hoisted(() => ({
list: vi.fn(),
detail: vi.fn(),
messages: vi.fn(),
- sends: vi.fn(),
+ delivery: vi.fn(),
send: vi.fn(),
upload: vi.fn(),
markRead: vi.fn(),
@@ -130,3 +130,87 @@ it('preserves the deliberate send key and maps quotes and reactions without a ch
reply_to: null,
});
});
+
+it('tells refusals from unknown outcomes and keeps the reason DSS gave', async () => {
+ client.send.mockResolvedValueOnce(
+ err([
+ {
+ code: 'invalid_input',
+ message: 'send an audio caption as a separate message',
+ },
+ ])
+ );
+ expect(
+ (
+ await whatsappGroupApi.send(
+ 'group-id',
+ { kind: 'text', text: 'x' },
+ 'key-1'
+ )
+ )._unsafeUnwrapErr()
+ ).toEqual({
+ kind: 'refused',
+ reason: 'Send an audio caption as a separate message.',
+ });
+ client.send.mockResolvedValueOnce(
+ err([
+ { code: 'disconnected', message: 'connect your WhatsApp account first' },
+ ])
+ );
+ expect(
+ (
+ await whatsappGroupApi.send(
+ 'group-id',
+ { kind: 'text', text: 'x' },
+ 'key-2'
+ )
+ )._unsafeUnwrapErr()
+ ).toEqual({
+ kind: 'refused',
+ reason: 'Connect your WhatsApp in External to send.',
+ });
+ for (const code of [
+ 'NETWORK_ERROR',
+ 'temporarily_unavailable',
+ 'rate_limited',
+ ] as const) {
+ client.send.mockResolvedValueOnce(err([{ code, message: code }]));
+ expect(
+ (
+ await whatsappGroupApi.send(
+ 'group-id',
+ { kind: 'text', text: 'x' },
+ 'key-3'
+ )
+ )._unsafeUnwrapErr()
+ ).toEqual({ kind: 'unknown' });
+ }
+});
+
+it('reads recorded progress by send id', async () => {
+ client.delivery.mockResolvedValue(
+ ok([
+ {
+ id: 'send-1',
+ group_id: 'group-id',
+ user_id: 'macro|[email protected]',
+ created_at: '2026-10-21T12:00:00Z',
+ state: 'accepted',
+ message_id: 'message-9',
+ payload: {
+ idempotency_key: 'key-1',
+ message: { type: 'text', text: 'x' },
+ },
+ },
+ ])
+ );
+ expect(await whatsappGroupApi.delivery('group-id', ['send-1'])).toEqual([
+ {
+ id: 'send-1',
+ state: 'accepted',
+ messageId: 'message-9',
+ errorCode: undefined,
+ },
+ ]);
+ expect(client.delivery).toHaveBeenCalledWith('group-id', ['send-1']);
+});
diff --git a/apps/web/src/features/whatsapp-group/queries/production-api.ts b/apps/web/src/features/whatsapp-group/queries/production-api.ts
index fd41398995..45edd8a13b 100644
--- a/apps/web/src/features/whatsapp-group/queries/production-api.ts
+++ b/apps/web/src/features/whatsapp-group/queries/production-api.ts
@@ -1,10 +1,15 @@
+import type { ResultError } from '@core/util/result';
import { throwOnErr } from '@core/util/result';
+import type { BaseFetchErrorCode } from '@core/util/safeFetch';
import type { WhatsAppGroupApi } from '@queries/whatsapp-groups';
import type { LinkedReplyContent } from '@service-storage/generated/schemas/linkedReplyContent';
+import type { LinkedSendProgress } from '@service-storage/generated/schemas/linkedSendProgress';
+import type { WhatsAppErrorCode } from '@service-storage/whatsapp-errors';
import { whatsappGroupsClient as client } from '@service-storage/whatsapp-groups';
-import { match } from 'ts-pattern';
+import { err, ok } from 'neverthrow';
+import { match, P } from 'ts-pattern';
import { phoneFromJid } from '../../whatsapp-linked/core/account';
-import type { GroupSend } from '../core/group';
+import type { GroupSend, SendFailure, SendProgress } from '../core/group';
function content(request: GroupSend): LinkedReplyContent {
return match(request)
@@ -38,6 +43,78 @@ function content(request: GroupSend): LinkedReplyContent {
});
}
+function sentenceCase(text: string) {
+ return `${text.charAt(0).toUpperCase()}${text.slice(1)}${/[.!?]$/.test(text) ? '' : '.'}`;
+}
+
+/**
+ * Refusals were never recorded and say why; anything else may have been
+ * recorded, so the caller retries with the same idempotency key.
+ */
+function writeFailure(
+ errors: ResultError<WhatsAppErrorCode | BaseFetchErrorCode>[]
+): SendFailure {
+ const [error] = errors;
+ if (!error) return { kind: 'unknown' };
+ return (
+ match(error.code)
+ .returnType<SendFailure>()
+ .with(
+ P.union(
+ 'NETWORK_ERROR',
+ 'SERVER_ERROR',
+ 'HTTP_ERROR',
+ 'INVALID_JSON',
+ 'UNKNOWN_ERROR',
+ 'temporarily_unavailable',
+ 'lease_fenced',
+ // Not recorded; DSS takes one write per second per person.
+ 'rate_limited'
+ ),
+ () => ({ kind: 'unknown' })
+ )
+ .with('invalid_input', () => ({
+ kind: 'refused',
+ reason: sentenceCase(error.message),
+ }))
+ .with(P.union('disconnected', 'UNAUTHORIZED'), () => ({
+ kind: 'refused',
+ reason: 'Connect your WhatsApp in External to send.',
+ }))
+ .with(P.union('forbidden', 'FORBIDDEN'), () => ({
+ kind: 'refused',
+ reason: "Your WhatsApp can't send to this group.",
+ }))
+ .with(P.union('not_found', 'NOT_FOUND', 'GONE'), () => ({
+ kind: 'refused',
+ reason: 'That message or upload is no longer available.',
+ }))
+ .with('configuration_required', () => ({
+ kind: 'refused',
+ reason: 'Sending to WhatsApp is turned off.',
+ }))
+ .with('send_expired', () => ({
+ kind: 'refused',
+ reason: "WhatsApp wasn't reachable in time, so this wasn't sent.",
+ }))
+ .with(P.union('conflict', 'CONFLICT', 'identity_conflict'), () => ({
+ kind: 'refused',
+ reason: 'This conflicts with an earlier WhatsApp request.',
+ }))
+ // A code this build doesn't know may have been recorded: retry quietly.
+ .exhaustive(() => ({ kind: 'unknown' }))
+ );
+}
+
+function progress(send: LinkedSendProgress): SendProgress {
+ return {
+ id: send.id,
+ state: send.state,
+ messageId: send.message_id ?? undefined,
+ errorCode: send.error_code ?? undefined,
+ };
+}
+
/** Decodes DSS's generated wire models at the feature boundary. */
export const whatsappGroupApi: WhatsAppGroupApi = {
list: async () =>
@@ -45,6 +122,7 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
id: group.id,
name: group.name,
unreadCount: group.unread_count,
+ canSend: group.can_send,
})),
detail: async (id) => {
const view = await throwOnErr(() => client.detail(id));
@@ -71,6 +149,7 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
textBytes: view.limits.text_limit_bytes,
attachmentBytes: view.limits.attachment_limit_bytes,
attachmentTypes: view.limits.attachment_types,
+ maxAttachments: view.limits.max_attachments,
editSeconds: view.limits.mutation_window_seconds,
mutations: view.limits.mutations,
},
@@ -100,40 +179,32 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
ordinal: attachment.ordinal,
state: attachment.state,
fileName: attachment.file_name,
+ mime: attachment.mime,
documentId: attachment.document_id ?? undefined,
})),
- delivery: message.delivery_state ?? undefined,
})),
};
},
- sends: async (id) =>
- (await throwOnErr(() => client.sends(id)))
- .filter(
- (send) =>
- !send.message_id &&
- !['accepted', 'sent', 'delivered', 'read'].includes(send.state)
- )
- .map((send) => ({
- id: send.id,
- state: send.state,
- errorCode: send.error_code ?? undefined,
- preview: match(send.payload.message)
- .with({ type: 'text' }, (message) => message.text)
- .with({ type: 'media' }, (message) => message.caption ?? 'Attachment')
- .with({ type: 'mutation' }, () => 'Message change')
- .exhaustive(() => 'Message'),
- })),
- send: (id, request, idempotencyKey) =>
- throwOnErr(() =>
- client.send(id, {
- idempotency_key: idempotencyKey,
- message: content(request),
- reply_to: 'replyTo' in request ? (request.replyTo ?? null) : null,
- })
- ),
+ send: async (id, request, idempotencyKey) => {
+ const result = await client.send(id, {
+ idempotency_key: idempotencyKey,
+ message: content(request),
+ reply_to: 'replyTo' in request ? (request.replyTo ?? null) : null,
+ });
+ return result.isOk()
+ ? ok(progress(result.value))
+ : err(writeFailure(result.error));
+ },
+ delivery: async (id, sendIds) =>
+ (await throwOnErr(() => client.delivery(id, sendIds))).map(progress),
upload: async (id, file) => {
- const result = await throwOnErr(() => client.upload(id, file));
- return { uploadId: result.upload_id, audio: result.kind === 'audio' };
+ const result = await client.upload(id, file);
+ return result.isOk()
+ ? ok({
+ uploadId: result.value.upload_id,
+ audio: result.value.kind === 'audio',
+ })
+ : err(writeFailure(result.error));
},
markRead: (id, messageId) => throwOnErr(() => client.markRead(id, messageId)),
stopSync: (id) => throwOnErr(() => client.stopSync(id)),
diff --git a/apps/web/src/features/whatsapp-group/route-views.tsx b/apps/web/src/features/whatsapp-group/route-views.tsx
index a00d3886b8..cd1d02f9d7 100644
--- a/apps/web/src/features/whatsapp-group/route-views.tsx
+++ b/apps/web/src/features/whatsapp-group/route-views.tsx
@@ -1,16 +1,27 @@
-import { useRouteParams } from '@app/lib/split-router';
-import { whatsappGroupRoute } from '@app/routes/routes';
+import { useNavigate, useRouteParams } from '@app/lib/split-router';
import {
- usePageViewTracking,
- withAuth,
-} from '@components/app/split-layout/split-router/app-route-shell';
-import {
- WhatsAppGroupEntry,
- WhatsAppGroupSkeleton,
-} from './whatsapp-group-entry';
+ externalWhatsappGroupRoute,
+ whatsappGroupRoute,
+} from '@app/routes/routes';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { onMount } from 'solid-js';
+import { WhatsAppGroupSkeleton } from './whatsapp-group-entry';
-export const WhatsAppGroupRouteView = withAuth(() => {
+/** Retired `/whatsapp-group/:groupId` links open the group inside External. */
+export function WhatsAppGroupRedirectRouteView() {
const params = useRouteParams(whatsappGroupRoute);
- usePageViewTracking('whatsapp-group');
- return <WhatsAppGroupEntry groupId={params.groupId} />;
-}, WhatsAppGroupSkeleton);
+ const navigate = useNavigate();
+ onMount(() =>
+ fireAndForget(
+ navigate(
+ {
+ route: externalWhatsappGroupRoute,
+ params: { groupId: params.groupId },
+ },
+ { replace: true }
+ ),
+ 'whatsapp-group.redirect'
+ )
+ );
+ return <WhatsAppGroupSkeleton />;
+}
diff --git a/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts b/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts
index ee93e4378c..ca74ca5322 100644
--- a/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts
+++ b/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts
@@ -1,3 +1,4 @@
+import { ok, type Result } from 'neverthrow';
import { createSignal } from 'solid-js';
import { vi } from 'vitest';
import type { SourceRead } from '../../whatsapp-linked/context/whatsapp-linked-context';
@@ -6,7 +7,8 @@ import type {
GroupDetail,
GroupMessage,
GroupSend,
- PendingSend,
+ SendFailure,
+ SendProgress,
} from '../core/group';
export const group: GroupDetail = {
@@ -23,6 +25,7 @@ export const group: GroupDetail = {
textBytes: 65536,
attachmentBytes: 33554432,
attachmentTypes: ['image/png', 'application/pdf', 'audio/ogg'],
+ maxAttachments: 1,
editSeconds: 900,
mutations: ['reaction', 'edit', 'delete'],
},
@@ -31,7 +34,7 @@ export const messages: GroupMessage[] = [
{
id: 'message-1',
sender: { name: 'Ana Ruiz' },
- body: 'The updated designs are ready for review.',
+ body: 'The *updated* designs are ready for review.',
sentAt: '2026-10-21T10:00:00Z',
edited: false,
deleted: false,
@@ -48,18 +51,14 @@ export const messages: GroupMessage[] = [
replyTo: 'message-1',
reactions: [],
attachments: [],
- delivery: 'delivered',
},
];
export function createFakeGroup(
- initial: {
- group?: GroupDetail;
- messages?: GroupMessage[];
- sends?: PendingSend[];
- } = {}
+ initial: { group?: GroupDetail; messages?: GroupMessage[] } = {}
) {
const [detail, setGroup] = createSignal(initial.group ?? group);
const [timeline, setMessages] = createSignal(initial.messages ?? messages);
+ const [delivery, setDelivery] = createSignal<SendProgress[]>([]);
const read = <T>(data: () => T): SourceRead<T> => ({
get data() {
return data();
@@ -71,19 +70,27 @@ export function createFakeGroup(
const capabilities = {
group: read(detail),
timeline: read(timeline),
- sends: read(() => initial.sends ?? []),
hasOlder: () => false,
loadingOlder: () => false,
loadOlder: vi.fn(async () => undefined),
send: vi.fn(
- async (_request: GroupSend, _idempotencyKey: string) => undefined
+ async (
+ _request: GroupSend,
+ idempotencyKey: string
+ ): Promise<Result<SendProgress, SendFailure>> =>
+ ok({ id: `send-${idempotencyKey}`, state: 'pending' })
),
- upload: vi.fn(async (_file: File) => ({
- uploadId: 'upload-1',
- audio: false,
- })),
+ delivery: () => read(delivery),
+ upload: vi.fn(
+ async (
+ _file: File
+ ): Promise<Result<{ uploadId: string; audio: boolean }, SendFailure>> =>
+ ok({ uploadId: 'upload-1', audio: false })
+ ),
+ fileUrl: (documentId: () => string) =>
+ read(() => `https://files.example.test/${documentId()}`),
markRead: vi.fn(async (_messageId: string) => undefined),
stopSync: vi.fn(async () => undefined),
} satisfies WhatsAppGroupCapabilities;
- return { capabilities, setGroup, setMessages };
+ return { capabilities, setGroup, setMessages, setDelivery };
}
diff --git a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx
index 6d5deebeba..fc35f5e502 100644
--- a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx
+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx
@@ -1,3 +1,5 @@
+import type { ChannelInputProps } from '@channel/Input/ChannelInput';
+import type { InputHandle, InputSnapshot } from '@channel/Input/types';
import {
cleanup,
fireEvent,
@@ -5,12 +7,46 @@ import {
screen,
waitFor,
} from '@solidjs/testing-library';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { err } from 'neverthrow';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { WhatsAppGroupProvider } from '../context/whatsapp-group-context';
-import { createFakeGroup, group, messages } from '../tests/fake-capabilities';
+import { createFakeGroup, group } from '../tests/fake-capabilities';
import { WhatsAppGroupView } from './whatsapp-group-view';
+const mocks = vi.hoisted(() => ({
+ composer: undefined as ChannelInputProps | undefined,
+ restore: vi.fn(),
+ focus: vi.fn(),
+ failure: vi.fn(),
+}));
+vi.mock('@core/context/user', () => ({
+ useUserId: () => () => 'macro|[email protected]',
+}));
+vi.mock('@core/component/UserIcon', () => ({
+ UserIcon: () => <span data-testid="macro-avatar" />,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: mocks.failure, alert: vi.fn() },
+}));
+vi.mock('@channel/Input/ChannelInput', () => ({
+ ChannelInput: (props: ChannelInputProps) => {
+ mocks.composer = props;
+ const handle: InputHandle = {
+ snapshot: vi.fn(),
+ clear: vi.fn(),
+ focus: mocks.focus,
+ send: vi.fn(),
+ attachFiles: vi.fn(),
+ restoreSnapshot: mocks.restore,
+ };
+ props.onReady?.(handle);
+ return <div data-testid="whatsapp-composer" />;
+ },
+}));
+
beforeEach(() => {
+ mocks.composer = undefined;
vi.stubGlobal('scrollTo', vi.fn());
vi.stubGlobal(
'ResizeObserver',
@@ -23,47 +59,101 @@ beforeEach(() => {
});
afterEach(() => {
cleanup();
+ vi.clearAllMocks();
vi.unstubAllGlobals();
});
function mount(fake: ReturnType<typeof createFakeGroup>) {
const share = vi.fn();
+ const connect = vi.fn();
render(() => (
- <WhatsAppGroupProvider value={fake.capabilities}>
- <WhatsAppGroupView
- userId={group.ownerId}
- onShare={share}
- onConnect={vi.fn()}
- renderAttachment={(id) => <span>document {id}</span>}
- />
- </WhatsAppGroupProvider>
+ <QueryClientProvider client={new QueryClient()}>
+ <WhatsAppGroupProvider value={fake.capabilities}>
+ <WhatsAppGroupView
+ userId={group.ownerId}
+ onShare={share}
+ onConnect={connect}
+ />
+ </WhatsAppGroupProvider>
+ </QueryClientProvider>
));
- return { share };
+ return { share, connect };
+}
+function snapshot(value: string): InputSnapshot {
+ return { value, mentions: [], attachments: [] };
}
-it('shows external names, quotes, reactions and the viewers own sending identity', async () => {
+
+it('renders WhatsApp messages as channel rows with quotes and reactions', () => {
const fake = createFakeGroup();
const { share } = mount(fake);
expect(screen.getByText('Ana Ruiz')).toBeTruthy();
expect(screen.getByText('Sending as +14155550142')).toBeTruthy();
+ // WhatsApp's `*updated*` renders bold.
+ expect(screen.getByText('updated').className).toContain('font-bold');
expect(
- screen.getByRole('button', { name: '👍 2, your reaction' })
+ screen.getByRole('button', { name: /Ana Ruiz: The \*updated\* designs/ })
).toBeTruthy();
- expect(screen.getByText(/Ana Ruiz: The updated designs/)).toBeTruthy();
+ const reaction = screen.getByRole('button', { name: /👍/ });
+ expect(reaction.getAttribute('aria-pressed')).toBe('true');
+ expect(reaction.textContent).toContain('2');
fireEvent.click(screen.getByRole('button', { name: 'Share' }));
expect(share).toHaveBeenCalledOnce();
- fireEvent.click(screen.getAllByRole('button', { name: 'Reply' })[0]);
- fireEvent.input(
- screen.getByRole('textbox', { name: 'Message WhatsApp group' }),
- { target: { value: 'My own account reply' } }
- );
- fireEvent.click(screen.getByRole('button', { name: 'Send' }));
+});
+
+it('replies through the shared composer and sends WhatsApp formatting', async () => {
+ const fake = createFakeGroup();
+ mount(fake);
+ const row = document.querySelector('[data-message-id="message-1"]');
+ if (!row) throw new Error('message row missing');
+ fireEvent.pointerEnter(row);
+ fireEvent.click(screen.getByRole('button', { name: 'Reply' }));
+ expect(screen.getByText('Replying to Ana Ruiz')).toBeTruthy();
+ expect(mocks.focus).toHaveBeenCalled();
+ expect(mocks.composer?.features).toEqual({
+ mentions: false,
+ createItems: false,
+ gifs: false,
+ richBlocks: false,
+ });
+ await mocks.composer?.onSend?.(snapshot('Looks **great**'));
await waitFor(() =>
expect(fake.capabilities.send).toHaveBeenCalledWith(
- { kind: 'text', text: 'My own account reply', replyTo: 'message-1' },
+ { kind: 'text', text: 'Looks *great*', replyTo: 'message-1' },
expect.any(String)
)
);
+ expect(screen.queryByText('Replying to Ana Ruiz')).toBeNull();
+ expect(screen.getByText('Looks')).toBeTruthy();
+});
+
+it('removes a refused send, toasts the reason and restores the draft', async () => {
+ const fake = createFakeGroup();
+ fake.capabilities.send.mockResolvedValueOnce(
+ err({ kind: 'refused', reason: "Your WhatsApp can't send to this group." })
+ );
+ mount(fake);
+ const draft = snapshot('Hello there');
+ await mocks.composer?.onSend?.(draft);
+ await waitFor(() =>
+ expect(mocks.failure).toHaveBeenCalledWith(
+ "Your WhatsApp can't send to this group."
+ )
+ );
+ expect(mocks.restore).toHaveBeenCalledWith(draft);
+ expect(screen.queryByText('Hello there')).toBeNull();
+});
+
+it('keeps a draft WhatsApp would refuse in the composer', () => {
+ const fake = createFakeGroup({
+ group: { ...group, limits: { ...group.limits, textBytes: 3 } },
+ });
+ mount(fake);
+ expect(() => mocks.composer?.onSend?.(snapshot('Too long'))).toThrow(
+ 'This message is too long for WhatsApp.'
+ );
+ expect(fake.capabilities.send).not.toHaveBeenCalled();
});
-it('lets a shared viewer without WhatsApp read the timeline and asks them to connect to reply', () => {
+
+it('lets a viewer without WhatsApp read and offers to connect', () => {
const fake = createFakeGroup({
group: {
...group,
@@ -72,67 +162,25 @@ it('lets a shared viewer without WhatsApp read the timeline and asks them to con
sendReason: 'no_account',
},
});
- mount(fake);
- expect(
- screen.getByText('The updated designs are ready for review.')
- ).toBeTruthy();
+ const { connect } = mount(fake);
expect(screen.getByText('Connect your WhatsApp to reply')).toBeTruthy();
- expect(screen.queryByRole('textbox')).toBeNull();
- expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();
- expect(fake.capabilities.send).not.toHaveBeenCalled();
+ expect(screen.queryByTestId('whatsapp-composer')).toBeNull();
+ const row = document.querySelector('[data-message-id="message-1"]');
+ if (!row) throw new Error('message row missing');
+ fireEvent.pointerEnter(row);
+ expect(screen.queryByRole('button', { name: 'Reply' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Connect WhatsApp' }));
+ expect(connect).toHaveBeenCalledOnce();
});
-it('keeps unknown sends visible without any automatic resend', () => {
+
+it('offers actions on rows that rendered before the viewer could send', () => {
const fake = createFakeGroup({
- sends: [
- { id: 'send-1', preview: 'Running 10 minutes late', state: 'unknown' },
- ],
- messages: [
- {
- ...messages[0],
- attachments: [
- {
- ordinal: 0,
- state: 'loading',
- fileName: 'design.pdf',
- documentId: undefined,
- },
- ],
- },
- ],
+ group: { ...group, canSend: false, sendReason: 'disconnected' },
});
mount(fake);
- expect(screen.getByText(/may already have arrived/)).toBeTruthy();
- expect(screen.getByText('Loading design.pdf…')).toBeTruthy();
- expect(fake.capabilities.send).not.toHaveBeenCalled();
-});
-it('offers edit and delete only for own messages, and confirms deletion', async () => {
- const fake = createFakeGroup();
- mount(fake);
- expect(screen.getAllByRole('button', { name: 'Edit' })).toHaveLength(1);
- fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
- expect(screen.queryByLabelText('Attach file')).toBeNull();
- expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(
- 'Looking now. Thanks, Ana!'
- );
- fireEvent.input(screen.getByRole('textbox'), {
- target: { value: 'Edited from my account' },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Send' }));
- await waitFor(() =>
- expect(fake.capabilities.send).toHaveBeenCalledWith(
- { kind: 'edit', messageId: 'message-2', text: 'Edited from my account' },
- expect.any(String)
- )
- );
- fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
- expect(fake.capabilities.send).toHaveBeenCalledTimes(1);
- const confirmation = screen.getAllByRole('button', { name: 'Delete' }).at(-1);
- if (!confirmation) throw new Error('Missing delete confirmation');
- fireEvent.click(confirmation);
- await waitFor(() =>
- expect(fake.capabilities.send).toHaveBeenCalledWith(
- { kind: 'delete', messageId: 'message-2' },
- expect.any(String)
- )
- );
+ fake.setGroup(group);
+ const row = document.querySelector('[data-message-id="message-1"]');
+ if (!row) throw new Error('message row missing');
+ fireEvent.pointerEnter(row);
+ expect(screen.getByRole('button', { name: 'Reply' })).toBeTruthy();
});
diff --git a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx
index 1ce49770a9..a27ff6a4d6 100644
--- a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx
+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx
@@ -1,7 +1,26 @@
+import { buildChannelMessageListMeta } from '@channel/Channel/message-list-meta';
+import { ChannelInput } from '@channel/Input/ChannelInput';
+import { ChannelInputContainer } from '@channel/Input/ChannelInputContainer';
+import { InputFlag } from '@channel/Input/InputFlag';
+import type { InputHandle, InputSnapshot } from '@channel/Input/types';
+import { hasSendableInputContent } from '@channel/Input/utils/sendable-content';
+import { ChannelMessage } from '@channel/Message/ChannelMessage';
+import { DateDivider } from '@channel/Message/DateDivider';
+import { NewDivider } from '@channel/Message/NewDivider';
+import { SenderName } from '@channel/Message/SenderName';
+import { MaybeMessageActionDrawerManager } from '@channel/Mobile/MessageActionDrawerManager';
+import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';
+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { toast } from '@core/component/Toast/Toast';
+import type {
+ MessageActionContext,
+ MessageActions,
+} from '@core/messages/types';
import { fireAndForget } from '@core/util/fireAndForget';
import { Button, ConfirmDialog } from '@ui';
import {
createEffect,
+ createMemo,
createSignal,
For,
type JSX,
@@ -9,23 +28,60 @@ import {
onMount,
Show,
} from 'solid-js';
-import { GroupComposer } from '../components/group-composer';
-import { GroupMessageRow } from '../components/group-message';
+import { InboundAttachmentPlaceholder } from '../components/inbound-attachment';
import { useWhatsAppGroup } from '../context/whatsapp-group-context';
-import { canChangeMessage, composerNote } from '../core/group';
-import { createConversation } from '../primitives/conversation';
+import { whatsappToMarkdown } from '../core/formatting';
+import {
+ canChangeMessage,
+ composerNote,
+ type GroupMessage,
+} from '../core/group';
+import { groupMessageData, senderKey } from '../core/message-data';
+import {
+ type ConversationTarget,
+ createConversation,
+ type Draft,
+} from '../primitives/conversation';
+
+/** WhatsApp carries text, formatting and files; nothing Macro-only. */
+const WHATSAPP_COMPOSER = {
+ mentions: false,
+ createItems: false,
+ gifs: false,
+ richBlocks: false,
+} as const;
+
+/** A draft the conversation refused; the composer keeps it. */
+class DraftRefusal extends Error {}
+
+function quotePreview(message: GroupMessage) {
+ if (message.deleted) return 'Deleted message';
+ return message.body || message.attachments[0]?.fileName || 'Attachment';
+}
export function WhatsAppGroupView(props: {
userId?: string;
leading?: JSX.Element;
onShare: () => void;
onConnect: () => void;
- renderAttachment: (id: string) => JSX.Element;
}) {
const source = useWhatsAppGroup();
- const conversation = createConversation(source, () => props.userId);
+ let input: InputHandle | undefined;
+ const [inputSnapshot, setInputSnapshot] = createSignal<InputSnapshot>();
+ // The composer's own attachment rows, to put back with a restored draft.
+ const snapshots = new WeakMap<Draft, InputSnapshot>();
+ const conversation = createConversation(source, () => props.userId, {
+ notify: (message) => toast.failure(message),
+ restore: (draft, target) => {
+ const snapshot = snapshots.get(draft);
+ const current = inputSnapshot();
+ if (!input || !snapshot || (current && hasSendableInputContent(current)))
+ return;
+ input.restoreSnapshot(snapshot);
+ if (target && !conversation.target()) setTarget(target);
+ },
+ });
const [deleting, setDeleting] = createSignal<string>();
- const [replyError, setReplyError] = createSignal<string>();
const [roster, setRoster] = createSignal(false);
const [stopping, setStopping] = createSignal(false);
const [stopped, setStopped] = createSignal(false);
@@ -37,40 +93,89 @@ export function WhatsAppGroupView(props: {
onCleanup(() => {
alive = false;
});
+
+ /** Choosing a reply or an edit puts the composer in that mode. */
+ const setTarget = (target: ConversationTarget | undefined) => {
+ const previous = conversation.target();
+ if (!target) {
+ conversation.cancelTarget();
+ if (previous?.kind === 'edit') input?.clear();
+ return;
+ }
+ if (target.kind === 'reply') conversation.reply(target.message);
+ else {
+ conversation.edit(target.message);
+ input?.restoreSnapshot(
+ {
+ value: whatsappToMarkdown(target.message.body),
+ mentions: [],
+ attachments: [],
+ },
+ { cursor: 'trailing-paragraph' }
+ );
+ }
+ input?.focus();
+ };
+
const nearBottom = () =>
!scroller ||
scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 80;
- const messages = () => source.timeline.data ?? [];
+ const markRead = () =>
+ fireAndForget(conversation.markRead(), 'whatsapp-group.read');
+ const rows = conversation.rows;
+ const storedCount = () => source.timeline.data?.length ?? 0;
const unreadIndex = () => {
+ const unread = conversation.initialUnreadCount();
const read = conversation.initialRead();
- if (!read)
- return conversation.initialUnreadCount()
- ? Math.max(0, messages().length - conversation.initialUnreadCount())
- : -1;
- const index = messages().findIndex((message) => message.id === read);
- return index < 0
- ? conversation.initialUnreadCount()
- ? Math.max(0, messages().length - conversation.initialUnreadCount())
- : -1
- : index + 1;
+ const index = read
+ ? (source.timeline.data ?? []).findIndex((message) => message.id === read)
+ : -1;
+ if (index >= 0) return index + 1;
+ return unread ? Math.max(0, storedCount() - unread) : -1;
};
+ const listMeta = createMemo(() => {
+ const firstNew = unreadIndex();
+ const newIds = new Set(
+ firstNew < 0
+ ? []
+ : (source.timeline.data ?? []).slice(firstNew).map((row) => row.id)
+ );
+ return buildChannelMessageListMeta(
+ rows().map((message) => ({
+ type: 'message' as const,
+ message: {
+ id: message.id,
+ sender_id: senderKey(message),
+ created_at: message.sentAt,
+ attachments: [],
+ deleted_at: message.deleted ? message.sentAt : null,
+ },
+ })),
+ (message) => newIds.has(message.id),
+ !source.hasOlder()
+ );
+ });
+ const messagesById = createMemo(
+ () => new Map(rows().map((message) => [message.id, message]))
+ );
+
onMount(() => {
const visible = () => {
- if (nearBottom())
- fireAndForget(conversation.markRead(), 'whatsapp-group.read');
+ if (nearBottom()) markRead();
};
document.addEventListener('visibilitychange', visible);
onCleanup(() => document.removeEventListener('visibilitychange', visible));
});
createEffect(() => {
- const latest = source.timeline.data?.at(-1)?.id;
+ const latest = rows().at(-1)?.id;
if (!latest || latest === newest) return;
- const follow = !newest || nearBottom();
+ const follow =
+ !newest || nearBottom() || !!messagesById().get(latest)?.pending;
newest = latest;
queueMicrotask(() => {
if (!alive || !follow) return;
if (scroller) scroller.scrollTop = scroller.scrollHeight;
- fireAndForget(conversation.markRead(), 'whatsapp-group.read');
+ markRead();
});
});
const older = async () => {
@@ -80,24 +185,92 @@ export function WhatsAppGroupView(props: {
if (alive && scroller)
scroller.scrollTop = offset + scroller.scrollHeight - height;
};
- const openReply = async (id: string) => {
- setReplyError(undefined);
+ const openQuoted = async (id: string) => {
const find = () =>
scroller?.querySelector(`[data-message-id="${CSS.escape(id)}"]`);
try {
while (alive && !find() && source.hasOlder()) {
- const count = messages().length;
+ const count = storedCount();
await older();
- if (messages().length === count) break;
+ if (storedCount() === count) break;
}
if (!alive) return;
const row = find();
if (row) row.scrollIntoView({ block: 'center', behavior: 'smooth' });
- else setReplyError('This quoted message is no longer available.');
+ else toast.alert('This quoted message is no longer available.');
} catch {
- if (alive) setReplyError("Couldn't load the quoted message. Try again.");
+ if (alive) toast.failure("Couldn't load the quoted message. Try again.");
}
};
+
+ /**
+ * Message rows read their actions once, when the row mounts and when its
+ * menu opens. Each action is a getter so it follows the group's current
+ * permissions, which can load or change after the row appears.
+ */
+ const actionsFor = (message: GroupMessage): MessageActions => {
+ const writable = () => {
+ const group = source.group.data;
+ return group?.canSend &&
+ !stopped() &&
+ !message.pending &&
+ !message.deleted
+ ? group
+ : undefined;
+ };
+ const changeable = (operation: 'edit' | 'delete') => {
+ const group = writable();
+ return (
+ !!group &&
+ canChangeMessage(message, props.userId, group, Date.now(), operation)
+ );
+ };
+ return {
+ get onReply() {
+ return writable()
+ ? () => setTarget({ kind: 'reply', message })
+ : undefined;
+ },
+ get onReact() {
+ return writable()?.limits.mutations.includes('reaction')
+ ? ({ emoji }: MessageActionContext) => {
+ if (emoji)
+ fireAndForget(
+ conversation.react(message, emoji),
+ 'whatsapp-group.react'
+ );
+ }
+ : undefined;
+ },
+ get onEdit() {
+ return changeable('edit')
+ ? () => setTarget({ kind: 'edit', message })
+ : undefined;
+ },
+ get onDelete() {
+ return changeable('delete')
+ ? () => {
+ setDeleting(message.id);
+ }
+ : undefined;
+ },
+ };
+ };
+
+ const send = (snapshot: InputSnapshot) => {
+ const draft: Draft = {
+ markdown: snapshot.value,
+ attachments: snapshot.attachments.map((file) => ({
+ id: file.id,
+ name: file.name,
+ })),
+ };
+ snapshots.set(draft, snapshot);
+ const delivery = conversation.submit(draft);
+ if (delivery.isErr()) throw new DraftRefusal(delivery.error);
+ fireAndForget(delivery.value, 'whatsapp-group.send');
+ };
+
return (
<div
class="flex h-full min-h-0 min-w-0 flex-col bg-panel text-ink touch:pt-(--mobile-content-inset-top)"
@@ -157,167 +330,256 @@ export function WhatsAppGroupView(props: {
</Show>
</aside>
</Show>
- <div
- ref={scroller}
- class="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-4 [overflow-anchor:none]"
- role="log"
- aria-label="WhatsApp messages"
- onScroll={() => {
- if (
- scroller &&
- scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight <
- 60
- )
- fireAndForget(conversation.markRead(), 'whatsapp-group.read');
- }}
- >
- <Show when={source.group.isPending || source.timeline.isPending}>
- <p role="status" class="p-6 text-sm text-ink-muted">
- Loading WhatsApp group…
- </p>
- </Show>
- <Show when={source.group.isError || source.timeline.isError}>
- <div class="p-4 text-sm">
- <p role="alert">
- Couldn't refresh this group. You may need access from its owner.
- </p>
- <Button
- variant="outline"
- size="sm"
- onClick={() => {
- source.group.refetch();
- source.timeline.refetch();
+ <StaticMarkdownContext>
+ <MaybeMessageActionDrawerManager>
+ <div
+ ref={scroller}
+ class="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-4 [overflow-anchor:none] mobile:pb-(--mobile-content-inset-bottom)"
+ role="log"
+ aria-label="WhatsApp messages"
+ onScroll={() => {
+ if (
+ scroller &&
+ scroller.scrollHeight -
+ scroller.scrollTop -
+ scroller.clientHeight <
+ 60
+ )
+ markRead();
+ }}
+ >
+ <Show when={source.group.isPending || source.timeline.isPending}>
+ <p role="status" class="p-6 text-sm text-ink-muted">
+ Loading WhatsApp group…
+ </p>
+ </Show>
+ <Show when={source.group.isError || source.timeline.isError}>
+ <div class="p-4 text-sm">
+ <p role="alert">
+ Couldn't load this group. You may need access from its owner.
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ source.group.refetch();
+ source.timeline.refetch();
+ }}
+ >
+ Try again
+ </Button>
+ </div>
+ </Show>
+ <Show when={source.hasOlder()}>
+ <div class="flex justify-center p-3">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={source.loadingOlder()}
+ onClick={() => fireAndForget(older(), 'whatsapp-group.older')}
+ >
+ {source.loadingOlder() ? 'Loading…' : 'Load earlier messages'}
+ </Button>
+ </div>
+ </Show>
+ <Show when={source.timeline.data && rows().length === 0}>
+ <p class="p-6 text-center text-sm text-ink-muted">
+ No messages yet. New WhatsApp messages will appear here.
+ </p>
+ </Show>
+ <For each={rows()}>
+ {(message) => {
+ const meta = () => listMeta()[message.id];
+ const quoted = () =>
+ message.replyTo
+ ? messagesById().get(message.replyTo)
+ : undefined;
+ const actions = actionsFor(message);
+ const placeholders = () =>
+ message.attachments.filter(
+ (attachment) => attachment.state !== 'ready'
+ );
+ return (
+ <>
+ <DateDivider createdAt={message.sentAt} listMeta={meta()} />
+ <NewDivider
+ createdAt={message.sentAt}
+ listMeta={meta()}
+ onDismiss={markRead}
+ />
+ <ChannelMessage
+ parent={{
+ type: 'whatsapp_group',
+ id: source.group.data?.id ?? '',
+ }}
+ message={groupMessageData(message, props.userId)}
+ actions={actions}
+ listMeta={meta()}
+ targeted={
+ conversation.target()?.message.id === message.id
+ }
+ renderContent={(content) => (
+ <>
+ <Show when={!message.deleted && message.replyTo}>
+ {(id) => (
+ <button
+ type="button"
+ class="mb-1 block max-w-full truncate border-l-2 border-accent py-0.5 pl-3 text-left text-xs text-ink-muted"
+ onClick={() =>
+ fireAndForget(
+ openQuoted(id()),
+ 'whatsapp-group.quote'
+ )
+ }
+ >
+ <Show
+ when={quoted()}
+ fallback="View quoted message"
+ >
+ {(reply) => (
+ <>
+ <SenderName
+ message={groupMessageData(
+ reply(),
+ props.userId
+ )}
+ />
+ : {quotePreview(reply())}
+ </>
+ )}
+ </Show>
+ </button>
+ )}
+ </Show>
+ {content}
+ <Show when={placeholders().length > 0}>
+ <div class="mt-1 flex flex-wrap gap-2">
+ <For each={placeholders()}>
+ {(attachment) => (
+ <InboundAttachmentPlaceholder
+ attachment={attachment}
+ />
+ )}
+ </For>
+ </div>
+ </Show>
+ </>
+ )}
+ />
+ </>
+ );
}}
- >
- Try again
- </Button>
- </div>
- </Show>
- <Show when={source.hasOlder()}>
- <div class="flex justify-center p-3">
- <Button
- variant="ghost"
- size="sm"
- disabled={source.loadingOlder()}
- onClick={() => fireAndForget(older(), 'whatsapp-group.older')}
- >
- {source.loadingOlder() ? 'Loading…' : 'Load earlier messages'}
- </Button>
+ </For>
</div>
- </Show>
- <Show when={source.timeline.data && messages().length === 0}>
- <p class="p-6 text-center text-sm text-ink-muted">
- No messages yet. New WhatsApp messages will appear here.
- </p>
- </Show>
- <For each={messages()}>
- {(message, index) => (
- <GroupMessageRow
- message={message}
- index={index()}
- previousSentAt={messages()[index() - 1]?.sentAt}
- firstUnread={index() === unreadIndex()}
- reply={messages().find((item) => item.id === message.replyTo)}
- canSend={source.group.data?.canSend ?? false}
- busy={conversation.busy()}
- canReact={
- !!source.group.data?.canSend &&
- source.group.data.limits.mutations.includes('reaction')
- }
- canEdit={
- !!source.group.data &&
- canChangeMessage(
- message,
- props.userId,
- source.group.data,
- Date.now(),
- 'edit'
- )
- }
- canDelete={
- !!source.group.data &&
- canChangeMessage(
- message,
- props.userId,
- source.group.data,
- Date.now(),
- 'delete'
- )
- }
- onReply={() => conversation.reply(message)}
- onEdit={() => conversation.edit(message)}
- onDelete={() => setDeleting(message.id)}
- onReact={(emoji) =>
- fireAndForget(
- conversation.mutate({
- kind: 'reaction',
- messageId: message.id,
- emoji,
- }),
- 'whatsapp-group.react'
- )
- }
- onRead={() =>
- fireAndForget(conversation.markRead(), 'whatsapp-group.read')
- }
- onOpenReply={(id) =>
- fireAndForget(openReply(id), 'whatsapp-group.quote')
- }
- renderAttachment={props.renderAttachment}
- />
- )}
- </For>
- </div>
- <Show when={replyError()}>
- <p role="status" class="px-4 py-2 text-xs text-ink-muted">
- {replyError()}
- </p>
- </Show>
- <Show when={source.sends.isError}>
- <div role="alert" class="px-4 py-2 text-xs text-ink-muted">
- Couldn't refresh pending messages. Check WhatsApp before sending
- again.{' '}
- <Button variant="ghost" size="sm" onClick={source.sends.refetch}>
- Try again
- </Button>
- </div>
- </Show>
+ </MaybeMessageActionDrawerManager>
+ </StaticMarkdownContext>
<Show when={source.group.data}>
{(group) => (
- <GroupComposer
- editing={!!conversation.editing()}
- canSend={group().canSend && !stopped()}
- note={
- stopped()
- ? 'This group is no longer syncing'
- : composerNote(group())
- }
- draft={conversation.draft()}
- busy={conversation.busy()}
- fileName={conversation.file()?.name}
- target={
- conversation.editing()
- ? {
- name: 'Editing message',
- body: conversation.editing()?.body ?? '',
- }
- : conversation.quote()
- ? {
- name: conversation.quote()?.sender.name ?? '',
- body: conversation.quote()?.body ?? '',
+ <FloatRegionOrInline region="accessory">
+ <Show
+ when={group().canSend && !stopped()}
+ fallback={
+ <div class="mx-3 mb-3 flex shrink-0 flex-wrap items-center gap-2 border-t border-edge-muted px-1 pt-3 text-sm text-ink-muted touch:pointer-events-auto touch:mx-(--mobile-chrome-gutter) touch:mb-2 touch:rounded-2xl touch:border-0 touch:island touch:px-3 touch:py-2">
+ <span role="status">
+ {stopped()
+ ? 'This group is no longer syncing'
+ : composerNote(group())}
+ </span>
+ <Show
+ when={
+ group().sendReason === 'no_account' ||
+ group().sendReason === 'disconnected'
}
- : undefined
- }
- pending={source.sends.data ?? []}
- error={conversation.error()}
- onDraft={conversation.setDraft}
- onFile={conversation.setFile}
- onCancelTarget={conversation.cancelTarget}
- onSubmit={() =>
- fireAndForget(conversation.submit(), 'whatsapp-group.send')
- }
- onConnect={props.onConnect}
- />
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={props.onConnect}
+ >
+ Connect WhatsApp
+ </Button>
+ </Show>
+ </div>
+ }
+ >
+ <ChannelInputContainer>
+ <div class="flex w-full min-w-0 flex-col px-3 touch:px-0">
+ <p class="px-1 pb-1 text-xs text-ink-muted">
+ {composerNote(group())}
+ </p>
+ <Show when={conversation.target()}>
+ {(target) => (
+ <InputFlag
+ label={
+ target().kind === 'edit' ? (
+ 'Editing message'
+ ) : (
+ <>
+ Replying to{' '}
+ <SenderName
+ message={groupMessageData(
+ target().message,
+ props.userId
+ )}
+ />
+ </>
+ )
+ }
+ onActivate={() =>
+ fireAndForget(
+ openQuoted(target().message.id),
+ 'whatsapp-group.quote'
+ )
+ }
+ dismissLabel={
+ target().kind === 'edit'
+ ? 'Cancel edit'
+ : 'Cancel reply'
+ }
+ onDismiss={() => setTarget(undefined)}
+ />
+ )}
+ </Show>
+ <ChannelInput
+ input={{
+ mode: 'channel',
+ id: `whatsapp-group-input-${group().id}`,
+ placeholder: `Message ${group().name}`,
+ }}
+ features={WHATSAPP_COMPOSER}
+ fileAccept={group().limits.attachmentTypes.join(',')}
+ uploadAttachment={async (file) => {
+ const result = await conversation.upload(file);
+ return result.isOk()
+ ? {
+ failed: false,
+ destination: 'staged',
+ id: result.value.uploadId,
+ }
+ : { failed: true, reason: result.error };
+ }}
+ onReady={(handle) => {
+ input = handle;
+ }}
+ onChange={setInputSnapshot}
+ onSend={send}
+ onSendError={(error) =>
+ toast.failure(
+ error instanceof DraftRefusal
+ ? error.message
+ : "Couldn't send to WhatsApp. Try again."
+ )
+ }
+ onEscape={
+ conversation.target()
+ ? () => setTarget(undefined)
+ : undefined
+ }
+ />
+ </div>
+ </ChannelInputContainer>
+ </Show>
+ </FloatRegionOrInline>
)}
</Show>
<ConfirmDialog
@@ -329,11 +591,10 @@ export function WhatsAppGroupView(props: {
body="This also deletes the message in WhatsApp."
confirmLabel="Delete"
tone="danger"
- pending={conversation.busy()}
onConfirm={async () => {
const id = deleting();
- if (id) await conversation.mutate({ kind: 'delete', messageId: id });
- if (alive) setDeleting(undefined);
+ setDeleting(undefined);
+ if (id) await conversation.remove(id);
}}
/>
<ConfirmDialog
diff --git a/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx b/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx
index b5ed15106c..54ac93c75d 100644
--- a/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx
+++ b/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx
@@ -2,7 +2,7 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useNavigate } from '@app/lib/split-router';
import { homeSplitRoute } from '@app/routes/routes';
import { enableWhatsappLinked } from '@core/constant/featureFlags';
-import { lazy, onMount, Show, Suspense } from 'solid-js';
+import { type JSX, lazy, onMount, Show, Suspense } from 'solid-js';
const Group = lazy(async () => ({
default: (await import('./whatsapp-group')).WhatsAppGroup,
@@ -22,7 +22,10 @@ function DisabledGroup() {
return null;
}
/** Gate before mounting any queries, including panes restored from session state. */
-export function WhatsAppGroupEntry(props: { groupId: string }) {
+export function WhatsAppGroupEntry(props: {
+ groupId: string;
+ leading?: JSX.Element;
+}) {
const flag = useFeatureFlag(enableWhatsappLinked);
return (
<Show
@@ -34,7 +37,7 @@ export function WhatsAppGroupEntry(props: { groupId: string }) {
}
>
<Suspense fallback={<WhatsAppGroupSkeleton />}>
- <Group groupId={props.groupId} />
+ <Group groupId={props.groupId} leading={props.leading} />
</Suspense>
</Show>
);
diff --git a/apps/web/src/features/whatsapp-group/whatsapp-group.tsx b/apps/web/src/features/whatsapp-group/whatsapp-group.tsx
index a7920035ec..c1b53375d7 100644
--- a/apps/web/src/features/whatsapp-group/whatsapp-group.tsx
+++ b/apps/web/src/features/whatsapp-group/whatsapp-group.tsx
@@ -2,17 +2,20 @@ import { useNavigate } from '@app/lib/split-router';
import { externalRoute } from '@app/routes/routes';
import { useSplitDisplayName } from '@components/app/split-layout/layoutUtils';
import { SplitPanel } from '@components/app/split-panel';
-import { ItemPreview } from '@core/component/ItemPreview';
import { getPermissions } from '@core/component/SharePermissions';
import { useShareModal } from '@core/component/TopBar/shareModal';
import { useUserId } from '@core/context/user';
-import { Suspense } from 'solid-js';
+import type { JSX } from 'solid-js';
import { WhatsAppGroupProvider } from './context/whatsapp-group-context';
import { createWhatsAppGroupCapabilities } from './queries/capabilities';
import { whatsappGroupApi } from './queries/production-api';
import { WhatsAppGroupView } from './views/whatsapp-group-view';
-export function WhatsAppGroup(props: { groupId: string }) {
+export function WhatsAppGroup(props: {
+ groupId: string;
+ /** Header control before the title; defaults to closing the split. */
+ leading?: JSX.Element;
+}) {
const userId = useUserId();
const navigate = useNavigate();
const source = createWhatsAppGroupCapabilities(
@@ -36,19 +39,10 @@ export function WhatsAppGroup(props: { groupId: string }) {
return (
<WhatsAppGroupProvider value={source}>
<WhatsAppGroupView
- leading={<SplitPanel.CloseButton class="shrink-0" />}
+ leading={props.leading ?? <SplitPanel.CloseButton class="shrink-0" />}
userId={userId()}
onShare={share}
onConnect={() => navigate({ route: externalRoute, params: {} })}
- renderAttachment={(id) => (
- <Suspense
- fallback={
- <span class="text-xs text-ink-muted">Loading attachment…</span>
- }
- >
- <ItemPreview id={id} type="document" />
- </Suspense>
- )}
/>
</WhatsAppGroupProvider>
);
diff --git a/apps/web/src/features/whatsapp-linked/AGENTS.md b/apps/web/src/features/whatsapp-linked/AGENTS.md
index f24dd43466..39a9444422 100644
--- a/apps/web/src/features/whatsapp-linked/AGENTS.md
+++ b/apps/web/src/features/whatsapp-linked/AGENTS.md
@@ -10,13 +10,16 @@ entity. Each person sends from their own account. Behind the `enable-whatsapp-li
- `whatsapp-linked.tsx`: production wiring (shared queries + split navigation).
- `context/whatsapp-linked-context.tsx`: the capability contract tests fake.
-- `views/whatsapp-page.tsx`: the three page states and both dialogs.
+- `views/whatsapp-page.tsx`: account states, the Add to Macro and Can't be
+ added sections, and the pairing/confirm dialogs.
## Scope
-- Owns: the WhatsApp account page, pairing dialog and name-only Add dialog.
+- Owns: the WhatsApp account page, pairing dialog and one-click adoption
+ (no dialog; DSS names the group after WhatsApp).
- Group timeline and sending: `features/whatsapp-group`; no channel integration.
-- Not here: the External tab shell and route → `features/external-view`;
+- Not here: the External tab shell, its In Macro sidebar and the
+ `/external/whatsapp/:groupId` route → `features/external-view`;
HTTP → `lib/service-clients/service-storage/whatsapp-linked.ts`; shared
queries → `lib/queries/whatsapp-linked`; DSS routes → `crates/whatsapp_linked`.
@@ -32,6 +35,8 @@ entity. Each person sends from their own account. Behind the `enable-whatsapp-li
must be handled there, not fall through to "preparing".
- Wire types come from DSS's generated `@service-storage/generated/schemas`
(`Linked*`); change `crates/whatsapp_linked` and regenerate, never hand-type.
+- Adoption failures carry DSS's `LinkedError` code (`whatsappErrorResponse`);
+ `core/adopt.ts` words each one. Never show a catch-all message.
- Adoption grants access only to its owner; the generic Share dialog manages
later access. No special audience lists or WhatsApp membership requirement
for viewing.
diff --git a/apps/web/src/features/whatsapp-linked/components/add-group-dialog.tsx b/apps/web/src/features/whatsapp-linked/components/add-group-dialog.tsx
deleted file mode 100644
index 1d5ebc04a8..0000000000
--- a/apps/web/src/features/whatsapp-linked/components/add-group-dialog.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { ActionDialogShell, Button, Dialog, TextField } from '@ui';
-import { createSignal, createUniqueId, Show } from 'solid-js';
-import type { WhatsAppGroup } from '../core/group';
-
-type AddGroupFormProps = {
- group: WhatsAppGroup;
- pending: boolean;
- error: string | undefined;
- onSubmit: (request: { name: string }) => void;
- onClose: () => void;
-};
-
-function AddGroupForm(props: AddGroupFormProps) {
- const [name, setName] = createSignal(props.group.name);
- const formId = createUniqueId();
- return (
- <ActionDialogShell>
- <form
- id={formId}
- class="contents"
- onSubmit={(event) => {
- event.preventDefault();
- if (!props.pending && name().trim())
- props.onSubmit({ name: name().trim() });
- }}
- >
- <ActionDialogShell.Body>
- <ActionDialogShell.Header>
- <ActionDialogShell.Title>
- Add “{props.group.name}” to Macro
- </ActionDialogShell.Title>
- <ActionDialogShell.Description>
- Read and reply to this WhatsApp group in Macro.
- </ActionDialogShell.Description>
- </ActionDialogShell.Header>
- <TextField value={name()} onChange={setName}>
- <TextField.Label>Group name</TextField.Label>
- <TextField.Input disabled={props.pending} />
- </TextField>
- <p class="text-sm leading-5 text-ink-muted">
- Only you have access at first. Use Share to invite others to read
- the group. Each person replies from their own WhatsApp.
- </p>
- <Show when={props.error}>
- {(error) => (
- <p role="alert" class="text-sm text-failure-ink">
- {error()}
- </p>
- )}
- </Show>
- </ActionDialogShell.Body>
- </form>
- <ActionDialogShell.Footer>
- <Button
- type="button"
- variant="ghost"
- depth={2}
- disabled={props.pending}
- onClick={props.onClose}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- form={formId}
- variant="strong"
- depth={2}
- disabled={props.pending || !name().trim()}
- >
- {props.pending ? 'Adding…' : 'Add group'}
- </Button>
- </ActionDialogShell.Footer>
- </ActionDialogShell>
- );
-}
-
-export function AddGroupDialog(
- props: Omit<AddGroupFormProps, 'group'> & { group: WhatsAppGroup | undefined }
-) {
- return (
- <Dialog
- open={props.group !== undefined}
- onOpenChange={(open) => {
- if (!open && !props.pending) props.onClose();
- }}
- position="center"
- class="w-110 max-w-[calc(100vw-2rem)]"
- >
- <Show when={props.group} keyed>
- {(group) => (
- <AddGroupForm
- group={group}
- pending={props.pending}
- error={props.error}
- onSubmit={props.onSubmit}
- onClose={props.onClose}
- />
- )}
- </Show>
- </Dialog>
- );
-}
diff --git a/apps/web/src/features/whatsapp-linked/components/delivery-and-attachments.test.tsx b/apps/web/src/features/whatsapp-linked/components/delivery-and-attachments.test.tsx
deleted file mode 100644
index 49113b012c..0000000000
--- a/apps/web/src/features/whatsapp-linked/components/delivery-and-attachments.test.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { DeliveryStatus } from './delivery-status';
-import { InboundAttachmentPlaceholder } from './inbound-attachment';
-
-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
-
-beforeEach(() => {
- vi.stubGlobal('scrollTo', vi.fn());
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe = vi.fn();
- unobserve = vi.fn();
- disconnect = vi.fn();
- }
- );
-});
-
-afterEach(() => {
- cleanup();
- vi.unstubAllGlobals();
-});
-
-it('keeps quiet delivery states to one line and explains failures', () => {
- render(() => <DeliveryStatus state="delivered" />);
- expect(screen.getByText('Delivered')).toBeTruthy();
- expect(screen.queryByRole('button')).toBeNull();
- cleanup();
-
- const onRecover = vi.fn();
- render(() => (
- <DeliveryStatus
- state="failed"
- errorCode="send_expired"
- onRecover={onRecover}
- />
- ));
- expect(screen.getByText(/waited 10 minutes and was not sent/)).toBeTruthy();
- fireEvent.click(screen.getByRole('button', { name: 'Edit and retry' }));
- expect(onRecover).toHaveBeenCalledOnce();
-});
-
-it('shows an imported WhatsApp file while it loads, fails, or is unsupported', () => {
- const file = { ordinal: 0, fileName: 'receipt.jpg', documentId: undefined };
- render(() => (
- <InboundAttachmentPlaceholder attachment={{ ...file, state: 'loading' }} />
- ));
- expect(screen.getByRole('status').textContent).toBe('Loading receipt.jpg…');
- cleanup();
- render(() => (
- <InboundAttachmentPlaceholder
- attachment={{ ...file, state: 'unavailable' }}
- />
- ));
- expect(screen.getByText('Attachment unavailable: receipt.jpg')).toBeTruthy();
- cleanup();
- render(() => (
- <InboundAttachmentPlaceholder
- attachment={{ ...file, state: 'unsupported' }}
- />
- ));
- expect(screen.getByText("receipt.jpg can't be shown in Macro")).toBeTruthy();
-});
diff --git a/apps/web/src/features/whatsapp-linked/components/delivery-status.tsx b/apps/web/src/features/whatsapp-linked/components/delivery-status.tsx
deleted file mode 100644
index c04cb52127..0000000000
--- a/apps/web/src/features/whatsapp-linked/components/delivery-status.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import CheckIcon from '@phosphor/check.svg';
-import ChecksIcon from '@phosphor/checks.svg';
-import ClockIcon from '@phosphor/clock.svg';
-import SpinnerIcon from '@phosphor/spinner.svg';
-import WarningIcon from '@phosphor/warning-circle.svg';
-import { Button, cn, Tooltip } from '@ui';
-import { Show } from 'solid-js';
-import { Dynamic } from 'solid-js/web';
-import {
- type DeliveryState,
- deliveryPresentation,
- needsAttention,
-} from '../core/delivery';
-
-const icons = {
- clock: ClockIcon,
- spinner: SpinnerIcon,
- check: CheckIcon,
- checks: ChecksIcon,
- warning: WarningIcon,
-};
-
-/**
- * One send's delivery under its message. Quiet states are a small icon line;
- * failed and unconfirmed sends explain themselves and offer recovery.
- */
-export function DeliveryStatus(props: {
- state: DeliveryState;
- errorCode?: string | null;
- onRecover?: () => void;
-}) {
- const status = () => deliveryPresentation(props.state, props.errorCode);
- const attention = () => needsAttention(props.state);
- return (
- <div
- class="mt-1 flex flex-col items-start gap-1"
- data-linked-delivery={props.state}
- >
- <div class="flex flex-wrap items-center gap-x-2 gap-y-1">
- <Tooltip label={status().detail} as="span">
- <span
- class={cn(
- 'inline-flex items-center gap-1 text-xs',
- status().tone === 'error' ? 'text-failure-ink' : 'text-ink-muted'
- )}
- role="status"
- tabIndex={0}
- >
- <Dynamic
- component={icons[status().icon]}
- class={cn(
- 'size-3 shrink-0',
- props.state === 'sending' && 'animate-spin'
- )}
- aria-hidden="true"
- />
- {status().label}
- </span>
- </Tooltip>
- <Show when={attention() && props.onRecover}>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={(event) => {
- event.stopPropagation();
- props.onRecover?.();
- }}
- >
- {props.state === 'unknown' ? 'Review message' : 'Edit and retry'}
- </Button>
- </Show>
- </div>
- <Show when={attention()}>
- <p class="max-w-prose text-xs leading-relaxed text-ink-muted">
- {status().detail}
- </p>
- </Show>
- </div>
- );
-}
diff --git a/apps/web/src/features/whatsapp-linked/components/group-list.tsx b/apps/web/src/features/whatsapp-linked/components/group-list.tsx
index ebd4f4094a..a74220c745 100644
--- a/apps/web/src/features/whatsapp-linked/components/group-list.tsx
+++ b/apps/web/src/features/whatsapp-linked/components/group-list.tsx
@@ -1,13 +1,18 @@
+import CaretDownIcon from '@phosphor/caret-down.svg';
import PlusIcon from '@phosphor/plus.svg';
-import { Avatar, Button, Item } from '@ui';
-import { For, Match, Show, Switch } from 'solid-js';
-import { groupInitials, type WhatsAppGroup } from '../core/group';
+import { Avatar, Button, cn, Item } from '@ui';
+import { CollapseTransition } from '@ui/components/CollapseTransition';
+import { createSignal, For, type JSX, Match, Show, Switch } from 'solid-js';
+import {
+ groupInitials,
+ unsupportedReason,
+ type WhatsAppGroup,
+} from '../core/group';
function GroupRow(props: {
group: WhatsAppGroup;
- canAdd: boolean;
- onAdd: () => void;
- onOpenGroup: (groupId: string) => void;
+ children: JSX.Element;
+ error?: string;
}) {
return (
<Item size="sm" class="px-3" data-whatsapp-group={props.group.jid}>
@@ -18,94 +23,129 @@ function GroupRow(props: {
</Avatar>
<Item.Content class="min-w-0 gap-0">
<Item.Title class="truncate">{props.group.name}</Item.Title>
- <Show when={props.group.unreadCount}>
- <span
- aria-label={`${props.group.unreadCount} unread messages`}
- class="rounded-full bg-accent px-2 text-xs text-panel"
- >
- {props.group.unreadCount}
- </span>
- </Show>
<Item.Metadata>
{props.group.memberCount === 1
? '1 member'
: `${props.group.memberCount} members`}
</Item.Metadata>
+ <Show when={props.error}>
+ <p role="alert" class="text-xs text-failure-ink">
+ {props.error}
+ </p>
+ </Show>
</Item.Content>
- <Item.Actions>
- <Switch
- fallback={
- <Button
- type="button"
- variant="outline"
- size="sm"
- disabled={!props.canAdd}
- onClick={props.onAdd}
- >
- <PlusIcon />
- Add to Macro
- </Button>
- }
- >
- <Match when={props.group.group}>
- {(group) => (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- tooltip={`Open ${group().name}`}
- onClick={() => props.onOpenGroup(group().id)}
- >
- <span class="text-ink-muted">In Macro →</span>
- <span class="flex items-center gap-0.5 font-medium text-ink">
- {group().name}
- </span>
- </Button>
- )}
- </Match>
- <Match when={props.group.unsupported}>
- {(reason) => (
- <span class="text-xs text-ink-subtle">
- {reason() === 'community'
- ? 'Communities not supported'
- : 'Disappearing messages on'}
- </span>
- )}
- </Match>
- </Switch>
- </Item.Actions>
+ <Item.Actions>{props.children}</Item.Actions>
</Item>
);
}
-/** The connected account's groups: adopted ones link to their group. */
-export function GroupList(props: {
+/**
+ * Groups the viewer can bring into Macro with one click, and ones someone
+ * already shared with them.
+ */
+export function AddableGroupList(props: {
groups: WhatsAppGroup[];
canAdd: boolean;
+ /** JIDs whose add is in flight. */
+ adding: ReadonlySet<string>;
+ errors: Readonly<Record<string, string>>;
onAdd: (group: WhatsAppGroup) => void;
onOpenGroup: (groupId: string) => void;
}) {
return (
- <ul class="flex flex-col gap-1" aria-label="Your WhatsApp groups">
+ <ul class="flex flex-col gap-1" aria-label="Groups to add to Macro">
<For
each={props.groups}
fallback={
<li class="px-3 py-2 text-sm text-ink-muted">
- This WhatsApp account isn't in any groups yet.
+ Every WhatsApp group you can add is already in Macro.
</li>
}
>
{(group) => (
<li>
- <GroupRow
- group={group}
- canAdd={props.canAdd}
- onAdd={() => props.onAdd(group)}
- onOpenGroup={props.onOpenGroup}
- />
+ <GroupRow group={group} error={props.errors[group.jid]}>
+ <Switch
+ fallback={
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={!props.canAdd || props.adding.has(group.jid)}
+ tooltip={
+ props.canAdd
+ ? undefined
+ : 'Adding WhatsApp groups is turned off'
+ }
+ onClick={() => props.onAdd(group)}
+ >
+ <PlusIcon />
+ {props.adding.has(group.jid) ? 'Adding…' : 'Add to Macro'}
+ </Button>
+ }
+ >
+ <Match
+ when={
+ group.inMacro?.kind === 'shared' ? group.inMacro : undefined
+ }
+ >
+ {(shared) => (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => props.onOpenGroup(shared().groupId)}
+ >
+ <span class="text-ink-muted">
+ Shared with you by {shared().ownerName} ·
+ </span>
+ <span class="font-medium text-ink">Open</span>
+ </Button>
+ )}
+ </Match>
+ </Switch>
+ </GroupRow>
</li>
)}
</For>
</ul>
);
}
+
+/** Groups Macro can't hold, folded away with the reason for each. */
+export function UnsupportedGroupList(props: { groups: WhatsAppGroup[] }) {
+ const [open, setOpen] = createSignal(false);
+ return (
+ <section class="flex flex-col gap-1">
+ <button
+ type="button"
+ aria-expanded={open()}
+ class="flex items-center gap-1 px-3 pb-1 text-left text-xs font-medium text-ink-subtle hover:text-ink"
+ onClick={() => setOpen((value) => !value)}
+ >
+ Can't be added ({props.groups.length})
+ <CaretDownIcon
+ aria-hidden="true"
+ class={cn('size-2.5 transition-transform', !open() && '-rotate-90')}
+ />
+ </button>
+ <CollapseTransition open={open()}>
+ <ul class="flex flex-col gap-1" aria-label="Can't be added">
+ <For each={props.groups}>
+ {(group) => (
+ <li>
+ <GroupRow group={group}>
+ <span class="text-xs text-ink-subtle">
+ {group.unsupported
+ ? unsupportedReason(group.unsupported)
+ : undefined}
+ </span>
+ </GroupRow>
+ </li>
+ )}
+ </For>
+ </ul>
+ </CollapseTransition>
+ </section>
+ );
+}
diff --git a/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx b/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx
index 04daf35ce7..2432898315 100644
--- a/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx
+++ b/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx
@@ -5,8 +5,8 @@ import {
type ParentProps,
useContext,
} from 'solid-js';
-import type { GroupSummary } from '../../whatsapp-group/core/group';
import type { WhatsAppAccount } from '../core/account';
+import type { AdoptFailure } from '../core/adopt';
import type { WhatsAppGroup } from '../core/group';
import type { PairingStep, PasskeyChallenge } from '../core/pairing';
@@ -75,8 +75,6 @@ export type WhatsAppLinkedCapabilities = {
account: SourceRead<WhatsAppAccount | null>;
/** Groups of the connected account; read only while `enabled`. */
groups: (enabled: Accessor<boolean>) => SourceRead<WhatsAppGroup[]>;
- /** All adopted groups this viewer can read, including shared groups without WhatsApp. */
- sharedGroups: SourceRead<GroupSummary[]>;
/** The live step of one pairing, polled while it is open. */
pairing: (pairingId: Accessor<string>) => SourceRead<PairingRead>;
passkey: PasskeyCapability;
@@ -88,14 +86,11 @@ export type WhatsAppLinkedCapabilities = {
disconnect: (
generation: number
) => ResultAsync<{ remoteUnlinkRequested: boolean }, RequestFailure>;
- adopt: (request: {
- groupJid: string;
- name: string;
- }) => ResultAsync<{ groupId: string }, RequestFailure>;
+ /** One click: the Macro group takes the WhatsApp group's name and follows it. */
+ adopt: (groupJid: string) => ResultAsync<{ groupId: string }, AdoptFailure>;
isConnecting: Accessor<boolean>;
isDisconnecting: Accessor<boolean>;
- isAdopting: Accessor<boolean>;
- /** Host action: open an adopted group. */
+ /** Host action: open a group in Macro. */
openGroup: (groupId: string) => void;
};
diff --git a/apps/web/src/features/whatsapp-linked/core/adopt.test.ts b/apps/web/src/features/whatsapp-linked/core/adopt.test.ts
new file mode 100644
index 0000000000..bfae16c730
--- /dev/null
+++ b/apps/web/src/features/whatsapp-linked/core/adopt.test.ts
@@ -0,0 +1,42 @@
+import { ThrownResultError } from '@core/util/result';
+import { describe, expect, it } from 'vitest';
+import { decodeAdoptRefusal } from '../queries/decode';
+import { adoptFailureMessage } from './adopt';
+
+describe('adoption refusals', () => {
+ it('reads DSS’s LinkedError codes, keeping its wording for rejected input', () => {
+ expect(
+ adoptFailureMessage(
+ decodeAdoptRefusal(
+ new ThrownResultError([{ code: 'forbidden', message: 'x' }])
+ )
+ )
+ ).toBe(
+ "Your WhatsApp isn't allowed to add this group. Check that you're still a member."
+ );
+ expect(
+ adoptFailureMessage(
+ decodeAdoptRefusal(
+ new ThrownResultError([
+ {
+ code: 'invalid_input',
+ message: 'groups with disappearing messages cannot be added',
+ },
+ ])
+ )
+ )
+ ).toBe(
+ "WhatsApp didn't accept this group: groups with disappearing messages cannot be added."
+ );
+ expect(
+ adoptFailureMessage(
+ decodeAdoptRefusal(
+ new ThrownResultError([{ code: 'NETWORK_ERROR', message: 'x' }])
+ )
+ )
+ ).toBe("Couldn't reach Macro. Check your connection and try again.");
+ expect(decodeAdoptRefusal(new TypeError('offline'))).toEqual({
+ reason: 'unreachable',
+ });
+ });
+});
diff --git a/apps/web/src/features/whatsapp-linked/core/adopt.ts b/apps/web/src/features/whatsapp-linked/core/adopt.ts
new file mode 100644
index 0000000000..57383cbb43
--- /dev/null
+++ b/apps/web/src/features/whatsapp-linked/core/adopt.ts
@@ -0,0 +1,58 @@
+import { match } from 'ts-pattern';
+
+/** Why adding a group did not happen, in the page's vocabulary. */
+export type AdoptRefusal =
+ | { reason: 'not-allowed' }
+ | { reason: 'gone' }
+ | { reason: 'already-added' }
+ | { reason: 'disconnected' }
+ | { reason: 'turned-off' }
+ | { reason: 'rate-limited' }
+ | { reason: 'unavailable' }
+ /** DSS rejected the request; its wording says why. */
+ | { reason: 'rejected'; detail: string }
+ | { reason: 'signed-out' }
+ | { reason: 'unreachable' };
+
+export type AdoptFailure = { kind: 'adopt-failed' } & AdoptRefusal;
+
+/** Specific words for each refusal; never a catch-all. */
+export function adoptFailureMessage(failure: AdoptRefusal): string {
+ return match(failure)
+ .with(
+ { reason: 'not-allowed' },
+ () =>
+ "Your WhatsApp isn't allowed to add this group. Check that you're still a member."
+ )
+ .with({ reason: 'gone' }, () => 'This group is no longer on your WhatsApp.')
+ .with({ reason: 'already-added' }, () => 'This group is already in Macro.')
+ .with(
+ { reason: 'disconnected' },
+ () => 'Your WhatsApp is disconnected. Reconnect it, then add the group.'
+ )
+ .with(
+ { reason: 'turned-off' },
+ () => 'Adding WhatsApp groups is turned off.'
+ )
+ .with(
+ { reason: 'rate-limited' },
+ () => 'Too many requests at once. Wait a second, then add it again.'
+ )
+ .with(
+ { reason: 'unavailable' },
+ () => 'WhatsApp is temporarily unavailable. Try again in a moment.'
+ )
+ .with(
+ { reason: 'rejected' },
+ ({ detail }) => `WhatsApp didn't accept this group: ${detail}.`
+ )
+ .with(
+ { reason: 'signed-out' },
+ () => 'Your Macro session expired. Sign in again to add this group.'
+ )
+ .with(
+ { reason: 'unreachable' },
+ () => "Couldn't reach Macro. Check your connection and try again."
+ )
+ .exhaustive();
+}
diff --git a/apps/web/src/features/whatsapp-linked/core/attachments.test.ts b/apps/web/src/features/whatsapp-linked/core/attachments.test.ts
deleted file mode 100644
index eb13ab7614..0000000000
--- a/apps/web/src/features/whatsapp-linked/core/attachments.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { expect, it } from 'vitest';
-import { attachmentProblem, captionOf, mediaKindOf } from './attachments';
-
-const MB = 1024 * 1024;
-
-it('sends only the file types WhatsApp groups accept', () => {
- expect(mediaKindOf('image/webp')).toBe('image');
- expect(mediaKindOf('audio/ogg')).toBe('audio');
- expect(mediaKindOf('video/mp4')).toBe('video');
- expect(mediaKindOf('text/plain')).toBe('document');
- expect(mediaKindOf('image/gif')).toBeUndefined();
-});
-
-it('explains a refused file by type, then by size', () => {
- expect(
- attachmentProblem({ name: 'a.gif', type: 'image/gif', size: 1 }, 32 * MB)
- ).toBe("WhatsApp doesn't accept a.gif's file type.");
- expect(
- attachmentProblem(
- { name: 'b.mp4', type: 'video/mp4', size: 33 * MB },
- 32 * MB
- )
- ).toBe("b.mp4 is larger than WhatsApp's 32 MB limit.");
- expect(
- attachmentProblem(
- { name: 'c.pdf', type: 'application/pdf', size: MB },
- 32 * MB
- )
- ).toBeUndefined();
-});
-
-it('keeps the person’s caption and drops DSS’s stand-in for the files', () => {
- const receipt = {
- ordinal: 0,
- state: 'unavailable' as const,
- fileName: 'receipt.jpg',
- documentId: undefined,
- };
- expect(captionOf('Loading attachment…', [receipt])).toBe('');
- expect(
- captionOf('Lunch was 12 euros\n\nAttachment unavailable: receipt.jpg', [
- receipt,
- ])
- ).toBe('Lunch was 12 euros');
- expect(captionOf('Attachment unavailable: other.pdf', [receipt])).toBe(
- 'Attachment unavailable: other.pdf'
- );
-});
diff --git a/apps/web/src/features/whatsapp-linked/core/attachments.ts b/apps/web/src/features/whatsapp-linked/core/attachments.ts
deleted file mode 100644
index 599acfa2e6..0000000000
--- a/apps/web/src/features/whatsapp-linked/core/attachments.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { match, P } from 'ts-pattern';
-
-/** WhatsApp's media categories for a linked-group send. */
-export type MediaKind = 'image' | 'audio' | 'video' | 'document';
-
-/** The category DSS sends a file type as; anything else is refused there. */
-export function mediaKindOf(mimeType: string): MediaKind | undefined {
- return match(mimeType)
- .with(
- P.union('image/jpeg', 'image/png', 'image/webp'),
- () => 'image' as const
- )
- .with(
- P.union('audio/mpeg', 'audio/ogg', 'audio/aac', 'audio/mp4'),
- () => 'audio' as const
- )
- .with('video/mp4', () => 'video' as const)
- .with(P.union('application/pdf', 'text/plain'), () => 'document' as const)
- .otherwise(() => undefined);
-}
-
-/** Why a file can't go to a WhatsApp group, or undefined when it can. */
-export function attachmentProblem(
- file: { name: string; type: string; size: number },
- limitBytes: number
-): string | undefined {
- if (!mediaKindOf(file.type))
- return `WhatsApp doesn't accept ${file.name}'s file type.`;
- if (file.size > limitBytes)
- return `${file.name} is larger than WhatsApp's ${Math.floor(limitBytes / (1024 * 1024))} MB limit.`;
- return undefined;
-}
-
-/** An imported WhatsApp file on a linked message, as DSS reports it. */
-export type InboundAttachment = {
- ordinal: number;
- state: 'loading' | 'ready' | 'unavailable' | 'unsupported';
- fileName: string;
- /** The Macro document holding the file, once ready. */
- documentId: string | undefined;
-};
-
-/**
- * The person's own text of a message with imported files. DSS also writes a
- * text stand-in for the files ("Loading attachment…", "Attachment
- * unavailable: <name>") as its own paragraph, for search and notifications;
- * that stand-in is dropped where the files show themselves.
- */
-export function captionOf(
- markdown: string,
- attachments: readonly InboundAttachment[]
-): string {
- const standIns = new Set([
- 'Loading attachment…',
- ...attachments.map(
- (attachment) => `Attachment unavailable: ${attachment.fileName}`
- ),
- ]);
- return markdown
- .split(/\n{2,}/)
- .filter((paragraph) => !standIns.has(paragraph.trim()))
- .join('\n\n')
- .trim();
-}
diff --git a/apps/web/src/features/whatsapp-linked/core/delivery.ts b/apps/web/src/features/whatsapp-linked/core/delivery.ts
deleted file mode 100644
index 82180107ca..0000000000
--- a/apps/web/src/features/whatsapp-linked/core/delivery.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { match } from 'ts-pattern';
-
-/** A deliberate send's state, as DSS records it. */
-export type DeliveryState =
- | 'pending'
- | 'sending'
- | 'unknown'
- | 'accepted'
- | 'sent'
- | 'delivered'
- | 'read'
- | 'failed';
-
-export type DeliveryPresentation = {
- label: string;
- detail: string;
- tone: 'muted' | 'read' | 'error' | 'uncertain';
- icon: 'clock' | 'spinner' | 'check' | 'checks' | 'warning';
-};
-
-/** Known failure codes in plain words; never a provider response. */
-export function sendFailure(code: string | null | undefined): string {
- return match(code ?? '')
- .with(
- 'send_expired',
- () =>
- 'This message waited 10 minutes and was not sent. Edit and retry when you’re ready.'
- )
- .with(
- 'disconnected',
- () => 'Your WhatsApp is disconnected. Link it again in External.'
- )
- .with(
- 'forbidden',
- 'not_found',
- () => 'You can no longer send to this group from Macro.'
- )
- .with(
- 'refreshing',
- 'temporarily_unavailable',
- () => 'WhatsApp is temporarily unavailable. Try again in a little while.'
- )
- .with(
- 'conflict',
- () => 'This message changed while sending. Review it and send again.'
- )
- .otherwise(
- () =>
- 'WhatsApp didn’t take this message. Your text is saved; review it and try again.'
- );
-}
-
-export function deliveryPresentation(
- state: DeliveryState,
- errorCode?: string | null
-): DeliveryPresentation {
- return match(state)
- .with('pending', () => ({
- label: 'Queued',
- detail: 'Waiting to send from your WhatsApp.',
- tone: 'muted' as const,
- icon: 'clock' as const,
- }))
- .with('sending', () => ({
- label: 'Sending…',
- detail: 'Sending from your WhatsApp.',
- tone: 'muted' as const,
- icon: 'spinner' as const,
- }))
- .with('accepted', 'sent', () => ({
- label: 'Sent',
- detail: 'WhatsApp accepted this message. Delivery is not confirmed yet.',
- tone: 'muted' as const,
- icon: 'check' as const,
- }))
- .with('delivered', () => ({
- label: 'Delivered',
- detail: 'WhatsApp reported this message delivered.',
- tone: 'muted' as const,
- icon: 'checks' as const,
- }))
- .with('read', () => ({
- label: 'Read',
- detail: 'WhatsApp reported this message read.',
- tone: 'read' as const,
- icon: 'checks' as const,
- }))
- .with('failed', () => ({
- label: 'Not sent',
- detail: sendFailure(errorCode),
- tone: 'error' as const,
- icon: 'warning' as const,
- }))
- .with('unknown', () => ({
- label: 'Delivery not confirmed',
- detail:
- 'This message may already have arrived. Check WhatsApp before sending it again.',
- tone: 'uncertain' as const,
- icon: 'warning' as const,
- }))
- .exhaustive();
-}
-
-/** States a person must look at: never retried automatically. */
-export function needsAttention(state: DeliveryState): boolean {
- return state === 'failed' || state === 'unknown';
-}
diff --git a/apps/web/src/features/whatsapp-linked/core/group.ts b/apps/web/src/features/whatsapp-linked/core/group.ts
index 4648c3f529..8f1d734ee5 100644
--- a/apps/web/src/features/whatsapp-linked/core/group.ts
+++ b/apps/web/src/features/whatsapp-linked/core/group.ts
@@ -1,15 +1,43 @@
+import { match } from 'ts-pattern';
+
+/** Where a WhatsApp group already is in Macro for this viewer. */
+export type InMacro =
+ | { kind: 'own'; groupId: string }
+ | { kind: 'shared'; groupId: string; ownerId: string; ownerName: string };
+
/** A WhatsApp group the connected account belongs to. */
export type WhatsAppGroup = {
jid: string;
+ /** WhatsApp's subject, or DSS's member-name fallback for unnamed groups. */
name: string;
memberCount: number;
- /** The shareable Macro group entity. */
- group: { id: string; name: string } | undefined;
- unreadCount?: number;
+ inMacro: InMacro | undefined;
/** Why this group cannot be added, when it cannot. */
unsupported: 'community' | 'disappearing' | undefined;
};
+/** The WhatsApp page's two lists; groups already added live in External's sidebar. */
+export function groupSections(groups: WhatsAppGroup[]) {
+ return {
+ /** Not yet in Macro for this viewer, or shared with them by someone else. */
+ addable: groups.filter(
+ (group) => !group.unsupported && group.inMacro?.kind !== 'own'
+ ),
+ unsupported: groups.filter(
+ (group) => group.unsupported && group.inMacro?.kind !== 'own'
+ ),
+ };
+}
+
+export function unsupportedReason(
+ reason: NonNullable<WhatsAppGroup['unsupported']>
+): string {
+ return match(reason)
+ .with('community', () => 'WhatsApp communities aren’t supported yet')
+ .with('disappearing', () => 'Disappearing messages are on')
+ .exhaustive();
+}
+
/** Up to two initials from the words of a group name that start with a letter. */
export function groupInitials(name: string): string {
return name
diff --git a/apps/web/src/features/whatsapp-linked/queries/decode.ts b/apps/web/src/features/whatsapp-linked/queries/decode.ts
index 185fa5c4b8..aed0dc2286 100644
--- a/apps/web/src/features/whatsapp-linked/queries/decode.ts
+++ b/apps/web/src/features/whatsapp-linked/queries/decode.ts
@@ -1,7 +1,10 @@
+import { ThrownResultError } from '@core/util/result';
import type { LinkedAccount } from '@service-storage/generated/schemas/linkedAccount';
import type { LinkedGroupInfo } from '@service-storage/generated/schemas/linkedGroupInfo';
import type { LinkedPairState } from '@service-storage/generated/schemas/linkedPairState';
+import { match } from 'ts-pattern';
import { phoneFromJid, type WhatsAppAccount } from '../core/account';
+import type { AdoptRefusal } from '../core/adopt';
import type { WhatsAppGroup } from '../core/group';
import { type PairingStep, pairingStep } from '../core/pairing';
@@ -18,14 +21,25 @@ export function decodeAccount(
};
}
-export function decodeGroup(group: LinkedGroupInfo): WhatsAppGroup {
+/** `ownerName` resolves a Macro user id; production reads the shared name cache. */
+export function decodeGroup(
+ group: LinkedGroupInfo,
+ ownerName: (ownerId: string) => string
+): WhatsAppGroup {
return {
jid: group.jid,
name: group.name,
memberCount: group.participants.length,
- group: group.group
- ? { id: group.group.id, name: group.group.name }
- : undefined,
+ inMacro: group.group
+ ? { kind: 'own', groupId: group.group.id }
+ : group.shared
+ ? {
+ kind: 'shared',
+ groupId: group.shared.id,
+ ownerId: group.shared.owner_id,
+ ownerName: ownerName(group.shared.owner_id),
+ }
+ : undefined,
unsupported: group.community
? 'community'
: group.disappearing
@@ -34,9 +48,38 @@ export function decodeGroup(group: LinkedGroupInfo): WhatsAppGroup {
};
}
+/** DSS's `LinkedError` code (or the transport's) in the page's words. */
+export function decodeAdoptRefusal(error: unknown): AdoptRefusal {
+ if (!(error instanceof ThrownResultError)) return { reason: 'unreachable' };
+ const [first] = error.errors;
+ if (!first) return { reason: 'unavailable' };
+ return match(first.code)
+ .returnType<AdoptRefusal>()
+ .with('forbidden', 'FORBIDDEN', () => ({ reason: 'not-allowed' }))
+ .with('not_found', 'NOT_FOUND', 'GONE', () => ({ reason: 'gone' }))
+ .with('conflict', 'CONFLICT', () => ({ reason: 'already-added' }))
+ .with('disconnected', 'identity_conflict', () => ({
+ reason: 'disconnected',
+ }))
+ .with('configuration_required', () => ({ reason: 'turned-off' }))
+ .with('rate_limited', () => ({ reason: 'rate-limited' }))
+ .with('invalid_input', () => ({
+ reason: 'rejected',
+ detail: first.message,
+ }))
+ .with('UNAUTHORIZED', () => ({ reason: 'signed-out' }))
+ .with('NETWORK_ERROR', () => ({ reason: 'unreachable' }))
+ .otherwise(() => ({ reason: 'unavailable' }));
+}
+
/** By name, so adding a group or a refetch never moves a row. */
-export function decodeGroups(groups: LinkedGroupInfo[]): WhatsAppGroup[] {
- return groups.map(decodeGroup).sort((a, b) => a.name.localeCompare(b.name));
+export function decodeGroups(
+ groups: LinkedGroupInfo[],
+ ownerName: (ownerId: string) => string
+): WhatsAppGroup[] {
+ return groups
+ .map((group) => decodeGroup(group, ownerName))
+ .sort((a, b) => a.name.localeCompare(b.name));
}
export function decodePairing(state: LinkedPairState): {
diff --git a/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts b/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts
index f2c9afadbd..323d82d70d 100644
--- a/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts
+++ b/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts
@@ -1,8 +1,9 @@
import { useUserId } from '@core/context/user';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
+import { getDisplayName } from '@core/user/displayName';
+import { isMacroId } from '@core/user/macroId';
import { fireAndForget } from '@core/util/fireAndForget';
import { queryReadyGate } from '@queries/gate';
-import { useWhatsappGroupsQuery } from '@queries/whatsapp-groups';
import {
refreshWhatsappLinkedAccount,
useAdoptWhatsappGroupMutation,
@@ -15,22 +16,33 @@ import {
useWhatsappLinkedGroupsQuery,
useWhatsappLinkedPairingQuery,
} from '@queries/whatsapp-linked';
+import {
+ traceWhatsappLoad,
+ type WhatsappLoadResult,
+} from '@queries/whatsapp-linked/operation';
import type { UseQueryResult } from '@tanstack/solid-query';
import { ResultAsync } from 'neverthrow';
-import { type Accessor, createMemo } from 'solid-js';
-import { whatsappGroupApi } from '../../whatsapp-group/queries/production-api';
+import { type Accessor, createMemo, createSignal } from 'solid-js';
import type {
PasskeyCapability,
RequestFailure,
SourceRead,
WhatsAppLinkedCapabilities,
} from '../context/whatsapp-linked-context';
+import { accountStatus, type WhatsAppAccount } from '../core/account';
+import type { AdoptFailure } from '../core/adopt';
+import type { WhatsAppGroup } from '../core/group';
import {
authenticateWhatsAppPasskey,
canAuthenticatePasskey,
desktopPairingUrl,
} from './authenticator';
-import { decodeAccount, decodeGroups, decodePairing } from './decode';
+import {
+ decodeAccount,
+ decodeAdoptRefusal,
+ decodeGroups,
+ decodePairing,
+} from './decode';
const failure = (): RequestFailure => ({ kind: 'request-failed' });
@@ -55,6 +67,28 @@ function sourceRead<Wire, Value>(
};
}
+/** The page has loaded once the account, and a connected account's groups, have. */
+function pageLoad(
+ account: SourceRead<WhatsAppAccount | null>,
+ groups: SourceRead<WhatsAppGroup[]> | undefined
+): WhatsappLoadResult | undefined {
+ if (account.isError) return { outcome: 'error' };
+ if (account.data === undefined) return;
+ if (accountStatus(account.data).kind !== 'connected')
+ return { outcome: 'success', attrs: { 'whatsapp.connected': false } };
+ if (groups?.isError) return { outcome: 'error' };
+ const list = groups?.data;
+ if (!list) return;
+ return {
+ outcome: 'success',
+ attrs: {
+ 'whatsapp.connected': true,
+ 'whatsapp.groups.count': list.length,
+ 'whatsapp.groups.in_macro': list.filter((group) => group.inMacro).length,
+ },
+ };
+}
+
/** The WhatsApp page's capabilities, from the shared linked-device queries. */
export function createWhatsAppLinkedCapabilities(host: {
openGroup: (groupId: string) => void;
@@ -65,10 +99,6 @@ export function createWhatsAppLinkedCapabilities(host: {
const disconnect = useDisconnectWhatsappMutation();
const cancel = useCancelWhatsappPairingMutation();
const adopt = useAdoptWhatsappGroupMutation();
- const sharedGroups = sourceRead(
- useWhatsappGroupsQuery(whatsappGroupApi, currentUser),
- (groups) => groups
- );
const submitPasskey = useSubmitWhatsappPasskeyMutation();
const passkey: PasskeyCapability = canAuthenticatePasskey()
? {
@@ -89,24 +119,32 @@ export function createWhatsAppLinkedCapabilities(host: {
: isNativeMobilePlatform()
? { kind: 'unsupported' }
: { kind: 'handoff', desktopUrl: desktopPairingUrl };
+ const account = sourceRead(
+ useWhatsappLinkedAccountQuery(currentUser),
+ (view) => decodeAccount(view.account)
+ );
+ const [groupsRead, setGroupsRead] =
+ createSignal<SourceRead<WhatsAppGroup[]>>();
+ traceWhatsappLoad('page.load', () => pageLoad(account, groupsRead()));
return {
features: sourceRead(useWhatsappLinkedConfigurationQuery(), (features) => ({
pairing: features.pairing,
adoption: features.adoption,
})),
- account: sourceRead(useWhatsappLinkedAccountQuery(currentUser), (view) =>
- decodeAccount(view.account)
- ),
- groups: (enabled: Accessor<boolean>) =>
- sourceRead(useWhatsappLinkedGroupsQuery(currentUser, enabled), (groups) =>
- decodeGroups(groups).map((group) => ({
- ...group,
- unreadCount: sharedGroups.data?.find(
- (shared) => shared.id === group.group?.id
- )?.unreadCount,
- }))
- ),
- sharedGroups,
+ account,
+ groups: (enabled: Accessor<boolean>) => {
+ const read = sourceRead(
+ useWhatsappLinkedGroupsQuery(currentUser, enabled),
+ (groups) =>
+ decodeGroups(groups, (ownerId) =>
+ isMacroId(ownerId)
+ ? getDisplayName(ownerId) || 'a teammate'
+ : 'a teammate'
+ )
+ );
+ setGroupsRead(() => read);
+ return read;
+ },
passkey,
pairing: (pairingId: Accessor<string>) =>
sourceRead(
@@ -128,14 +166,16 @@ export function createWhatsAppLinkedCapabilities(host: {
remoteUnlinkRequested: result.remote_unlink_requested,
})
),
- adopt: (request) =>
+ adopt: (groupJid) =>
ResultAsync.fromPromise(
- adopt.mutateAsync({ group_jid: request.groupJid }),
- failure
+ adopt.mutateAsync({ group_jid: groupJid }),
+ (error): AdoptFailure => ({
+ kind: 'adopt-failed',
+ ...decodeAdoptRefusal(error),
+ })
).map((binding) => ({ groupId: binding.group_id })),
isConnecting: () => connect.isPending,
isDisconnecting: () => disconnect.isPending,
- isAdopting: () => adopt.isPending,
openGroup: host.openGroup,
};
}
diff --git a/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts b/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts
index 03cdbf51b4..297a719ad7 100644
--- a/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts
+++ b/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts
@@ -1,7 +1,6 @@
import { okAsync, type ResultAsync } from 'neverthrow';
import { type Accessor, createSignal, type Setter } from 'solid-js';
import { vi } from 'vitest';
-import type { GroupSummary } from '../../whatsapp-group/core/group';
import type {
PairingRead,
PasskeyCapability,
@@ -10,6 +9,7 @@ import type {
WhatsAppLinkedCapabilities,
} from '../context/whatsapp-linked-context';
import type { WhatsAppAccount } from '../core/account';
+import type { AdoptFailure } from '../core/adopt';
import type { WhatsAppGroup } from '../core/group';
import type { PairingStep } from '../core/pairing';
@@ -37,7 +37,6 @@ export function createFakeWhatsApp(initial: {
account: WhatsAppAccount | null;
groups?: WhatsAppGroup[];
passkey?: PasskeyCapability;
- sharedGroups?: GroupSummary[];
}) {
const [account, setAccount] = signalRead<WhatsAppAccount | null>(
initial.account
@@ -53,7 +52,6 @@ export function createFakeWhatsApp(initial: {
const groupsEnabled: Accessor<boolean>[] = [];
const capabilities = {
features,
- sharedGroups: signalRead(initial.sharedGroups ?? [])[0],
account,
groups: vi.fn((enabled: Accessor<boolean>) => {
groupsEnabled.push(enabled);
@@ -89,15 +87,11 @@ export function createFakeWhatsApp(initial: {
okAsync({ remoteUnlinkRequested: false })
),
adopt: vi.fn(
- (_request: {
- groupJid: string;
- name: string;
- }): ResultAsync<{ groupId: string }, RequestFailure> =>
- okAsync({ groupId: 'channel-new' })
+ (_groupJid: string): ResultAsync<{ groupId: string }, AdoptFailure> =>
+ okAsync({ groupId: 'group-new' })
),
isConnecting: () => false,
isDisconnecting: () => false,
- isAdopting: () => false,
openGroup: vi.fn(),
} satisfies WhatsAppLinkedCapabilities;
return { capabilities, setAccount, setGroups, setPairing, groupsEnabled };
diff --git a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx
index 80fc9d88a3..0ecb746659 100644
--- a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx
+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx
@@ -54,16 +54,35 @@ const groups = [
name: 'Design Crit',
memberCount: 14,
- group: { id: 'channel-design', name: 'design-crit' },
+ inMacro: { kind: 'own' as const, groupId: 'group-design' },
unsupported: undefined,
},
{
name: 'Launch War Room',
memberCount: 23,
- group: undefined,
+ inMacro: undefined,
unsupported: undefined,
},
+ {
+ name: 'Ana, Ben, +2',
+ memberCount: 4,
+ inMacro: {
+ kind: 'shared' as const,
+ groupId: 'group-family',
+ ownerId: 'macro|[email protected]',
+ ownerName: 'Ana Silva',
+ },
+ unsupported: undefined,
+ },
+ {
+ name: 'Neighbourhood',
+ memberCount: 120,
+ inMacro: undefined,
+ unsupported: 'community' as const,
+ },
];
describe('not connected', () => {
@@ -190,7 +209,7 @@ describe('connected', () => {
expect(dialogOpen()).toBe(true);
});
- it('lists groups, opens adopted groups, and disconnects after confirming', async () => {
+ it('lists groups to add, opens shared ones, and disconnects after confirming', async () => {
const fake = createFakeWhatsApp({
account: { generation: 3, phone: '+14155550142', health: 'connected' },
groups,
@@ -201,11 +220,24 @@ describe('connected', () => {
expect(screen.getByText('Connected · linked device')).toBeTruthy();
expect(fake.groupsEnabled[0]?.()).toBe(true);
const list = within(
- screen.getByRole('list', { name: 'Your WhatsApp groups' })
+ screen.getByRole('list', { name: 'Groups to add to Macro' })
+ );
+ // Groups already in Macro live in External's sidebar, not here.
+ expect(list.queryByText('Design Crit')).toBeNull();
+ expect(list.getByText('23 members')).toBeTruthy();
+ fireEvent.click(
+ list.getByRole('button', { name: /Shared with you by Ana Silva/ })
);
- expect(list.getByText('14 members')).toBeTruthy();
- fireEvent.click(list.getByRole('button', { name: /In Macro/ }));
- expect(fake.capabilities.openGroup).toHaveBeenCalledWith('channel-design');
+ expect(fake.capabilities.openGroup).toHaveBeenCalledWith('group-family');
+
+ expect(screen.queryByText('Neighbourhood')).toBeNull();
+ fireEvent.click(
+ screen.getByRole('button', { name: /Can't be added \(1\)/ })
+ );
+ expect(await screen.findByText('Neighbourhood')).toBeTruthy();
+ expect(
+ screen.getByText('WhatsApp communities aren’t supported yet')
+ ).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }));
const confirm = within(await screen.findByRole('dialog'));
@@ -221,7 +253,7 @@ describe('connected', () => {
expect(screen.getByRole('button', { name: 'Connect' })).toBeTruthy();
});
- it('adds a group with a name and owner-only access', async () => {
+ it('adds a group in one click, without a dialog', async () => {
const fake = createFakeWhatsApp({
account: { generation: 3, phone: '+14155550142', health: 'connected' },
groups,
@@ -229,44 +261,30 @@ describe('connected', () => {
mount(fake);
fireEvent.click(screen.getByRole('button', { name: 'Add to Macro' }));
- const dialog = within(await screen.findByRole('dialog'));
- expect(dialog.getByText('Add “Launch War Room” to Macro')).toBeTruthy();
- const name = dialog.getByLabelText('Group name') as HTMLInputElement;
- expect(name.value).toBe('Launch War Room');
- expect(dialog.queryByRole('checkbox')).toBeNull();
- expect(dialog.getByText(/Only you have access at first/)).toBeTruthy();
- expect(
- dialog.getByText(/Each person replies from their own WhatsApp/)
- ).toBeTruthy();
-
- fireEvent.input(name, { target: { value: 'war-room' } });
- fireEvent.click(dialog.getByRole('button', { name: 'Add group' }));
await waitFor(() =>
- expect(fake.capabilities.adopt).toHaveBeenCalledWith({
- groupJid: '[email protected]',
- name: 'war-room',
- })
- );
- await waitFor(() =>
- expect(screen.queryByText('Add “Launch War Room” to Macro')).toBeNull()
+ expect(fake.capabilities.adopt).toHaveBeenCalledWith('[email protected]')
);
+ expect(screen.queryByRole('dialog')).toBeNull();
});
- it('keeps the dialog open with an explanation when adding fails', async () => {
+ it('says exactly why adding failed, on the group it failed for', async () => {
const fake = createFakeWhatsApp({
account: { generation: 3, phone: '+14155550142', health: 'connected' },
groups,
});
fake.capabilities.adopt.mockReturnValueOnce(
- errAsync({ kind: 'request-failed' })
+ errAsync({ kind: 'adopt-failed', reason: 'disconnected' })
);
mount(fake);
fireEvent.click(screen.getByRole('button', { name: 'Add to Macro' }));
- const dialog = within(await screen.findByRole('dialog'));
- fireEvent.click(dialog.getByRole('button', { name: 'Add group' }));
- expect(await dialog.findByText(/Couldn't add this group/)).toBeTruthy();
- expect(screen.getByRole('dialog')).toBeTruthy();
+ const row = within(
+ screen.getByText('Launch War Room').closest('li') as HTMLElement
+ );
+ expect((await row.findByRole('alert')).textContent).toBe(
+ 'Your WhatsApp is disconnected. Reconnect it, then add the group.'
+ );
+ expect(row.getByRole('button', { name: 'Add to Macro' })).toBeTruthy();
});
});
@@ -362,17 +380,3 @@ describe('passkey', () => {
expect(fake.capabilities.connect).not.toHaveBeenCalled();
});
});
-
-it('opens a shared group before the viewer connects WhatsApp', () => {
- const fake = createFakeWhatsApp({
- account: null,
- sharedGroups: [
- { id: 'shared-group', name: 'Shared Design Crit', unreadCount: 3 },
- ],
- });
- mount(fake);
- expect(screen.getByLabelText('3 unread messages')).toBeTruthy();
- fireEvent.click(screen.getByRole('button', { name: /Shared Design Crit/ }));
- expect(fake.capabilities.openGroup).toHaveBeenCalledWith('shared-group');
- expect(fake.capabilities.connect).not.toHaveBeenCalled();
-});
diff --git a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx
index 1de04f47c9..a83ae27955 100644
--- a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx
+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx
@@ -1,14 +1,17 @@
import { fireAndForget } from '@core/util/fireAndForget';
import { Button, ConfirmDialog } from '@ui';
-import { createSignal, For, Match, onMount, Show, Switch } from 'solid-js';
+import { createSignal, Match, onMount, Show, Switch } from 'solid-js';
import { match } from 'ts-pattern';
import { AccountCard, ConnectCard } from '../components/account-card';
-import { AddGroupDialog } from '../components/add-group-dialog';
-import { GroupList } from '../components/group-list';
+import {
+ AddableGroupList,
+ UnsupportedGroupList,
+} from '../components/group-list';
import { PairingDialog, type PasskeyMode } from '../components/pairing-dialog';
import { useWhatsAppLinked } from '../context/whatsapp-linked-context';
import { accountStatus } from '../core/account';
-import type { WhatsAppGroup } from '../core/group';
+import { adoptFailureMessage } from '../core/adopt';
+import { groupSections, type WhatsAppGroup } from '../core/group';
import { createPairingFlow } from '../primitives/pairing-flow';
function Notice(props: { children: string }) {
@@ -30,7 +33,10 @@ function LoadFailure(props: { what: string; onRetry: () => void }) {
);
}
-/** The External tab's WhatsApp page: link an account, then add its groups. */
+/**
+ * The External tab's WhatsApp page: link an account, then add its groups.
+ * Groups already in Macro are listed in External's sidebar.
+ */
export function WhatsAppPage(props: {
/** A pairing to show at once, handed off by id from another device. */
resumePairingId?: string;
@@ -71,8 +77,8 @@ export function WhatsAppPage(props: {
const [confirmingDisconnect, setConfirmingDisconnect] = createSignal(false);
const [confirmingReplace, setConfirmingReplace] = createSignal(false);
const [notice, setNotice] = createSignal<string>();
- const [adding, setAdding] = createSignal<WhatsAppGroup>();
- const [addError, setAddError] = createSignal<string>();
+ const [adding, setAdding] = createSignal<ReadonlySet<string>>(new Set());
+ const [addErrors, setAddErrors] = createSignal<Record<string, string>>({});
const disconnect = async (generation: number) => {
setNotice(undefined);
@@ -91,23 +97,24 @@ export function WhatsAppPage(props: {
);
};
- const openAddDialog = (group: WhatsAppGroup) => {
- setAddError(undefined);
- setAdding(group);
- };
-
- const adopt = async (request: { name: string }) => {
- const group = adding();
- if (!group) return;
- setAddError(undefined);
- const result = await whatsapp.adopt({ groupJid: group.jid, ...request });
- if (result.isErr()) {
- setAddError(
- "Couldn't add this group. Check that you're still in it, then try again."
- );
- return;
- }
- setAdding(undefined);
+ const setPending = (jid: string, pending: boolean) =>
+ setAdding((current) => {
+ const next = new Set(current);
+ if (pending) next.add(jid);
+ else next.delete(jid);
+ return next;
+ });
+ const adopt = async (group: WhatsAppGroup) => {
+ if (adding().has(group.jid)) return;
+ setAddErrors(({ [group.jid]: _previous, ...rest }) => rest);
+ setPending(group.jid, true);
+ const result = await whatsapp.adopt(group.jid);
+ setPending(group.jid, false);
+ if (result.isErr())
+ setAddErrors((current) => ({
+ ...current,
+ [group.jid]: adoptFailureMessage(result.error),
+ }));
};
return (
@@ -137,42 +144,48 @@ export function WhatsAppPage(props: {
<Notice>Couldn't start linking WhatsApp. Try again.</Notice>
</Show>
<Show when={notice()}>{(text) => <Notice>{text()}</Notice>}</Show>
- <section
- class="flex flex-col gap-1"
- aria-labelledby="whatsapp-groups"
- >
- <h2
- id="whatsapp-groups"
- class="px-3 pb-1 text-xs font-medium text-ink-subtle"
- >
- Your WhatsApp groups
- </h2>
- <Switch>
- <Match when={groups.data}>
- {(list) => (
- <GroupList
- groups={list().map((group) => ({
- ...group,
- unreadCount: whatsapp.sharedGroups.data?.find(
- (item) => item.id === group.group?.id
- )?.unreadCount,
- }))}
- canAdd={whatsapp.features.data?.adoption ?? false}
- onAdd={openAddDialog}
- onOpenGroup={whatsapp.openGroup}
- />
- )}
- </Match>
- <Match when={groups.isPending}>
- <p role="status" class="px-3 py-2 text-sm text-ink-muted">
- Loading groups…
- </p>
- </Match>
- <Match when={groups.isError}>
- <LoadFailure what="your groups" onRetry={groups.refetch} />
- </Match>
- </Switch>
- </section>
+ <Switch>
+ <Match when={groups.data}>
+ {(list) => (
+ <>
+ <section
+ class="flex flex-col gap-1"
+ aria-labelledby="whatsapp-add-groups"
+ >
+ <h2
+ id="whatsapp-add-groups"
+ class="px-3 pb-1 text-xs font-medium text-ink-subtle"
+ >
+ Add to Macro
+ </h2>
+ <AddableGroupList
+ groups={groupSections(list()).addable}
+ canAdd={whatsapp.features.data?.adoption ?? false}
+ adding={adding()}
+ errors={addErrors()}
+ onAdd={(group) =>
+ fireAndForget(adopt(group), 'whatsapp-linked.adopt')
+ }
+ onOpenGroup={whatsapp.openGroup}
+ />
+ </section>
+ <Show when={groupSections(list()).unsupported.length}>
+ <UnsupportedGroupList
+ groups={groupSections(list()).unsupported}
+ />
+ </Show>
+ </>
+ )}
+ </Match>
+ <Match when={groups.isPending}>
+ <p role="status" class="px-3 py-2 text-sm text-ink-muted">
+ Loading groups…
+ </p>
+ </Match>
+ <Match when={groups.isError}>
+ <LoadFailure what="your groups" onRetry={groups.refetch} />
+ </Match>
+ </Switch>
<ConfirmDialog
open={confirmingDisconnect()}
onOpenChange={setConfirmingDisconnect}
@@ -214,55 +227,6 @@ export function WhatsAppPage(props: {
)}
</Match>
</Switch>
- <Show
- when={
- whatsapp.sharedGroups.data?.filter(
- (group) =>
- !connected() ||
- !groups.data?.some((remote) => remote.group?.id === group.id)
- ).length
- }
- >
- <section
- aria-label="Shared WhatsApp groups"
- class="flex flex-col gap-2"
- >
- <h2 class="px-3 text-xs font-medium text-ink-subtle">
- Groups in Macro
- </h2>
- <For
- each={whatsapp.sharedGroups.data?.filter(
- (group) =>
- !connected() ||
- !groups.data?.some((remote) => remote.group?.id === group.id)
- )}
- >
- {(group) => (
- <Button
- variant="ghost"
- class="justify-between"
- onClick={() => whatsapp.openGroup(group.id)}
- >
- <span class="truncate">{group.name}</span>
- <Show when={group.unreadCount}>
- <span
- aria-label={`${group.unreadCount} unread messages`}
- class="rounded-full bg-accent px-2 text-xs text-panel"
- >
- {group.unreadCount}
- </span>
- </Show>
- </Button>
- )}
- </For>
- </section>
- </Show>
- <Show when={whatsapp.sharedGroups.isError}>
- <LoadFailure
- what="groups shared with you"
- onRetry={whatsapp.sharedGroups.refetch}
- />
- </Show>
<PairingDialog
open={pairing.open()}
step={pairing.step()}
@@ -276,13 +240,6 @@ export function WhatsAppPage(props: {
onRetry={pairing.retry}
onCancel={pairing.cancel}
/>
- <AddGroupDialog
- group={adding()}
- pending={whatsapp.isAdopting()}
- error={addError()}
- onSubmit={adopt}
- onClose={() => setAdding(undefined)}
- />
</div>
);
}
diff --git a/apps/web/src/features/whatsapp-linked/whatsapp-linked.tsx b/apps/web/src/features/whatsapp-linked/whatsapp-linked.tsx
index 3f134f3fd3..8713b4982e 100644
--- a/apps/web/src/features/whatsapp-linked/whatsapp-linked.tsx
+++ b/apps/web/src/features/whatsapp-linked/whatsapp-linked.tsx
@@ -1,5 +1,5 @@
import { useNavigate } from '@app/lib/split-router';
-import { whatsappGroupRoute } from '@app/routes/routes';
+import { externalWhatsappGroupRoute } from '@app/routes/routes';
import { WhatsAppLinkedProvider } from './context/whatsapp-linked-context';
import { createWhatsAppLinkedCapabilities } from './queries/production-capabilities';
import { WhatsAppPage } from './views/whatsapp-page';
@@ -9,7 +9,7 @@ export function WhatsAppLinked(props: { resumePairingId?: string }) {
const navigate = useNavigate();
const capabilities = createWhatsAppLinkedCapabilities({
openGroup: (groupId) =>
- navigate({ route: whatsappGroupRoute, params: { groupId } }),
+ navigate({ route: externalWhatsappGroupRoute, params: { groupId } }),
});
return (
<WhatsAppLinkedProvider value={capabilities}>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
index c1193800b2..6423f7483a 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
@@ -1,8 +1,10 @@
import { parseLocalDate } from '@app/features/calendar/utils/calendar-date';
import { calendarMentionOpen } from '@app/features/calendar-view/mention-open-target';
import { openCalendarEventSplit } from '@app/features/calendar-view/open-calendar-event';
+import { whatsappGroupContent } from '@app/features/external-view/hosted-content';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
+import { useSplitLayout } from '@components/app/split-layout/layout';
import {
type BlockAlias,
type BlockName,
@@ -435,6 +437,9 @@ export function DocumentMention(props: DocumentMentionDecoratorProps) {
<Match when={props.blockName === 'skill'}>
<SkillDocumentMention {...props} />
</Match>
+ <Match when={props.blockName === 'whatsapp_group'}>
+ <WhatsAppGroupMention {...props} />
+ </Match>
</Switch>
);
}
@@ -779,6 +784,48 @@ function FormMention(props: DocumentMentionDecoratorProps) {
);
}
+/**
+ * A WhatsApp group: not a previewable document, so it shows its stored name
+ * and opens inside External.
+ */
+function WhatsAppGroupMention(props: DocumentMentionDecoratorProps) {
+ const { openWithSplit } = useSplitLayout();
+ const open = (event: MouseEvent | KeyboardEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openWithSplit(whatsappGroupContent(props.documentId), {
+ preferNewSplit: openInNewSplitForMention(event.shiftKey, true),
+ });
+ };
+ return (
+ <span
+ class="rounded-xs hover:bg-hover focus-visible:outline-2 focus-visible:outline-ink/30"
+ role="link"
+ tabIndex={0}
+ on:mousedown={(event) => event.preventDefault()}
+ on:click={open}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') open(event);
+ }}
+ >
+ <MentionContainer
+ icon={<EntityIcon targetType="whatsapp_group" size="fill" />}
+ collapsed={props.collapsed}
+ text={
+ <span
+ data-document-mention="true"
+ data-document-id={props.documentId}
+ data-block-name="whatsapp_group"
+ data-document-name={props.documentName}
+ >
+ {props.documentName || 'WhatsApp group'}
+ </span>
+ }
+ />
+ </span>
+ );
+}
+
function SkillDocumentMention(props: DocumentMentionDecoratorProps) {
const systemSkills = useSystemSkillsQuery();
return (
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/WhatsAppGroupMention.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/WhatsAppGroupMention.test.tsx
new file mode 100644
index 0000000000..110042287e
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/WhatsAppGroupMention.test.tsx
@@ -0,0 +1,47 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, expect, it, vi } from 'vitest';
+import { DocumentMention } from './DocumentMention';
+
+const mocks = vi.hoisted(() => ({ openWithSplit: vi.fn() }));
+vi.mock('@components/app/split-layout/layout', () => ({
+ useSplitLayout: () => ({ openWithSplit: mocks.openWithSplit }),
+}));
+vi.mock('@core/component/EntityIcon', () => ({ EntityIcon: () => null }));
+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));
+
+afterEach(() => {
+ cleanup();
+ mocks.openWithSplit.mockClear();
+});
+
+it('shows a WhatsApp group mention by name and opens it inside External', () => {
+ render(() => (
+ <DocumentMention
+ key="node-1"
+ documentId="01a16445-9fdc-7bb1-80b4-8935a1243c98"
+ documentName="Design Crit"
+ blockName="whatsapp_group"
+ theme={{}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('link', { name: /Design Crit/ }));
+ expect(mocks.openWithSplit).toHaveBeenCalledWith(
+ {
+ type: 'component',
+ id: 'external',
+ entryMetadata: {
+ route: {
+ matches: [
+ { id: 'app', params: {} },
+ { id: 'view-external', params: {} },
+ {
+ id: 'external-whatsapp-group',
+ params: { groupId: '01a16445-9fdc-7bb1-80b4-8935a1243c98' },
+ },
+ ],
+ },
+ },
+ },
+ { preferNewSplit: true }
+ );
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx
index 1b4a320a93..a28f54f166 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx
@@ -11,6 +11,8 @@ import * as mobileSort from './utils/mobileSort';
const mocks = vi.hoisted(() => ({
crmEnabled: false,
+ whatsappEnabled: false,
+ whatsappUserIds: [] as string[],
mobile: false,
requestedBuckets: [] as string[],
contacts: [] as import('@core/context/quickAccess').EntityItem[],
@@ -41,10 +43,34 @@ vi.mock('@core/block', () => ({
useMaybeBlockId: () => undefined,
useMaybeBlockName: () => undefined,
}));
-vi.mock('@core/constant/featureFlags', () => ({
- enableCrm: {},
- isFeatureEnabled: () => mocks.crmEnabled,
- ENABLE_BEARER_TOKEN_AUTH: false,
+vi.mock('@core/constant/featureFlags', () => {
+ const enableCrm = { name: 'crm' };
+ const enableWhatsappLinked = { name: 'whatsapp' };
+ return {
+ enableCrm,
+ enableWhatsappLinked,
+ isFeatureEnabled: (flag: unknown) =>
+ flag === enableWhatsappLinked ? mocks.whatsappEnabled : mocks.crmEnabled,
+ ENABLE_BEARER_TOKEN_AUTH: false,
+ };
+});
+vi.mock('@app/features/whatsapp-group/queries/production-api', () => ({
+ whatsappGroupApi: {},
+}));
+vi.mock('@queries/gate', () => ({
+ queryReadyGate: (query: { isSuccess: boolean }) => query.isSuccess,
+}));
+vi.mock('@queries/whatsapp-groups', () => ({
+ useWhatsappGroupsQuery: (_api: unknown, userId: () => string) => ({
+ get isSuccess() {
+ mocks.whatsappUserIds.push(userId());
+ return userId() !== '';
+ },
+ data: [
+ { id: 'group-1', name: 'Design Crit', unreadCount: 0, canSend: true },
+ { id: 'group-2', name: 'Launch Room', unreadCount: 0, canSend: true },
+ ],
+ }),
}));
vi.mock('@core/context/quickAccess', () => ({
useQuickAccess: () => ({
@@ -70,6 +96,7 @@ vi.mock('@core/context/quickAccess', () => ({
}));
vi.mock('@core/context/user', () => ({
useEmail: () => () => '[email protected]',
+ useUserId: () => () => 'macro|[email protected]',
}));
vi.mock('@core/constant/allBlocks', () => ({
fileTypeToBlockName: () => 'md',
@@ -126,6 +153,8 @@ const manyUsers: IUser[] = Array.from({ length: 20 }, (_, i) => ({
afterEach(() => {
mocks.crmEnabled = false;
+ mocks.whatsappEnabled = false;
+ mocks.whatsappUserIds = [];
mocks.mobile = false;
mocks.requestedBuckets = [];
mocks.contacts = [];
@@ -426,3 +455,43 @@ it('records mentions against the editing source outside a legacy block', () => {
expect.objectContaining({ blockId: 'doc-1' })
);
});
+
+it('offers WhatsApp groups to share by mention, only in channel composers', () => {
+ mocks.whatsappEnabled = true;
+ Element.prototype.scrollIntoView = vi.fn();
+ vi.mocked(useEmailSearchMention).mockReturnValue({
+ emails: () => [],
+ totalCount: () => 0,
+ hasMore: () => false,
+ isLoadingMore: () => false,
+ loadMore: async () => {},
+ } as unknown as ReturnType<typeof useEmailSearchMention>);
+ const menu = createMenuOperations();
+ menu.openMenu();
+ menu.setSearchTerm('design');
+ render(() => (
+ <MentionsMenu
+ menu={menu}
+ users={() => []}
+ block="channel"
+ anchor={document.createElement('div')}
+ onPick={vi.fn()}
+ />
+ ));
+ expect(screen.getByText('WhatsApp groups')).toBeTruthy();
+ expect(screen.getByText('Design Crit')).toBeTruthy();
+ expect(screen.queryByText('Launch Room')).toBeNull();
+ cleanup();
+
+ mocks.whatsappUserIds = [];
+ render(() => (
+ <MentionsMenu
+ menu={menu}
+ users={() => []}
+ anchor={document.createElement('div')}
+ onPick={vi.fn()}
+ />
+ ));
+ expect(screen.queryByText('WhatsApp groups')).toBeNull();
+ expect(mocks.whatsappUserIds.every((id) => id === '')).toBe(true);
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
index 85fd08259f..d8a5fd88ef 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
@@ -1,16 +1,22 @@
import { useCrmContactMentionSource } from '@app/features/crm/record-adapter';
+import { whatsappGroupApi } from '@app/features/whatsapp-group/queries/production-api';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { globalSplitManager } from '@app/signal/splitLayout';
import type { BlockName } from '@core/block';
import { useMaybeBlockId, useMaybeBlockName } from '@core/block';
import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';
import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';
-import { enableCrm, isFeatureEnabled } from '@core/constant/featureFlags';
+import {
+ enableCrm,
+ enableWhatsappLinked,
+ isFeatureEnabled,
+} from '@core/constant/featureFlags';
import {
type EntityBucket,
type EntityItem,
useQuickAccess,
} from '@core/context/quickAccess';
+import { useUserId } from '@core/context/user';
import clickOutside from '@core/directive/clickOutside';
import { isMobile } from '@core/mobile/isMobile';
import type { ChannelWithParticipants, IUser } from '@core/user';
@@ -20,7 +26,9 @@ import { fireAndForget } from '@core/util/fireAndForget';
import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
import type { EmailEntity } from '@entity';
import { Telemetry } from '@macro-inc/observability';
+import { queryReadyGate } from '@queries/gate';
import type { HistoryItem as Item } from '@queries/history/history';
+import { useWhatsappGroupsQuery } from '@queries/whatsapp-groups';
import { Key } from '@solid-primitives/keyed';
import { createLazyMemo } from '@solid-primitives/memo';
import { createVirtualizer } from '@tanstack/solid-virtual';
@@ -47,6 +55,7 @@ import type {
DateMentionItem,
MentionItem,
UserMentionRecord,
+ WhatsAppGroupMentionItem,
} from '../../../utils/mentionsUtils';
import { useMenuKeyboardNavigation } from '../useMenuKeyboardNavigation';
import { ItemBin } from './components/ItemBin';
@@ -255,6 +264,30 @@ function MentionsMenuInner(props: MentionsMenuProps) {
enabled: () => !props.sources || props.sources.includes('emails'),
});
+ // A WhatsApp group mentioned in a channel is shared with its members.
+ const whatsappGroupsEnabled = () =>
+ !hasCustomEntities() &&
+ props.block === 'channel' &&
+ props.menu.isOpen() &&
+ isFeatureEnabled(enableWhatsappLinked) &&
+ (!props.sources || props.sources.includes('whatsappGroups'));
+ const userId = useUserId();
+ const whatsappGroupsQuery = useWhatsappGroupsQuery(whatsappGroupApi, () =>
+ whatsappGroupsEnabled() ? (userId() ?? '') : ''
+ );
+ const whatsappGroups = createLazyMemo((): WhatsAppGroupMentionItem[] => {
+ if (!whatsappGroupsEnabled() || !queryReadyGate(whatsappGroupsQuery))
+ return [];
+ const term = searchTerm().trim().toLocaleLowerCase();
+ return whatsappGroupsQuery.data
+ .filter((group) => group.name.toLocaleLowerCase().includes(term))
+ .map((group) => ({
+ kind: 'whatsappGroup',
+ id: group.id,
+ data: { id: group.id, name: group.name },
+ }));
+ });
+
const dateOptions = useDateSearch({ query: searchTerm });
const dates = createLazyMemo((): DateMentionItem[] => {
return dateOptions().map(
@@ -341,6 +374,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {
...users,
...(sourceEnabled('documents') ? (docs() ?? []) : []),
...(sourceEnabled('channels') ? (channels() ?? []) : []),
+ ...whatsappGroups(),
...(sourceEnabled('agentSessions') ? agentSessions() : []),
...(sourceEnabled('companies') ? (companies() ?? []) : []),
...(sourceEnabled('emails') ? (emails() ?? []) : []),
@@ -367,6 +401,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {
(sourceEnabled('documents') ? docsMention.totalCount() : 0) +
(sourceEnabled('agentSessions') ? agentSessions().length : 0) +
(sourceEnabled('channels') ? channelsMention.totalCount() : 0) +
+ whatsappGroups().length +
(sourceEnabled('companies')
? (companyMention?.totalCount() ?? 0)
: 0) +
@@ -447,6 +482,12 @@ function MentionsMenuInner(props: MentionsMenuProps) {
isLoadingMore: channelsMention.isLoadingMore,
loadMore: channelsMention.loadMore,
},
+ {
+ id: 'whatsappGroups',
+ label: 'WhatsApp groups',
+ getData: whatsappGroups,
+ getFullCount: () => whatsappGroups().length,
+ },
{
id: 'agentSessions',
label: 'Recent agent sessions',
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
index cd17d1342e..1c18e8d9fb 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
@@ -7,6 +7,7 @@ export type MentionBucketId =
| 'all'
| 'users'
| 'documents'
+ | 'whatsappGroups'
| 'agentSessions'
| 'channels'
| 'companies'
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx
index 6e19a48733..685de8d04d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx
@@ -82,6 +82,8 @@ export function MentionsMenuItem(props: {
case 'bookingLink':
return <CalendarBlankIcon class="size-4 text-accent" />;
+ case 'whatsappGroup':
+ return <EntityIcon targetType="whatsapp_group" size="xs" />;
case 'calendarEvent':
return <EntityIcon targetType="calendar" size="xs" />;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts
index 7fa09ecf75..bf639f333d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts
@@ -61,5 +61,7 @@ export function getMentionItemName(item: MentionItem): string {
return item.data.title;
case 'entity':
return item.data.name ?? (item.bucket === 'email' ? 'No Subject' : '');
+ case 'whatsappGroup':
+ return item.data.name;
}
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts
index c2a200a04d..3a001fec72 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts
@@ -215,6 +215,21 @@ async function handleCalendarEventMention(
});
}
+/**
+ * Insert a WhatsApp group chip. Posting it in a channel shares the group with
+ * the channel's members; nothing else tracks or attaches it.
+ */
+async function handleWhatsAppGroupMention(
+ group: { id: string; name: string },
+ dependencies: HandlerDependencies
+): Promise<void> {
+ dependencies.editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
+ documentId: group.id,
+ documentName: group.name,
+ blockName: 'whatsapp_group',
+ });
+}
+
/**
* Creates a handler for MentionItem selection.
*/
@@ -243,6 +258,8 @@ export function createItemHandler(dependencies: HandlerDependencies) {
return await handleCalendarEventMention(item, dependencies);
case 'entity':
return await handleEntityMention(item, dependencies);
+ case 'whatsappGroup':
+ return await handleWhatsAppGroupMention(item.data, dependencies);
}
};
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.ts
index 0efc47a606..ed5265ad95 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.ts
@@ -6,6 +6,7 @@ function getMentionName(item: MentionItem): string {
if (item.kind === 'group') return item.data.groupAlias;
if (item.kind === 'bookingLink' || item.kind === 'calendarEvent')
return item.data.title;
+ if (item.kind === 'whatsappGroup') return item.data.name;
return item.searchText;
}
@@ -14,7 +15,8 @@ function getMentionTimestamps(item: MentionItem) {
item.kind === 'date' ||
item.kind === 'group' ||
item.kind === 'bookingLink' ||
- item.kind === 'calendarEvent'
+ item.kind === 'calendarEvent' ||
+ item.kind === 'whatsappGroup'
)
return {};
return item.timestamps;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts
index 891c869f6d..8573ca9cc4 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts
@@ -98,6 +98,25 @@ describe('mentionsPlugin', () => {
);
});
+ it('tracks a WhatsApp group mention as a whatsapp_group reference', () => {
+ const { editor, created } = composer();
+ discrete(editor, () => {
+ $getRoot().append($createParagraphNode()).selectEnd();
+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
+ documentId: 'group-1',
+ documentName: 'Design Crit',
+ blockName: 'whatsapp_group',
+ });
+ });
+ expect(created).toContainEqual(
+ expect.objectContaining({
+ itemType: 'whatsapp_group',
+ itemId: 'group-1',
+ documentName: 'Design Crit',
+ })
+ );
+ });
+
it('keeps database mentions compact in composers', () => {
const { editor } = composer();
discrete(editor, () => {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
index fc4c9928ec..a98e03ea39 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
@@ -164,7 +164,8 @@ export type ItemMention = {
| 'crm_company'
| 'crm_contact'
| 'crm_pipeline'
- | 'skill';
+ | 'skill'
+ | 'whatsapp_group';
itemId: string;
fileType?: string;
documentName?: string;
@@ -262,6 +263,10 @@ function $mentionItemFromNode(node: MentionNode): ItemMention {
} else if (blockName === 'pipeline') {
fileType = 'pipeline';
itemType = 'crm_pipeline';
+ } else if (blockName === 'whatsapp_group') {
+ // Posting it shares the group with the channel's members.
+ fileType = 'whatsapp_group';
+ itemType = 'whatsapp_group';
} else if (blockName === 'unknown') {
fileType = 'unknown';
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts
index 7363b6bcea..7202176017 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts
@@ -418,13 +418,21 @@ export type AgentSessionMentionItem = Omit<
'kind'
> & { kind: 'agentSession' };
+/** A WhatsApp group in Macro; not a Soup entity, so it has its own kind. */
+export type WhatsAppGroupMentionItem = {
+ kind: 'whatsappGroup';
+ id: string;
+ data: { id: string; name: string };
+};
+
export type MentionItem =
| QuickAccessItem
| DateMentionItem
| GroupMentionItem
| AgentSessionMentionItem
| BookingLinkMentionItem
- | CalendarEventMentionItem;
+ | CalendarEventMentionItem
+ | WhatsAppGroupMentionItem;
/**
* Type guard for DateMentionItem.
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
index 250e365037..12c08d9d88 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
@@ -180,7 +180,7 @@ type ShareBlockType = BlockName | BlockAlias | 'initiative' | 'whatsapp_group';
function shareUrl(type: ShareBlockType, id: string): string {
if (type === 'whatsapp_group')
- return buildSimpleEntityUrl({ type: 'whatsapp-group', id });
+ return buildSimpleEntityUrl({ type: 'external/whatsapp', id });
if (type !== 'initiative') return buildSimpleEntityUrl({ type, id });
return buildSimpleEntityUrl({
type: 'component',
diff --git a/apps/web/src/lib/core/messages/configured-message-editor.ts b/apps/web/src/lib/core/messages/configured-message-editor.ts
index e2a4c9ad0c..86530c2ae4 100644
--- a/apps/web/src/lib/core/messages/configured-message-editor.ts
+++ b/apps/web/src/lib/core/messages/configured-message-editor.ts
@@ -36,6 +36,8 @@ export type MessageEditorOptions = {
files: FileSystemFileEntry[],
directories: FileSystemDirectoryEntry[]
) => void;
+ /** Shared slash actions a surface can't carry, e.g. tables in a WhatsApp group. */
+ ignoreActionIds?: string[];
/** Slash actions a surface adds beyond the shared set, e.g. a channel's `/poll`. */
additionalActions?: Action[];
/** Invoked when the user picks the "Image" slash action. Opens a file picker and hands files back. */
@@ -69,9 +71,10 @@ export function createConfiguredMessageEditor(options: MessageEditorOptions) {
editor
.withEmojis()
.withActions({
- ignoreActionIds: options.inlineMedia
- ? ['hr', 'table', 'latex']
- : ['hr', 'latex'],
+ ignoreActionIds: [
+ ...(options.inlineMedia ? ['hr', 'table', 'latex'] : ['hr', 'latex']),
+ ...(options.ignoreActionIds ?? []),
+ ],
})
.withLinks({ floatingMenu: true, autoLinkMatchMode: 'common-tlds' })
.withHistory({ timeGap: 400 })
diff --git a/apps/web/src/lib/queries/whatsapp-groups/index.ts b/apps/web/src/lib/queries/whatsapp-groups/index.ts
index 6452c67a20..0ed25a4624 100644
--- a/apps/web/src/lib/queries/whatsapp-groups/index.ts
+++ b/apps/web/src/lib/queries/whatsapp-groups/index.ts
@@ -3,18 +3,18 @@ import type {
GroupSend,
GroupSummary,
MessagePage,
- PendingSend,
+ SendFailure,
+ SendProgress,
} from '@app/features/whatsapp-group/core/group';
import {
infiniteQueryOptions,
queryOptions,
useInfiniteQuery,
- useMutation,
useQuery,
} from '@tanstack/solid-query';
+import type { Result } from 'neverthrow';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
-import { whatsappOperation } from '../whatsapp-linked/operation';
import { whatsappGroupsKeys } from './keys';
/** Decoded group operations. Production decodes generated DSS types before this seam. */
@@ -22,28 +22,30 @@ export type WhatsAppGroupApi = {
list: () => Promise<GroupSummary[]>;
detail: (groupId: string) => Promise<GroupDetail>;
messages: (groupId: string, before?: string) => Promise<MessagePage>;
- sends: (groupId: string) => Promise<PendingSend[]>;
+ /** Records one deliberate send; DSS dedupes by the idempotency key. */
send: (
groupId: string,
request: GroupSend,
idempotencyKey: string
- ) => Promise<unknown>;
+ ) => Promise<Result<SendProgress, SendFailure>>;
+ /** The caller's progress for recorded sends, by send id. */
+ delivery: (groupId: string, sendIds: string[]) => Promise<SendProgress[]>;
upload: (
groupId: string,
file: File
- ) => Promise<{ uploadId: string; audio: boolean }>;
+ ) => Promise<Result<{ uploadId: string; audio: boolean }, SendFailure>>;
markRead: (groupId: string, messageId: string) => Promise<unknown>;
stopSync: (groupId: string) => Promise<unknown>;
};
+// DSS pushes `whatsapp_changed` through the connection gateway (`./sync`);
+// these reads do not poll.
function listOptions(api: WhatsAppGroupApi, userId: string) {
return queryOptions({
queryKey: whatsappGroupsKeys.list(userId).queryKey,
queryFn: api.list,
enabled: !!userId,
staleTime: 5000,
- refetchInterval: 15000,
- refetchIntervalInBackground: false,
throwOnError: false,
});
}
@@ -53,8 +55,6 @@ function detailOptions(api: WhatsAppGroupApi, userId: string, groupId: string) {
queryFn: () => api.detail(groupId),
enabled: !!userId && !!groupId,
staleTime: 5000,
- refetchInterval: 15000,
- refetchIntervalInBackground: false,
throwOnError: false,
});
}
@@ -70,18 +70,25 @@ function messagesOptions(
getNextPageParam: (page) => page.before,
enabled: !!userId && !!groupId,
staleTime: 0,
- refetchInterval: 5000,
- refetchIntervalInBackground: false,
throwOnError: false,
});
}
-function sendsOptions(api: WhatsAppGroupApi, userId: string, groupId: string) {
+/** Outcomes of this viewer's in-flight sends; checked again on every push. */
+const DELIVERY_CHECK_MS = 5000;
+function deliveryOptions(
+ api: WhatsAppGroupApi,
+ userId: string,
+ groupId: string,
+ sendIds: string[]
+) {
return queryOptions({
- queryKey: whatsappGroupsKeys.sends(userId, groupId).queryKey,
- queryFn: () => api.sends(groupId),
- enabled: !!userId && !!groupId,
+ queryKey: whatsappGroupsKeys.delivery(userId, groupId)._ctx.sends(sendIds)
+ .queryKey,
+ queryFn: () => api.delivery(groupId, sendIds),
+ enabled: !!userId && !!groupId && sendIds.length > 0,
staleTime: 0,
- refetchInterval: 5000,
+ // A missed push must not leave a sent message pending forever.
+ refetchInterval: DELIVERY_CHECK_MS,
refetchIntervalInBackground: false,
throwOnError: false,
});
@@ -101,35 +108,33 @@ export function useWhatsappGroupQueries(
const messages = useInfiniteQuery(() =>
messagesOptions(api, userId(), groupId())
);
- const sends = useQuery(() => sendsOptions(api, userId(), groupId()));
- const send = useMutation(() => ({
- mutationFn: (input: {
- userId: string;
- groupId: string;
- request: GroupSend;
- idempotencyKey: string;
- }) =>
- whatsappOperation(
- 'group.send',
- () => api.send(input.groupId, input.request, input.idempotencyKey),
- input.groupId
- ),
- // Pending/unknown sends refresh independently; never retry a write.
- retry: false,
- onSuccess: (_result, input) =>
- Promise.all([
- queryClient.invalidateQueries({
- queryKey: whatsappGroupsKeys.sends(input.userId, input.groupId)
- .queryKey,
- }),
- queryClient.invalidateQueries({
- queryKey: whatsappGroupsKeys.messages(input.userId, input.groupId)
- .queryKey,
- }),
- ]),
- }));
- return { group, messages, sends, send };
+ return { group, messages };
+}
+export function useWhatsappGroupDeliveryQuery(
+ api: WhatsAppGroupApi,
+ userId: Accessor<string>,
+ groupId: Accessor<string>,
+ sendIds: Accessor<string[]>
+) {
+ return useQuery(() => deliveryOptions(api, userId(), groupId(), sendIds()));
+}
+/** Unread counts and names in every group list. */
+export function invalidateWhatsappGroupList() {
+ return queryClient.invalidateQueries({
+ queryKey: whatsappGroupsKeys.list._def,
+ });
}
export function invalidateWhatsappGroups() {
return queryClient.invalidateQueries({ queryKey: whatsappGroupsKeys._def });
}
+/** A send was recorded: its row and the group's place in lists follow. */
+export function refreshWhatsappGroupTimeline(userId: string, groupId: string) {
+ return Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: whatsappGroupsKeys.messages(userId, groupId).queryKey,
+ }),
+ queryClient.invalidateQueries({
+ queryKey: whatsappGroupsKeys.delivery(userId, groupId).queryKey,
+ }),
+ ]);
+}
diff --git a/apps/web/src/lib/queries/whatsapp-groups/keys.ts b/apps/web/src/lib/queries/whatsapp-groups/keys.ts
index 1198a85f04..482ae749af 100644
--- a/apps/web/src/lib/queries/whatsapp-groups/keys.ts
+++ b/apps/web/src/lib/queries/whatsapp-groups/keys.ts
@@ -5,5 +5,10 @@ export const whatsappGroupsKeys = createQueryKeys('whatsapp-groups', {
list: (userId: string) => [userId],
detail: (userId: string, groupId: string) => [userId, groupId],
messages: (userId: string, groupId: string) => [userId, groupId],
- sends: (userId: string, groupId: string) => [userId, groupId],
+ delivery: (userId: string, groupId: string) => ({
+ queryKey: [userId, groupId],
+ contextQueries: {
+ sends: (sendIds: string[]) => ({ queryKey: [sendIds] }),
+ },
+ }),
});
diff --git a/apps/web/src/lib/queries/whatsapp-groups/sync.ts b/apps/web/src/lib/queries/whatsapp-groups/sync.ts
new file mode 100644
index 0000000000..41eec0ca94
--- /dev/null
+++ b/apps/web/src/lib/queries/whatsapp-groups/sync.ts
@@ -0,0 +1,100 @@
+/** Gateway liveness for WhatsApp, apart from `./index` to keep the websocket out of startup. */
+
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
+import { createConnectionWebsocketEffect } from '@service-connection/websocket';
+import { debounce } from '@solid-primitives/scheduled';
+import type { Accessor } from 'solid-js';
+import { z } from 'zod';
+import { queryClient } from '../client';
+import { parseMessageData } from '../storage/databases-sync';
+import { whatsappLinkedKeys } from '../whatsapp-linked/keys';
+import { whatsappGroupsKeys } from './keys';
+
+/** DSS pings this with no data; readers re-fetch. */
+const WHATSAPP_CHANGED_MESSAGE_TYPE = 'whatsapp_changed';
+const whatsappChangedSchema = z.discriminatedUnion('scope', [
+ z.object({ scope: z.literal('groups') }),
+ z.object({ scope: z.literal('group'), group_id: z.string() }),
+]);
+type WhatsappChange = z.infer<typeof whatsappChangedSchema>;
+
+/**
+ * Opening a page asks DSS for a WhatsApp refresh that can finish before this
+ * subscription exists; without a push by then, re-fetch once.
+ */
+const WHATSAPP_FALLBACK_REFETCH_MS = 3000;
+
+function onWhatsappChanged(handle: (change: WhatsappChange) => void) {
+ createConnectionWebsocketEffect((message) => {
+ if (message.type !== WHATSAPP_CHANGED_MESSAGE_TYPE) return;
+ const change = parseMessageData(message, whatsappChangedSchema);
+ if (change) handle(change);
+ });
+}
+
+/** Schedules one re-fetch, cleared by the first push or by unmount. */
+function fallbackRefetch(refetch: () => void) {
+ const scheduled = debounce(refetch, WHATSAPP_FALLBACK_REFETCH_MS);
+ scheduled();
+ return scheduled.clear;
+}
+
+const refreshGroupLists = () =>
+ Promise.all([
+ queryClient.invalidateQueries({ queryKey: whatsappLinkedKeys.groups._def }),
+ queryClient.invalidateQueries({ queryKey: whatsappGroupsKeys.list._def }),
+ ]);
+
+/**
+ * While External is open: the owner's WhatsApp groups (`groups`) and every
+ * readable group's summary (`group`, for unread counts and names).
+ */
+export function useWhatsappGroupListsSync() {
+ const cancel = fallbackRefetch(() =>
+ fireAndForget(
+ Telemetry.span('whatsapp.groups.fallback_refetch', refreshGroupLists),
+ 'whatsapp-sync'
+ )
+ );
+ onWhatsappChanged((change) => {
+ cancel();
+ if (change.scope === 'groups') {
+ queryClient.invalidateQueries({
+ queryKey: whatsappLinkedKeys.groups._def,
+ });
+ }
+ queryClient.invalidateQueries({ queryKey: whatsappGroupsKeys.list._def });
+ });
+}
+
+function refreshGroup(userId: string, groupId: string) {
+ return Promise.all(
+ [
+ whatsappGroupsKeys.detail(userId, groupId).queryKey,
+ whatsappGroupsKeys.messages(userId, groupId).queryKey,
+ whatsappGroupsKeys.delivery(userId, groupId).queryKey,
+ ].map((queryKey) => queryClient.invalidateQueries({ queryKey }))
+ );
+}
+
+/** While one group is open: its roster, timeline and send outcomes. */
+export function useWhatsappGroupSync(
+ userId: Accessor<string>,
+ groupId: Accessor<string>
+) {
+ const cancel = fallbackRefetch(() =>
+ fireAndForget(
+ Telemetry.span('whatsapp.group.fallback_refetch', (span) => {
+ span.setAttr('whatsapp.group.id', groupId());
+ return refreshGroup(userId(), groupId());
+ }),
+ 'whatsapp-sync'
+ )
+ );
+ onWhatsappChanged((change) => {
+ if (change.scope !== 'group' || change.group_id !== groupId()) return;
+ cancel();
+ fireAndForget(refreshGroup(userId(), groupId()), 'whatsapp-sync');
+ });
+}
diff --git a/apps/web/src/lib/queries/whatsapp-linked/operation.ts b/apps/web/src/lib/queries/whatsapp-linked/operation.ts
index 42ef846ade..6b68f255f6 100644
--- a/apps/web/src/lib/queries/whatsapp-linked/operation.ts
+++ b/apps/web/src/lib/queries/whatsapp-linked/operation.ts
@@ -1,4 +1,5 @@
import { Telemetry } from '@macro-inc/observability';
+import { type Accessor, createEffect, onCleanup } from 'solid-js';
/** Keep server error bodies and pairing material out of operation telemetry. */
export function whatsappOperation<T>(
@@ -18,3 +19,36 @@ export function whatsappOperation<T>(
}
});
}
+
+export type WhatsappLoadResult = {
+ outcome: 'success' | 'error';
+ /** Opaque ids and counts only. */
+ attrs?: Record<string, string | number | boolean>;
+};
+
+/**
+ * One span from mount until `settled` first reports an outcome, such as a
+ * page whose reads have all loaded; unmounting first records `abandoned`.
+ */
+export function traceWhatsappLoad(
+ name: string,
+ settled: Accessor<WhatsappLoadResult | undefined>
+) {
+ const span = Telemetry.span(`whatsapp.${name}`);
+ let ended = false;
+ const end = (result: WhatsappLoadResult | { outcome: 'abandoned' }) => {
+ if (ended) return;
+ ended = true;
+ span.setAttr('whatsapp.outcome', result.outcome);
+ if ('attrs' in result)
+ for (const [key, value] of Object.entries(result.attrs ?? {}))
+ span.setAttr(key, value);
+ if (result.outcome === 'error') span.error(`WhatsApp ${name} failed`);
+ span.end();
+ };
+ createEffect(() => {
+ const result = settled();
+ if (result) end(result);
+ });
+ onCleanup(() => end({ outcome: 'abandoned' }));
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/whatsapp-errors.ts b/apps/web/src/lib/service-clients/service-storage/whatsapp-errors.ts
new file mode 100644
index 0000000000..44896dca5d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/whatsapp-errors.ts
@@ -0,0 +1,37 @@
+import type { ResultError } from '@core/util/result';
+import { type BaseFetchErrorCode, statusError } from '@core/util/safeFetch';
+import { z } from 'zod';
+
+/** `LinkedError::code()` in `crates/whatsapp_linked`; DSS answers `{ code, message }`. */
+export const whatsappErrorCodes = [
+ 'invalid_input',
+ 'configuration_required',
+ 'not_found',
+ 'forbidden',
+ 'conflict',
+ 'disconnected',
+ 'identity_conflict',
+ 'send_expired',
+ 'lease_fenced',
+ 'rate_limited',
+ 'temporarily_unavailable',
+] as const;
+export type WhatsAppErrorCode = (typeof whatsappErrorCodes)[number];
+
+const whatsappErrorBody = z.object({
+ code: z.enum(whatsappErrorCodes),
+ message: z.string(),
+});
+
+/** Keeps DSS's WhatsApp error code and wording; other failures keep the status error. */
+export async function whatsappErrorResponse(
+ response: Response
+): Promise<ResultError<WhatsAppErrorCode | BaseFetchErrorCode>> {
+ try {
+ const body = whatsappErrorBody.safeParse(await response.json());
+ if (body.success) return body.data;
+ } catch {
+ // Not a WhatsApp error body, such as a gateway timeout page.
+ }
+ return statusError(response.status);
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/whatsapp-groups.ts b/apps/web/src/lib/service-clients/service-storage/whatsapp-groups.ts
index e84519c8db..3bc43ef0fb 100644
--- a/apps/web/src/lib/service-clients/service-storage/whatsapp-groups.ts
+++ b/apps/web/src/lib/service-clients/service-storage/whatsapp-groups.ts
@@ -1,4 +1,7 @@
/** Independent WhatsApp group entity API; no channel endpoints or context. */
+import { SERVER_HOSTS } from '@core/constant/servers';
+import { fetchWithToken } from '@core/util/fetchWithToken';
+import type { ObjectLike } from '@core/util/result';
import { dssFetch } from './client';
import type {
LinkedSendProgress,
@@ -10,9 +13,21 @@ import type {
WhatsAppGroupMessages,
WhatsAppGroupSummary,
} from './generated/schemas';
+import {
+ type WhatsAppErrorCode,
+ whatsappErrorResponse,
+} from './whatsapp-errors';
const root = '/meta/linked/whatsapp-groups';
const group = (id: string) => `${root}/${encodeURIComponent(id)}`;
+
+/** Writes keep DSS's error code: a refusal is reported, an unknown outcome retried. */
+function write<T extends ObjectLike>(path: string, body: BodyInit) {
+ return fetchWithToken<T, WhatsAppErrorCode>(
+ `${SERVER_HOSTS['document-storage-service']}${path}`,
+ { method: 'POST', body, errorResponseHandler: whatsappErrorResponse }
+ );
+}
export const whatsappGroupsClient = {
list: () => dssFetch<WhatsAppGroupSummary[]>(root),
detail: (id: string) => dssFetch<WhatsAppGroupDetail>(group(id)),
@@ -21,19 +36,18 @@ export const whatsappGroupsClient = {
if (before) params.set('before', before);
return dssFetch<WhatsAppGroupMessages>(`${group(id)}/messages?${params}`);
},
- sends: (id: string) => dssFetch<LinkedSendProgress[]>(`${group(id)}/sends`),
send: (id: string, request: LinkedSendReply) =>
- dssFetch<LinkedSendProgress>(`${group(id)}/sends`, {
+ write<LinkedSendProgress>(`${group(id)}/sends`, JSON.stringify(request)),
+ /** The caller's progress for the given send intents. */
+ delivery: (id: string, sendIds: string[]) =>
+ dssFetch<LinkedSendProgress[]>(`${group(id)}/delivery`, {
method: 'POST',
- body: JSON.stringify(request),
+ body: JSON.stringify(sendIds),
}),
upload: (id: string, file: File) => {
const body = new FormData();
body.set('file', file);
- return dssFetch<LinkedUploadedAttachment>(`${group(id)}/attachments`, {
- method: 'POST',
- body,
- });
+ return write<LinkedUploadedAttachment>(`${group(id)}/attachments`, body);
},
markRead: (id: string, messageId: string) =>
dssFetch(`${group(id)}/read`, {
diff --git a/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts b/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts
index 774b283aa2..4607737ab1 100644
--- a/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts
+++ b/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts
@@ -11,15 +11,20 @@ import type { LinkedGroupInfo } from './generated/schemas/linkedGroupInfo';
import type { LinkedPairing } from './generated/schemas/linkedPairing';
import type { LinkedPairState } from './generated/schemas/linkedPairState';
import type { LinkedPasskeyBody } from './generated/schemas/linkedPasskeyBody';
+import {
+ type WhatsAppErrorCode,
+ whatsappErrorResponse,
+} from './whatsapp-errors';
const root = `${SERVER_HOSTS['document-storage-service']}/meta/linked`;
const pairing = (id: string) => `${root}/pairing/${encodeURIComponent(id)}`;
function post<T extends ObjectLike>(url: string, body: unknown) {
- return fetchWithToken<T>(url, {
+ return fetchWithToken<T, WhatsAppErrorCode>(url, {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
+ errorResponseHandler: whatsappErrorResponse,
});
}
diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsx
index 5498312acb..916556e955 100644
--- a/apps/web/src/routes/app-router-view.tsx
+++ b/apps/web/src/routes/app-router-view.tsx
@@ -116,6 +116,7 @@ import {
emailSplitRoute,
emailThreadRoute,
externalRoute,
+ externalWhatsappGroupRoute,
foldersRoute,
formRespondRoute,
homeCalendarRoute,
@@ -163,9 +164,13 @@ import {
withMeetingShell,
} from './shells';
-const WhatsAppGroupRouteView = lazyNamed(
+const WhatsAppGroupRedirectRouteView = lazyNamed(
() => import('@app/features/whatsapp-group/route-views'),
- 'WhatsAppGroupRouteView'
+ 'WhatsAppGroupRedirectRouteView'
+);
+const ExternalWhatsAppGroupRouteView = lazyNamed(
+ () => import('@app/features/external-view/route-views'),
+ 'ExternalWhatsAppGroupRouteView'
);
const { Router, Route } = SplitRouter;
@@ -400,7 +405,12 @@ export function AppRouterView() {
definition={externalRoute}
component={ExternalRouteView}
loading={ExternalViewSkeleton}
- />
+ >
+ <Route
+ definition={externalWhatsappGroupRoute}
+ component={ExternalWhatsAppGroupRouteView}
+ />
+ </Route>
<Route
definition={calendarSplitRoute}
component={CalendarRouteView}
@@ -422,7 +432,7 @@ export function AppRouterView() {
</Route>
<Route
definition={whatsappGroupRoute}
- component={WhatsAppGroupRouteView}
+ component={WhatsAppGroupRedirectRouteView}
/>
<Route definition={callDetailRoute} component={CallDetailRouteView} />
<Route definition={companiesRoute} component={CompaniesRouteView}>
diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.ts
index 278bacd3c9..8d9590cb60 100644
--- a/apps/web/src/routes/routes.ts
+++ b/apps/web/src/routes/routes.ts
@@ -578,12 +578,20 @@ export const reviewsSplitRoute = defineRoute({
search: [reviewsTabSearch.namespace],
});
-/** A shareable WhatsApp conversation, with no channel or legacy block. */
+/** Retired `/whatsapp-group/:groupId` links; redirects into External. */
export const whatsappGroupRoute = defineRoute({
id: 'whatsapp-group',
path: 'whatsapp-group/:groupId',
params: z.object({ groupId: z.string().uuid() }),
remountKey: ({ groupId }) => groupId,
+});
+
+/** A shareable WhatsApp conversation in External's main pane, with no channel or legacy block. */
+export const externalWhatsappGroupRoute = defineRoute({
+ id: 'external-whatsapp-group',
+ path: 'whatsapp/:groupId',
+ params: z.object({ groupId: z.string().uuid() }),
+ remountKey: ({ groupId }) => groupId,
claim: ({ groupId }) => ({ namespace: 'whatsapp-group', id: groupId }),
});
diff --git a/apps/web/tests/functional/whatsapp-linked.spec.ts b/apps/web/tests/functional/whatsapp-linked.spec.ts
index 9f0cecd778..7500cdaea3 100644
--- a/apps/web/tests/functional/whatsapp-linked.spec.ts
+++ b/apps/web/tests/functional/whatsapp-linked.spec.ts
@@ -8,6 +8,7 @@ type Group = {
name: string;
members: number;
group: { id: string; name: string } | null;
+ shared?: { id: string; name: string; owner_id: string };
};
/** Server state the mocked DSS `/meta/linked` routes answer from. */
@@ -30,6 +31,10 @@ type LinkedServer = {
grants: { userId: string; accessLevel: string }[];
permissionUpdates: unknown[];
readMessages: string[];
+ /** Responses for the next sends, in order; afterwards a send is recorded. */
+ sendReplies: { status: number; json: unknown }[];
+ /** Progress `POST /delivery` reports, by send id. */
+ delivery: Record<string, { state: string; message_id: string | null }>;
};
function server(): LinkedServer {
@@ -49,6 +54,17 @@ function server(): LinkedServer {
members: 23,
group: null,
},
+ {
+ name: 'Ana, Ben, +2',
+ members: 4,
+ group: null,
+ shared: {
+ id: 'group-shared-family',
+ name: 'Ana, Ben, +2',
+ owner_id: 'macro|[email protected]',
+ },
+ },
],
requests: [],
adoptions: [],
@@ -59,6 +75,8 @@ function server(): LinkedServer {
grants: [],
permissionUpdates: [],
readMessages: [],
+ sendReplies: [],
+ delivery: {},
};
}
@@ -235,31 +253,38 @@ async function mount(page: Page, state: LinkedServer, query = '') {
],
},
});
- if (suffix === '/sends' && method === 'GET')
- return route.fulfill({
- json: [
- {
- id: 'send-unknown',
- message_id: null,
- state: 'unknown',
- error_code: null,
- payload: {
- idempotency_key: 'unknown-intent',
- message: {
- type: 'text',
- text: 'Running 10 minutes late, start without me',
- },
- reply_to: null,
- },
- },
- ],
- });
if (suffix === '/sends' && method === 'POST') {
- state.outgoing.push(route.request().postDataJSON());
+ const body = route.request().postDataJSON();
+ state.outgoing.push(body);
+ const reply = state.sendReplies.shift();
+ if (reply)
+ return route.fulfill({ status: reply.status, json: reply.json });
+ const id = `send-${body.idempotency_key}`;
+ state.delivery[id] ??= { state: 'pending', message_id: null };
return route.fulfill({
- json: { id: 'new-send', state: 'pending', message_id: null },
+ json: {
+ id,
+ group_id: GROUP_ID,
+ user_id: USER_ID,
+ created_at: new Date().toISOString(),
+ payload: body,
+ ...state.delivery[id],
+ },
});
}
+ if (suffix === '/delivery')
+ return route.fulfill({
+ json: (route.request().postDataJSON() as string[])
+ .filter((id) => state.delivery[id])
+ .map((id) => ({
+ id,
+ group_id: GROUP_ID,
+ user_id: USER_ID,
+ created_at: new Date().toISOString(),
+ payload: {},
+ ...state.delivery[id],
+ })),
+ });
if (suffix === '/read') {
state.readMessages.push(route.request().postDataJSON().message_id);
return route.fulfill({ json: {} });
@@ -300,7 +325,10 @@ async function mount(page: Page, state: LinkedServer, query = '') {
.map((item) => ({
id: item.group?.id,
name: item.group?.name,
- unread_count: 2,
+ user_id: USER_ID,
+ unread_count: item.group?.id === GROUP_ID ? 2 : 0,
+ can_send: item.group?.id === GROUP_ID,
+ send_reason: item.group?.id === GROUP_ID ? null : 'not_observing',
})),
});
if (path === 'account')
@@ -352,6 +380,7 @@ async function mount(page: Page, state: LinkedServer, query = '') {
disappearing: false,
observedAt: '2026-10-20T12:00:00Z',
group: group.group,
+ shared: group.shared ?? null,
participants: Array.from({ length: group.members }, (_, i) => ({
jid: `1415555${String(i).padStart(4, '0')}@s.whatsapp.net`,
admin: i === 0,
@@ -361,7 +390,6 @@ async function mount(page: Page, state: LinkedServer, query = '') {
if (path === 'groups/adopt' && method === 'POST') {
const body = route.request().postDataJSON() as { group_jid: string };
state.adoptions.push(body);
- // The group's name follows WhatsApp.
const group = state.groups.find(({ jid }) => jid === body.group_jid);
if (group) group.group = { id: 'group-new', name: group.name };
return route.fulfill({
@@ -369,6 +397,7 @@ async function mount(page: Page, state: LinkedServer, query = '') {
id: 'binding-1',
group_id: 'group-new',
group_jid: body.group_jid,
+ team_id: 'team-acme',
user_id: USER_ID,
adopted_at: '2026-10-20T12:00:00Z',
ownership_state: 'active',
@@ -414,23 +443,71 @@ test('links WhatsApp by QR, then adds a shareable WhatsApp group', async ({
await expect(dialog).toBeHidden();
expect(state.requests).not.toContain('DELETE pairing/pairing-1');
- const groups = page.getByRole('list', { name: 'Your WhatsApp groups' });
- await expect(groups.getByText('Design Crit')).toBeVisible();
- await expect(groups.getByLabel('2 unread messages')).toBeVisible();
- await groups.getByRole('button', { name: /In Macro/ }).click();
- expect(await page.evaluate(() => window.openedGroups)).toEqual([GROUP_ID]);
+ const groups = page.getByRole('list', { name: 'Groups to add to Macro' });
+ await expect(groups.getByText('Launch War Room')).toBeVisible();
+ // Already in Macro: listed in External's sidebar instead.
+ await expect(groups.getByText('Design Crit')).toHaveCount(0);
+ await groups
+ .getByRole('button', { name: /Shared with you by Group Owner/ })
+ .click();
+ expect(await page.evaluate(() => window.openedGroups)).toEqual([
+ 'group-shared-family',
+ ]);
await groups.getByRole('button', { name: 'Add to Macro' }).click();
- const add = page.getByRole('dialog');
- await expect(add.getByText('Add “Launch War Room” to Macro')).toBeVisible();
- await expect(add.getByLabel('Group name')).toHaveValue('Launch War Room');
- await expect(add.getByRole('checkbox')).toHaveCount(0);
- await expect(add.getByText(/Only you have access at first/)).toBeVisible();
- await add.getByRole('button', { name: 'Add group' }).click();
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+ await expect(groups.getByText('Launch War Room')).toHaveCount(0);
+ expect(state.adoptions).toEqual([{ group_jid: '[email protected]' }]);
+ expect(unexpected).toEqual([]);
+});
+
+test('a refused add says why, on that group', async ({ page }) => {
+ const state = server();
+ state.account = {
+ id: 'account-1',
+ user_id: USER_ID,
+ authorization_generation: 4,
+ identity_jid: '14155550142:[email protected]',
+ state: 'connected',
+ };
+ const unexpected = await mount(page, state);
+ // Registered last, so it answers before the catch-all mock.
+ await page.route('**/dss/meta/linked/groups/adopt', (route) =>
+ route.fulfill({
+ status: 409,
+ json: {
+ code: 'disconnected',
+ message: 'connect your WhatsApp account first',
+ },
+ })
+ );
+ const row = page
+ .getByRole('list', { name: 'Groups to add to Macro' })
+ .getByRole('listitem')
+ .filter({ hasText: 'Launch War Room' });
+ await row.getByRole('button', { name: 'Add to Macro' }).click();
+ await expect(row.getByRole('alert')).toHaveText(
+ 'Your WhatsApp is disconnected. Reconnect it, then add the group.'
+ );
+ expect(unexpected).toEqual([]);
+});
+
+test('External lists groups in Macro with unread counts and read-only tags', async ({
+ page,
+}) => {
+ const state = server();
+ state.groups[1].group = { id: 'group-shared', name: 'Launch War Room' };
+ const unexpected = await mount(page, state, '?view=in-macro');
+ const nav = page.getByRole('navigation', {
+ name: 'WhatsApp groups in Macro',
+ });
+ const design = nav.getByRole('button', { name: /design-crit/ });
+ await expect(design.getByLabel('2 unread messages')).toBeVisible();
await expect(
- groups.getByRole('button', { name: 'In Macro → Launch War Room' })
+ nav.getByRole('button', { name: /Launch War Room/ }).getByText('Read-only')
).toBeVisible();
- expect(state.adoptions).toEqual([{ group_jid: '[email protected]' }]);
+ await design.click();
+ expect(await page.evaluate(() => window.openedGroups)).toEqual([GROUP_ID]);
expect(unexpected).toEqual([]);
});
@@ -504,7 +581,16 @@ test('Macro desktop shows its authenticator’s QR while the phone confirms', as
).toBeDisabled();
});
-test('an independent group reads, replies, reacts and pages without channel requests', async ({
+/** The shared channel composer; Lexical takes typed text. */
+async function typeInComposer(page: Page, text: string) {
+ const editor = page.locator(
+ '[data-input-editor-shell] [contenteditable="true"]'
+ );
+ await editor.click();
+ await page.keyboard.type(text);
+}
+
+test('an independent group reads, replies, reacts and pages through channel rows', async ({
page,
}) => {
const state = server();
@@ -514,24 +600,25 @@ test('an independent group reads, replies, reacts and pages without channel requ
).toBeVisible();
await expect(page.getByText('Sending as +14155550142')).toBeVisible();
await expect(page.getByText('Loading design.pdf…')).toBeVisible();
- await expect(page.getByText(/may already have arrived/)).toBeVisible();
+ await expect(page.getByText(/may already have arrived/)).toHaveCount(0);
await expect.poll(() => state.readMessages).toContain('message-2');
expect(state.outgoing).toEqual([]);
- await page
- .getByRole('button', { name: 'Reply', exact: true })
- .first()
- .click();
- await page
- .getByRole('textbox', { name: 'Message WhatsApp group' })
- .fill('Thanks from my own WhatsApp');
- await page.getByRole('button', { name: 'Send', exact: true }).click();
+ await page.locator('[data-message-id="message-1"]').hover();
+ await page.getByRole('button', { name: 'Reply', exact: true }).click();
+ await expect(page.getByText('Replying to Ana Ruiz')).toBeVisible();
+ await typeInComposer(page, 'Thanks from my own WhatsApp');
+ await page.getByRole('button', { name: 'Send message' }).click();
await expect.poll(() => state.outgoing.length).toBe(1);
expect(state.outgoing[0]).toMatchObject({
message: { type: 'text', text: 'Thanks from my own WhatsApp' },
reply_to: 'message-1',
});
- await expect(page.getByRole('textbox')).toHaveValue('');
- await page.getByRole('button', { name: '👍 2' }).click();
+ // Shown at once, before WhatsApp accepts it.
+ await expect(
+ page.getByText('Thanks from my own WhatsApp', { exact: true })
+ ).toBeVisible();
+ await expect(page.getByText('Replying to Ana Ruiz')).toHaveCount(0);
+ await page.locator('[data-message-reaction-chip][data-emoji="👍"]').click();
await expect.poll(() => state.outgoing.length).toBe(2);
expect(state.outgoing[1]).toMatchObject({
message: {
@@ -549,6 +636,57 @@ test('an independent group reads, replies, reacts and pages without channel requ
expect(unexpected).toEqual([]);
});
+test('a refused send leaves the conversation, says why and restores the draft', async ({
+ page,
+}) => {
+ const state = server();
+ state.sendReplies.push({
+ status: 403,
+ json: {
+ code: 'forbidden',
+ message: 'you do not have permission for this WhatsApp operation',
+ },
+ });
+ const unexpected = await mount(page, state, `?group=${GROUP_ID}`);
+ await typeInComposer(page, 'Not allowed here');
+ await page.getByRole('button', { name: 'Send message' }).click();
+ await expect(
+ page.getByText("Your WhatsApp can't send to this group.")
+ ).toBeVisible();
+ await expect(
+ page.locator('[role="log"]').getByText('Not allowed here')
+ ).toHaveCount(0);
+ await expect(
+ page.locator('[data-input-editor-shell]').getByText('Not allowed here')
+ ).toBeVisible();
+ expect(state.outgoing).toHaveLength(1);
+ expect(unexpected).toEqual([]);
+});
+
+test('an unknown outcome retries quietly under the same key', async ({
+ page,
+}) => {
+ const state = server();
+ state.sendReplies.push({
+ status: 503,
+ json: {
+ code: 'temporarily_unavailable',
+ message: 'WhatsApp is temporarily unavailable; retry shortly',
+ },
+ });
+ const unexpected = await mount(page, state, `?group=${GROUP_ID}`);
+ await typeInComposer(page, 'Arrives once');
+ await page.getByRole('button', { name: 'Send message' }).click();
+ await expect.poll(() => state.outgoing.length).toBe(2);
+ const [first, second] = state.outgoing as { idempotency_key: string }[];
+ expect(second?.idempotency_key).toBe(first?.idempotency_key);
+ await expect(page.getByText(/Couldn't reach WhatsApp/)).toHaveCount(0);
+ await expect(
+ page.locator('[role="log"]').getByText('Arrives once')
+ ).toBeVisible();
+ expect(unexpected).toEqual([]);
+});
+
test('a shared viewer can read without connecting WhatsApp', async ({
page,
}) => {
@@ -583,7 +721,7 @@ for (const mobile of [false, true]) {
const unexpected = await mount(page, state, `?group=${GROUP_ID}`);
await expect(page.getByText('Sending as +14155550142')).toBeVisible();
await expect(
- page.getByRole('button', { name: 'Send', exact: true })
+ page.getByRole('textbox', { name: 'Message Design Crit' })
).toBeVisible();
expect(await page.evaluate(() => innerWidth)).toBe(mobile ? 390 : 1440);
expect(
diff --git a/apps/web/tests/functional/whatsapp-linked/fixture.tsx b/apps/web/tests/functional/whatsapp-linked/fixture.tsx
index 9c89774e49..29d88c9bba 100644
--- a/apps/web/tests/functional/whatsapp-linked/fixture.tsx
+++ b/apps/web/tests/functional/whatsapp-linked/fixture.tsx
@@ -1,6 +1,7 @@
import { EmailLinksContextProvider } from '@core/context/emailLinks';
import { ImperativeDialogHost } from '@ui';
import '@fontsource-variable/inter';
+import { InMacroSection } from '@app/features/external-view/components/in-macro-section';
import { WhatsAppGroupProvider } from '@app/features/whatsapp-group/context/whatsapp-group-context';
import { createWhatsAppGroupCapabilities } from '@app/features/whatsapp-group/queries/capabilities';
import { whatsappGroupApi } from '@app/features/whatsapp-group/queries/production-api';
@@ -12,7 +13,7 @@ import { Route, Router } from '@solidjs/router';
import { macroDarkTheme } from '@theme/themes/macro-dark';
import { macroLightTheme } from '@theme/themes/macro-light';
import { themeCssVars } from '@theme/utils/themeColorTokens';
-import { onMount, Suspense } from 'solid-js';
+import { onMount, Show, Suspense } from 'solid-js';
// The app's styles, so the page and its screenshots look like the app.
import '../../../src/index.css';
import {
@@ -23,8 +24,13 @@ import { createWhatsAppLinkedCapabilities } from '@app/features/whatsapp-linked/
import { WhatsAppPage } from '@app/features/whatsapp-linked/views/whatsapp-page';
import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
import { PosthogProvider } from '@app/lib/analytics/posthog';
+import { FloatRegionHost } from '@components/app/mobile/float-regions/FloatRegionHost';
+import { ToastRegion } from '@core/component/Toast/ToastRegion';
import { UserContextProvider } from '@core/context/user';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { queryClient } from '@queries/client';
+import { queryReadyGate } from '@queries/gate';
+import { useWhatsappGroupsQuery } from '@queries/whatsapp-groups';
import { QueryClientProvider } from '@tanstack/solid-query';
import { ResultAsync } from 'neverthrow';
import { render } from 'solid-js/web';
@@ -69,7 +75,12 @@ function GroupHarness(props: { groupId: string }) {
};
});
return (
- <div class="h-dvh">
+ <div class="relative h-dvh">
+ <ToastRegion />
+ {/* The app's bottom chrome host, where the composer floats on touch. */}
+ <Show when={isTouchDevice()}>
+ <FloatRegionHost />
+ </Show>
<WhatsAppGroupProvider value={source}>
<WhatsAppGroupView
userId={userId()}
@@ -77,13 +88,32 @@ function GroupHarness(props: { groupId: string }) {
onConnect={() => {
location.search = '';
}}
- renderAttachment={(id) => <span>Document {id}</span>}
/>
</WhatsAppGroupProvider>
</div>
);
}
+/** External's sidebar section over the real groups query. */
+function InMacroHarness() {
+ const userId = useUserId();
+ const groups = useWhatsappGroupsQuery(whatsappGroupApi, () => userId() ?? '');
+ return (
+ <main class="w-72 bg-panel p-2 text-ink">
+ <InMacroSection
+ groups={queryReadyGate(groups) ? groups.data : undefined}
+ isPending={groups.isPending}
+ isError={groups.isError}
+ activeGroupId={undefined}
+ open
+ onOpenChange={() => {}}
+ onOpenGroup={(groupId) => window.openedGroups.push(groupId)}
+ onRetry={() => {}}
+ />
+ </main>
+ );
+}
+
function Page() {
onMount(() => {
const dark = matchMedia('(prefers-color-scheme: dark)').matches;
@@ -94,7 +124,9 @@ function Page() {
document.documentElement.style.colorScheme = dark ? 'dark' : 'light';
document.documentElement.dataset.themeLight = String(!dark);
});
- const groupId = new URLSearchParams(location.search).get('group');
+ const search = new URLSearchParams(location.search);
+ if (search.get('view') === 'in-macro') return <InMacroHarness />;
+ const groupId = search.get('group');
if (groupId)
return (
<Suspense fallback={<p>Loading group…</p>}>
diff --git a/docs/agent-guide/external.md b/docs/agent-guide/external.md
index 2382949677..2a5b7bff65 100644
--- a/docs/agent-guide/external.md
+++ b/docs/agent-guide/external.md
@@ -12,8 +12,18 @@ it on locally with `VITE_ENABLE_WHATSAPP_LINKED=true`.
hideable in **More → Customize sidebar**), or `g x`, or **Go to External** in
the command menu.
- Mobile: **More views → External**. It never takes a dock slot and has no
- back button, like other navigation views; the External list sidebar is
- hidden on touch, so the WhatsApp page fills the pane.
+ back button, like other navigation views; the External sidebar is hidden on
+ touch, so the WhatsApp page fills the pane with **In Macro** first. Opening a
+ group drills in full-screen; its **Back to WhatsApp** button returns.
+
+## Sidebar
+
+Desktop's External sidebar has **WhatsApp** (the page below) and a collapsible
+**In Macro** section: every WhatsApp group the viewer can read (their own and
+shared ones), each with its unread count and a **Read-only** tag when the
+viewer's WhatsApp can't send there. The open group's row is highlighted.
+DSS's `whatsapp_changed` gateway events refresh the lists; without one, External
+re-fetches once ~3 s after opening.
## WhatsApp page states
@@ -22,8 +32,7 @@ it on locally with `VITE_ENABLE_WHATSAPP_LINKED=true`.
| Not linked | Outlined WhatsApp row, the unofficial-client account-risk note, **Connect** (disabled with a tooltip when the server turns pairing off). A signed-out device reads **Reconnect**. |
| Passkey | When WhatsApp asks for a passkey, the dialog says **Confirm on your desktop**. In Macro desktop, **Confirm with passkey** runs the native `whatsapp_passkey_authenticate` command (its caBLE QR shows in the dialog) and posts the assertion to `pairing/<id>/passkey`; a returned code then shows to type on the phone. In a browser, **Continue in Macro desktop** opens `macro:///external?whatsappPairing=<id>`, which reopens the same pairing there; closing the browser dialog then doesn't cancel it. |
| Pairing | Dialog **Link WhatsApp**: a locally encoded QR (`role="img"`, name "Scan this code with WhatsApp on your phone"), **Expires in m:ss**, four numbered steps, **Cancel**. The dialog carries `ph-no-capture`. A code confirmation step shows **The codes match**; expiry or failure shows **Show a new code**. |
-| Linked | Account row with the phone number, **Use a different account** (asks to confirm, then pairs with `replace: true`) and **Disconnect** (asks to confirm), then **Your WhatsApp groups**: adopted groups show **In Macro** with an unread badge (opens the standalone group), others **Add to Macro**. Community and disappearing-message groups say why they can't be added. |
-| Add to Macro | Dialog **Add “<group>” to Macro**: a group name prefilled from the subject and **Add to Macro**. The adopter owns the entity and shares it afterward with the normal Share dialog. |
+| Linked | Account row with the phone number, **Use a different account** (asks to confirm, then pairs with `replace: true`) and **Disconnect** (asks to confirm), then **Add to Macro**: the account's groups not yet in Macro, each with a one-click **Add to Macro** (no dialog, no name: the Macro group follows the WhatsApp name; unnamed groups show member names), and groups someone already shared with the viewer as **Shared with you by <owner> · Open**. Groups already in Macro are only in the sidebar. **Can't be added (n)** is collapsed and lists community and disappearing-message groups with the reason. A refused add shows DSS's specific reason under that group. |
Cancel sends `DELETE /meta/linked/pairing/<id>`; closing after the phone links
does not. Disconnect that WhatsApp did not confirm tells the person to remove
@@ -35,17 +44,22 @@ No environment has the WhatsApp session service yet, so intercept DSS
`/meta/linked/*` in the browser (Playwright `page.route`). The functional test
`apps/web/tests/functional/whatsapp-linked.spec.ts` is the reference mock: it
answers `configuration`, `account`, `connect`, `pairing/<id>` (poll and
-`DELETE`), `groups` (`GET`), `groups/adopt` (`POST`), standalone `whatsapp-groups` routes and `disconnect`, and flips the pairing
+`DELETE`), `groups` (`GET`), `groups/adopt` (`POST`, body `{group_jid}`), standalone `whatsapp-groups` routes and `disconnect`, and flips the pairing
to `success` to simulate the phone scanning. Never link a real account from an
automated run.
## Adopted group view
-Open the adopted group from External or a shared link at `/app/whatsapp-group/:id`.
+Open the adopted group from External's sidebar or a shared link at
+`/app/external/whatsapp/:id`, in External's main pane. The retired
+`/app/whatsapp-group/:id` links and saved `whatsapp-group:<id>` layouts redirect there.
The group has its own timeline, data layer and entity sharing; it does not appear
as a native channel. **Share** uses ordinary people grants, access requests,
team sharing and link sharing for `whatsapp_group`. Viewers can read the whole
timeline without connecting WhatsApp or belonging to the remote group.
+In a channel composer, `@` offers **WhatsApp groups** (behind the WhatsApp flag);
+posting the mention shares the group with the channel's members (View), and the
+chip opens the group in External.
The timeline pages newest-first from
`GET /meta/linked/whatsapp-groups/<id>/messages`, including verified sender names,
diff --git a/packages/lexical-core/tests/whatsapp-group-references.test.ts b/packages/lexical-core/tests/whatsapp-group-references.test.ts
new file mode 100644
index 0000000000..c62387d20d
--- /dev/null
+++ b/packages/lexical-core/tests/whatsapp-group-references.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { extractChannelMentionsFromMarkdown } from '../utils/markdown-mentions';
+import { messageReference } from '../utils/message-references';
+
+describe('WhatsApp group references in channel messages', () => {
+ it('keeps the WhatsApp group entity type on an authored reference', () => {
+ expect(
+ messageReference('whatsapp_group', '01a16445-9fdc-7bb1-80b4-8935a1243c98')
+ ).toEqual({
+ entityType: 'whatsapp_group',
+ entityId: '01a16445-9fdc-7bb1-80b4-8935a1243c98',
+ });
+ });
+
+ it('extracts a WhatsApp group mention without treating it as a document', () => {
+ expect(
+ extractChannelMentionsFromMarkdown(
+ '<m-document-mention>{"documentId":"01a16445-9fdc-7bb1-80b4-8935a1243c98","blockName":"whatsapp_group","documentName":"Design Crit","blockParams":{}}</m-document-mention>'
+ )
+ ).toEqual([
+ {
+ entityType: 'whatsapp_group',
+ entityId: '01a16445-9fdc-7bb1-80b4-8935a1243c98',
+ },
+ ]);
+ });
+});
diff --git a/packages/lexical-core/utils/mentions.ts b/packages/lexical-core/utils/mentions.ts
index bc3240dce5..d6981d6a18 100644
--- a/packages/lexical-core/utils/mentions.ts
+++ b/packages/lexical-core/utils/mentions.ts
@@ -104,7 +104,8 @@ function documentMentionEntityType(blockName: string): string {
'call',
'automation',
'form',
- 'database'
+ 'database',
+ 'whatsapp_group'
),
(kind) => kind
)
diff --git a/packages/lexical-core/utils/message-references.ts b/packages/lexical-core/utils/message-references.ts
index 97b6facf59..bde9abba65 100644
--- a/packages/lexical-core/utils/message-references.ts
+++ b/packages/lexical-core/utils/message-references.ts
@@ -19,7 +19,8 @@ export type MessageReferenceKind =
| 'group'
| 'automation'
| 'crm_company'
- | 'crm_contact';
+ | 'crm_contact'
+ | 'whatsapp_group';
export type AuthoredMessageReference = {
entityType: MessageReferenceKind;
entityId: string;
@@ -52,7 +53,9 @@ export function messageReference(
'group',
'automation',
'crm_company',
- 'crm_contact'
+ 'crm_contact',
+ // Mentioning a WhatsApp group in a channel shares it with the members.
+ 'whatsapp_group'
),
(entityType) => ({ entityType, entityId: id })
)