Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(web): link WhatsApp accounts and open shared WhatsApp groups (#8540)
Wolf Mermelstein0b1f2a1b68ab
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex b6db9a64a4..a463c0d0c9 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -232,6 +232,7 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.- Compose multiselect filters with `Dropdown.MultiSelectItem` and the sharedsearchable 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.- All API/network calls live in service-clients.- Open projects through `openProject` (`features/projects/open-project.ts`): itretargets an already-open project split to the section or comment in place.diff --git a/apps/web/package.json b/apps/web/package.jsonindex 9255001adf..38b758fcb4 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -172,6 +172,7 @@"tailwindcss": "^4.2.4","ts-pattern": "^5.9.0","unicode-emoji-json": "^0.8.0",+ "uqr": "0.1.3","uuid": "^10.0.0","virtua": "0.48.8","vite-plugin-wasm": "^3.5.0",diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsxindex 1d99aba056..a2b286ebe2 100644--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx@@ -1,5 +1,9 @@import { GO_TO_COMMAND_SCOPE, GO_TO_LEADER_KEY } from '@app/constants/hotkeys';-import { LIST_VIEW_PATHS, type ListView } from '@app/constants/list-views';+import {+ EXTERNAL_VIEW_PATH,+ LIST_VIEW_PATHS,+ type ListView,+} from '@app/constants/list-views';import { useActivityFeedFlag } from '@app/features/activity/use-activity-feed-flag';import { useCalendarUiFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';import { calendarPath } from '@app/features/calendar-view/calendar-url';@@ -27,6 +31,7 @@ import {ENABLE_CALLS,enableCrm,enableTasksReviews,+ enableWhatsappLinked,isFeatureEnabled,} from '@core/constant/featureFlags';import { getRunnableHotkeys } from '@core/hotkey/getCommands';@@ -39,6 +44,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import BellIcon from '@icon/system/regular/bell.svg';import HomeIcon from '@icon/system/regular/house.svg';import SearchIcon from '@icon/system/regular/magnifying-glass.svg';+import PlugIcon from '@icon/system/regular/plug.svg';import ActivityIcon from '@icon/system/regular/pulse.svg';import { ContextMenu } from '@kobalte/core/context-menu';import { debounce } from '@solid-primitives/scheduled';@@ -223,12 +229,14 @@ export const GoToHotkeys = () => {const activityFeedEnabled = useActivityFeedFlag();const recentViewEnabled = useRecentViewFlag();const reviews = useFeatureFlag(enableTasksReviews);+ const external = useFeatureFlag(enableWhatsappLinked);const links = createMemo((): SidebarItem[] =>buildSidebarLinks(calendarUiEnabled(),activityFeedEnabled(),recentViewEnabled(),- reviews().enabled+ reviews().enabled,+ external().enabled));@@ -410,9 +418,19 @@ const REVIEWS_LINK: SidebarItem = {hotkeyToken: TOKENS.sidebar.goTo.reviews,};+const EXTERNAL_LINK: SidebarItem = {+ id: 'external',+ label: 'External',+ href: EXTERNAL_VIEW_PATH,+ icon: PlugIcon,+ // `e` is Email; `x` is the only free letter of "external".+ hotkey: 'x',+ hotkeyToken: TOKENS.sidebar.goTo.external,+};+/*** Assemble the ordered sidebar link list: the static links plus the- * flag-gated Recent, Activity, Calendar, Calls, Reviews, and CRM+ * flag-gated Recent, Activity, Calendar, Calls, Reviews, CRM, and External* entries in their correct positions.* Call from a reactive context — it reads `ENABLE_CALLS` / `isFeatureEnabled(enableCrm)`.*/@@ -420,7 +438,8 @@ const buildSidebarLinks = (showCalendar: boolean,showActivity: boolean,showRecent: boolean,- showReviews: boolean+ showReviews: boolean,+ showExternal: boolean): SidebarItem[] => {let links: SidebarItem[] = SIDEBAR_LINKS.filter((link) => showCalendar || link.id !== 'calendar'@@ -460,6 +479,8 @@ const buildSidebarLinks = (links = [...links, REVIEWS_LINK];}+ if (showExternal) links = [...links, EXTERNAL_LINK];+return links;};diff --git a/apps/web/src/components/app/mobile/mobile-dock-views.ts b/apps/web/src/components/app/mobile/mobile-dock-views.tsindex 05a672f8bd..78fbae2d85 100644--- a/apps/web/src/components/app/mobile/mobile-dock-views.ts+++ b/apps/web/src/components/app/mobile/mobile-dock-views.ts@@ -5,6 +5,7 @@ import {enableCalendarScheduling,enableCrm,enableTasksReviews,+ enableWhatsappLinked,} from '@core/constant/featureFlags';import BellFillIcon from '@icon/system/fill/bell-fill.svg';import CalendarFillIcon from '@icon/system/fill/calendar-fill.svg';@@ -15,6 +16,7 @@ import BellIcon from '@icon/system/regular/bell.svg';import CalendarCheckIcon from '@icon/system/regular/calendar-check.svg';import ChatsCircleIcon from '@icon/system/regular/chats-circle.svg';import GitPullRequestIcon from '@icon/system/regular/git-pull-request.svg';+import PlugIcon from '@icon/system/regular/plug.svg';import { createMemo } from 'solid-js';import type { MobileDockIcon } from './MobileDockButton';import type { MobileNavViewId } from './mobile-nav-views';@@ -68,6 +70,7 @@ export const MOBILE_DOCK_VIEWS: readonly MobileDockView[] = [{ id: 'companies', label: 'CRM', icon: getIconConfig('company').icon },{ id: 'reviews', label: 'Reviews', icon: GitPullRequestIcon },{ id: 'booking-links', label: 'Scheduling', icon: CalendarCheckIcon },+ { id: 'external', label: 'External', icon: PlugIcon },];export function useMobileDockViews() {@@ -75,6 +78,7 @@ export function useMobileDockViews() {const crm = useFeatureFlag(enableCrm);const reviews = useFeatureFlag(enableTasksReviews);const scheduling = useFeatureFlag(enableCalendarScheduling);+ const external = useFeatureFlag(enableWhatsappLinked);return createMemo(() =>MOBILE_DOCK_VIEWS.filter((view) => view.id !== 'calendar' || calendarEnabled()@@ -82,5 +86,6 @@ export function useMobileDockViews() {.filter((view) => view.id !== 'companies' || crm().enabled).filter((view) => view.id !== 'reviews' || reviews().enabled).filter((view) => view.id !== 'booking-links' || scheduling().enabled)+ .filter((view) => view.id !== 'external' || external().enabled));}diff --git a/apps/web/src/components/app/mobile/mobile-nav-views.ts b/apps/web/src/components/app/mobile/mobile-nav-views.tsindex a4b33f36c3..ae721f0c4a 100644--- a/apps/web/src/components/app/mobile/mobile-nav-views.ts+++ b/apps/web/src/components/app/mobile/mobile-nav-views.ts@@ -2,7 +2,7 @@* Views reachable from mobile navigation, in display order.* `search` is the "All" pill, first in the scope pill row;* `settings` navigates through the settings state (not `openWithSplit`), and- * `calendar`, `reviews`, and `booking-links` are feature-gated.+ * `calendar`, `reviews`, `booking-links`, and `external` are feature-gated.*/export const MOBILE_NAV_VIEW_IDS = ['search',@@ -15,6 +15,7 @@ export const MOBILE_NAV_VIEW_IDS = ['tasks','reviews','booking-links',+ 'external','calls','companies','settings',diff --git a/apps/web/src/components/app/mobile/use-mobile-nav.ts b/apps/web/src/components/app/mobile/use-mobile-nav.tsindex bf88baf640..4835284133 100644--- a/apps/web/src/components/app/mobile/use-mobile-nav.ts+++ b/apps/web/src/components/app/mobile/use-mobile-nav.ts@@ -23,6 +23,7 @@ export type MobileDockNavId =| 'calendar'| 'reviews'| 'booking-links'+ | 'external'| 'settings';function mobileNavContent(id: Exclude<MobileDockNavId, 'settings'>) {diff --git a/apps/web/src/components/app/sidebar-next/customize-sidebar-modal.test.tsx b/apps/web/src/components/app/sidebar-next/customize-sidebar-modal.test.tsxindex eaee87cfa6..81fd539098 100644--- a/apps/web/src/components/app/sidebar-next/customize-sidebar-modal.test.tsx+++ b/apps/web/src/components/app/sidebar-next/customize-sidebar-modal.test.tsx@@ -49,6 +49,7 @@ function Modal() {showCalls: true,showReviews: true,showActivity: true,+ showExternal: true,get prefs() {return prefs();},diff --git a/apps/web/src/components/app/sidebar-next/nav-items.test.ts b/apps/web/src/components/app/sidebar-next/nav-items.test.tsindex ce62ac4fb0..f6f11507f7 100644--- a/apps/web/src/components/app/sidebar-next/nav-items.test.ts+++ b/apps/web/src/components/app/sidebar-next/nav-items.test.ts@@ -22,6 +22,7 @@ const defaultGates = (overrides: Partial<NavItemGates> = {}): NavItemGates => ({showCalls: true,showReviews: true,showActivity: true,+ showExternal: true,prefs: defaultPrefs(),...overrides,});@@ -154,6 +155,30 @@ describe('sidebar visibility preferences', () => {});});+describe('External', () => {+ it('shows External on the rail when WhatsApp linking is enabled', () => {+ expect(+ visibleNavItems(defaultGates()).some((item) => item.id === 'external')+ ).toBe(true);+ });++ it('keeps External absent everywhere when its feature flag is off', () => {+ for (const hidden of [new Set<string>(), new Set(['external'])]) {+ const gates = defaultGates({+ showExternal: false,+ prefs: defaultPrefs({ hidden }),+ });+ for (const items of [+ customizableNavItems(gates),+ visibleNavItems(gates),+ moreMenuItems(gates),+ ]) {+ expect(items.some((item) => item.id === 'external')).toBe(false);+ }+ }+ });+});+describe('orderNavItems', () => {it('keeps home first and applies a custom order', () => {const ordered = orderNavItems(SIDEBAR_NEXT_NAV_ITEMS, [diff --git a/apps/web/src/components/app/sidebar-next/nav-items.ts b/apps/web/src/components/app/sidebar-next/nav-items.tsindex ac1a7959f5..f821def16e 100644--- a/apps/web/src/components/app/sidebar-next/nav-items.ts+++ b/apps/web/src/components/app/sidebar-next/nav-items.ts@@ -1,4 +1,4 @@-import { LIST_VIEW_PATHS } from '@app/constants/list-views';+import { EXTERNAL_VIEW_PATH, LIST_VIEW_PATHS } from '@app/constants/list-views';import { calendarPath } from '@app/features/calendar-view/calendar-url';import type { SidebarItem } from '@components/app/app-sidebar/sidebar';import { TOKENS } from '@core/hotkey/tokens';@@ -22,8 +22,10 @@ import GitPullRequestIcon from '@icon/system/regular/git-pull-request.svg';import HouseIcon from '@icon/system/regular/house.svg';import ListChecksIcon from '@icon/system/regular/list-checks.svg';import PhoneCallIcon from '@icon/system/regular/phone-call.svg';+import PlugIcon from '@icon/system/regular/plug.svg';import PulseIcon from '@icon/system/regular/pulse.svg';import AgentIcon from '@icon/system/regular/sparkle.svg';+import PlugFillIcon from '@phosphor-fill/plug-fill.svg';import PulseFillIcon from '@phosphor-fill/pulse-fill.svg';import type { NavIcon } from './nav-glyph';import type { SidebarPrefs } from './use-sidebar-prefs';@@ -164,6 +166,15 @@ export const SIDEBAR_NEXT_NAV_ITEMS = [icon: CalendarCheckIcon,iconActive: CalendarCheckIcon,},+ {+ id: 'external',+ label: 'External',+ href: EXTERNAL_VIEW_PATH,+ icon: PlugIcon,+ iconActive: PlugFillIcon,+ hotkey: 'x',+ hotkeyToken: TOKENS.sidebar.goTo.external,+ },] satisfies SidebarNextNavItem[];/** Feature flag gates for sidebar destinations. */@@ -174,6 +185,7 @@ export type NavItemGates = {showCalls: boolean;showReviews: boolean;showActivity: boolean;+ showExternal: boolean;/** User preferences for which items are shown and in what order. */prefs: SidebarPrefs;};@@ -189,6 +201,7 @@ export const isNavItemAvailable = (if (item.id === 'calls') return gates.showCalls;if (item.id === 'reviews') return gates.showReviews;if (item.id === 'activity') return gates.showActivity;+ if (item.id === 'external') return gates.showExternal;return true;};diff --git a/apps/web/src/components/app/sidebar-next/use-nav-item-gates.ts b/apps/web/src/components/app/sidebar-next/use-nav-item-gates.tsindex 6cdec5eaf9..3ba317b335 100644--- a/apps/web/src/components/app/sidebar-next/use-nav-item-gates.ts+++ b/apps/web/src/components/app/sidebar-next/use-nav-item-gates.ts@@ -6,6 +6,7 @@ import {enableCalendarScheduling,enableCrm,enableTasksReviews,+ enableWhatsappLinked,} from '@core/constant/featureFlags';import { type Accessor, createMemo } from 'solid-js';import type { NavItemGates } from './nav-items';@@ -22,6 +23,7 @@ export function useNavItemGates(): Accessor<NavItemGates> {const crm = useFeatureFlag(enableCrm);const reviews = useFeatureFlag(enableTasksReviews);const activity = useActivityFeedFlag();+ const external = useFeatureFlag(enableWhatsappLinked);const { prefs } = useSidebarPrefs();return createMemo(() => ({@@ -31,6 +33,7 @@ export function useNavItemGates(): Accessor<NavItemGates> {showCalls: ENABLE_CALLS,showReviews: reviews().enabled,showActivity: activity(),+ showExternal: external().enabled,prefs: prefs(),}));}diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex 820313517d..355eef4535 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -4,6 +4,7 @@ import type { EventEditorInitialValues } from '@app/features/calendar/componentsimport type { CalendarEvent } from '@app/features/calendar/types';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';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { NOT_FOUND_ROUTE_ID } from '@app/routes/app-route';import { LoadingBlock } from '@core/component/LoadingBlock';@@ -101,6 +102,14 @@ 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'+);const ReviewsRouteView = lazyNamed(() => import('@app/features/reviews-view/route-views'),'ReviewsRouteView'@@ -200,6 +209,15 @@ export function resolveComponent(): ResolvedComponent {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 (parseProjectRoute(name)) {const base = REGISTRY.get('initiative-view');if (base)@@ -489,6 +507,22 @@ registerComponent(() => <BookingLinksRouteView />,() => composableLayout());+registerComponent(+ 'whatsapp-group',+ withAuth((params) =>+ typeof params.groupId === 'string' ? (+ <WhatsAppGroup groupId={params.groupId} />+ ) : (+ <NotFound />+ )+ ),+ { splitPanelLayout: 'composable' }+);+registerComponent(+ 'external',+ () => <ExternalRouteView />,+ () => composableLayout()+);if (LOCAL_ONLY) {registerComponent(diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsxindex 42db17106b..f0efec62e5 100644--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx@@ -382,7 +382,8 @@ export function SplitHeader(props: {const content = panel.handle.content();return (isListViewID(content.id) ||- (content.type === 'component' && content.id === 'booking-links')+ (content.type === 'component' &&+ (content.id === 'booking-links' || content.id === 'external')));};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.tsindex 24e143cfda..483caf61e0 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@@ -4,9 +4,14 @@ import {homeSplitRoute,legacyContentRoute,notFoundRoute,+ whatsappGroupRoute,} from '@app/routes/routes';import { describe, expect, it, vi } from 'vitest';-import { resolveContentLocation, upgradeLegacyPath } from './legacy-route';+import {+ resolveContentLocation,+ splitContentFromLocation,+ upgradeLegacyPath,+} from './legacy-route';vi.mock('@components/app/split-layout/componentRegistry', () => ({resolveComponent: vi.fn(() => ({ type: 'mock-component' })),@@ -26,7 +31,12 @@ const routes = createRoutesManifest({definitions: [{...appRoute,- children: [homeSplitRoute, legacyContentRoute, notFoundRoute],+ children: [+ homeSplitRoute,+ whatsappGroupRoute,+ legacyContentRoute,+ notFoundRoute,+ ],},],defaultRoute: () => ({ matches: [{ id: 'view-home', params: {} }] }),@@ -59,3 +69,16 @@ describe('resolveContentLocation', () => {).toBeUndefined();});});++it('round-trips WhatsApp group components through their own route without a block', () => {+ const content = {+ type: 'component' as const,+ 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);+});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.tsindex 40d80ab2a4..a678c59cce 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,6 +21,10 @@ import {routineIdFromContent,routineLocation,} from '@app/features/routines/routine-navigation';+import {+ parseWhatsAppGroupComponentId,+ whatsappGroupComponentId,+} from '@app/features/whatsapp-group/core/route';import {canonicalRoute,decodePane,@@ -291,6 +295,11 @@ export function splitLocationFromContent(}if (content.type === 'component') {+ const groupId = parseWhatsAppGroupComponentId(content.id);+ if (groupId)+ return {+ route: paneRoute({ id: 'whatsapp-group', params: { groupId } }),+ };const viewId = `view-${content.id}`;if (routes.byId.has(viewId)) {return { route: paneRoute({ id: viewId, params: {} }) };@@ -408,6 +417,12 @@ 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');+ }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.tsindex e7d42328e3..eb2364d333 100644--- a/apps/web/src/components/app/split-layout/tests/fixtures.ts+++ b/apps/web/src/components/app/split-layout/tests/fixtures.ts@@ -14,6 +14,7 @@ import {homeSplitRoute,legacyContentRoute,notFoundRoute,+ whatsappGroupRoute,} from '@app/routes/routes';import type { BlockOrchestrator } from '@core/orchestrator';import { createSplitLayout, type SplitManager } from '../layoutManager';@@ -33,6 +34,7 @@ const routes: SplitRoutes = {...appRoute,children: [homeSplitRoute,+ whatsappGroupRoute,{ ...channelsSplitRoute, children: [channelDetailRoute] },legacyContentRoute,notFoundRoute,diff --git a/apps/web/src/features/access-requests/core/types.ts b/apps/web/src/features/access-requests/core/types.tsindex b12d3ed0d5..054468be82 100644--- a/apps/web/src/features/access-requests/core/types.ts+++ b/apps/web/src/features/access-requests/core/types.ts@@ -9,7 +9,8 @@ export type ShareEntity = {| 'database'| 'call'| 'email_thread'- | 'agent_session';+ | 'agent_session'+ | 'whatsapp_group';entityId: string;};export type AccessRequest = {@@ -55,6 +56,7 @@ export function shareEntity(case 'call':case 'email_thread':case 'agent_session':+ case 'whatsapp_group':return { entityType: itemType, entityId: id };}}diff --git a/apps/web/src/features/access-requests/primitives/direct-access-invite.test.ts b/apps/web/src/features/access-requests/primitives/direct-access-invite.test.tsnew file mode 100644index 0000000000..3a140b9c72--- /dev/null+++ b/apps/web/src/features/access-requests/primitives/direct-access-invite.test.ts@@ -0,0 +1,41 @@+import { createRoot } from 'solid-js';+import { expect, it, vi } from 'vitest';+import type { SharingSource } from '../context/contracts';+import { createDirectAccessInvite } from './direct-access-invite';++it('grants view access by Macro email and preserves the address when the write fails', async () => {+ const setGrant = vi.fn().mockResolvedValue(undefined);+ const state = createRoot((dispose) => {+ const source: SharingSource = {+ state: () => ({+ canReview: true,+ supportedLevels: ['view'],+ requests: [],+ pendingCount: 0,+ }),+ grants: () => [],+ loading: () => false,+ busy: () => false,+ error: () => undefined,+ refresh: async () => undefined,+ submit: async () => undefined,+ cancel: async () => undefined,+ resolve: async () => undefined,+ setGrant,+ nextPage: () => {},+ firstPage: () => {},+ };+ return { invite: createDirectAccessInvite(source), dispose };+ });+ state.invite.setEmail(' [email protected] ');+ await state.invite.invite();+ expect(setGrant).toHaveBeenCalledWith('macro|[email protected]', 'view');+ expect(state.invite.email()).toBe('');+ expect(state.invite.notice()).toBe('View access added.');+ setGrant.mockRejectedValueOnce(new Error('not registered'));+ state.invite.setEmail('[email protected]');+ await state.invite.invite();+ expect(state.invite.email()).toBe('[email protected]');+ expect(state.invite.error()).toContain("Couldn't add this person");+ state.dispose();+});diff --git a/apps/web/src/features/access-requests/primitives/direct-access-invite.ts b/apps/web/src/features/access-requests/primitives/direct-access-invite.tsnew file mode 100644index 0000000000..d8de2ad314--- /dev/null+++ b/apps/web/src/features/access-requests/primitives/direct-access-invite.ts@@ -0,0 +1,32 @@+import { emailToMacroId } from '@core/user/macroId';+import { createSignal, onCleanup } from 'solid-js';+import type { SharingSource } from '../context/contracts';++/** Direct people invitations for entities that do not forward through channels. */+export function createDirectAccessInvite(source: SharingSource) {+ const [email, setEmail] = createSignal('');+ const [notice, setNotice] = createSignal<string>();+ const [error, setError] = createSignal<string>();+ let alive = true;+ onCleanup(() => {+ alive = false;+ });+ const invite = async () => {+ const userId = emailToMacroId(email().trim().toLowerCase());+ if (!userId || !source.state()?.canReview || source.busy()) return;+ setNotice(undefined);+ setError(undefined);+ try {+ await source.setGrant(userId, 'view');+ if (!alive) return;+ setEmail('');+ setNotice('View access added.');+ } catch {+ if (alive)+ setError(+ "Couldn't add this person. Check their Macro email and try again."+ );+ }+ };+ return { email, setEmail, notice, error, invite };+}diff --git a/apps/web/src/features/access-requests/views/DirectAccessInvite.tsx b/apps/web/src/features/access-requests/views/DirectAccessInvite.tsxnew file mode 100644index 0000000000..8c5ad47baa--- /dev/null+++ b/apps/web/src/features/access-requests/views/DirectAccessInvite.tsx@@ -0,0 +1,59 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { Button, TextField } from '@ui';+import { Show } from 'solid-js';+import type { SharingSource } from '../context/contracts';+import { createDirectAccessInvite } from '../primitives/direct-access-invite';++export function DirectAccessInvite(props: {+ source: SharingSource;+ description: string;+}) {+ const invite = createDirectAccessInvite(props.source);+ return (+ <form+ class="flex flex-col gap-2 px-4 py-3"+ onSubmit={(event) => {+ event.preventDefault();+ fireAndForget(invite.invite(), 'access-requests.invite');+ }}+ >+ <p class="text-sm text-ink-muted">{props.description}</p>+ <div class="flex flex-wrap items-end gap-2">+ <TextField+ class="min-w-0 flex-1"+ value={invite.email()}+ onChange={invite.setEmail}+ >+ <TextField.Label>Macro email address</TextField.Label>+ <TextField.Input+ type="email"+ required+ disabled={props.source.busy()}+ placeholder="[email protected]"+ />+ </TextField>+ <Button+ type="submit"+ variant="strong"+ disabled={+ props.source.busy() ||+ !props.source.state()?.canReview ||+ !invite.email().trim()+ }+ >+ Add person+ </Button>+ </div>+ <Show when={invite.notice()}>+ <p role="status" class="text-xs text-ink-muted">+ {invite.notice()}+ </p>+ </Show>+ <Show when={invite.error()}>+ <p role="alert" class="text-xs text-failure-ink">+ {invite.error()}+ </p>+ </Show>+ </form>+ );+}diff --git a/apps/web/src/features/external-view/external-view-skeleton.tsx b/apps/web/src/features/external-view/external-view-skeleton.tsxnew file mode 100644index 0000000000..7800148d40--- /dev/null+++ b/apps/web/src/features/external-view/external-view-skeleton.tsx@@ -0,0 +1,15 @@+import { ViewSkeleton } from '@app/components/view-shell/ViewSkeleton';+import { isTouchDevice } from '@core/mobile/isTouchDevice';++/** External while its code or the rollout flag loads. */+export function ExternalViewSkeleton() {+ return (+ <ViewSkeleton.Root+ asidePreferenceKey="external"+ aside={isTouchDevice() ? false : undefined}+ >+ <ViewSkeleton.Sidebar title="External" />+ <ViewSkeleton.Main title="WhatsApp" />+ </ViewSkeleton.Root>+ );+}diff --git a/apps/web/src/features/external-view/external-view.tsx b/apps/web/src/features/external-view/external-view.tsxnew file mode 100644index 0000000000..b553c7a48e--- /dev/null+++ b/apps/web/src/features/external-view/external-view.tsx@@ -0,0 +1,67 @@+import { ViewShell, ViewSidebar } from '@app/components/view-shell';+import { useSplitDisplayName } from '@components/app/split-layout/layoutUtils';+import { SplitPanel } from '@components/app/split-panel';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import WhatsappIcon from '@phosphor/whatsapp-logo.svg';+import { useSearchParams } from '@solidjs/router';+import { z } from 'zod';+import { WhatsAppLinked } from '../whatsapp-linked/whatsapp-linked';++/**+ * External: accounts on outside messaging apps that bring conversations into+ * Macro. WhatsApp is the only one today, so the list has one entry.+ */+export function ExternalView() {+ useSplitDisplayName(() => 'External');+ // Read once: the pairing id is consumed, then dropped from the URL.+ const [search, setSearch] = useSearchParams();+ const handedOffPairing = z.uuid().safeParse(search.whatsappPairing).data;+ if (search.whatsappPairing !== undefined)+ setSearch({ whatsappPairing: undefined }, { replace: true });+ return (+ <SplitPanel.Root>+ <SplitPanel.Body>+ <ViewShell.Root+ asidePreferenceKey="external"+ aside={isTouchDevice() ? false : undefined}+ resizable={!isTouchDevice()}+ >+ <ViewShell.Aside>+ <ViewSidebar.Root aria-label="External navigation">+ <ViewSidebar.Header>+ <div class="flex min-w-0 items-center gap-1">+ <ViewSidebar.CloseButton class="shrink-0" />+ <ViewSidebar.Title>External</ViewSidebar.Title>+ </div>+ </ViewSidebar.Header>+ <ViewSidebar.Content>+ <ViewSidebar.Nav aria-label="External apps">+ <ViewSidebar.Item active aria-current="page" title="WhatsApp">+ <ViewSidebar.Icon>+ <WhatsappIcon class="size-4" />+ </ViewSidebar.Icon>+ <span class="truncate">WhatsApp</span>+ </ViewSidebar.Item>+ </ViewSidebar.Nav>+ </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">+ </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">+ </h1>+ <WhatsAppLinked resumePairingId={handedOffPairing} />+ </ViewShell.Content>+ </ViewShell.Main>+ </ViewShell.Root>+ </SplitPanel.Body>+ </SplitPanel.Root>+ );+}diff --git a/apps/web/src/features/external-view/route-views.tsx b/apps/web/src/features/external-view/route-views.tsxnew file mode 100644index 0000000000..a32481aaef--- /dev/null+++ b/apps/web/src/features/external-view/route-views.tsx@@ -0,0 +1,44 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useNavigate } from '@app/lib/split-router';+import { 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 { lazy, onMount, Show } from 'solid-js';+import { ExternalViewSkeleton } from './external-view-skeleton';++const ExternalView = lazy(async () => ({+ default: (await import('./external-view')).ExternalView,+}));++function DisabledExternalRoute() {+ const navigate = useNavigate();+ onMount(() =>+ navigate({ route: homeSplitRoute, params: {} }, { replace: true })+ );+ return null;+}++function TrackedExternalView() {+ usePageViewTracking('external');+ return <ExternalView />;+}++/** `/external`; a deep link with the flag off goes Home once the flag resolves. */+export const ExternalRouteView = withAuth(() => {+ const flag = useFeatureFlag(enableWhatsappLinked);+ return (+ <Show+ when={flag().enabled}+ fallback={+ <Show when={!flag().loading} fallback={<ExternalViewSkeleton />}>+ <DisabledExternalRoute />+ </Show>+ }+ >+ <TrackedExternalView />+ </Show>+ );+}, ExternalViewSkeleton);diff --git a/apps/web/src/features/notifications/notification-navigation.ts b/apps/web/src/features/notifications/notification-navigation.tsindex cabdbddc88..93c085e7c7 100644--- a/apps/web/src/features/notifications/notification-navigation.ts+++ b/apps/web/src/features/notifications/notification-navigation.ts@@ -20,6 +20,7 @@ import { itemToBlockName, resolveBlockAlias } from '@core/constant/allBlocks';import {enableCalendarUi,enableProjects,+ enableWhatsappLinked,isFeatureEnabled,USE_MACRO_PR_SUMMARY_BLOCK,} from '@core/constant/featureFlags';@@ -36,6 +37,7 @@ import { errAsync, ResultAsync } from 'neverthrow';import { match, P } from 'ts-pattern';import { shareEntity } from '../access-requests/core/types';import { projectRouteId } from '../projects/core/route';+import { whatsappGroupComponentId } from '../whatsapp-group/core/route';import {getDocumentCommentLocation,type NotificationEntityOverride,@@ -226,9 +228,16 @@ function getSupportedHandler(onApplied,}))- // Group notifications open the WhatsApp group view, which ships with- // the web app layer.- .with('whatsapp_group_message', () => null)+ .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 }+ );+ }).with('new_email', () => {const meta = notification.notification_metadata;if (meta.tag !== 'new_email') return null;@@ -261,7 +270,12 @@ function getSupportedHandler(notification.entity_type,notification.entity_id);- if (!target) return null;+ if (+ !target ||+ (target.entityType === 'whatsapp_group' &&+ !isFeatureEnabled(enableWhatsappLinked))+ )+ return null;return async (lm: SplitManager, newSplit = false) =>Telemetry.span('access_requests.notification.open', async (span) => {span.setAttr('entity.id', target.entityId);@@ -321,24 +335,26 @@ function getSupportedHandler(): undefined;const block =- target.entityType === 'initiative'- ? 'initiative'- : itemToBlockName({- type:- target.entityType === 'email_thread'- ? 'email'- : target.entityType,- fileType:- document?.fileType ??- entity?.fileType ??- meta.content.fileType ??- undefined,- subType:- document?.subType &&- document.subType !== 'initiative_description'- ? { type: document.subType }- : undefined,- });+ target.entityType === 'whatsapp_group'+ ? 'whatsapp_group'+ : target.entityType === 'initiative'+ ? 'initiative'+ : itemToBlockName({+ type:+ target.entityType === 'email_thread'+ ? 'email'+ : target.entityType,+ fileType:+ document?.fileType ??+ entity?.fileType ??+ meta.content.fileType ??+ undefined,+ subType:+ document?.subType &&+ document.subType !== 'initiative_description'+ ? { type: document.subType }+ : undefined,+ });const applied = () => {onApplied?.();if (meta.tag === 'entity_access_requested')@@ -359,10 +375,17 @@ function getSupportedHandler(span.setAttr('access_requests.outcome', 'navigation_requested');openSplitIfNotOpen(lm,- block === 'initiative' ? 'component' : block,- block === 'initiative'- ? projectRouteId({ id: target.entityId, section: 'overview' })- : target.entityId,+ block === 'initiative' || block === 'whatsapp_group'+ ? 'component'+ : block,+ block === 'whatsapp_group'+ ? whatsappGroupComponentId(target.entityId)+ : block === 'initiative'+ ? projectRouteId({+ id: target.entityId,+ section: 'overview',+ })+ : target.entityId,{ newSplit, sourceHandle, onApplied: applied });} catch {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.tsindex dc701e4da5..634eee5fcb 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@@ -1,5 +1,9 @@import { createRoutedSplitLayout } from '@components/app/split-layout/tests/fixtures';import { toast } from '@core/component/Toast/Toast';+import {+ enableWhatsappLinked,+ isFeatureEnabled,+} from '@core/constant/featureFlags';import type { BlockOrchestrator } from '@core/orchestrator';import { getNotificationById } from '@queries/notification/user-notifications';import { createRoot } from 'solid-js';@@ -234,3 +238,48 @@ it.each(['split', 'closed'] as const)(});});++it('opens a WhatsApp notification in its own component without a channel block', async () => {+ vi.mocked(isFeatureEnabled).mockImplementation(+ (flag) => flag === enableWhatsappLinked+ );+ const { layout, createBlockInstance, navigate } = setup('closed');+ const open = vi.spyOn(layout, 'openWithSplit');+ await openNotification(+ {+ entity_id: '11111111-1111-4111-8111-111111111111',+ notification_metadata: {+ tag: 'whatsapp_group_message',+ content: { groupName: 'Family', messageId: 'message' },+ },+ } as UnifiedNotification,+ layout+ );+ expect(open).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'component',+ id: 'whatsapp-group:11111111-1111-4111-8111-111111111111',+ }),+ expect.anything()+ );+ expect(createBlockInstance).not.toHaveBeenCalled();+ expect(navigate).not.toHaveBeenCalled();+});++it('keeps WhatsApp notifications behind the existing feature flag', async () => {+ vi.mocked(isFeatureEnabled).mockReturnValue(false);+ const { layout, createBlockInstance } = setup('closed');+ const open = vi.spyOn(layout, 'openWithSplit');+ await openNotification(+ {+ entity_id: '11111111-1111-4111-8111-111111111111',+ notification_metadata: {+ tag: 'whatsapp_group_message',+ content: { groupName: 'Family', messageId: 'message' },+ },+ } as UnifiedNotification,+ layout+ );+ expect(open).not.toHaveBeenCalled();+ expect(createBlockInstance).not.toHaveBeenCalled();+});diff --git a/apps/web/src/features/notifications/tests/notification-source.test.ts b/apps/web/src/features/notifications/tests/notification-source.test.tsindex 2cda675563..9db480ca39 100644--- a/apps/web/src/features/notifications/tests/notification-source.test.ts+++ b/apps/web/src/features/notifications/tests/notification-source.test.ts@@ -14,7 +14,7 @@ import {createNotificationSource,setDoneOverride,} from '../notification-source';-import type { UnifiedNotification } from '../types';+import { type UnifiedNotification, unifiedNotificationSchema } from '../types';const mocks = vi.hoisted(() => ({graphqlCacheEnabled: true,@@ -1192,3 +1192,22 @@ describe('createNotificationSource', () => {}});});++it('accepts the independent WhatsApp notification through the generated wire schema', () => {+ const row: UnifiedNotification = {+ ...notification(+ '019a061e-0000-7000-8000-000000000003',+ 'whatsapp_group',+ '019a061e-0000-7000-8000-000000000001'+ ),+ notification_event_type: 'whatsapp_group_message',+ notification_metadata: {+ tag: 'whatsapp_group_message',+ content: {+ groupName: 'Design Crit',+ messageId: '019a061e-0000-7000-8000-000000000002',+ },+ },+ };+ expect(unifiedNotificationSchema.safeParse(row).success).toBe(true);+});diff --git a/apps/web/src/features/notifications/use-notification-updates.ts b/apps/web/src/features/notifications/use-notification-updates.tsindex 77ebc8b3a2..86257b3e85 100644--- a/apps/web/src/features/notifications/use-notification-updates.ts+++ b/apps/web/src/features/notifications/use-notification-updates.ts@@ -12,6 +12,7 @@ import {refetchSoupEntity,} from '@queries/soup/normalized-cache';import { teamKeys } from '@queries/team/keys';+import { invalidateWhatsappGroups } from '@queries/whatsapp-groups';import { onCleanup } from 'solid-js';import { match, P } from 'ts-pattern';import { shareEntity } from '../access-requests/core/types';@@ -154,6 +155,9 @@ export function handleNotificationUpdate(notification: UnifiedNotification) {.with({ tag: 'call_started' }, () => {refreshChannel(notification);})+ .with({ tag: 'whatsapp_group_message' }, () => {+ fireAndForget(invalidateWhatsappGroups(), 'whatsapp-group.notification');+ }).with({ tag: 'new_email' }, () => {refreshEmailThread(notification);})diff --git a/apps/web/src/features/whatsapp-group/AGENTS.md b/apps/web/src/features/whatsapp-group/AGENTS.mdnew file mode 100644index 0000000000..e4a380fab7--- /dev/null+++ b/apps/web/src/features/whatsapp-group/AGENTS.md@@ -0,0 +1,38 @@+# WhatsApp group++## 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`.++## Map++- `core/`: feature vocabulary, sending identity and edit eligibility.+- `context/`: source and action contracts; no production imports.+- `primitives/conversation.ts`: drafts, quotes, uploads and deliberate sends.+- `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.+- `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.++## 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.+- 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.++## Checks++- `bunx vitest run --project app src/features/whatsapp-group src/features/whatsapp-linked`+- `bun run test:functional -- 'whatsapp-linked.spec.ts$'`+- `bun run check`diff --git a/apps/web/src/features/whatsapp-group/CLAUDE.md b/apps/web/src/features/whatsapp-group/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/apps/web/src/features/whatsapp-group/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/apps/web/src/features/whatsapp-group/components/group-composer.tsx b/apps/web/src/features/whatsapp-group/components/group-composer.tsxnew file mode 100644index 0000000000..8a80b86a54--- /dev/null+++ b/apps/web/src/features/whatsapp-group/components/group-composer.tsx@@ -0,0 +1,126 @@+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.tsxnew file mode 100644index 0000000000..53d4c4df20--- /dev/null+++ b/apps/web/src/features/whatsapp-group/components/group-message.tsx@@ -0,0 +1,211 @@+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-group/context/whatsapp-group-context.tsx b/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsxnew file mode 100644index 0000000000..e9201c3706--- /dev/null+++ b/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx@@ -0,0 +1,40 @@+import {+ type Accessor,+ createContext,+ type ParentProps,+ useContext,+} from 'solid-js';+import type { SourceRead } from '../../whatsapp-linked/context/whatsapp-linked-context';+import type {+ GroupDetail,+ GroupMessage,+ GroupSend,+ PendingSend,+} from '../core/group';++/** One mounted group's independent data and writes. */+export type WhatsAppGroupCapabilities = {+ group: SourceRead<GroupDetail>;+ 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 }>;+ markRead: (messageId: string) => Promise<unknown>;+ stopSync: () => Promise<unknown>;+};+const Context = createContext<WhatsAppGroupCapabilities>();+export function WhatsAppGroupProvider(+ props: ParentProps<{ value: WhatsAppGroupCapabilities }>+) {+ return (+ <Context.Provider value={props.value}>{props.children}</Context.Provider>+ );+}+export function useWhatsAppGroup() {+ const value = useContext(Context);+ if (!value) throw new Error('WhatsAppGroupProvider is required');+ return value;+}diff --git a/apps/web/src/features/whatsapp-group/core/group.test.ts b/apps/web/src/features/whatsapp-group/core/group.test.tsnew file mode 100644index 0000000000..f38c5f265f--- /dev/null+++ b/apps/web/src/features/whatsapp-group/core/group.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';+import { group, messages } from '../tests/fake-capabilities';+import { canChangeMessage, composerNote } from './group';++describe('personal sending identity', () => {+ it('lets a shared viewer read while explaining their missing account', () => {+ expect(+ composerNote({ ...group, canSend: false, sendReason: 'no_account' })+ ).toBe('Connect your WhatsApp to reply');+ expect(+ composerNote({ ...group, canSend: false, sendReason: 'not_member' })+ ).toBe("Your WhatsApp isn't in this group");+ expect(composerNote(group)).toBe('Sending as +14155550142');+ });+ it('offers changes only on own messages inside the server window', () => {+ const own = messages[1];+ const now = Date.parse(own.sentAt) + 5000;+ expect(canChangeMessage(own, group.ownerId, group, now, 'edit')).toBe(true);+ expect(canChangeMessage(own, 'another-person', group, now, 'edit')).toBe(+ false+ );+ expect(+ canChangeMessage(own, group.ownerId, group, now + 900000, 'edit')+ ).toBe(false);+ expect(+ canChangeMessage(+ { ...own, deleted: true },+ group.ownerId,+ group,+ now,+ 'edit'+ )+ ).toBe(false);+ expect(+ canChangeMessage(+ own,+ group.ownerId,+ { ...group, canSend: false },+ now,+ 'edit'+ )+ ).toBe(false);+ });+});diff --git a/apps/web/src/features/whatsapp-group/core/group.ts b/apps/web/src/features/whatsapp-group/core/group.tsnew file mode 100644index 0000000000..02c62cf78e--- /dev/null+++ b/apps/web/src/features/whatsapp-group/core/group.ts@@ -0,0 +1,91 @@+import type { InboundAttachment } from '../../whatsapp-linked/core/attachments';+import type { DeliveryState } from '../../whatsapp-linked/core/delivery';++/** Feature vocabulary; transport decoding lives in queries/. */+export type GroupSummary = {+ id: string;+ name: string;+ unreadCount: number;+};+export type GroupDetail = {+ id: string;+ name: string;+ ownerId: string;+ accessLevel: 'view' | 'comment' | 'edit' | 'owner';+ canSend: boolean;+ sendReason?: string;+ phone?: string;+ lastReadMessageId?: string;+ unreadCount: number;+ members: { id: string; name: string; admin: boolean }[];+ limits: {+ textBytes: number;+ attachmentBytes: number;+ attachmentTypes: string[];+ editSeconds: number;+ mutations: ('reaction' | 'edit' | 'delete')[];+ };+};+export type GroupMessage = {+ id: string;+ sender: { name: string; userId?: string };+ body: string;+ sentAt: string;+ edited: boolean;+ deleted: boolean;+ replyTo?: string;+ reactions: { emoji: string; count: number; mine: boolean }[];+ attachments: InboundAttachment[];+ delivery?: DeliveryState;+};+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 }+ | { kind: 'reaction'; messageId: string; emoji: string }+ | { kind: 'edit'; messageId: string; text: string }+ | { kind: 'delete'; messageId: string };++/** Both identity and the current backend limit are required for message changes. */+export function canChangeMessage(+ message: GroupMessage,+ userId: string | undefined,+ group: GroupDetail,+ now: number,+ operation: 'edit' | 'delete'+): boolean {+ const age = now - Date.parse(message.sentAt);+ return (+ !!userId &&+ group.canSend &&+ group.limits.mutations.includes(operation) &&+ !message.deleted &&+ message.sender.userId === userId &&+ age >= 0 &&+ age < group.limits.editSeconds * 1000+ );+}++export function composerNote(group: GroupDetail): string {+ if (group.canSend)+ 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';+}diff --git a/apps/web/src/features/whatsapp-group/core/route.ts b/apps/web/src/features/whatsapp-group/core/route.tsnew file mode 100644index 0000000000..d2d779d7d5--- /dev/null+++ b/apps/web/src/features/whatsapp-group/core/route.ts@@ -0,0 +1,13 @@+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}`;+}+export function parseWhatsAppGroupComponentId(+ componentId: string+): string | undefined {+ if (!componentId.startsWith(prefix)) return;+ return z.uuid().safeParse(componentId.slice(prefix.length)).data;+}diff --git a/apps/web/src/features/whatsapp-group/primitives/conversation.test.ts b/apps/web/src/features/whatsapp-group/primitives/conversation.test.tsnew file mode 100644index 0000000000..e1742bac10--- /dev/null+++ b/apps/web/src/features/whatsapp-group/primitives/conversation.test.ts@@ -0,0 +1,152 @@+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it } 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');+ state.conversation.reply(messages[0]);+ state.fake.setMessages([...messages]);+ expect(state.conversation.draft()).toBe('Reply from my own WhatsApp');+ await state.conversation.submit();+ expect(state.fake.capabilities.send).toHaveBeenCalledWith(+ {+ kind: 'text',+ text: 'Reply from my own WhatsApp',+ replyTo: 'message-1',+ },+ expect.any(String)+ );+ expect(state.conversation.draft()).toBe('');+ expect(state.conversation.quote()).toBeUndefined();+ 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,+ };+ });+ 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,+ };+ });+ state.conversation.setDraft('Cannot send');+ await state.conversation.submit();+ expect(state.fake.capabilities.send).not.toHaveBeenCalled();+ state.fake.setGroup(group);+ state.conversation.setFile(+ new File(['test'], 'program.exe', { type: 'application/octet-stream' })+ );+ await state.conversation.submit();+ expect(state.fake.capabilities.upload).not.toHaveBeenCalled();+ expect(state.conversation.error()).toContain('not supported');+ 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 };+ });+ 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,+ };+ });+ 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(+ () =>+ new Promise((resolve) => {+ finishUpload = resolve;+ })+ );+ return {+ fake,+ setUserId,+ conversation: createConversation(fake.capabilities, userId),+ 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.tsnew file mode 100644index 0000000000..71351a97ed--- /dev/null+++ b/apps/web/src/features/whatsapp-group/primitives/conversation.ts@@ -0,0 +1,181 @@+import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';+import type { WhatsAppGroupCapabilities } from '../context/whatsapp-group-context';+import {+ canChangeMessage,+ type GroupMessage,+ type GroupSend,+} from '../core/group';++/** Drafts survive background refresh; failed and unknown sends are never retried. */+export function createConversation(+ source: WhatsAppGroupCapabilities,+ userId: Accessor<string | undefined>+) {+ 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 [initialRead, setInitialRead] = createSignal<string>();+ const [initialUnreadCount, setInitialUnreadCount] = createSignal(0);+ const [readCaptured, setReadCaptured] = createSignal(false);+ let marked: string | undefined;+ let disposed = false;+ onCleanup(() => {+ disposed = true;+ });++ createEffect(() => {+ const group = source.group.data;+ if (group && !readCaptured()) {+ setInitialRead(group.lastReadMessageId);+ setInitialUnreadCount(group.unreadCount);+ 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 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;+ }+ 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;+ }+ 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."+ );+ } finally {+ if (!disposed) setBusy(false);+ }+ };+ const mutate = async (request: GroupSend) => {+ 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+ );+ if (+ !message ||+ !canChangeMessage(message, userId(), group, Date.now(), request.kind)+ ) {+ setError('This message can no longer be changed.');+ return;+ }+ }+ setBusy(true);+ setError(undefined);+ 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);+ }+ };+ return {+ draft,+ setDraft,+ quote,+ editing,+ file,+ setFile,+ busy,+ error,+ initialRead,+ initialUnreadCount,+ markRead,+ submit,+ mutate,+ reply: (message: GroupMessage) => {+ setQuote(message);+ setEditing(undefined);+ },+ edit: (message: GroupMessage) => {+ setEditing(message);+ setQuote(undefined);+ setDraft(message.body);+ setFile(undefined);+ },+ cancelTarget: () => {+ if (editing()) setDraft('');+ setEditing(undefined);+ setQuote(undefined);+ },+ };+}+export type Conversation = ReturnType<typeof createConversation>;diff --git a/apps/web/src/features/whatsapp-group/queries/capabilities.ts b/apps/web/src/features/whatsapp-group/queries/capabilities.tsnew file mode 100644index 0000000000..287720ff38--- /dev/null+++ b/apps/web/src/features/whatsapp-group/queries/capabilities.ts@@ -0,0 +1,104 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { queryReadyGate } from '@queries/gate';+import {+ invalidateWhatsappGroups,+ useWhatsappGroupQueries,+ type WhatsAppGroupApi,+} from '@queries/whatsapp-groups';+import { whatsappOperation } from '@queries/whatsapp-linked/operation';+import type { UseQueryResult } from '@tanstack/solid-query';+import { type Accessor, createEffect } 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';+import type { GroupMessage } from '../core/group';++function sourceRead<T>(query: UseQueryResult<T>): SourceRead<T> {+ return {+ get data() {+ return queryReadyGate(query) ? query.data : undefined;+ },+ get isPending() {+ return query.isPending;+ },+ get isError() {+ return query.isError;+ },+ refetch: () => fireAndForget(query.refetch(), 'whatsapp-group.refresh'),+ };+}+/** Mounted sources own row reconciliation; cached query callbacks own only resolved IDs. */+export function createWhatsAppGroupCapabilities(+ api: WhatsAppGroupApi,+ userId: Accessor<string>,+ groupId: Accessor<string>+): WhatsAppGroupCapabilities {+ const queries = useWhatsappGroupQueries(api, userId, groupId);+ 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' }+ )+ );+ });+ return {+ group: sourceRead(queries.group),+ timeline: {+ get data() {+ return queryReadyGate(queries.messages) ? rows : undefined;+ },+ get isPending() {+ return queries.messages.isPending;+ },+ get isError() {+ return queries.messages.isError;+ },+ 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,+ }),+ upload: (file) =>+ whatsappOperation(+ 'group.upload',+ () => api.upload(groupId(), file),+ groupId()+ ),+ markRead: async (messageId) => {+ await whatsappOperation(+ 'group.read',+ () => api.markRead(groupId(), messageId),+ groupId()+ );+ await invalidateWhatsappGroups();+ },+ stopSync: async () => {+ await whatsappOperation(+ 'group.stop_sync',+ () => api.stopSync(groupId()),+ groupId()+ );+ await invalidateWhatsappGroups();+ },+ };+}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.tsnew file mode 100644index 0000000000..03b47d72ab--- /dev/null+++ b/apps/web/src/features/whatsapp-group/queries/production-api.test.ts@@ -0,0 +1,132 @@+import type {+ WhatsAppGroupDetail,+ WhatsAppGroupMessages,+} from '@service-storage/generated/schemas';+import { ok } from 'neverthrow';+import { beforeEach, expect, it, vi } from 'vitest';+import { whatsappGroupApi } from './production-api';++const client = vi.hoisted(() => ({+ list: vi.fn(),+ detail: vi.fn(),+ messages: vi.fn(),+ sends: vi.fn(),+ send: vi.fn(),+ upload: vi.fn(),+ markRead: vi.fn(),+ stopSync: vi.fn(),+}));+vi.mock('@service-storage/whatsapp-groups', () => ({+ whatsappGroupsClient: client,+}));+beforeEach(() => vi.clearAllMocks());++it('decodes shared viewing separately from the callers own sending account and handles an absent roster', async () => {+ const detail = {+ id: '019a061e-0000-7000-8000-000000000001',+ name: 'Shared group',+ user_id: 'macro|[email protected]',+ unread_count: 3,+ last_message_at: null,+ can_send: false,+ send_reason: 'no_account',+ access_level: 'view',+ sending_identity: null,+ roster: null,+ share_permission: {+ id: 'share-1',+ owner: 'macro|[email protected]',+ channelSharePermissions: [],+ },+ limits: {+ text_limit_bytes: 65536,+ attachment_limit_bytes: 33554432,+ max_attachments: 1,+ mutations: ['reaction', 'edit', 'delete'],+ mutation_window_seconds: 900,+ attachment_types: ['image/png', 'application/pdf'],+ },+ } satisfies WhatsAppGroupDetail;+ client.detail.mockResolvedValue(ok(detail));+ const group = await whatsappGroupApi.detail(detail.id);+ expect(group.ownerId).toBe('macro|[email protected]');+ expect(group.accessLevel).toBe('view');+ expect(group.canSend).toBe(false);+ expect(group.phone).toBeUndefined();+ expect(group.members).toEqual([]);+ expect(group.limits.attachmentTypes).toEqual([+ 'image/png',+ 'application/pdf',+ ]);+});++it('decodes pagination, deleted flags, reaction ownership and attachment states from the independent timeline', async () => {+ const page = {+ next_cursor: '019a061e-0000-7000-8000-000000000002',+ messages: [+ {+ id: '019a061e-0000-7000-8000-000000000003',+ sender: { person_id: 'person-1', user_id: null, name: 'Ana Ruiz' },+ body: '',+ reply_to: null,+ sent_at: '2026-10-21T12:00:00Z',+ received_at: '2026-10-21T12:00:01Z',+ edited_at: null,+ deleted: true,+ reactions: [{ emoji: '👍', count: 2, mine: true }],+ attachments: [+ {+ ordinal: 0,+ state: 'unsupported',+ file_name: 'drawing.psd',+ mime: 'image/vnd.adobe.photoshop',+ size: 1024,+ document_id: null,+ },+ ],+ delivery_state: null,+ },+ ],+ } satisfies WhatsAppGroupMessages;+ client.messages.mockResolvedValue(ok(page));+ const result = await whatsappGroupApi.messages('group-id', 'before-id');+ expect(client.messages).toHaveBeenCalledWith('group-id', 'before-id');+ expect(result.before).toBe(page.next_cursor);+ expect(result.messages[0]).toMatchObject({+ deleted: true,+ sender: { name: 'Ana Ruiz' },+ reactions: [{ emoji: '👍', count: 2, mine: true }],+ attachments: [+ { state: 'unsupported', fileName: 'drawing.psd', documentId: undefined },+ ],+ });+});++it('preserves the deliberate send key and maps quotes and reactions without a channel request', async () => {+ client.send.mockResolvedValue(ok({ id: 'send-1' }));+ await whatsappGroupApi.send(+ 'group-id',+ { kind: 'text', text: 'Reply', replyTo: 'quoted-id' },+ 'intent-key'+ );+ expect(client.send).toHaveBeenCalledWith('group-id', {+ idempotency_key: 'intent-key',+ message: { type: 'text', text: 'Reply' },+ reply_to: 'quoted-id',+ });+ await whatsappGroupApi.send(+ 'group-id',+ { kind: 'reaction', messageId: 'message-id', emoji: '' },+ 'reaction-key'+ );+ expect(client.send).toHaveBeenLastCalledWith('group-id', {+ idempotency_key: 'reaction-key',+ message: {+ type: 'mutation',+ message_id: 'message-id',+ operation: 'reaction',+ text: '',+ },+ reply_to: null,+ });+});diff --git a/apps/web/src/features/whatsapp-group/queries/production-api.ts b/apps/web/src/features/whatsapp-group/queries/production-api.tsnew file mode 100644index 0000000000..fd41398995--- /dev/null+++ b/apps/web/src/features/whatsapp-group/queries/production-api.ts@@ -0,0 +1,140 @@+import { throwOnErr } from '@core/util/result';+import type { WhatsAppGroupApi } from '@queries/whatsapp-groups';+import type { LinkedReplyContent } from '@service-storage/generated/schemas/linkedReplyContent';+import { whatsappGroupsClient as client } from '@service-storage/whatsapp-groups';+import { match } from 'ts-pattern';+import { phoneFromJid } from '../../whatsapp-linked/core/account';+import type { GroupSend } from '../core/group';++function content(request: GroupSend): LinkedReplyContent {+ return match(request)+ .with({ kind: 'text' }, ({ text }) => ({ type: 'text' as const, text }))+ .with({ kind: 'media' }, ({ uploadId, caption }) => ({+ type: 'media' as const,+ upload_id: uploadId,+ caption: caption ?? null,+ }))+ .with({ kind: 'reaction' }, ({ messageId, emoji }) => ({+ type: 'mutation' as const,+ message_id: messageId,+ operation: 'reaction' as const,+ text: emoji,+ }))+ .with({ kind: 'edit' }, ({ messageId, text }) => ({+ type: 'mutation' as const,+ message_id: messageId,+ operation: 'edit' as const,+ text,+ }))+ .with({ kind: 'delete' }, ({ messageId }) => ({+ type: 'mutation' as const,+ message_id: messageId,+ operation: 'delete' as const,+ text: null,+ }))+ .exhaustive((unknown) => {+ // GroupSend is built by this client, so an unknown kind is a bug here.+ throw new Error(`Unsupported WhatsApp send: ${JSON.stringify(unknown)}`);+ });+}++/** Decodes DSS's generated wire models at the feature boundary. */+export const whatsappGroupApi: WhatsAppGroupApi = {+ list: async () =>+ (await throwOnErr(client.list)).map((group) => ({+ id: group.id,+ name: group.name,+ unreadCount: group.unread_count,+ })),+ detail: async (id) => {+ const view = await throwOnErr(() => client.detail(id));+ return {+ id,+ name: view.name,+ ownerId: view.user_id,+ accessLevel: view.access_level,+ canSend: view.can_send,+ sendReason: view.send_reason ?? undefined,+ phone: view.sending_identity+ ? phoneFromJid(view.sending_identity)+ : undefined,+ unreadCount: view.unread_count,+ members: (view.roster?.participants ?? []).map((person) => ({+ id: person.jid,+ name:+ person.displayName ??+ phoneFromJid(person.jid) ??+ 'WhatsApp participant',+ admin: person.admin,+ })),+ limits: {+ textBytes: view.limits.text_limit_bytes,+ attachmentBytes: view.limits.attachment_limit_bytes,+ attachmentTypes: view.limits.attachment_types,+ editSeconds: view.limits.mutation_window_seconds,+ mutations: view.limits.mutations,+ },+ };+ },+ messages: async (id, before) => {+ const page = await throwOnErr(() => client.messages(id, before));+ return {+ before: page.next_cursor ?? undefined,+ messages: page.messages.map((message) => ({+ id: message.id,+ sender: {+ name: message.sender.name,+ userId: message.sender.user_id ?? undefined,+ },+ body: message.body,+ sentAt: message.sent_at,+ edited: !!message.edited_at,+ deleted: message.deleted,+ replyTo: message.reply_to ?? undefined,+ reactions: message.reactions.map((reaction) => ({+ emoji: reaction.emoji,+ count: reaction.count,+ mine: reaction.mine,+ })),+ attachments: message.attachments.map((attachment) => ({+ ordinal: attachment.ordinal,+ state: attachment.state,+ fileName: attachment.file_name,+ 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,+ })+ ),+ upload: async (id, file) => {+ const result = await throwOnErr(() => client.upload(id, file));+ return { uploadId: result.upload_id, audio: result.kind === 'audio' };+ },+ 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.tsxnew file mode 100644index 0000000000..a00d3886b8--- /dev/null+++ b/apps/web/src/features/whatsapp-group/route-views.tsx@@ -0,0 +1,16 @@+import { useRouteParams } from '@app/lib/split-router';+import { whatsappGroupRoute } from '@app/routes/routes';+import {+ usePageViewTracking,+ withAuth,+} from '@components/app/split-layout/split-router/app-route-shell';+import {+ WhatsAppGroupEntry,+ WhatsAppGroupSkeleton,+} from './whatsapp-group-entry';++export const WhatsAppGroupRouteView = withAuth(() => {+ const params = useRouteParams(whatsappGroupRoute);+ usePageViewTracking('whatsapp-group');+ return <WhatsAppGroupEntry groupId={params.groupId} />;+}, WhatsAppGroupSkeleton);diff --git a/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts b/apps/web/src/features/whatsapp-group/tests/fake-capabilities.tsnew file mode 100644index 0000000000..ee93e4378c--- /dev/null+++ b/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts@@ -0,0 +1,89 @@+import { createSignal } from 'solid-js';+import { vi } from 'vitest';+import type { SourceRead } from '../../whatsapp-linked/context/whatsapp-linked-context';+import type { WhatsAppGroupCapabilities } from '../context/whatsapp-group-context';+import type {+ GroupDetail,+ GroupMessage,+ GroupSend,+ PendingSend,+} from '../core/group';++export const group: GroupDetail = {+ id: '019a061e-0000-7000-8000-000000000001',+ name: 'Design Crit',+ ownerId: 'macro|[email protected]',+ accessLevel: 'owner',+ canSend: true,+ phone: '+14155550142',+ unreadCount: 1,+ lastReadMessageId: 'message-1',+ members: [{ id: 'ana', name: 'Ana Ruiz', admin: true }],+ limits: {+ textBytes: 65536,+ attachmentBytes: 33554432,+ attachmentTypes: ['image/png', 'application/pdf', 'audio/ogg'],+ editSeconds: 900,+ mutations: ['reaction', 'edit', 'delete'],+ },+};+export const messages: GroupMessage[] = [+ {+ id: 'message-1',+ sender: { name: 'Ana Ruiz' },+ body: 'The updated designs are ready for review.',+ sentAt: '2026-10-21T10:00:00Z',+ edited: false,+ deleted: false,+ reactions: [{ emoji: '👍', count: 2, mine: true }],+ attachments: [],+ },+ {+ id: 'message-2',+ sender: { name: 'Me', userId: 'macro|[email protected]' },+ body: 'Looking now. Thanks, Ana!',+ sentAt: new Date().toISOString(),+ edited: false,+ deleted: false,+ replyTo: 'message-1',+ reactions: [],+ attachments: [],+ delivery: 'delivered',+ },+];+export function createFakeGroup(+ initial: {+ group?: GroupDetail;+ messages?: GroupMessage[];+ sends?: PendingSend[];+ } = {}+) {+ const [detail, setGroup] = createSignal(initial.group ?? group);+ const [timeline, setMessages] = createSignal(initial.messages ?? messages);+ const read = <T>(data: () => T): SourceRead<T> => ({+ get data() {+ return data();+ },+ isPending: false,+ isError: false,+ refetch: vi.fn(),+ });+ 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+ ),+ upload: vi.fn(async (_file: File) => ({+ uploadId: 'upload-1',+ audio: false,+ })),+ markRead: vi.fn(async (_messageId: string) => undefined),+ stopSync: vi.fn(async () => undefined),+ } satisfies WhatsAppGroupCapabilities;+ return { capabilities, setGroup, setMessages };+}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.tsxnew file mode 100644index 0000000000..6d5deebeba--- /dev/null+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx@@ -0,0 +1,138 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { WhatsAppGroupProvider } from '../context/whatsapp-group-context';+import { createFakeGroup, group, messages } from '../tests/fake-capabilities';+import { WhatsAppGroupView } from './whatsapp-group-view';++beforeEach(() => {+ vi.stubGlobal('scrollTo', vi.fn());+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe = vi.fn();+ unobserve = vi.fn();+ disconnect = vi.fn();+ }+ );+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});+function mount(fake: ReturnType<typeof createFakeGroup>) {+ const share = vi.fn();+ render(() => (+ <WhatsAppGroupProvider value={fake.capabilities}>+ <WhatsAppGroupView+ userId={group.ownerId}+ onShare={share}+ onConnect={vi.fn()}+ renderAttachment={(id) => <span>document {id}</span>}+ />+ </WhatsAppGroupProvider>+ ));+ return { share };+}+it('shows external names, quotes, reactions and the viewers own sending identity', async () => {+ const fake = createFakeGroup();+ const { share } = mount(fake);+ expect(screen.getByText('Ana Ruiz')).toBeTruthy();+ expect(screen.getByText('Sending as +14155550142')).toBeTruthy();+ expect(+ screen.getByRole('button', { name: '👍 2, your reaction' })+ ).toBeTruthy();+ expect(screen.getByText(/Ana Ruiz: The updated designs/)).toBeTruthy();+ 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' }));+ await waitFor(() =>+ expect(fake.capabilities.send).toHaveBeenCalledWith(+ { kind: 'text', text: 'My own account reply', replyTo: 'message-1' },+ expect.any(String)+ )+ );+});+it('lets a shared viewer without WhatsApp read the timeline and asks them to connect to reply', () => {+ const fake = createFakeGroup({+ group: {+ ...group,+ accessLevel: 'view',+ canSend: false,+ sendReason: 'no_account',+ },+ });+ mount(fake);+ expect(+ screen.getByText('The updated designs are ready for review.')+ ).toBeTruthy();+ 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();+});+it('keeps unknown sends visible without any automatic resend', () => {+ 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,+ },+ ],+ },+ ],+ });+ 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)+ )+ );+});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.tsxnew file mode 100644index 0000000000..1ce49770a9--- /dev/null+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx@@ -0,0 +1,368 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { Button, ConfirmDialog } from '@ui';+import {+ createEffect,+ createSignal,+ For,+ type JSX,+ onCleanup,+ onMount,+ Show,+} from 'solid-js';+import { GroupComposer } from '../components/group-composer';+import { GroupMessageRow } from '../components/group-message';+import { useWhatsAppGroup } from '../context/whatsapp-group-context';+import { canChangeMessage, composerNote } from '../core/group';+import { createConversation } from '../primitives/conversation';++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);+ 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);+ const [stopError, setStopError] = createSignal<string>();+ const [stopPending, setStopPending] = createSignal(false);+ let scroller: HTMLDivElement | undefined;+ let alive = true;+ let newest: string | undefined;+ onCleanup(() => {+ alive = false;+ });+ const nearBottom = () =>+ !scroller ||+ scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 80;+ const messages = () => source.timeline.data ?? [];+ const unreadIndex = () => {+ 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;+ };+ onMount(() => {+ const visible = () => {+ if (nearBottom())+ fireAndForget(conversation.markRead(), 'whatsapp-group.read');+ };+ document.addEventListener('visibilitychange', visible);+ onCleanup(() => document.removeEventListener('visibilitychange', visible));+ });+ createEffect(() => {+ const latest = source.timeline.data?.at(-1)?.id;+ if (!latest || latest === newest) return;+ const follow = !newest || nearBottom();+ newest = latest;+ queueMicrotask(() => {+ if (!alive || !follow) return;+ if (scroller) scroller.scrollTop = scroller.scrollHeight;+ fireAndForget(conversation.markRead(), 'whatsapp-group.read');+ });+ });+ const older = async () => {+ const height = scroller?.scrollHeight ?? 0;+ const offset = scroller?.scrollTop ?? 0;+ await source.loadOlder();+ if (alive && scroller)+ scroller.scrollTop = offset + scroller.scrollHeight - height;+ };+ const openReply = async (id: string) => {+ setReplyError(undefined);+ const find = () =>+ scroller?.querySelector(`[data-message-id="${CSS.escape(id)}"]`);+ try {+ while (alive && !find() && source.hasOlder()) {+ const count = messages().length;+ await older();+ if (messages().length === 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.');+ } catch {+ if (alive) setReplyError("Couldn't load the quoted message. Try again.");+ }+ };+ return (+ <div+ class="flex h-full min-h-0 min-w-0 flex-col bg-panel text-ink touch:pt-(--mobile-content-inset-top)"+ style={{ '--user-icon-width': '32px', '--message-padding-x': '16px' }}+ >+ <header class="flex min-h-14 shrink-0 items-center gap-2 border-b border-edge-muted px-4">+ {props.leading}+ <div class="min-w-0 flex-1">+ <h1 class="truncate text-sm font-semibold">+ {source.group.data?.name ?? 'WhatsApp group'}+ </h1>+ <span class="text-xs text-ink-muted">WhatsApp</span>+ </div>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setRoster((value) => !value)}+ >+ Members+ </Button>+ <Button+ variant="outline"+ size="sm"+ disabled={!source.group.data}+ onClick={props.onShare}+ >+ Share+ </Button>+ </header>+ <Show when={roster()}>+ <aside class="max-h-56 shrink-0 overflow-y-auto border-b border-edge-muted p-4">+ <h2 class="mb-2 text-sm font-medium">WhatsApp members</h2>+ <p class="mb-2 text-xs text-ink-muted">+ WhatsApp membership controls who can send. Share controls who can+ read in Macro.+ </p>+ <ul class="space-y-1 text-sm">+ <For each={source.group.data?.members}>+ {(member) => (+ <li>+ {member.name}+ {member.admin ? ' · Admin' : ''}+ </li>+ )}+ </For>+ </ul>+ <Show when={source.group.data?.accessLevel === 'owner'}>+ <Button+ class="mt-3"+ variant="outline"+ size="sm"+ disabled={stopped()}+ onClick={() => setStopping(true)}+ >+ {stopped() ? 'Syncing stopped' : 'Stop syncing'}+ </Button>+ </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();+ }}+ >+ 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 && 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>+ <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 ?? '',+ }+ : 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}+ />+ )}+ </Show>+ <ConfirmDialog+ open={!!deleting()}+ onOpenChange={(open) => {+ if (!open) setDeleting(undefined);+ }}+ title="Delete this message for everyone?"+ 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);+ }}+ />+ <ConfirmDialog+ open={stopping()}+ onOpenChange={setStopping}+ title="Stop syncing this group?"+ body="Its history stays in Macro. New messages will stop syncing."+ confirmLabel="Stop syncing"+ tone="danger"+ pending={stopPending()}+ onConfirm={async () => {+ setStopPending(true);+ try {+ await source.stopSync();+ if (!alive) return;+ setStopped(true);+ setStopping(false);+ } catch {+ if (alive) setStopError("Couldn't stop syncing. Try again.");+ } finally {+ if (alive) setStopPending(false);+ }+ }}+ />+ <Show when={stopError()}>+ <p role="alert" class="p-2 text-xs text-failure-ink">+ {stopError()}+ </p>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx b/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsxnew file mode 100644index 0000000000..b5ed15106c--- /dev/null+++ b/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx@@ -0,0 +1,41 @@+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';++const Group = lazy(async () => ({+ default: (await import('./whatsapp-group')).WhatsAppGroup,+}));+export function WhatsAppGroupSkeleton() {+ return (+ <p role="status" class="p-6 text-sm text-ink-muted">+ Loading WhatsApp group…+ </p>+ );+}+function DisabledGroup() {+ const navigate = useNavigate();+ onMount(() =>+ navigate({ route: homeSplitRoute, params: {} }, { replace: true })+ );+ return null;+}+/** Gate before mounting any queries, including panes restored from session state. */+export function WhatsAppGroupEntry(props: { groupId: string }) {+ const flag = useFeatureFlag(enableWhatsappLinked);+ return (+ <Show+ when={flag().enabled}+ fallback={+ <Show when={!flag().loading} fallback={<WhatsAppGroupSkeleton />}>+ <DisabledGroup />+ </Show>+ }+ >+ <Suspense fallback={<WhatsAppGroupSkeleton />}>+ <Group groupId={props.groupId} />+ </Suspense>+ </Show>+ );+}diff --git a/apps/web/src/features/whatsapp-group/whatsapp-group.tsx b/apps/web/src/features/whatsapp-group/whatsapp-group.tsxnew file mode 100644index 0000000000..a7920035ec--- /dev/null+++ b/apps/web/src/features/whatsapp-group/whatsapp-group.tsx@@ -0,0 +1,55 @@+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 { 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 }) {+ const userId = useUserId();+ const navigate = useNavigate();+ const source = createWhatsAppGroupCapabilities(+ whatsappGroupApi,+ () => userId() ?? '',+ () => props.groupId+ );+ useSplitDisplayName(() => source.group.data?.name ?? 'WhatsApp group');+ const share = useShareModal(() => {+ const group = source.group.data;+ if (!group) return;+ return {+ id: props.groupId,+ itemType: 'whatsapp_group',+ blockAlias: 'whatsapp_group',+ name: group.name,+ owner: group.ownerId,+ userPermissions: getPermissions(group.accessLevel),+ };+ });+ return (+ <WhatsAppGroupProvider value={source}>+ <WhatsAppGroupView+ 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.mdnew file mode 100644index 0000000000..f24dd43466--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/AGENTS.md@@ -0,0 +1,47 @@+# whatsapp-linked++## What it is++Personal WhatsApp accounts linked as devices (External tab → WhatsApp): link an+account by QR, list its groups, and add a group as its own shareable Macro+entity. Each person sends from their own account. Behind the `enable-whatsapp-linked` flag.++## Start here++- `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.++## Scope++- Owns: the WhatsApp account page, pairing dialog and name-only Add dialog.+- Group timeline and sending: `features/whatsapp-group`; no channel integration.+- Not here: the External tab shell and route → `features/external-view`;+ HTTP → `lib/service-clients/service-storage/whatsapp-linked.ts`; shared+ queries → `lib/queries/whatsapp-linked`; DSS routes → `crates/whatsapp_linked`.++## Gotchas++- Mutations open `whatsapp.*` operation spans in the shared queries; HTTP+ trace propagation uses `safeFetch`. Record outcomes without server error bodies+ or pairing material.+- Pairing material (QR, codes) stays in the `ph-no-capture` dialog and the+ never-persisted, `gcTime: 0` pairing query. Never put it in a URL or log.+- The QR is encoded locally with `uqr`; never send the value to an image service.+- `core/pairing.ts` matches DSS's pairing states exhaustively; a new state+ 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 grants access only to its owner; the generic Share dialog manages+ later access. No special audience lists or WhatsApp membership requirement+ for viewing.++## Checks++- `bunx vitest run --project app src/features/whatsapp-linked`+- `bun run test:functional -- 'whatsapp-linked.spec.ts$'` (mocked `/meta/linked` routes)++## Related++- Rules: `.agents/rules/web/architecture.md` (FE-33) · Docs:+ `docs/agent-guide/external.md`diff --git a/apps/web/src/features/whatsapp-linked/CLAUDE.md b/apps/web/src/features/whatsapp-linked/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/apps/web/src/features/whatsapp-linked/components/account-card.tsx b/apps/web/src/features/whatsapp-linked/components/account-card.tsxnew file mode 100644index 0000000000..8aa62dc45e--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/account-card.tsx@@ -0,0 +1,83 @@+import { Button, Item } from '@ui';+import type { WhatsAppAccount } from '../core/account';+import { WhatsAppTile } from './whatsapp-tile';++/** Nothing linked yet: what linking means, its risk, and Connect. */+export function ConnectCard(props: {+ reconnect: boolean;+ /** Pairing is switched off on the server. */+ unavailable: boolean;+ pending: boolean;+ onConnect: () => void;+}) {+ return (+ <Item variant="outlined">+ <WhatsAppTile />+ <Item.Content>+ <Item.Title>WhatsApp</Item.Title>+ <Item.Description>+ {props.reconnect+ ? 'WhatsApp signed this device out. Link it again to keep your groups syncing.'+ : 'Link your personal WhatsApp as a linked device. Only groups you choose come into Macro.'}+ </Item.Description>+ <Item.Metadata>+ Macro connects as an unofficial WhatsApp client, which WhatsApp may+ restrict or ban accounts for.+ </Item.Metadata>+ </Item.Content>+ <Item.Actions class="self-center">+ <Button+ type="button"+ variant="strong"+ disabled={props.unavailable || props.pending}+ tooltip={+ props.unavailable ? 'Linking WhatsApp is turned off' : undefined+ }+ onClick={props.onConnect}+ >+ {props.reconnect ? 'Reconnect' : 'Connect'}+ </Button>+ </Item.Actions>+ </Item>+ );+}++/** The linked account and its Disconnect action. */+export function AccountCard(props: {+ account: WhatsAppAccount;+ pending: boolean;+ onDisconnect: () => void;+ onReplace: () => void;+}) {+ return (+ <Item variant="outlined">+ <WhatsAppTile />+ <Item.Content>+ <Item.Title>{props.account.phone ?? 'Your WhatsApp'}</Item.Title>+ <Item.Description>Connected · linked device</Item.Description>+ <div>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ class="-ml-2"+ disabled={props.pending}+ onClick={props.onReplace}+ >+ Use a different account+ </Button>+ </div>+ </Item.Content>+ <Item.Actions class="self-center">+ <Button+ type="button"+ variant="danger"+ disabled={props.pending}+ onClick={props.onDisconnect}+ >+ Disconnect+ </Button>+ </Item.Actions>+ </Item>+ );+}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.tsxnew file mode 100644index 0000000000..1d5ebc04a8--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/add-group-dialog.tsx@@ -0,0 +1,102 @@+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/connection-code.tsx b/apps/web/src/features/whatsapp-linked/components/connection-code.tsxnew file mode 100644index 0000000000..85dcea2b49--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/connection-code.tsx@@ -0,0 +1,28 @@+import { createMemo } from 'solid-js';+import { encode } from 'uqr';++/**+ * The pairing QR, encoded here: the value never reaches an image URL or a+ * third party. Black on white in both themes so phones can read it.+ */+export function ConnectionCode(props: { value: string; label: string }) {+ const code = createMemo(() => encode(props.value, { ecc: 'M', border: 2 }));+ const path = () =>+ code()+ .data.flatMap((row, y) =>+ row.flatMap((dark, x) => (dark ? [`M${x} ${y}h1v1h-1z`] : []))+ )+ .join('');+ return (+ <svg+ role="img"+ aria-label={props.label}+ viewBox={`0 0 ${code().size} ${code().size}`}+ shape-rendering="crispEdges"+ class="size-56 rounded-xl border border-edge-muted"+ >+ <rect width="100%" height="100%" fill="#fff" />+ <path d={path()} fill="#000" />+ </svg>+ );+}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.tsxnew file mode 100644index 0000000000..49113b012c--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/delivery-and-attachments.test.tsx@@ -0,0 +1,64 @@+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.tsxnew file mode 100644index 0000000000..c04cb52127--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/delivery-status.tsx@@ -0,0 +1,81 @@+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.tsxnew file mode 100644index 0000000000..ebd4f4094a--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/group-list.tsx@@ -0,0 +1,111 @@+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';++function GroupRow(props: {+ group: WhatsAppGroup;+ canAdd: boolean;+ onAdd: () => void;+ onOpenGroup: (groupId: string) => void;+}) {+ return (+ <Item size="sm" class="px-3" data-whatsapp-group={props.group.jid}>+ <Avatar size="lg">+ <Avatar.Fallback class="text-sm font-medium">+ {groupInitials(props.group.name)}+ </Avatar.Fallback>+ </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>+ </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>+ );+}++/** The connected account's groups: adopted ones link to their group. */+export function GroupList(props: {+ groups: WhatsAppGroup[];+ canAdd: boolean;+ onAdd: (group: WhatsAppGroup) => void;+ onOpenGroup: (groupId: string) => void;+}) {+ return (+ <ul class="flex flex-col gap-1" aria-label="Your WhatsApp groups">+ <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.+ </li>+ }+ >+ {(group) => (+ <li>+ <GroupRow+ group={group}+ canAdd={props.canAdd}+ onAdd={() => props.onAdd(group)}+ onOpenGroup={props.onOpenGroup}+ />+ </li>+ )}+ </For>+ </ul>+ );+}diff --git a/apps/web/src/features/whatsapp-linked/components/inbound-attachment.tsx b/apps/web/src/features/whatsapp-linked/components/inbound-attachment.tsxnew file mode 100644index 0000000000..ce168b9a70--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/inbound-attachment.tsx@@ -0,0 +1,44 @@+import SpinnerIcon from '@phosphor/spinner.svg';+import WarningIcon from '@phosphor/warning-circle.svg';+import { Match, Switch } from 'solid-js';+import type { InboundAttachment } from '../core/attachments';++/**+ * A WhatsApp file that isn't a Macro document yet: still importing, failed,+ * or of a kind Macro can't keep. Every state is the same height, so the+ * channel doesn't jump when it resolves.+ */+export function InboundAttachmentPlaceholder(props: {+ attachment: InboundAttachment;+}) {+ return (+ <div+ class="flex h-12 max-w-sm items-center gap-2 rounded-lg border border-edge-muted px-3 text-sm text-ink-muted"+ data-linked-inbound-attachment={props.attachment.state}+ >+ <Switch>+ <Match when={props.attachment.state === 'loading'}>+ <SpinnerIcon+ class="size-4 shrink-0 animate-spin"+ aria-hidden="true"+ />+ <span role="status" class="min-w-0 truncate">+ Loading {props.attachment.fileName}…+ </span>+ </Match>+ <Match when={props.attachment.state === 'unavailable'}>+ <WarningIcon class="size-4 shrink-0" aria-hidden="true" />+ <span class="min-w-0 truncate">+ Attachment unavailable: {props.attachment.fileName}+ </span>+ </Match>+ <Match when={props.attachment.state === 'unsupported'}>+ <WarningIcon class="size-4 shrink-0" aria-hidden="true" />+ <span class="min-w-0 truncate">+ {props.attachment.fileName} can't be shown in Macro+ </span>+ </Match>+ </Switch>+ </div>+ );+}diff --git a/apps/web/src/features/whatsapp-linked/components/pairing-dialog.tsx b/apps/web/src/features/whatsapp-linked/components/pairing-dialog.tsxnew file mode 100644index 0000000000..110103fd6c--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/pairing-dialog.tsx@@ -0,0 +1,277 @@+import { ActionDialogShell, Button, Dialog } from '@ui';+import { For, Match, Show, Switch } from 'solid-js';+import type { PasskeyCeremony } from '../context/whatsapp-linked-context';+import { formatCountdown, type PairingStep } from '../core/pairing';+import { ConnectionCode } from './connection-code';++const STEPS = [+ 'Open WhatsApp on your phone',+ 'Go to Settings → Linked devices',+ 'Tap Link a device',+ 'Point your phone at this code',+];++function CodeSlot(props: {+ qr: string | undefined;+ secondsLeft: number | undefined;+}) {+ return (+ <div class="flex flex-col items-center gap-2">+ <Show+ when={props.qr}+ fallback={+ <div+ role="status"+ class="flex size-56 items-center justify-center rounded-xl border border-edge-muted text-sm text-ink-muted"+ >+ Preparing code…+ </div>+ }+ >+ {(qr) => (+ <ConnectionCode+ value={qr()}+ label="Scan this code with WhatsApp on your phone"+ />+ )}+ </Show>+ <p class="h-4 text-xs text-ink-subtle">+ <Show when={props.qr ? props.secondsLeft : undefined}>+ {(seconds) => <>Expires in {formatCountdown(seconds())}</>}+ </Show>+ </p>+ </div>+ );+}++function Steps() {+ return (+ <ol class="flex flex-col gap-2 text-sm text-ink-muted">+ <For each={STEPS}>+ {(step, index) => (+ <li class="flex items-start gap-3">+ <span class="flex size-5 shrink-0 items-center justify-center rounded-full bg-hover text-xs font-medium text-ink">+ {index() + 1}+ </span>+ <span class="leading-5">{step}</span>+ </li>+ )}+ </For>+ </ol>+ );+}++/** How this device can answer WhatsApp's passkey challenge. */+export type PasskeyMode =+ | { kind: 'native' }+ | { kind: 'handoff'; desktopUrl: string }+ | { kind: 'unsupported' };++function PasskeyStep(props: {+ mode: PasskeyMode;+ challengeReady: boolean;+ ceremony: PasskeyCeremony;+ onConfirm: () => void;+ onHandOff: () => void;+}) {+ const running = () =>+ props.ceremony.kind === 'running' ? props.ceremony : undefined;+ const failure = () =>+ props.ceremony.kind === 'failed' ? props.ceremony.message : undefined;+ const fidoQr = () => {+ const event = running()?.event;+ return event?.type === 'qr' ? event.value : undefined;+ };+ const desktopUrl = () =>+ props.mode.kind === 'handoff' ? props.mode.desktopUrl : undefined;+ return (+ <div class="flex flex-col items-start gap-3" data-linked-passkey>+ <p class="text-sm font-medium text-ink">Confirm on your desktop</p>+ <Switch>+ <Match when={props.mode.kind === 'native'}>+ <p class="text-sm text-ink-muted">+ WhatsApp asks you to confirm this link with your phone's passkey.+ Keep Bluetooth on and your phone nearby.+ </p>+ <Show when={fidoQr()}>+ {(value) => (+ <div class="flex w-full flex-col items-center gap-2">+ <ConnectionCode+ value={value()}+ label="Scan this code with your phone's camera to confirm"+ />+ <p class="text-xs text-ink-subtle">+ Scan with your phone's camera, not WhatsApp.+ </p>+ </div>+ )}+ </Show>+ <Show when={running()?.event?.type === 'touch'}>+ <p role="status" class="text-sm text-ink">+ Confirm on your phone.+ </p>+ </Show>+ <Show when={running()?.event?.type === 'processing'}>+ <p role="status" class="text-sm text-ink-muted">+ Checking with WhatsApp…+ </p>+ </Show>+ <Show when={failure()}>+ {(message) => (+ <p role="alert" class="text-sm text-failure-ink">+ {message()}+ </p>+ )}+ </Show>+ <Button+ type="button"+ variant="strong"+ disabled={!props.challengeReady || !!running()}+ onClick={props.onConfirm}+ >+ {running()+ ? 'Waiting for your phone…'+ : failure()+ ? 'Try again'+ : 'Confirm with passkey'}+ </Button>+ </Match>+ <Match when={desktopUrl()}>+ {(url) => (+ <>+ <p class="text-sm text-ink-muted">+ WhatsApp asks for your phone's passkey, which only the Macro+ desktop app can use. Finish this same request there.+ </p>+ <a+ href={url()}+ onClick={props.onHandOff}+ class="text-sm font-medium text-ink underline underline-offset-2"+ >+ Continue in Macro desktop+ </a>+ </>+ )}+ </Match>+ <Match when={props.mode.kind === 'unsupported'}>+ <p role="alert" class="text-sm text-ink-muted">+ WhatsApp asks for your phone's passkey, which only the Macro desktop+ app can use. Start linking again from Macro on your computer.+ </p>+ </Match>+ </Switch>+ </div>+ );+}++/**+ * Linking WhatsApp as a device. Pairing material stays inside this+ * `ph-no-capture` dialog, out of session replay.+ */+export function PairingDialog(props: {+ open: boolean;+ step: PairingStep;+ secondsLeft: number | undefined;+ passkey: PasskeyMode;+ ceremony: PasskeyCeremony;+ onConfirmPasskey: () => void;+ /** The person continued in Macro desktop; closing must not cancel. */+ onHandOff: () => void;+ onRetry: () => void;+ onCancel: () => void;+}) {+ const qr = () => (props.step.kind === 'scan' ? props.step.qr : undefined);+ const code = () => (props.step.kind === 'code' ? props.step.code : undefined);+ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => {+ if (!open) props.onCancel();+ }}+ position="center"+ class="ph-no-capture w-110"+ >+ <ActionDialogShell>+ <ActionDialogShell.Body>+ <ActionDialogShell.Header>+ <ActionDialogShell.Title>Link WhatsApp</ActionDialogShell.Title>+ <ActionDialogShell.Description>+ {props.step.kind === 'passkey'+ ? 'WhatsApp wants to confirm it’s you before linking.'+ : props.step.kind === 'code'+ ? 'Enter this code on the phone that has your WhatsApp account.'+ : 'Scan this code with the phone that has your WhatsApp account.'}+ </ActionDialogShell.Description>+ </ActionDialogShell.Header>+ <Switch>+ <Match+ when={+ props.step.kind === 'scan' || props.step.kind === 'preparing'+ }+ >+ <CodeSlot qr={qr()} secondsLeft={props.secondsLeft} />+ <Steps />+ </Match>+ <Match when={code()}>+ {(code) => (+ <div class="flex flex-col items-center gap-4">+ <p class="text-sm text-ink-muted">+ In WhatsApp, open Linked devices, tap Link with phone number+ instead, and enter this code.+ </p>+ <strong class="text-2xl tracking-widest text-ink">+ {code()}+ </strong>+ </div>+ )}+ </Match>+ <Match when={props.step.kind === 'passkey'}>+ <PasskeyStep+ mode={props.passkey}+ challengeReady={+ props.step.kind === 'passkey' && !!props.step.challenge+ }+ ceremony={props.ceremony}+ onConfirm={props.onConfirmPasskey}+ onHandOff={props.onHandOff}+ />+ </Match>+ <Match when={props.step.kind === 'connected'}>+ <p role="status" class="text-sm text-ink-muted">+ Linked. Loading your groups…+ </p>+ </Match>+ <Match+ when={+ props.step.kind === 'expired' ||+ props.step.kind === 'failed' ||+ props.step.kind === 'cancelled'+ }+ >+ <div class="flex flex-col items-start gap-3">+ <p role="alert" class="text-sm text-ink-muted">+ {props.step.kind === 'expired'+ ? 'This code expired before it was scanned.'+ : "Linking didn't finish."}+ </p>+ <Button type="button" variant="strong" onClick={props.onRetry}>+ Show a new code+ </Button>+ </div>+ </Match>+ </Switch>+ </ActionDialogShell.Body>+ <ActionDialogShell.Footer>+ <Button+ type="button"+ variant="ghost"+ depth={2}+ onClick={props.onCancel}+ >+ Cancel+ </Button>+ </ActionDialogShell.Footer>+ </ActionDialogShell>+ </Dialog>+ );+}diff --git a/apps/web/src/features/whatsapp-linked/components/whatsapp-tile.tsx b/apps/web/src/features/whatsapp-linked/components/whatsapp-tile.tsxnew file mode 100644index 0000000000..9b5c345b9f--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/whatsapp-tile.tsx@@ -0,0 +1,11 @@+import WhatsappIcon from '@phosphor/whatsapp-logo.svg';+import { Item } from '@ui';++/** WhatsApp's brand tile, the media slot of the account rows. */+export function WhatsAppTile() {+ return (+ <Item.Media class="bg-[#25D366] text-[#fff]">+ <WhatsappIcon />+ </Item.Media>+ );+}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.tsxnew file mode 100644index 0000000000..04daf35ce7--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx@@ -0,0 +1,116 @@+import type { ResultAsync } from 'neverthrow';+import {+ type Accessor,+ createContext,+ type ParentProps,+ useContext,+} from 'solid-js';+import type { GroupSummary } from '../../whatsapp-group/core/group';+import type { WhatsAppAccount } from '../core/account';+import type { WhatsAppGroup } from '../core/group';+import type { PairingStep, PasskeyChallenge } from '../core/pairing';++/** A server read as the WhatsApp page needs it; `data` is set once loaded. */+export type SourceRead<Value> = {+ readonly isPending: boolean;+ readonly isError: boolean;+ readonly data: Value | undefined;+ refetch: () => void;+};++/** A pairing to show; a resumed one learns its deadline from the poll. */+export type StartedPairing = { pairingId: string; expiresAt?: string };++/** One polled read of a pairing. */+export type PairingRead = { step: PairingStep; expiresAt: string };++/** What the desktop authenticator asks the dialog to show. */+export type PasskeyEvent =+ | { type: 'qr'; value: string }+ | { type: 'touch' }+ | { type: 'processing' }+ | { type: 'dismiss' };++/** The desktop authenticator's progress on WhatsApp's passkey challenge. */+export type PasskeyCeremony =+ | { kind: 'idle' }+ | { kind: 'running'; event: PasskeyEvent | undefined }+ | { kind: 'failed'; message: string };++/** Why the passkey step did not finish, in words for the person. */+export type PasskeyFailure = { kind: 'passkey-failed'; message: string };++/**+ * Answering WhatsApp's passkey challenge. Only Macro desktop can; a browser+ * hands the pairing off to it by id.+ */+export type PasskeyCapability =+ | {+ kind: 'native';+ /** Signs the challenge on this device, then sends the assertion to DSS. */+ authenticate: (+ pairingId: string,+ challenge: PasskeyChallenge,+ onEvent: (event: PasskeyEvent) => void+ ) => ResultAsync<void, PasskeyFailure>;+ }+ | {+ kind: 'handoff';+ /** Opens this pairing in Macro desktop; carries only the pairing id. */+ desktopUrl: (pairingId: string) => string;+ }+ | { kind: 'unsupported' };++/** A request that did not reach a result; the page shows its own message. */+export type RequestFailure = { kind: 'request-failed' };++/**+ * Everything the WhatsApp page reads and does. Production builds it from the+ * shared `whatsapp-linked` queries; tests pass fakes.+ */+export type WhatsAppLinkedCapabilities = {+ /** The backend switches; pairing or adoption may be turned off. */+ features: SourceRead<{ pairing: boolean; adoption: boolean }>;+ /** The person's own account, `null` when they never connected one. */+ 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;+ /** `replace` retires the current identity for a different WhatsApp account. */+ connect: (replace: boolean) => ResultAsync<StartedPairing, RequestFailure>;+ cancelPairing: (pairingId: string) => ResultAsync<void, RequestFailure>;+ /** Pairing finished: refresh the account and its groups. */+ pairingFinished: () => Promise<unknown>;+ disconnect: (+ generation: number+ ) => ResultAsync<{ remoteUnlinkRequested: boolean }, RequestFailure>;+ adopt: (request: {+ groupJid: string;+ name: string;+ }) => ResultAsync<{ groupId: string }, RequestFailure>;+ isConnecting: Accessor<boolean>;+ isDisconnecting: Accessor<boolean>;+ isAdopting: Accessor<boolean>;+ /** Host action: open an adopted group. */+ openGroup: (groupId: string) => void;+};++const Context = createContext<WhatsAppLinkedCapabilities>();++export function WhatsAppLinkedProvider(+ props: ParentProps<{ value: WhatsAppLinkedCapabilities }>+) {+ return (+ <Context.Provider value={props.value}>{props.children}</Context.Provider>+ );+}++export function useWhatsAppLinked() {+ const value = useContext(Context);+ if (!value) throw new Error('WhatsAppLinkedProvider is required');+ return value;+}diff --git a/apps/web/src/features/whatsapp-linked/core/account.ts b/apps/web/src/features/whatsapp-linked/core/account.tsnew file mode 100644index 0000000000..e80e582d62--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/core/account.ts@@ -0,0 +1,48 @@+import { match } from 'ts-pattern';++/** Connection health of the person's own linked account. */+export type WhatsAppHealth =+ | 'pairing'+ | 'connected'+ | 'logged_out'+ | 'disconnected';++/** The signed-in person's linked WhatsApp account. */+export type WhatsAppAccount = {+ /** Consent generation; fences a disconnect against a later re-pairing. */+ generation: number;+ /** Verified phone number, once pairing finished. */+ phone: string | undefined;+ health: WhatsAppHealth;+};++/** What the WhatsApp page shows for an account. */+export type AccountStatus =+ | { kind: 'not-connected'; reconnect: boolean }+ | { kind: 'connected'; account: WhatsAppAccount };++export function accountStatus(account: WhatsAppAccount | null): AccountStatus {+ if (!account) return { kind: 'not-connected', reconnect: false };+ return match(account.health)+ .with('connected', () => ({ kind: 'connected' as const, account }))+ .with('logged_out', () => ({+ kind: 'not-connected' as const,+ reconnect: true,+ }))+ .with('pairing', 'disconnected', () => ({+ kind: 'not-connected' as const,+ reconnect: false,+ }))+ .exhaustive();+}++/**+ * The phone number in a WhatsApp user JID (`15551230142:[email protected]`),+ * as `+15551230142`. Other JID kinds (LID, groups) carry no phone number.+ */+export function phoneFromJid(jid: string): string | undefined {+ const [user, server] = jid.split('@');+ if (server !== 's.whatsapp.net' || !user) return undefined;+ const number = user.split(':')[0];+ return number && /^\d+$/.test(number) ? `+${number}` : undefined;+}diff --git a/apps/web/src/features/whatsapp-linked/core/attachments.test.ts b/apps/web/src/features/whatsapp-linked/core/attachments.test.tsnew file mode 100644index 0000000000..eb13ab7614--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/core/attachments.test.ts@@ -0,0 +1,48 @@+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.tsnew file mode 100644index 0000000000..599acfa2e6--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/core/attachments.ts@@ -0,0 +1,64 @@+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/core.test.ts b/apps/web/src/features/whatsapp-linked/core/core.test.tsnew file mode 100644index 0000000000..2270542f15--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/core/core.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';+import { accountStatus, phoneFromJid } from './account';+import { groupInitials } from './group';+import { formatCountdown, pairingStep, secondsLeft } from './pairing';++describe('pairingStep', () => {+ it('shows the QR only once the server has one', () => {+ expect(pairingStep({ state: 'qr', qr: null })).toEqual({+ kind: 'preparing',+ });+ expect(pairingStep({ state: 'qr', qr: '2@abc,def' })).toEqual({+ kind: 'scan',+ qr: '2@abc,def',+ });+ expect(pairingStep({ state: 'qr', code: 'ABCD-1234' })).toEqual({+ kind: 'code',+ code: 'ABCD-1234',+ });+ });++ it('carries WhatsApp’s passkey challenge for the desktop authenticator', () => {+ expect(+ pairingStep({ state: 'passkey', challenge: { rpId: 'whatsapp.com' } })+ ).toEqual({ kind: 'passkey', challenge: { rpId: 'whatsapp.com' } });+ expect(pairingStep({ state: 'passkey' })).toEqual({+ kind: 'passkey',+ challenge: undefined,+ });+ });++ it('reads the terminal states', () => {+ expect(pairingStep({ state: 'success' })).toEqual({ kind: 'connected' });+ expect(pairingStep({ state: 'expired' })).toEqual({ kind: 'expired' });+ expect(pairingStep({ state: 'cancelled' })).toEqual({ kind: 'cancelled' });+ expect(pairingStep({ state: 'failed' })).toEqual({ kind: 'failed' });+ });+});++describe('countdown', () => {+ it('rounds up to whole seconds and stops at zero', () => {+ const deadline = '2026-10-20T12:00:52.000Z';+ expect(secondsLeft(deadline, Date.parse('2026-10-20T12:00:00.500Z'))).toBe(+ 52+ );+ expect(secondsLeft(deadline, Date.parse('2026-10-20T12:01:00.000Z'))).toBe(+ 0+ );+ expect(formatCountdown(52)).toBe('0:52');+ expect(formatCountdown(125)).toBe('2:05');+ });+});++describe('account', () => {+ it('reads the phone number from a user JID with a device suffix', () => {+ expect(phoneFromJid('14155550142:[email protected]')).toBe('+14155550142');+ expect(phoneFromJid('[email protected]')).toBe('+14155550142');+ expect(phoneFromJid('81234567@lid')).toBeUndefined();+ });++ it('treats a signed-out device as needing a reconnect', () => {+ expect(+ accountStatus({ generation: 2, phone: undefined, health: 'logged_out' })+ ).toEqual({ kind: 'not-connected', reconnect: true });+ expect(accountStatus(null)).toEqual({+ kind: 'not-connected',+ reconnect: false,+ });+ expect(+ accountStatus({ generation: 2, phone: undefined, health: 'pairing' })+ ).toEqual({ kind: 'not-connected', reconnect: false });+ });+});++describe('group', () => {+ it('uses at most two letter initials', () => {+ expect(groupInitials('Launch War Room')).toBe('LW');+ expect(groupInitials('🎉 Design Crit')).toBe('DC');+ });+});diff --git a/apps/web/src/features/whatsapp-linked/core/delivery.ts b/apps/web/src/features/whatsapp-linked/core/delivery.tsnew file mode 100644index 0000000000..82180107ca--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/core/delivery.ts@@ -0,0 +1,107 @@+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.tsnew file mode 100644index 0000000000..4648c3f529--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/core/group.ts@@ -0,0 +1,21 @@+/** A WhatsApp group the connected account belongs to. */+export type WhatsAppGroup = {+ jid: string;+ name: string;+ memberCount: number;+ /** The shareable Macro group entity. */+ group: { id: string; name: string } | undefined;+ unreadCount?: number;+ /** Why this group cannot be added, when it cannot. */+ unsupported: 'community' | 'disappearing' | undefined;+};++/** Up to two initials from the words of a group name that start with a letter. */+export function groupInitials(name: string): string {+ return name+ .split(/\s+/)+ .filter((word) => /^\p{L}/u.test(word))+ .slice(0, 2)+ .map((word) => word[0]?.toLocaleUpperCase() ?? '')+ .join('');+}diff --git a/apps/web/src/features/whatsapp-linked/core/pairing.ts b/apps/web/src/features/whatsapp-linked/core/pairing.tsnew file mode 100644index 0000000000..5936cc04df--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/core/pairing.ts@@ -0,0 +1,69 @@+import { match, P } from 'ts-pattern';++/** One step of linking WhatsApp as a device, as the pairing dialog shows it. */+export type PairingStep =+ | { kind: 'preparing' }+ | { kind: 'scan'; qr: string }+ | { kind: 'code'; code: string }+ /** WhatsApp's WebAuthn request options, for the desktop authenticator only. */+ | { kind: 'passkey'; challenge: PasskeyChallenge | undefined }+ | { kind: 'connected' }+ | { kind: 'expired' }+ | { kind: 'cancelled' }+ | { kind: 'failed' };++/** WhatsApp's WebAuthn request options, passed through untouched. */+export type PasskeyChallenge = { [key: string]: unknown };++/** The pairing transaction's state, as DSS reports it. */+export type PairingState =+ | 'waiting'+ | 'qr'+ | 'passkey'+ | 'success'+ | 'expired'+ | 'cancelled'+ | 'failed';++/** What the dialog shows: a QR to scan, a code to type on the phone, or an outcome. */+export function pairingStep(state: {+ state: PairingState;+ qr?: string | null;+ code?: string | null;+ challenge?: PasskeyChallenge | null;+}): PairingStep {+ return match(state)+ .with({ state: 'waiting' }, () => ({ kind: 'preparing' as const }))+ .with({ state: 'qr', qr: P.string.minLength(1) }, ({ qr }) => ({+ kind: 'scan' as const,+ qr,+ }))+ .with({ state: 'qr', code: P.string.minLength(1) }, ({ code }) => ({+ kind: 'code' as const,+ code,+ }))+ .with({ state: 'qr' }, () => ({ kind: 'preparing' as const }))+ .with({ state: 'passkey' }, ({ challenge }) => ({+ kind: 'passkey' as const,+ challenge: challenge ?? undefined,+ }))+ .with({ state: 'success' }, () => ({+ kind: 'connected' as const,+ }))+ .with({ state: 'expired' }, () => ({ kind: 'expired' as const }))+ .with({ state: 'cancelled' }, () => ({ kind: 'cancelled' as const }))+ .with({ state: 'failed' }, () => ({ kind: 'failed' as const }))+ .exhaustive();+}++/** Whole seconds left before `expiresAt`, never negative. */+export function secondsLeft(expiresAt: string, now: number): number {+ return Math.max(0, Math.ceil((Date.parse(expiresAt) - now) / 1000));+}++/** `52` → `0:52`, `125` → `2:05`. */+export function formatCountdown(seconds: number): string {+ const minutes = Math.floor(seconds / 60);+ const rest = seconds % 60;+ return `${minutes}:${rest.toString().padStart(2, '0')}`;+}diff --git a/apps/web/src/features/whatsapp-linked/primitives/countdown.ts b/apps/web/src/features/whatsapp-linked/primitives/countdown.tsnew file mode 100644index 0000000000..7cfb6019c3--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/primitives/countdown.ts@@ -0,0 +1,20 @@+import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';+import { secondsLeft } from '../core/pairing';++/** Seconds left before `expiresAt`, ticking once a second only while there is one. */+export function createCountdown(+ expiresAt: Accessor<string | undefined>+): Accessor<number | undefined> {+ const [now, setNow] = createSignal(Date.now());+ // The clock is the external system: run it only while a deadline exists.+ createEffect(() => {+ if (expiresAt() === undefined) return;+ setNow(Date.now());+ const timer = setInterval(() => setNow(Date.now()), 1000);+ onCleanup(() => clearInterval(timer));+ });+ return () => {+ const deadline = expiresAt();+ return deadline === undefined ? undefined : secondsLeft(deadline, now());+ };+}diff --git a/apps/web/src/features/whatsapp-linked/primitives/pairing-flow.ts b/apps/web/src/features/whatsapp-linked/primitives/pairing-flow.tsnew file mode 100644index 0000000000..bd1e46f3aa--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/primitives/pairing-flow.ts@@ -0,0 +1,154 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { type Accessor, createEffect, createSignal, on } from 'solid-js';+import type {+ PasskeyCeremony,+ StartedPairing,+ WhatsAppLinkedCapabilities,+} from '../context/whatsapp-linked-context';+import type { PairingStep } from '../core/pairing';+import { createCountdown } from './countdown';++export type PairingFlow = {+ /** Whether the pairing dialog is open. */+ open: Accessor<boolean>;+ step: Accessor<PairingStep>;+ secondsLeft: Accessor<number | undefined>;+ /** Starting a pairing failed before any dialog opened. */+ startFailed: Accessor<boolean>;+ start: (replace: boolean) => Promise<void>;+ /** Shows a pairing started elsewhere, e.g. handed off to Macro desktop. */+ resume: (pairingId: string) => void;+ pairingId: Accessor<string | undefined>;+ passkey: Accessor<PasskeyCeremony>;+ /** The pairing continues in Macro desktop; closing here leaves it running. */+ handOff: () => void;+ /** Answers WhatsApp's passkey challenge on this device. */+ confirmPasskey: () => Promise<void>;+ retry: () => Promise<void>;+ cancel: () => Promise<void>;+};++/**+ * One owner-bound pairing at a time: start it, poll its step, count down its+ * deadline, and close once WhatsApp reports the device linked.+ */+export function createPairingFlow(+ /** The account already reads as linked, e.g. its poll beat the pairing poll. */+ accountLinked: Accessor<boolean>,+ capabilities: Pick<+ WhatsAppLinkedCapabilities,+ 'connect' | 'pairing' | 'cancelPairing' | 'pairingFinished' | 'passkey'+ >+): PairingFlow {+ const [current, setCurrent] = createSignal<StartedPairing>();+ const [replacing, setReplacing] = createSignal(false);+ const [startFailed, setStartFailed] = createSignal(false);+ const [handedOff, setHandedOff] = createSignal(false);+ const [passkey, setPasskey] = createSignal<PasskeyCeremony>({+ kind: 'idle',+ });+ const poll = capabilities.pairing(() => current()?.pairingId ?? '');+ const secondsLeft = createCountdown(+ () => current()?.expiresAt ?? poll.data?.expiresAt+ );++ // While replacing, the old account still reads linked; only the new+ // pairing's own success counts.+ const linkedByAccount = () => !replacing() && accountLinked();+ const step = (): PairingStep => {+ const polled = poll.data?.step ?? { kind: 'preparing' };+ // The deadline is the server's; once it passes, a stale QR is not scannable.+ if (polled.kind === 'scan' && secondsLeft() === 0) {+ return { kind: 'expired' };+ }+ return polled;+ };++ const finish = async () => {+ await capabilities.pairingFinished();+ setCurrent(undefined);+ };++ // The poll is the external system here: react to it reporting success.+ createEffect(+ on(+ () =>+ current() !== undefined &&+ (step().kind === 'connected' || linkedByAccount()),+ (connected) => {+ if (connected) fireAndForget(finish(), 'whatsapp-linked.pairing');+ }+ )+ );++ const start = async (replace: boolean) => {+ setStartFailed(false);+ setReplacing(replace);+ const started = await capabilities.connect(replace);+ if (started.isErr()) {+ setStartFailed(true);+ return;+ }+ setPasskey({ kind: 'idle' });+ setHandedOff(false);+ setCurrent(started.value);+ };++ const confirmPasskey = async () => {+ const pairing = current();+ const polled = step();+ const capability = capabilities.passkey;+ if (+ !pairing ||+ polled.kind !== 'passkey' ||+ !polled.challenge ||+ capability.kind !== 'native' ||+ passkey().kind === 'running'+ )+ return;+ setPasskey({ kind: 'running', event: undefined });+ const result = await capability.authenticate(+ pairing.pairingId,+ polled.challenge,+ (event) => {+ if (passkey().kind === 'running')+ setPasskey({ kind: 'running', event });+ }+ );+ setPasskey(+ result.isErr()+ ? { kind: 'failed', message: result.error.message }+ : { kind: 'idle' }+ );+ };++ const cancel = async () => {+ const pairing = current();+ const finished =+ step().kind === 'connected' || linkedByAccount() || handedOff();+ setCurrent(undefined);+ if (!pairing || finished) return;+ // The server also expires an abandoned pairing; nothing to recover here.+ await capabilities.cancelPairing(pairing.pairingId);+ };++ return {+ open: () => current() !== undefined,+ step,+ secondsLeft,+ startFailed,+ start,+ resume: (pairingId) => {+ setReplacing(false);+ setHandedOff(false);+ setPasskey({ kind: 'idle' });+ setCurrent({ pairingId });+ },+ pairingId: () => current()?.pairingId,+ passkey,+ handOff: () => setHandedOff(true),+ confirmPasskey,+ retry: () => start(replacing()),+ cancel,+ };+}diff --git a/apps/web/src/features/whatsapp-linked/queries/authenticator.test.ts b/apps/web/src/features/whatsapp-linked/queries/authenticator.test.tsnew file mode 100644index 0000000000..f05a25935f--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/queries/authenticator.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it, vi } from 'vitest';++const invoke = vi.hoisted(() => vi.fn());+vi.mock('@tauri-apps/api/core', () => ({+ invoke,+ Channel: class {+ onmessage: ((event: unknown) => void) | undefined;+ },+}));++import { authenticateWhatsAppPasskey } from './authenticator';++describe('authenticateWhatsAppPasskey', () => {+ it('passes the challenge verbatim and returns the assertion', async () => {+ invoke.mockResolvedValueOnce({ id: 'credential', type: 'public-key' });+ const result = await authenticateWhatsAppPasskey(+ 'pairing-1',+ { challenge: 'abc', rpId: 'whatsapp.com' },+ vi.fn()+ );+ expect(result._unsafeUnwrap()).toEqual({+ id: 'credential',+ type: 'public-key',+ });+ expect(invoke).toHaveBeenCalledWith('whatsapp_passkey_authenticate', {+ pairingId: 'pairing-1',+ challenge: { challenge: 'abc', rpId: 'whatsapp.com' },+ onEvent: expect.anything(),+ });+ });++ it('asks for a desktop update when the command is missing', async () => {+ invoke.mockRejectedValueOnce(+ 'Command whatsapp_passkey_authenticate not found'+ );+ const result = await authenticateWhatsAppPasskey('p', {}, vi.fn());+ expect(result._unsafeUnwrapErr().message).toBe(+ 'Update Macro desktop to confirm WhatsApp passkeys, then try again.'+ );+ });++ it('puts the desktop app’s error codes into words', async () => {+ invoke.mockRejectedValueOnce('unverified');+ const result = await authenticateWhatsAppPasskey('p', {}, vi.fn());+ expect(result._unsafeUnwrapErr().message).toBe(+ 'Your phone did not verify you. Unlock your phone and try again.'+ );+ });+});diff --git a/apps/web/src/features/whatsapp-linked/queries/authenticator.ts b/apps/web/src/features/whatsapp-linked/queries/authenticator.tsnew file mode 100644index 0000000000..aca41ff439--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/queries/authenticator.ts@@ -0,0 +1,69 @@+import { isPlatform, isTauri } from '@core/util/platform';+import { Channel, invoke } from '@tauri-apps/api/core';+import { ResultAsync } from 'neverthrow';+import { match, P } from 'ts-pattern';+import type {+ PasskeyEvent,+ PasskeyFailure,+} from '../context/whatsapp-linked-context';+import type { PasskeyChallenge } from '../core/pairing';++/** Whether this is Macro desktop, the only place a passkey can be answered. */+export function canAuthenticatePasskey(): boolean {+ return isTauri() && isPlatform('desktop');+}++/** The desktop app's errors (`whatsapp_passkey::AuthenticationError`) in words. */+function passkeyFailure(error: unknown): PasskeyFailure {+ const message = match(error)+ .with(+ 'invalid',+ () =>+ 'This connection request is no longer valid. Start connecting again.'+ )+ .with(+ 'unverified',+ () => 'Your phone did not verify you. Unlock your phone and try again.'+ )+ // Desktop builds from before the command answer "command ... not found".+ .with(+ P.string.regex(/not found/i),+ () => 'Update Macro desktop to confirm WhatsApp passkeys, then try again.'+ )+ .with(+ P.union('unavailable', 'unsupported'),+ () =>+ 'WhatsApp authentication was cancelled or unavailable. Check Bluetooth, keep your phone nearby, and try again.'+ )+ .otherwise(+ () =>+ 'WhatsApp authentication could not finish. Check Bluetooth and try again.'+ );+ return { kind: 'passkey-failed', message };+}++/**+ * Signs WhatsApp's passkey challenge with the desktop authenticator (caBLE or+ * the OS WebAuthn API). The assertion only leaves through the passkey route.+ */+export function authenticateWhatsAppPasskey(+ pairingId: string,+ challenge: PasskeyChallenge,+ onEvent: (event: PasskeyEvent) => void+): ResultAsync<Record<string, unknown>, PasskeyFailure> {+ const events = new Channel<PasskeyEvent>();+ events.onmessage = onEvent;+ return ResultAsync.fromPromise(+ invoke<Record<string, unknown>>('whatsapp_passkey_authenticate', {+ pairingId,+ challenge,+ onEvent: events,+ }),+ passkeyFailure+ );+}++/** A deep link that opens this pairing in Macro desktop, by id only. */+export function desktopPairingUrl(pairingId: string): string {+ return `macro:///external?whatsappPairing=${encodeURIComponent(pairingId)}`;+}diff --git a/apps/web/src/features/whatsapp-linked/queries/decode.ts b/apps/web/src/features/whatsapp-linked/queries/decode.tsnew file mode 100644index 0000000000..185fa5c4b8--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/queries/decode.ts@@ -0,0 +1,47 @@+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 { phoneFromJid, type WhatsAppAccount } from '../core/account';+import type { WhatsAppGroup } from '../core/group';+import { type PairingStep, pairingStep } from '../core/pairing';++export function decodeAccount(+ account: LinkedAccount | null | undefined+): WhatsAppAccount | null {+ if (!account) return null;+ return {+ generation: account.authorization_generation,+ phone: account.identity_jid+ ? phoneFromJid(account.identity_jid)+ : undefined,+ health: account.state,+ };+}++export function decodeGroup(group: LinkedGroupInfo): WhatsAppGroup {+ return {+ jid: group.jid,+ name: group.name,+ memberCount: group.participants.length,+ group: group.group+ ? { id: group.group.id, name: group.group.name }+ : undefined,+ unsupported: group.community+ ? 'community'+ : group.disappearing+ ? 'disappearing'+ : undefined,+ };+}++/** 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 decodePairing(state: LinkedPairState): {+ step: PairingStep;+ expiresAt: string;+} {+ return { step: pairingStep(state), expiresAt: state.expiresAt };+}diff --git a/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts b/apps/web/src/features/whatsapp-linked/queries/production-capabilities.tsnew file mode 100644index 0000000000..317f7fcfcc--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts@@ -0,0 +1,144 @@+import { useUserId } from '@core/context/user';+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';+import { fireAndForget } from '@core/util/fireAndForget';+import { queryReadyGate } from '@queries/gate';+import { useWhatsappGroupsQuery } from '@queries/whatsapp-groups';+import {+ refreshWhatsappLinkedAccount,+ useAdoptWhatsappGroupMutation,+ useCancelWhatsappPairingMutation,+ useConnectWhatsappMutation,+ useDisconnectWhatsappMutation,+ useSubmitWhatsappPasskeyMutation,+ useWhatsappLinkedAccountQuery,+ useWhatsappLinkedConfigurationQuery,+ useWhatsappLinkedGroupsQuery,+ useWhatsappLinkedPairingQuery,+} from '@queries/whatsapp-linked';+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 {+ PasskeyCapability,+ RequestFailure,+ SourceRead,+ WhatsAppLinkedCapabilities,+} from '../context/whatsapp-linked-context';+import {+ authenticateWhatsAppPasskey,+ canAuthenticatePasskey,+ desktopPairingUrl,+} from './authenticator';+import { decodeAccount, decodeGroups, decodePairing } from './decode';++const failure = (): RequestFailure => ({ kind: 'request-failed' });++function sourceRead<Wire, Value>(+ query: UseQueryResult<Wire>,+ decode: (wire: Wire) => Value+): SourceRead<Value> {+ const data = createMemo(() =>+ queryReadyGate(query) ? decode(query.data) : undefined+ );+ return {+ get isPending() {+ return query.isPending;+ },+ get isError() {+ return query.isError;+ },+ get data() {+ return data();+ },+ refetch: () => fireAndForget(query.refetch(), 'whatsapp-linked'),+ };+}++/** The WhatsApp page's capabilities, from the shared linked-device queries. */+export function createWhatsAppLinkedCapabilities(host: {+ openGroup: (groupId: string) => void;+}): WhatsAppLinkedCapabilities {+ const user = useUserId();+ const currentUser = () => user() ?? '';+ const connect = useConnectWhatsappMutation();+ const disconnect = useDisconnectWhatsappMutation();+ const cancel = useCancelWhatsappPairingMutation();+ const adopt = useAdoptWhatsappGroupMutation();+ const sharedGroups = sourceRead(+ useWhatsappGroupsQuery(whatsappGroupApi, currentUser),+ (groups) => groups+ );+ const submitPasskey = useSubmitWhatsappPasskeyMutation();+ const passkey: PasskeyCapability = canAuthenticatePasskey()+ ? {+ kind: 'native',+ authenticate: (pairingId, challenge, onEvent) =>+ authenticateWhatsAppPasskey(pairingId, challenge, onEvent).andThen(+ (response) =>+ ResultAsync.fromPromise(+ submitPasskey.mutateAsync({ pairingId, response }),+ () => ({+ kind: 'passkey-failed' as const,+ message:+ "Your phone confirmed, but Macro couldn't pass it on to WhatsApp. Try again.",+ })+ ).map(() => undefined)+ ),+ }+ : isNativeMobilePlatform()+ ? { kind: 'unsupported' }+ : { kind: 'handoff', desktopUrl: desktopPairingUrl };+ 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,+ passkey,+ pairing: (pairingId: Accessor<string>) =>+ sourceRead(+ useWhatsappLinkedPairingQuery(currentUser, pairingId),+ decodePairing+ ),+ connect: (replace) =>+ ResultAsync.fromPromise(connect.mutateAsync(replace), failure).map(+ (pairing) => ({ pairingId: pairing.id, expiresAt: pairing.expires_at })+ ),+ cancelPairing: (pairingId) =>+ ResultAsync.fromPromise(cancel.mutateAsync(pairingId), failure).map(+ () => undefined+ ),+ pairingFinished: refreshWhatsappLinkedAccount,+ disconnect: (generation) =>+ ResultAsync.fromPromise(disconnect.mutateAsync(generation), failure).map(+ (result) => ({+ remoteUnlinkRequested: result.remote_unlink_requested,+ })+ ),+ adopt: (request) =>+ ResultAsync.fromPromise(+ adopt.mutateAsync({+ group_jid: request.groupJid,+ name: request.name,+ }),+ failure+ ).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.tsnew file mode 100644index 0000000000..03cdbf51b4--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts@@ -0,0 +1,104 @@+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,+ RequestFailure,+ SourceRead,+ WhatsAppLinkedCapabilities,+} from '../context/whatsapp-linked-context';+import type { WhatsAppAccount } from '../core/account';+import type { WhatsAppGroup } from '../core/group';+import type { PairingStep } from '../core/pairing';++function signalRead<Value>(+ initial: Value | undefined+): [SourceRead<Value>, Setter<Value | undefined>] {+ const [data, setData] = createSignal<Value | undefined>(initial);+ return [+ {+ get isPending() {+ return data() === undefined;+ },+ isError: false,+ get data() {+ return data();+ },+ refetch: vi.fn(),+ },+ setData,+ ];+}++/** Server state a test drives by setting signals; actions are spies. */+export function createFakeWhatsApp(initial: {+ account: WhatsAppAccount | null;+ groups?: WhatsAppGroup[];+ passkey?: PasskeyCapability;+ sharedGroups?: GroupSummary[];+}) {+ const [account, setAccount] = signalRead<WhatsAppAccount | null>(+ initial.account+ );+ const [groups, setGroups] = signalRead<WhatsAppGroup[]>(initial.groups);+ const [features] = signalRead({ pairing: true, adoption: true });+ const [pairing, setPairingRead] = signalRead<PairingRead>(undefined);+ const setPairing = (step: PairingStep, expiresAt?: string) =>+ setPairingRead({+ step,+ expiresAt: expiresAt ?? new Date(Date.now() + 52_000).toISOString(),+ });+ const groupsEnabled: Accessor<boolean>[] = [];+ const capabilities = {+ features,+ sharedGroups: signalRead(initial.sharedGroups ?? [])[0],+ account,+ groups: vi.fn((enabled: Accessor<boolean>) => {+ groupsEnabled.push(enabled);+ return groups;+ }),+ passkey: initial.passkey ?? {+ kind: 'handoff',+ desktopUrl: (pairingId: string) =>+ `macro:///external?whatsappPairing=${pairingId}`,+ },+ pairing: vi.fn((_pairingId: Accessor<string>) => pairing),+ connect: vi.fn(+ (+ _replace: boolean+ ): ResultAsync<+ { pairingId: string; expiresAt: string },+ RequestFailure+ > =>+ okAsync({+ pairingId: 'pairing-1',+ expiresAt: new Date(Date.now() + 52_000).toISOString(),+ })+ ),+ cancelPairing: vi.fn(+ (_pairingId: string): ResultAsync<void, RequestFailure> =>+ okAsync(undefined)+ ),+ pairingFinished: vi.fn(async () => undefined),+ disconnect: vi.fn(+ (+ _generation: number+ ): ResultAsync<{ remoteUnlinkRequested: boolean }, RequestFailure> =>+ okAsync({ remoteUnlinkRequested: false })+ ),+ adopt: vi.fn(+ (_request: {+ groupJid: string;+ name: string;+ }): ResultAsync<{ groupId: string }, RequestFailure> =>+ okAsync({ groupId: 'channel-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.tsxnew file mode 100644index 0000000000..80fc9d88a3--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx@@ -0,0 +1,378 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@solidjs/testing-library';+import { errAsync, okAsync } from 'neverthrow';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { WhatsAppLinkedProvider } from '../context/whatsapp-linked-context';+import { createFakeWhatsApp } from '../tests/fake-capabilities';+import { WhatsAppPage } from './whatsapp-page';++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.useRealTimers();+ vi.unstubAllGlobals();+});++function mount(+ fake: ReturnType<typeof createFakeWhatsApp>,+ resumePairingId?: string+) {+ render(() => (+ <WhatsAppLinkedProvider value={fake.capabilities}>+ <WhatsAppPage resumePairingId={resumePairingId} />+ </WhatsAppLinkedProvider>+ ));+}++/** Kobalte keeps a closing dialog mounted, marked closed, until its exit animation. */+const dialogOpen = () =>+ screen+ .queryAllByRole('dialog')+ .some((dialog) => !dialog.hasAttribute('data-closed'));++const groups = [+ {+ jid: '[email protected]',+ name: 'Design Crit',+ memberCount: 14,+ group: { id: 'channel-design', name: 'design-crit' },+ unsupported: undefined,+ },+ {+ jid: '[email protected]',+ name: 'Launch War Room',+ memberCount: 23,+ group: undefined,+ unsupported: undefined,+ },+];++describe('not connected', () => {+ it('explains the account risk and links WhatsApp through a QR dialog', async () => {+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });+ vi.setSystemTime(new Date('2026-10-20T12:00:00.000Z'));+ const fake = createFakeWhatsApp({ account: null });+ mount(fake);++ expect(+ screen.getByText(/unofficial WhatsApp client/, { exact: false })+ ).toBeTruthy();+ expect(fake.groupsEnabled[0]?.()).toBe(false);++ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));+ expect(fake.capabilities.connect).toHaveBeenCalledWith(false);+ const dialog = within(await screen.findByRole('dialog'));+ expect(dialog.getByText('Link WhatsApp')).toBeTruthy();+ expect(dialog.getByText('Preparing code…')).toBeTruthy();+ expect(dialog.getByText('Tap Link a device')).toBeTruthy();++ fake.setPairing({ kind: 'scan', qr: '2@pairing-ref,key,identity,adv' });+ expect(+ dialog.getByRole('img', {+ name: 'Scan this code with WhatsApp on your phone',+ })+ ).toBeTruthy();+ expect(dialog.getByText('Expires in 0:52')).toBeTruthy();+ vi.advanceTimersByTime(2_000);+ expect(dialog.getByText('Expires in 0:50')).toBeTruthy();++ fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));+ await waitFor(() =>+ expect(fake.capabilities.cancelPairing).toHaveBeenCalledWith('pairing-1')+ );+ await waitFor(() => expect(dialogOpen()).toBe(false));+ });++ it('turns a QR that outlived its deadline into an expired step with a retry', async () => {+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });+ vi.setSystemTime(new Date('2026-10-20T12:00:00.000Z'));+ const fake = createFakeWhatsApp({ account: null });+ mount(fake);+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));+ const dialog = within(await screen.findByRole('dialog'));+ fake.setPairing({ kind: 'scan', qr: '2@pairing-ref' });++ vi.advanceTimersByTime(53_000);+ expect(+ dialog.getByText('This code expired before it was scanned.')+ ).toBeTruthy();+ expect(dialog.queryByRole('img')).toBeNull();++ fireEvent.click(dialog.getByRole('button', { name: 'Show a new code' }));+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(2);+ });++ it('closes the dialog and refreshes the account once the phone links', async () => {+ const fake = createFakeWhatsApp({ account: null });+ mount(fake);+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));+ await screen.findByRole('dialog');++ fake.setPairing({ kind: 'connected' });+ await waitFor(() =>+ expect(fake.capabilities.pairingFinished).toHaveBeenCalledOnce()+ );+ await waitFor(() => expect(dialogOpen()).toBe(false));+ expect(fake.capabilities.cancelPairing).not.toHaveBeenCalled();+ });++ it('closes the dialog when the account reads linked before the pairing poll does', async () => {+ const fake = createFakeWhatsApp({ account: null });+ mount(fake);+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));+ await screen.findByRole('dialog');+ fake.setPairing({ kind: 'scan', qr: '2@pairing-ref' });++ fake.setAccount({+ generation: 4,+ phone: '+14155550142',+ health: 'connected',+ });+ await waitFor(() => expect(dialogOpen()).toBe(false));+ expect(screen.getByText('+14155550142')).toBeTruthy();+ expect(fake.capabilities.cancelPairing).not.toHaveBeenCalled();+ });++ it('says so when linking could not start', async () => {+ const fake = createFakeWhatsApp({ account: null });+ fake.capabilities.connect.mockReturnValueOnce(+ errAsync({ kind: 'request-failed' })+ );+ mount(fake);+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));+ expect(+ await screen.findByText("Couldn't start linking WhatsApp. Try again.")+ ).toBeTruthy();+ expect(screen.queryByRole('dialog')).toBeNull();+ });+});++describe('connected', () => {+ it('links a different account only after confirming the replacement', async () => {+ const fake = createFakeWhatsApp({+ account: { generation: 3, phone: '+14155550142', health: 'connected' },+ groups,+ });+ mount(fake);++ fireEvent.click(+ screen.getByRole('button', { name: 'Use a different account' })+ );+ expect(fake.capabilities.connect).not.toHaveBeenCalled();+ const confirm = within(await screen.findByRole('dialog'));+ fireEvent.click(+ confirm.getByRole('button', { name: 'Link another account' })+ );+ await waitFor(() =>+ expect(fake.capabilities.connect).toHaveBeenCalledWith(true)+ );+ expect(await screen.findByText('Link WhatsApp')).toBeTruthy();+ // The old account still reads linked; only the new pairing closes it.+ expect(dialogOpen()).toBe(true);+ });++ it('lists groups, opens adopted groups, and disconnects after confirming', async () => {+ const fake = createFakeWhatsApp({+ account: { generation: 3, phone: '+14155550142', health: 'connected' },+ groups,+ });+ mount(fake);++ expect(screen.getByText('+14155550142')).toBeTruthy();+ expect(screen.getByText('Connected · linked device')).toBeTruthy();+ expect(fake.groupsEnabled[0]?.()).toBe(true);+ const list = within(+ screen.getByRole('list', { name: 'Your WhatsApp groups' })+ );+ expect(list.getByText('14 members')).toBeTruthy();+ fireEvent.click(list.getByRole('button', { name: /In Macro/ }));+ expect(fake.capabilities.openGroup).toHaveBeenCalledWith('channel-design');++ fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }));+ const confirm = within(await screen.findByRole('dialog'));+ expect(confirm.getByText('Disconnect WhatsApp?')).toBeTruthy();+ fireEvent.click(confirm.getByRole('button', { name: 'Disconnect' }));+ await waitFor(() =>+ expect(fake.capabilities.disconnect).toHaveBeenCalledWith(3)+ );+ fake.setAccount(null);+ expect(+ await screen.findByText(/remove Macro under WhatsApp → Linked devices/)+ ).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Connect' })).toBeTruthy();+ });++ it('adds a group with a name and owner-only access', async () => {+ const fake = createFakeWhatsApp({+ account: { generation: 3, phone: '+14155550142', health: 'connected' },+ groups,+ });+ 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()+ );+ });++ it('keeps the dialog open with an explanation when adding fails', async () => {+ const fake = createFakeWhatsApp({+ account: { generation: 3, phone: '+14155550142', health: 'connected' },+ groups,+ });+ fake.capabilities.adopt.mockReturnValueOnce(+ errAsync({ kind: 'request-failed' })+ );+ 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();+ });+});++describe('passkey', () => {+ it('answers WhatsApp’s passkey on desktop, then shows the code that comes back', async () => {+ const authenticate = vi.fn(+ (+ _pairingId: string,+ _challenge: Record<string, unknown>,+ onEvent: (event: { type: 'qr'; value: string }) => void+ ) => {+ onEvent({ type: 'qr', value: 'FIDO:/0123456789' });+ return okAsync(undefined);+ }+ );+ const fake = createFakeWhatsApp({+ account: null,+ passkey: { kind: 'native', authenticate },+ });+ mount(fake);+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));+ const dialog = within(await screen.findByRole('dialog'));+ fake.setPairing({ kind: 'passkey', challenge: { rpId: 'whatsapp.com' } });++ expect(dialog.getByText('Confirm on your desktop')).toBeTruthy();+ fireEvent.click(+ dialog.getByRole('button', { name: 'Confirm with passkey' })+ );+ await waitFor(() =>+ expect(authenticate).toHaveBeenCalledWith(+ 'pairing-1',+ { rpId: 'whatsapp.com' },+ expect.any(Function)+ )+ );++ fake.setPairing({ kind: 'code', code: 'ABCD-EFGH' });+ expect(await dialog.findByText('ABCD-EFGH')).toBeTruthy();+ });++ it('explains a failed passkey and lets the person try again', async () => {+ const fake = createFakeWhatsApp({+ account: null,+ passkey: {+ kind: 'native',+ authenticate: () =>+ errAsync({+ kind: 'passkey-failed',+ message:+ 'Your phone did not verify you. Unlock your phone and try again.',+ }),+ },+ });+ mount(fake);+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));+ const dialog = within(await screen.findByRole('dialog'));+ fake.setPairing({ kind: 'passkey', challenge: { rpId: 'whatsapp.com' } });+ fireEvent.click(+ dialog.getByRole('button', { name: 'Confirm with passkey' })+ );+ expect(+ await dialog.findByText(/Your phone did not verify you/)+ ).toBeTruthy();+ expect(dialog.getByRole('button', { name: 'Try again' })).toBeTruthy();+ });++ it('hands a browser pairing to Macro desktop by id and keeps it alive on close', async () => {+ const fake = createFakeWhatsApp({ account: null });+ mount(fake);+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));+ const dialog = within(await screen.findByRole('dialog'));+ fake.setPairing({ kind: 'passkey', challenge: { rpId: 'whatsapp.com' } });++ const link = dialog.getByRole('link', {+ name: 'Continue in Macro desktop',+ });+ expect(link.getAttribute('href')).toBe(+ 'macro:///external?whatsappPairing=pairing-1'+ );+ link.addEventListener('click', (event) => event.preventDefault());+ fireEvent.click(link);+ fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));+ await waitFor(() => expect(dialogOpen()).toBe(false));+ expect(fake.capabilities.cancelPairing).not.toHaveBeenCalled();+ });++ it('opens a handed-off pairing at once in desktop', async () => {+ const fake = createFakeWhatsApp({ account: null });+ mount(fake, '01920000-0000-7000-8000-000000000009');+ expect(await screen.findByText('Link WhatsApp')).toBeTruthy();+ const pairingId = fake.capabilities.pairing.mock.calls[0]?.[0];+ expect(pairingId?.()).toBe('01920000-0000-7000-8000-000000000009');+ 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.tsxnew file mode 100644index 0000000000..1de04f47c9--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx@@ -0,0 +1,288 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { Button, ConfirmDialog } from '@ui';+import { createSignal, For, 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 { 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 { createPairingFlow } from '../primitives/pairing-flow';++function Notice(props: { children: string }) {+ return (+ <p role="alert" class="px-1 text-sm text-ink-muted">+ {props.children}+ </p>+ );+}++function LoadFailure(props: { what: string; onRetry: () => void }) {+ return (+ <div class="flex items-center gap-3 px-1 text-sm text-ink-muted">+ <span role="alert">Couldn't load {props.what}.</span>+ <Button type="button" size="sm" variant="outline" onClick={props.onRetry}>+ Try again+ </Button>+ </div>+ );+}++/** The External tab's WhatsApp page: link an account, then add its groups. */+export function WhatsAppPage(props: {+ /** A pairing to show at once, handed off by id from another device. */+ resumePairingId?: string;+}) {+ const whatsapp = useWhatsAppLinked();+ const status = () =>+ whatsapp.account.data === undefined+ ? undefined+ : accountStatus(whatsapp.account.data);+ const linked = () => {+ const current = status();+ return current?.kind === 'connected' ? current : undefined;+ };+ const unlinked = () => {+ const current = status();+ return current?.kind === 'not-connected' ? current : undefined;+ };+ const connected = () => linked() !== undefined;+ const groups = whatsapp.groups(connected);+ const pairing = createPairingFlow(connected, whatsapp);+ // A pairing handed off from a browser opens here in Macro desktop.+ onMount(() => {+ if (props.resumePairingId) pairing.resume(props.resumePairingId);+ });+ const passkeyMode = (): PasskeyMode => {+ const capability = whatsapp.passkey;+ const pairingId = pairing.pairingId();+ return match(capability)+ .with({ kind: 'native' }, () => ({ kind: 'native' as const }))+ .with({ kind: 'handoff' }, ({ desktopUrl }) =>+ pairingId+ ? { kind: 'handoff' as const, desktopUrl: desktopUrl(pairingId) }+ : { kind: 'unsupported' as const }+ )+ .with({ kind: 'unsupported' }, () => ({ kind: 'unsupported' as const }))+ .exhaustive();+ };+ 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 disconnect = async (generation: number) => {+ setNotice(undefined);+ const result = await whatsapp.disconnect(generation);+ setConfirmingDisconnect(false);+ if (result.isErr()) {+ setNotice("Couldn't disconnect WhatsApp. Try again.");+ return;+ }+ // WhatsApp unlinks the device asynchronously; its Linked devices list is+ // the authority either way.+ setNotice(+ result.value.remoteUnlinkRequested+ ? 'Disconnected. Macro will disappear from WhatsApp → Linked devices on your phone shortly.'+ : 'Disconnected in Macro. To finish, remove Macro under WhatsApp → Linked devices on your phone.'+ );+ };++ 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);+ };++ return (+ <div class="flex max-w-2xl flex-col gap-6">+ <Switch>+ <Match when={whatsapp.account.isPending}>+ <p role="status" class="px-1 text-sm text-ink-muted">+ Loading your WhatsApp connection…+ </p>+ </Match>+ <Match when={!status()}>+ <LoadFailure+ what="your WhatsApp connection"+ onRetry={whatsapp.account.refetch}+ />+ </Match>+ <Match when={linked()}>+ {(current) => (+ <>+ <AccountCard+ account={current().account}+ pending={whatsapp.isDisconnecting() || whatsapp.isConnecting()}+ onDisconnect={() => setConfirmingDisconnect(true)}+ onReplace={() => setConfirmingReplace(true)}+ />+ <Show when={pairing.startFailed()}>+ <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>+ <ConfirmDialog+ open={confirmingDisconnect()}+ onOpenChange={setConfirmingDisconnect}+ title="Disconnect WhatsApp?"+ body="Macro stops syncing and sending from this account. Groups and their history stay in Macro."+ confirmLabel="Disconnect"+ tone="danger"+ pending={whatsapp.isDisconnecting()}+ onConfirm={() => disconnect(current().account.generation)}+ />+ <ConfirmDialog+ open={confirmingReplace()}+ onOpenChange={setConfirmingReplace}+ title="Use a different WhatsApp account?"+ body="Sending and syncing from this account stop. Group history stays in Macro. After linking the new account, add its groups again."+ confirmLabel="Link another account"+ onConfirm={() => {+ setConfirmingReplace(false);+ fireAndForget(pairing.start(true), 'whatsapp-linked.replace');+ }}+ />+ </>+ )}+ </Match>+ <Match when={unlinked()}>+ {(current) => (+ <div class="flex flex-col gap-3">+ <ConnectCard+ reconnect={current().reconnect}+ unavailable={whatsapp.features.data?.pairing === false}+ pending={whatsapp.isConnecting()}+ onConnect={() => pairing.start(false)}+ />+ <Show when={pairing.startFailed()}>+ <Notice>Couldn't start linking WhatsApp. Try again.</Notice>+ </Show>+ <Show when={notice()}>{(text) => <Notice>{text()}</Notice>}</Show>+ </div>+ )}+ </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()}+ secondsLeft={pairing.secondsLeft()}+ passkey={passkeyMode()}+ ceremony={pairing.passkey()}+ onConfirmPasskey={() =>+ fireAndForget(pairing.confirmPasskey(), 'whatsapp-linked.passkey')+ }+ onHandOff={pairing.handOff}+ 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.tsxnew file mode 100644index 0000000000..3f134f3fd3--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/whatsapp-linked.tsx@@ -0,0 +1,19 @@+import { useNavigate } from '@app/lib/split-router';+import { whatsappGroupRoute } from '@app/routes/routes';+import { WhatsAppLinkedProvider } from './context/whatsapp-linked-context';+import { createWhatsAppLinkedCapabilities } from './queries/production-capabilities';+import { WhatsAppPage } from './views/whatsapp-page';++/** The WhatsApp page wired to the app: shared queries and split navigation. */+export function WhatsAppLinked(props: { resumePairingId?: string }) {+ const navigate = useNavigate();+ const capabilities = createWhatsAppLinkedCapabilities({+ openGroup: (groupId) =>+ navigate({ route: whatsappGroupRoute, params: { groupId } }),+ });+ return (+ <WhatsAppLinkedProvider value={capabilities}>+ <WhatsAppPage resumePairingId={props.resumePairingId} />+ </WhatsAppLinkedProvider>+ );+}diff --git a/apps/web/src/lib/constants/list-views.ts b/apps/web/src/lib/constants/list-views.tsindex d1cf9e3e4a..424702f8e8 100644--- a/apps/web/src/lib/constants/list-views.ts+++ b/apps/web/src/lib/constants/list-views.ts@@ -37,6 +37,9 @@ export const LIST_VIEW_PATHS = {search: '/search',} as const satisfies Record<ListView, string>;+/** External linked accounts (WhatsApp); a settings-like view, not an entity list. */+export const EXTERNAL_VIEW_PATH = '/external';+export const LIST_VIEW_ID = {home: 'home',recent: 'recent',diff --git a/apps/web/src/lib/core/component/EntityIcon.tsx b/apps/web/src/lib/core/component/EntityIcon.tsxindex a03b7b2f9b..1fe8a2bb52 100644--- a/apps/web/src/lib/core/component/EntityIcon.tsx+++ b/apps/web/src/lib/core/component/EntityIcon.tsx@@ -99,7 +99,9 @@ import Table from '@icon/system/regular/table.svg';import Users from '@icon/system/regular/users.svg';import UsersThree from '@icon/system/regular/users-three.svg';import FigmaLogo from '@phosphor/figma-logo.svg';+import WhatsappLogo from '@phosphor/whatsapp-logo.svg';import FigmaLogoBold from '@phosphor-icons/core/bold/figma-logo-bold.svg';+import WhatsappLogoBold from '@phosphor-icons/core/bold/whatsapp-logo-bold.svg';import type { PreviewItem } from '@queries/preview';import type { ChannelType } from '@service-cognition/generated/schemas/channelType';import { FileTypeMap } from '@service-storage/fileTypeMap';@@ -137,7 +139,8 @@ export type EntityWithValidIcon =| 'crm_company'| 'html'| 'initiative'- | 'reminder';+ | 'reminder'+ | 'whatsapp_group';const ARCHIVE_EXTENSIONS = new Set(Object.values(FileTypeMap)@@ -146,6 +149,13 @@ const ARCHIVE_EXTENSIONS = new Set();export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {+ whatsapp_group: {+ icon: WhatsappLogo,+ boldIcon: WhatsappLogoBold,+ foreground: 'text-communication',+ background: 'bg-communication/20',+ prettyName: 'WhatsApp group',+ },document: {icon: File,boldIcon: FileBold,diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsxindex f2ba36c1f1..e7d7d987a3 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx@@ -1930,8 +1930,9 @@ describe('form share roles', () => {);});- it('offers View and Edit on a form, which has no comments, and every level elsewhere', () => {+ it('offers View and Edit on a form, which has no comments, View on a WhatsApp chat, and every level elsewhere', () => {expect(shareLevelsFor('form')).toEqual(['view', 'edit']);+ expect(shareLevelsFor('whatsapp_group')).toEqual(['view']);expect(shareLevelsFor('document')).toBeUndefined();render(() => (<ShareOptionsdiff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsxindex f3d4120c5e..3404d345c7 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx@@ -12,6 +12,7 @@ import {ShareRequestIcon,useShareRequestTrigger,} from '@app/features/access-requests/share-request-trigger';+import { DirectAccessInvite } from '@app/features/access-requests/views/DirectAccessInvite';import type { MeetingAccessState } from '@app/features/calendar-notes/core/types';import { DocumentMeetingNotes } from '@app/features/calendar-notes/document-meeting-notes';import {@@ -100,6 +101,7 @@ import {} from '@queries/storage/entity-mutations';import { updateFormSharePermissions } from '@queries/storage/forms';import { useCurrentTeamQuery } from '@queries/team/teams';+import { updateWhatsappGroupPermissions } from '@queries/whatsapp-groups/share-permissions';import { cognitionApiServiceClient } from '@service-cognition/client';import {blockNameToItemType,@@ -174,9 +176,11 @@ const isLinkSharingDisabledForItem = (itemType: ShareItemType): boolean =>itemType === 'crm_pipeline';/** Blocks, plus native entities that are shared without one. */-type ShareBlockType = BlockName | BlockAlias | 'initiative';+type ShareBlockType = BlockName | BlockAlias | 'initiative' | 'whatsapp_group';function shareUrl(type: ShareBlockType, id: string): string {+ if (type === 'whatsapp_group')+ return buildSimpleEntityUrl({ type: 'whatsapp-group', id });if (type !== 'initiative') return buildSimpleEntityUrl({ type, id });return buildSimpleEntityUrl({type: 'component',@@ -184,7 +188,10 @@ function shareUrl(type: ShareBlockType, id: string): string {});}-/** The levels a recipient can hold on an item; forms have no comments. */+/**+ * The levels a recipient can hold on an item: forms have no comments, and a+ * WhatsApp chat is read-only in Macro (sending follows WhatsApp membership).+ */export function shareLevelsFor(itemType: ShareItemType,blockAlias?: ShareBlockType@@ -193,6 +200,7 @@ export function shareLevelsFor(if (itemType === 'document' &&blockAlias &&+ blockAlias !== 'whatsapp_group' &&resolveBlockAlias(blockAlias) === 'md') {const levels: AccessLevel[] = ['view'];@@ -200,6 +208,7 @@ export function shareLevelsFor(if (ENABLE_MARKDOWN_LIVE_COLLABORATION) levels.push('edit');return levels;}+ if (itemType === 'whatsapp_group') return ['view'];return undefined;}@@ -210,6 +219,8 @@ const SHARE_LINK_SUBTEXT =// they may forward. Their links don't grant access to recipients either, so// copying skips SHARE_LINK_SUBTEXT.const RESTRICTED_SHARE_DESCRIPTIONS: Partial<Record<ShareItemType, string>> = {+ whatsapp_group:+ 'Only the owner can share access to this WhatsApp group. Sending always requires your own connected WhatsApp account.',crm_pipeline:'Only editors can share this pipeline. You can copy a link for people who already have access.',agent_session:@@ -248,6 +259,8 @@ function forwardTarget(`Could not share this ${blockAlias === 'pipeline' ? 'pipeline' : 'project'}`);};+ if (blockAlias === 'whatsapp_group')+ throw new Error('WhatsApp groups use direct people sharing');if (blockAlias === 'pipeline')return { blockId: id, blockName: blockAlias, prepareChannel };if (blockAlias !== 'initiative')@@ -828,10 +841,23 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {display: effectiveActiveTab() === 'share' ? undefined : 'none',}}>- <Show when={!props.canForward}>- <p class="px-4 py-3 text-sm text-ink-muted">- {RESTRICTED_SHARE_DESCRIPTIONS[props.itemType]}- </p>+ <Show+ when={+ props.itemType === 'whatsapp_group' &&+ props.userPermissions === Permissions.OWNER+ }+ fallback={+ <Show when={!props.canForward}>+ <p class="px-4 py-3 text-sm text-ink-muted">+ {RESTRICTED_SHARE_DESCRIPTIONS[props.itemType]}+ </p>+ </Show>+ }+ >+ <DirectAccessInvite+ source={props.requests}+ description="Invite someone to read this conversation. Sending requires their own connected WhatsApp account."+ /></Show><Show when={props.canForward}><AfterFirstPaint fallback={<ShareFormSkeleton />}>@@ -1067,7 +1093,8 @@ export function ShareModal(props: ShareModalProps) {enclosingBlockId === props.id &&props.itemType !== 'agent_session' &&props.itemType !== 'initiative' &&- props.itemType !== 'crm_pipeline';+ props.itemType !== 'crm_pipeline' &&+ props.itemType !== 'whatsapp_group';// Outside a block the dialog reads a cached query, which the Share trigger// warms on hover, so it opens with the roster already in hand.const queryClient = useQueryClient();@@ -1156,10 +1183,12 @@ export function ShareModal(props: ShareModalProps) {props.userPermissions === Permissions.OWNER ||props.userPermissions === Permissions.CAN_EDIT;const canForward = () =>- props.itemType === 'crm_pipeline'- ? canSharePipeline()- : !RESTRICTED_SHARE_DESCRIPTIONS[props.itemType] ||- (Boolean(userId()) && props.owner === userId());+ props.itemType === 'whatsapp_group'+ ? false+ : props.itemType === 'crm_pipeline'+ ? canSharePipeline()+ : !RESTRICTED_SHARE_DESCRIPTIONS[props.itemType] ||+ (Boolean(userId()) && props.owner === userId());const userPermissions = () =>props.itemType === 'agent_session' && !canForward()? Permissions.CAN_VIEW@@ -1169,10 +1198,14 @@ export function ShareModal(props: ShareModalProps) {props.itemType === 'crm_pipeline' && canSharePipeline()? Permissions.OWNER: userPermissions();+ const directSharingOwner = () =>+ props.itemType === 'whatsapp_group' &&+ props.userPermissions === Permissions.OWNER;const editPermissionEnabled = () => {if (props.itemType === 'agent_session') return true;if (props.itemType === 'document' &&+ props.blockAlias !== 'whatsapp_group' &&resolveBlockAlias(props.blockAlias) === 'md')return ENABLE_MARKDOWN_LIVE_COLLABORATION;@@ -1247,7 +1280,11 @@ export function ShareModal(props: ShareModalProps) {});const removeChannelAccess = createCallback(async (channelId: string) => {- if (recipientPermissions() !== Permissions.OWNER) return;+ if (+ recipientPermissions() !== Permissions.OWNER ||+ props.itemType === 'whatsapp_group'+ )+ return;if (usesGraphqlSharePolicy(props.itemType)) {const result = await updateEntitySharePolicy(props.itemType, props.id, {channelSharePermissions: [{ operation: 'remove', channelId }],@@ -1407,7 +1444,11 @@ export function ShareModal(props: ShareModalProps) {accessLevel: AccessLevel,hideSuccessToast?: boolean) => {- if (recipientPermissions() !== Permissions.OWNER) return;+ if (+ recipientPermissions() !== Permissions.OWNER ||+ props.itemType === 'whatsapp_group'+ )+ return;let result:| Result<any, ResultError<any>[]>@@ -1556,7 +1597,15 @@ export function ShareModal(props: ShareModalProps) {getTeamShareScope(sharePermission.teamShareAccessLevel) !== 'NONE';let result: Result<unknown, ResultError<any>[]>;- if (props.itemType !== 'call' && usesGraphqlSharePolicy(props.itemType)) {+ if (props.itemType === 'whatsapp_group') {+ result = await updateWhatsappGroupPermissions(+ props.id,+ sharePermission+ );+ } else if (+ props.itemType !== 'call' &&+ usesGraphqlSharePolicy(props.itemType)+ ) {result = await updateEntitySharePolicy(props.itemType,props.id,@@ -1667,7 +1716,12 @@ export function ShareModal(props: ShareModalProps) {const scope = getLinkShareScope(sharePermission.linkShare);let result: Result<any, ResultError<any>[]> | undefined;- if (usesGraphqlSharePolicy(props.itemType)) {+ if (props.itemType === 'whatsapp_group') {+ result = await updateWhatsappGroupPermissions(+ props.id,+ sharePermission+ );+ } else if (usesGraphqlSharePolicy(props.itemType)) {result = await updateEntitySharePolicy(props.itemType,props.id,@@ -1827,11 +1881,17 @@ export function ShareModal(props: ShareModalProps) {</Dialog.Title></Panel.Header><Panel.Body>- <Show when={!canForward()}>+ <Show when={!canForward() && !directSharingOwner()}><p class="px-4 py-3 text-sm text-ink-muted">{RESTRICTED_SHARE_DESCRIPTIONS[props.itemType]}</p></Show>+ <Show when={directSharingOwner()}>+ <DirectAccessInvite+ source={requests}+ description="Invite someone to read this conversation. Sending requires their own connected WhatsApp account."+ />+ </Show><Show when={canForward()}><AfterFirstPaint fallback={<ShareFormSkeleton />}><ForwardToChannel@@ -2182,10 +2242,12 @@ export function ShareTrigger(props: {throw new Error('<ShareTrigger> requires an explicit block id');};- const itemType = (): ShareItemType =>- blockType() === 'initiative'- ? 'initiative'- : blockNameToItemType(blockType());+ const itemType = (): ShareItemType => {+ const type = blockType();+ return type === 'initiative' || type === 'whatsapp_group'+ ? type+ : blockNameToItemType(type);+ };// Hovering or focusing Share loads what the dialog shows first, so a click// opens it with its roster instead of waiting on the network.diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.ts b/apps/web/src/lib/core/component/TopBar/linkShare.tsindex 338eeba623..0d9435346c 100644--- a/apps/web/src/lib/core/component/TopBar/linkShare.ts+++ b/apps/web/src/lib/core/component/TopBar/linkShare.ts@@ -6,7 +6,11 @@ import { match } from 'ts-pattern';export const NO_LINK_SHARE = 'NONE' as const;-export type ShareItemType = ItemType | 'initiative' | 'crm_pipeline';+export type ShareItemType =+ | ItemType+ | 'initiative'+ | 'crm_pipeline'+ | 'whatsapp_group';const TEAM_SHAREABLE_ITEM_TYPES: ReadonlySet<ShareItemType> =new Set<ShareItemType>([@@ -18,6 +22,7 @@ const TEAM_SHAREABLE_ITEM_TYPES: ReadonlySet<ShareItemType> ='initiative','crm_pipeline','database',+ 'whatsapp_group',]);export function isTeamShareSupportedForItem(itemType: ShareItemType): boolean {@@ -41,6 +46,7 @@ export function getShareItemNoun(itemType: ShareItemType): string {.with('channel_message', () => 'message').with('channel_thread', () => 'thread').with('foreign', () => 'item')+ .with('whatsapp_group', () => 'WhatsApp group').with('document','chat',@@ -135,7 +141,7 @@ export function teamShareScopeOptionsForItem(itemType: ShareItemType) {return TEAM_SHARE_SCOPE_OPTIONS.filter((option) => option.value === 'NONE' || option.value === 'edit');- return itemType === 'call'+ return itemType === 'call' || itemType === 'whatsapp_group'? CALL_TEAM_SHARE_SCOPE_OPTIONS: TEAM_SHARE_SCOPE_OPTIONS;}diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex faf02d09c3..61596ca7d6 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -896,3 +896,15 @@ export const enableInAppTours = defineFlag({key: 'enable-in-app-tours',env: 'ENABLE_IN_APP_TOURS',});++/**+ * Personal WhatsApp linked devices: the External tab, pairing, group adoption+ * and linked-channel composing. Off in dev too: dev has no WhatsApp session+ * service, so the tab would only show errors. Override locally with+ * VITE_ENABLE_WHATSAPP_LINKED=true. Backend switches gate each operation+ * independently.+ */+export const enableWhatsappLinked = defineFlag({+ key: 'enable-whatsapp-linked',+ env: 'ENABLE_WHATSAPP_LINKED',+});diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.tsindex 4035042a45..d091ec5e72 100644--- a/apps/web/src/lib/core/hotkey/tokens.ts+++ b/apps/web/src/lib/core/hotkey/tokens.ts@@ -134,6 +134,7 @@ export const TOKENS = {channels: 'sidebar.goTo.channels',calls: 'sidebar.goTo.calls',reviews: 'sidebar.goTo.reviews',+ external: 'sidebar.goTo.external',companies: 'sidebar.goTo.companies',folders: 'sidebar.goTo.folders',},diff --git a/apps/web/src/lib/queries/access-requests/requests.ts b/apps/web/src/lib/queries/access-requests/requests.tsindex b8385969c0..d709b371b3 100644--- a/apps/web/src/lib/queries/access-requests/requests.ts+++ b/apps/web/src/lib/queries/access-requests/requests.ts@@ -14,6 +14,7 @@ import { refreshActiveGraphqlSoupQueries } from '../soup/graphql/active-queries'import { soupKeys } from '../soup/keys';import { invalidateAllSoup } from '../soup/normalized-cache';import { databasesKeys, entityKeys } from '../storage/keys';+import { invalidateWhatsappGroups } from '../whatsapp-groups';import { accessRequestKeys } from './keys';export function fetchAccessRequestState(entity: ShareEntity, offset = 0) {@@ -49,6 +50,10 @@ export function invalidateAccessRequests(entity: ShareEntity) {}export function refreshSharedAccess(entity: ShareEntity) {fireAndForget(invalidateAccessRequests(entity), 'access-requests');+ if (entity.entityType === 'whatsapp_group') {+ fireAndForget(invalidateWhatsappGroups(), 'access-requests');+ return;+ }// Permissions change list membership even when the item was never cached.invalidateAllSoup();queryClient.invalidateQueries({ queryKey: soupKeys.search._def });diff --git a/apps/web/src/lib/queries/share/share-permissions.ts b/apps/web/src/lib/queries/share/share-permissions.tsindex 8ff82d8832..2a809bcc82 100644--- a/apps/web/src/lib/queries/share/share-permissions.ts+++ b/apps/web/src/lib/queries/share/share-permissions.ts@@ -9,6 +9,7 @@ import { queryClient } from '../client';import { fetchInitiativeSharePermissions } from '../initiative/share-permissions';import { getDatabaseSharePermissions } from '../storage/databases';import { getFormSharePermissions } from '../storage/forms';+import { fetchWhatsappGroupPermissions } from '../whatsapp-groups/share-permissions';import { sharePermissionKeys } from './keys';// Long enough that hovering Share and then clicking it fetches once; short@@ -20,6 +21,7 @@ export async function fetchSharePermissions(id: string,itemType: ShareItemType) {+ if (itemType === 'whatsapp_group') return fetchWhatsappGroupPermissions(id);if (itemType === 'crm_pipeline') return fetchPipelineSharePermissions(id);if (itemType === 'agent_session') {return fetchAgentSessionSharePermissions(id);diff --git a/apps/web/src/lib/queries/whatsapp-groups/index.ts b/apps/web/src/lib/queries/whatsapp-groups/index.tsnew file mode 100644index 0000000000..6452c67a20--- /dev/null+++ b/apps/web/src/lib/queries/whatsapp-groups/index.ts@@ -0,0 +1,135 @@+import type {+ GroupDetail,+ GroupSend,+ GroupSummary,+ MessagePage,+ PendingSend,+} from '@app/features/whatsapp-group/core/group';+import {+ infiniteQueryOptions,+ queryOptions,+ useInfiniteQuery,+ useMutation,+ useQuery,+} from '@tanstack/solid-query';+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. */+export type WhatsAppGroupApi = {+ list: () => Promise<GroupSummary[]>;+ detail: (groupId: string) => Promise<GroupDetail>;+ messages: (groupId: string, before?: string) => Promise<MessagePage>;+ sends: (groupId: string) => Promise<PendingSend[]>;+ send: (+ groupId: string,+ request: GroupSend,+ idempotencyKey: string+ ) => Promise<unknown>;+ upload: (+ groupId: string,+ file: File+ ) => Promise<{ uploadId: string; audio: boolean }>;+ markRead: (groupId: string, messageId: string) => Promise<unknown>;+ stopSync: (groupId: string) => Promise<unknown>;+};++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,+ });+}+function detailOptions(api: WhatsAppGroupApi, userId: string, groupId: string) {+ return queryOptions({+ queryKey: whatsappGroupsKeys.detail(userId, groupId).queryKey,+ queryFn: () => api.detail(groupId),+ enabled: !!userId && !!groupId,+ staleTime: 5000,+ refetchInterval: 15000,+ refetchIntervalInBackground: false,+ throwOnError: false,+ });+}+function messagesOptions(+ api: WhatsAppGroupApi,+ userId: string,+ groupId: string+) {+ return infiniteQueryOptions({+ queryKey: whatsappGroupsKeys.messages(userId, groupId).queryKey,+ queryFn: ({ pageParam }) => api.messages(groupId, pageParam),+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (page) => page.before,+ enabled: !!userId && !!groupId,+ staleTime: 0,+ refetchInterval: 5000,+ refetchIntervalInBackground: false,+ throwOnError: false,+ });+}+function sendsOptions(api: WhatsAppGroupApi, userId: string, groupId: string) {+ return queryOptions({+ queryKey: whatsappGroupsKeys.sends(userId, groupId).queryKey,+ queryFn: () => api.sends(groupId),+ enabled: !!userId && !!groupId,+ staleTime: 0,+ refetchInterval: 5000,+ refetchIntervalInBackground: false,+ throwOnError: false,+ });+}+export function useWhatsappGroupsQuery(+ api: WhatsAppGroupApi,+ userId: Accessor<string>+) {+ return useQuery(() => listOptions(api, userId()));+}+export function useWhatsappGroupQueries(+ api: WhatsAppGroupApi,+ userId: Accessor<string>,+ groupId: Accessor<string>+) {+ const group = useQuery(() => detailOptions(api, userId(), groupId()));+ 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 };+}+export function invalidateWhatsappGroups() {+ return queryClient.invalidateQueries({ queryKey: whatsappGroupsKeys._def });+}diff --git a/apps/web/src/lib/queries/whatsapp-groups/keys.ts b/apps/web/src/lib/queries/whatsapp-groups/keys.tsnew file mode 100644index 0000000000..1198a85f04--- /dev/null+++ b/apps/web/src/lib/queries/whatsapp-groups/keys.ts@@ -0,0 +1,9 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';++/** WhatsApp groups never share channel cache keys or persisted pairing state. */+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],+});diff --git a/apps/web/src/lib/queries/whatsapp-groups/share-permissions.ts b/apps/web/src/lib/queries/whatsapp-groups/share-permissions.tsnew file mode 100644index 0000000000..8a4dd7b1ab--- /dev/null+++ b/apps/web/src/lib/queries/whatsapp-groups/share-permissions.ts@@ -0,0 +1,17 @@+import { fireAndForget } from '@core/util/fireAndForget';+import type { UpdateSharePermissionRequestV2 } from '@service-storage/generated/schemas/updateSharePermissionRequestV2';+import { whatsappGroupsClient } from '@service-storage/whatsapp-groups';+import { invalidateWhatsappGroups } from './index';++export function fetchWhatsappGroupPermissions(groupId: string) {+ return whatsappGroupsClient.permissions(groupId);+}+export async function updateWhatsappGroupPermissions(+ groupId: string,+ request: UpdateSharePermissionRequestV2+) {+ const result = await whatsappGroupsClient.updatePermissions(groupId, request);+ if (result.isOk())+ fireAndForget(invalidateWhatsappGroups(), 'whatsapp-group.share');+ return result;+}diff --git a/apps/web/src/lib/queries/whatsapp-linked/index.ts b/apps/web/src/lib/queries/whatsapp-linked/index.tsnew file mode 100644index 0000000000..2fb6ce7acb--- /dev/null+++ b/apps/web/src/lib/queries/whatsapp-linked/index.ts@@ -0,0 +1,138 @@+import { throwOnErr } from '@core/util/result';+import type { LinkedAdoptGroup } from '@service-storage/generated/schemas/linkedAdoptGroup';+import type { LinkedPasskeyBody } from '@service-storage/generated/schemas/linkedPasskeyBody';+import { whatsappLinkedClient as client } from '@service-storage/whatsapp-linked';+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { queryClient } from '../client';+import { invalidateWhatsappGroups } from '../whatsapp-groups';+import { whatsappLinkedKeys } from './keys';+import { whatsappOperation } from './operation';++/** How often an open pairing dialog asks for a rotated QR or a result. */+export const PAIRING_POLL_MS = 1500;++const configurationOptions = queryOptions({+ queryKey: whatsappLinkedKeys.configuration.queryKey,+ queryFn: () => throwOnErr(client.configuration),+ staleTime: 30_000,+});++function accountOptions(userId: string) {+ return queryOptions({+ queryKey: whatsappLinkedKeys.account(userId).queryKey,+ queryFn: () => throwOnErr(client.account),+ enabled: !!userId,+ staleTime: 5_000,+ });+}++function pairingOptions(userId: string, pairingId: string) {+ return queryOptions({+ queryKey: whatsappLinkedKeys.pairing(userId, pairingId).queryKey,+ queryFn: () => throwOnErr(() => client.pairing(pairingId)),+ enabled: !!userId && !!pairingId,+ gcTime: 0,+ staleTime: 0,+ retry: false,+ refetchInterval: PAIRING_POLL_MS,+ refetchIntervalInBackground: false,+ });+}++function groupsOptions(userId: string, enabled: boolean) {+ return queryOptions({+ queryKey: whatsappLinkedKeys.groups(userId).queryKey,+ queryFn: () => throwOnErr(client.groups),+ enabled: !!userId && enabled,+ staleTime: 10_000,+ });+}++/** Which linked-device operations the backend currently allows. */+export function useWhatsappLinkedConfigurationQuery() {+ return useQuery(() => configurationOptions);+}++/** The signed-in person's own linked account, or `account: null`. */+export function useWhatsappLinkedAccountQuery(userId: Accessor<string>) {+ return useQuery(() => accountOptions(userId()));+}++/** Polls one pairing transaction while its dialog is open; never cached. */+export function useWhatsappLinkedPairingQuery(+ userId: Accessor<string>,+ pairingId: Accessor<string>+) {+ return useQuery(() => pairingOptions(userId(), pairingId()));+}++/** Groups the connected account belongs to, with their adopted channel. */+export function useWhatsappLinkedGroupsQuery(+ userId: Accessor<string>,+ enabled: Accessor<boolean>+) {+ return useQuery(() => groupsOptions(userId(), enabled()));+}++const invalidateAccount = () =>+ queryClient.invalidateQueries({+ queryKey: whatsappLinkedKeys.account._def,+ });+const invalidateGroups = () =>+ queryClient.invalidateQueries({ queryKey: whatsappLinkedKeys.groups._def });++export function useConnectWhatsappMutation() {+ return useMutation(() => ({+ mutationFn: (replace: boolean) =>+ whatsappOperation('connect', () =>+ throwOnErr(() => client.connect(replace))+ ),+ onSuccess: invalidateAccount,+ }));+}++export function useDisconnectWhatsappMutation() {+ return useMutation(() => ({+ mutationFn: (authorizationGeneration: number) =>+ whatsappOperation('disconnect', () =>+ throwOnErr(() => client.disconnect(authorizationGeneration))+ ),+ onSuccess: () => Promise.all([invalidateAccount(), invalidateGroups()]),+ }));+}++export function useCancelWhatsappPairingMutation() {+ return useMutation(() => ({+ mutationFn: (pairingId: string) =>+ whatsappOperation('cancel_pairing', () =>+ throwOnErr(() => client.cancelPairing(pairingId))+ ),+ onSettled: invalidateAccount,+ }));+}++/** Pairing finished: the account and its groups changed. */+export function refreshWhatsappLinkedAccount() {+ return Promise.all([invalidateAccount(), invalidateGroups()]);+}++export function useSubmitWhatsappPasskeyMutation() {+ return useMutation(() => ({+ mutationFn: (input: { pairingId: string; response: LinkedPasskeyBody }) =>+ whatsappOperation('submit_passkey', () =>+ throwOnErr(() => client.passkey(input.pairingId, input.response))+ ),+ }));+}++export function useAdoptWhatsappGroupMutation() {+ return useMutation(() => ({+ mutationFn: (request: LinkedAdoptGroup) =>+ whatsappOperation('adopt_group', () =>+ throwOnErr(() => client.adopt(request))+ ),+ onSuccess: () =>+ Promise.all([invalidateGroups(), invalidateWhatsappGroups()]),+ }));+}diff --git a/apps/web/src/lib/queries/whatsapp-linked/keys.ts b/apps/web/src/lib/queries/whatsapp-linked/keys.tsnew file mode 100644index 0000000000..4616cf813d--- /dev/null+++ b/apps/web/src/lib/queries/whatsapp-linked/keys.ts@@ -0,0 +1,10 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';++// Deliberately absent from persisted query scopes: pairing material lives only+// in memory while its dialog is open.+export const whatsappLinkedKeys = createQueryKeys('whatsapp-linked', {+ configuration: null,+ account: (userId: string) => [userId],+ pairing: (userId: string, pairingId: string) => [userId, pairingId],+ groups: (userId: string) => [userId],+});diff --git a/apps/web/src/lib/queries/whatsapp-linked/operation.test.ts b/apps/web/src/lib/queries/whatsapp-linked/operation.test.tsnew file mode 100644index 0000000000..e548e8637c--- /dev/null+++ b/apps/web/src/lib/queries/whatsapp-linked/operation.test.ts@@ -0,0 +1,48 @@+import { Telemetry } from '@macro-inc/observability';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { whatsappOperation } from './operation';++const span = vi.hoisted(() => ({ setAttr: vi.fn(), error: vi.fn() }));+vi.mock('@macro-inc/observability', () => ({+ Telemetry: {+ span: vi.fn(+ async (+ _name: string,+ operation: (value: typeof span) => Promise<unknown>+ ) => operation(span)+ ),+ },+}));++beforeEach(() => vi.clearAllMocks());++describe('WhatsApp operation telemetry', () => {+ it('records successful operations without copying their result', async () => {+ const pairing = { qr_code: 'sensitive pairing material' };+ await expect(+ whatsappOperation('connect', async () => pairing)+ ).resolves.toBe(pairing);+ expect(Telemetry.span).toHaveBeenCalledWith(+ 'whatsapp.connect',+ expect.any(Function)+ );+ expect(span.setAttr).toHaveBeenCalledExactlyOnceWith(+ 'whatsapp.outcome',+ 'success'+ );+ expect(span.error).not.toHaveBeenCalled();+ });++ it('marks errors without recording sensitive server details', async () => {+ const failure = new Error('sensitive passkey assertion');+ await expect(+ whatsappOperation('submit_passkey', async () => {+ throw failure;+ })+ ).rejects.toBe(failure);+ expect(span.error).toHaveBeenCalledExactlyOnceWith(+ 'WhatsApp operation failed'+ );+ expect(span.setAttr).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/queries/whatsapp-linked/operation.ts b/apps/web/src/lib/queries/whatsapp-linked/operation.tsnew file mode 100644index 0000000000..42ef846ade--- /dev/null+++ b/apps/web/src/lib/queries/whatsapp-linked/operation.ts@@ -0,0 +1,20 @@+import { Telemetry } from '@macro-inc/observability';++/** Keep server error bodies and pairing material out of operation telemetry. */+export function whatsappOperation<T>(+ name: string,+ operation: () => Promise<T>,+ groupId?: string+) {+ return Telemetry.span(`whatsapp.${name}`, async (span) => {+ if (groupId) span.setAttr('whatsapp.group.id', groupId);+ try {+ const result = await operation();+ span.setAttr('whatsapp.outcome', 'success');+ return result;+ } catch (error) {+ span.error('WhatsApp operation failed');+ throw error;+ }+ });+}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.tsnew file mode 100644index 0000000000..e84519c8db--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/whatsapp-groups.ts@@ -0,0 +1,54 @@+/** Independent WhatsApp group entity API; no channel endpoints or context. */+import { dssFetch } from './client';+import type {+ LinkedSendProgress,+ LinkedSendReply,+ LinkedUploadedAttachment,+ SharePermissionV2,+ UpdateSharePermissionRequestV2,+ WhatsAppGroupDetail,+ WhatsAppGroupMessages,+ WhatsAppGroupSummary,+} from './generated/schemas';++const root = '/meta/linked/whatsapp-groups';+const group = (id: string) => `${root}/${encodeURIComponent(id)}`;+export const whatsappGroupsClient = {+ list: () => dssFetch<WhatsAppGroupSummary[]>(root),+ detail: (id: string) => dssFetch<WhatsAppGroupDetail>(group(id)),+ messages: (id: string, before?: string) => {+ const params = new URLSearchParams({ limit: '50' });+ 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`, {+ method: 'POST',+ body: JSON.stringify(request),+ }),+ upload: (id: string, file: File) => {+ const body = new FormData();+ body.set('file', file);+ return dssFetch<LinkedUploadedAttachment>(`${group(id)}/attachments`, {+ method: 'POST',+ body,+ });+ },+ markRead: (id: string, messageId: string) =>+ dssFetch(`${group(id)}/read`, {+ method: 'POST',+ body: JSON.stringify({ message_id: messageId }),+ }),+ stopSync: (id: string) => dssFetch(group(id), { method: 'DELETE' }),+ permissions: (id: string) =>+ dssFetch<SharePermissionV2>(`${group(id)}/permissions`),+ updatePermissions: (+ id: string,+ permissions: UpdateSharePermissionRequestV2+ ) =>+ dssFetch(`${group(id)}/permissions`, {+ method: 'PATCH',+ body: JSON.stringify(permissions),+ }),+};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.tsnew file mode 100644index 0000000000..774b283aa2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts@@ -0,0 +1,47 @@+/** The `/meta/linked` routes of DSS: personal WhatsApp accounts linked as devices. */+import { SERVER_HOSTS } from '@core/constant/servers';+import { fetchWithToken } from '@core/util/fetchWithToken';+import type { ObjectLike } from '@core/util/result';+import type { AdoptedGroup } from './generated/schemas/adoptedGroup';+import type { LinkedAccountView } from './generated/schemas/linkedAccountView';+import type { LinkedAdoptGroup } from './generated/schemas/linkedAdoptGroup';+import type { LinkedDisconnect } from './generated/schemas/linkedDisconnect';+import type { LinkedFeatures } from './generated/schemas/linkedFeatures';+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';++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, {+ method: 'POST',+ body: JSON.stringify(body),+ headers: { 'Content-Type': 'application/json' },+ });+}++export const whatsappLinkedClient = {+ configuration: () => fetchWithToken<LinkedFeatures>(`${root}/configuration`),+ account: () => fetchWithToken<LinkedAccountView>(`${root}/account`),+ /** Starts an owner-bound pairing; `replace` retires the retained identity. */+ connect: (replace: boolean) =>+ post<LinkedPairing>(`${root}/connect`, { replace }),+ disconnect: (authorizationGeneration: number) =>+ post<LinkedDisconnect>(`${root}/disconnect`, {+ authorization_generation: authorizationGeneration,+ }),+ /** Pairing material is never cached by the browser. */+ pairing: (id: string) =>+ fetchWithToken<LinkedPairState>(pairing(id), { cache: 'no-store' }),+ cancelPairing: (id: string) =>+ fetchWithToken<Record<string, never>>(pairing(id), { method: 'DELETE' }),+ /** The WebAuthn assertion answering WhatsApp's passkey challenge. */+ passkey: (id: string, response: LinkedPasskeyBody) =>+ post<Record<string, never>>(`${pairing(id)}/passkey`, response),+ groups: () => fetchWithToken<LinkedGroupInfo[]>(`${root}/groups`),+ adopt: (request: LinkedAdoptGroup) =>+ post<AdoptedGroup>(`${root}/groups/adopt`, request),+};diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsxindex 66cd98031a..5498312acb 100644--- a/apps/web/src/routes/app-router-view.tsx+++ b/apps/web/src/routes/app-router-view.tsx@@ -6,6 +6,7 @@ import { ChannelInviteAcceptance } from '@app/features/channel-invitations/Channimport { ChannelsViewSkeleton } from '@app/features/channels-view/channels-view-skeleton';import { DriveViewSkeleton } from '@app/features/drive-view/drive-view-skeleton';import { EmailViewSkeleton } from '@app/features/email-view/email-view-skeleton';+import { ExternalViewSkeleton } from '@app/features/external-view/external-view-skeleton';import { InviteLinksPortal } from '@app/features/gtm-invite/InviteLinksPortal';import { InviteWelcome } from '@app/features/gtm-invite/InviteWelcome';import {@@ -114,6 +115,7 @@ import {emailSignupCallbackRoute,emailSplitRoute,emailThreadRoute,+ externalRoute,foldersRoute,formRespondRoute,homeCalendarRoute,@@ -151,6 +153,7 @@ import {tasksSplitRoute,teamInviteRoute,welcomeRoute,+ whatsappGroupRoute,} from './routes';import {AppShell,@@ -160,6 +163,11 @@ import {withMeetingShell,} from './shells';+const WhatsAppGroupRouteView = lazyNamed(+ () => import('@app/features/whatsapp-group/route-views'),+ 'WhatsAppGroupRouteView'+);+const { Router, Route } = SplitRouter;// Views under appRoute load lazily (lazy-route-views.ts); auth and booking@@ -168,6 +176,10 @@ const BookingLinksRouteView = lazyNamed(() => import('@app/features/scheduling/route-views'),'BookingLinksRouteView');+const ExternalRouteView = lazyNamed(+ () => import('@app/features/external-view/route-views'),+ 'ExternalRouteView'+);/** Debug views stay behind the registry's lazy import. */function debugView(componentId: string) {@@ -384,6 +396,11 @@ export function AppRouterView() {definition={bookingLinksRoute}component={BookingLinksRouteView}/>+ <Route+ definition={externalRoute}+ component={ExternalRouteView}+ loading={ExternalViewSkeleton}+ /><Routedefinition={calendarSplitRoute}component={CalendarRouteView}@@ -403,6 +420,10 @@ export function AppRouterView() {<Route definition={callsRoute} component={CallsRouteView}><Route definition={callsCallRoute} component={CallsCallDetail} /></Route>+ <Route+ definition={whatsappGroupRoute}+ component={WhatsAppGroupRouteView}+ /><Route definition={callDetailRoute} component={CallDetailRouteView} /><Route definition={companiesRoute} component={CompaniesRouteView}><Route definition={crmPipelineRoute}>diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.tsindex bdb48589f9..278bacd3c9 100644--- a/apps/web/src/routes/routes.ts+++ b/apps/web/src/routes/routes.ts@@ -578,6 +578,23 @@ export const reviewsSplitRoute = defineRoute({search: [reviewsTabSearch.namespace],});+/** A shareable WhatsApp conversation, with no channel or legacy block. */+export const whatsappGroupRoute = defineRoute({+ id: 'whatsapp-group',+ path: 'whatsapp-group/:groupId',+ params: z.object({ groupId: z.string().uuid() }),+ remountKey: ({ groupId }) => groupId,+ claim: ({ groupId }) => ({ namespace: 'whatsapp-group', id: groupId }),+});++/** External: outside messaging accounts (WhatsApp) linked into Macro. */+export const externalRoute = defineRoute({+ id: 'view-external',+ path: 'external',+ // A WhatsApp pairing handed off to Macro desktop, by id only.+ externalSearch: ['whatsappPairing'],+});+export const bookingLinksRoute = defineRoute({id: 'view-booking-links',path: 'scheduling',diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.tsindex 2ffd1cdfe8..90d59777c0 100644--- a/apps/web/src/vite-env.d.ts+++ b/apps/web/src/vite-env.d.ts@@ -16,6 +16,7 @@ interface ImportMetaEnv {readonly VITE_ENABLE_REMINDERS?: string;readonly VITE_ENABLE_CALENDAR_MEETING_NOTES?: string;readonly VITE_DISABLE_BROWSER_TURSO_CACHE?: string;+ readonly VITE_ENABLE_WHATSAPP_LINKED?: string;}interface ImportMeta {diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex 24abab1708..a536dd2a29 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -20,7 +20,7 @@ version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"dependencies = [- "crypto-common",+ "crypto-common 0.1.7","generic-array",]@@ -59,6 +59,15 @@ dependencies = ["subtle",]+[[package]]+name = "aes-kw"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69fa2b352dcefb5f7f3a5fb840e02665d311d878955380515e4fd50095dd3d8c"+dependencies = [+ "aes",+]+[[package]]name = "ahash"version = "0.7.8"@@ -251,23 +260,24 @@ dependencies = [name = "app"version = "0.1.0"dependencies = [- "block2",+ "base64 0.22.1",+ "block2 0.6.2","clap","futures-util","graphql_cache_plugin","gtk","http",- "jni",+ "jni 0.21.1","libc","log","logger","macro_bundle_updater_plugin","mime_guess","navigation_plugin",- "nom",+ "nom 8.0.0","objc2 0.5.2","objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2","objc2-intents","objc2-ui-kit","objc2-user-notifications",@@ -277,6 +287,7 @@ dependencies = ["serde","serde_json","serde_qs",+ "sha2 0.10.9","specta","specta-serde","specta-typescript",@@ -317,6 +328,8 @@ dependencies = ["url","urlencoding","uuid",+ "webauthn-authenticator-rs",+ "webauthn-rs-proto","zbus",]@@ -338,6 +351,18 @@ dependencies = ["rustversion",]+[[package]]+name = "argon2"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"+dependencies = [+ "base64ct",+ "blake2",+ "cpufeatures 0.2.17",+ "password-hash",+]+[[package]]name = "ariadne"version = "0.6.0"@@ -375,6 +400,45 @@ version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"+[[package]]+name = "asn1-rs"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048"+dependencies = [+ "asn1-rs-derive",+ "asn1-rs-impl",+ "displaydoc",+ "nom 7.1.3",+ "num-traits",+ "rusticata-macros",+ "thiserror 1.0.69",+ "time",+]++[[package]]+name = "asn1-rs-derive"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+ "synstructure",+]++[[package]]+name = "asn1-rs-impl"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "assoc"version = "0.1.3"@@ -495,6 +559,28 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "async-stream"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"+dependencies = [+ "async-stream-impl",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-stream-impl"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "async-task"version = "4.7.1"@@ -579,6 +665,12 @@ dependencies = ["pkg-config",]+[[package]]+name = "base16ct"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"+[[package]]name = "base64"version = "0.21.7"@@ -591,6 +683,12 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+[[package]]name = "battery"version = "0.7.8"@@ -663,6 +761,15 @@ dependencies = ["wyz",]+[[package]]+name = "blake2"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"+dependencies = [+ "digest 0.10.7",+]+[[package]]name = "block-buffer"version = "0.10.4"@@ -672,6 +779,33 @@ dependencies = ["generic-array",]+[[package]]+name = "block-buffer"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96eb4cdd6cf1b31d671e9efe75c5d1ec614776856cefbe109ca373554a6d514f"+dependencies = [+ "hybrid-array",+]++[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array",+]++[[package]]+name = "block2"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"+dependencies = [+ "objc2 0.5.2",+]+[[package]]name = "block2"version = "0.6.2"@@ -694,6 +828,35 @@ dependencies = ["piper",]+[[package]]+name = "bluez-async"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "84ae4213cc2a8dc663acecac67bbdad05142be4d8ef372b6903abf878b0c690a"+dependencies = [+ "bitflags 2.11.1",+ "bluez-generated",+ "dbus",+ "dbus-tokio",+ "futures",+ "itertools",+ "log",+ "serde",+ "serde-xml-rs",+ "thiserror 2.0.18",+ "tokio",+ "uuid",+]++[[package]]+name = "bluez-generated"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9676783265eadd6f11829982792c6f303f3854d014edfba384685dcf237dd062"+dependencies = [+ "dbus",+]+[[package]]name = "borsh"version = "1.6.1"@@ -723,7 +886,7 @@ name = "bot_id"version = "0.1.0"dependencies = ["cowlike",- "nom",+ "nom 8.0.0","serde","thiserror 2.0.18","uuid",@@ -768,6 +931,34 @@ dependencies = ["tinyvec",]+[[package]]+name = "btleplug"+version = "0.11.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c9a11621cb2c8c024e444734292482b1ad86fb50ded066cf46252e46643c8748"+dependencies = [+ "async-trait",+ "bitflags 2.11.1",+ "bluez-async",+ "dashmap 6.2.1",+ "dbus",+ "futures",+ "jni 0.19.0",+ "jni-utils",+ "log",+ "objc2 0.5.2",+ "objc2-core-bluetooth",+ "objc2-foundation 0.2.2",+ "once_cell",+ "static_assertions",+ "thiserror 2.0.18",+ "tokio",+ "tokio-stream",+ "uuid",+ "windows 0.61.3",+ "windows-future 0.2.1",+]+[[package]]name = "bumpalo"version = "3.20.2"@@ -866,7 +1057,7 @@ dependencies = ["predicate-index","serde","serde_json",- "sha2",+ "sha2 0.10.9","thiserror 2.0.18","uuid",]@@ -952,6 +1143,15 @@ dependencies = ["toml 1.1.2+spec-1.1.0",]+[[package]]+name = "cbc"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"+dependencies = [+ "cipher",+]+[[package]]name = "cc"version = "1.4.3"@@ -1051,7 +1251,7 @@ version = "0.4.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"dependencies = [- "crypto-common",+ "crypto-common 0.1.7","inout",]@@ -1158,6 +1358,12 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "const-oid"+version = "0.9.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"+[[package]]name = "const-random"version = "0.1.18"@@ -1270,7 +1476,7 @@ dependencies = ["bitflags 2.11.1","core-foundation 0.10.1","core-graphics-types",- "foreign-types",+ "foreign-types 0.5.0","libc",]@@ -1385,6 +1591,18 @@ version = "0.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"+[[package]]+name = "crypto-bigint"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"+dependencies = [+ "generic-array",+ "rand_core 0.6.4",+ "subtle",+ "zeroize",+]+[[package]]name = "crypto-common"version = "0.1.7"@@ -1396,6 +1614,63 @@ dependencies = ["typenum",]+[[package]]+name = "crypto-common"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"+dependencies = [+ "hybrid-array",+ "rand_core 0.10.1",+]++[[package]]+name = "crypto-glue"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b5a869a3c08beca4e6a5bb0245c116c621c1988dbdb43a65ae37c2d8daa2167"+dependencies = [+ "aes",+ "aes-gcm",+ "aes-kw",+ "argon2",+ "base64 0.22.1",+ "cbc",+ "cipher",+ "const-oid",+ "crypto-common 0.1.7",+ "crypto-common 0.2.2",+ "der",+ "digest 0.11.0-rc.12",+ "ecdsa",+ "elliptic-curve",+ "generic-array",+ "hex",+ "hkdf",+ "hmac 0.12.1",+ "hmac 0.13.0-rc.5",+ "hybrid-array",+ "kbkdf",+ "p256",+ "p384",+ "p521",+ "pbkdf2",+ "pkcs8",+ "rand 0.8.6",+ "rsa",+ "sec1",+ "serde",+ "sha1",+ "sha2 0.10.9",+ "sha2 0.11.0-rc.5",+ "spki",+ "subtle",+ "tracing",+ "uuid",+ "x509-cert",+ "zeroize",+]+[[package]]name = "cssparser"version = "0.29.6"@@ -1530,6 +1805,33 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "dashmap"+version = "5.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856"+dependencies = [+ "cfg-if",+ "hashbrown 0.14.5",+ "lock_api",+ "once_cell",+ "parking_lot_core",+]++[[package]]+name = "dashmap"+version = "6.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c"+dependencies = [+ "cfg-if",+ "crossbeam-utils",+ "hashbrown 0.14.5",+ "lock_api",+ "once_cell",+ "parking_lot_core",+]+[[package]]name = "data-encoding"version = "2.10.0"@@ -1548,11 +1850,24 @@ version = "0.9.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b942602992bb7acfd1f51c49811c58a610ef9181b6e66f3e519d79b540a3bf73"dependencies = [+ "futures-channel",+ "futures-util","libc","libdbus-sys","windows-sys 0.61.2",]+[[package]]+name = "dbus-tokio"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "007688d459bc677131c063a3a77fb899526e17b7980f390b69644bdbc41fad13"+dependencies = [+ "dbus",+ "libc",+ "tokio",+]+[[package]]name = "default-net"version = "0.22.0"@@ -1576,6 +1891,44 @@ version = "0.1.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"+[[package]]+name = "der"+version = "0.7.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"+dependencies = [+ "const-oid",+ "der_derive",+ "flagset",+ "pem-rfc7468",+ "zeroize",+]++[[package]]+name = "der-parser"+version = "9.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553"+dependencies = [+ "asn1-rs",+ "displaydoc",+ "nom 7.1.3",+ "num-bigint",+ "num-traits",+ "rusticata-macros",+]++[[package]]+name = "der_derive"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "deranged"version = "0.5.8"@@ -1668,8 +2021,20 @@ version = "0.10.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = [- "block-buffer",- "crypto-common",+ "block-buffer 0.10.4",+ "const-oid",+ "crypto-common 0.1.7",+ "subtle",+]++[[package]]+name = "digest"+version = "0.11.0-rc.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4b37eb2004a3548553a44cc1e688aac70f0345b896c9d822b4a0e520bc9183b"+dependencies = [+ "block-buffer 0.11.0",+ "crypto-common 0.2.2","subtle",]@@ -1710,7 +2075,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"dependencies = ["bitflags 2.11.1",- "block2",+ "block2 0.6.2","libc","objc2 0.6.4",]@@ -1877,12 +2242,47 @@ version = "1.0.20"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"+[[package]]+name = "ecdsa"+version = "0.16.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"+dependencies = [+ "der",+ "digest 0.10.7",+ "elliptic-curve",+ "rfc6979",+ "signature",+ "spki",+]+[[package]]name = "either"version = "1.15.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"+[[package]]+name = "elliptic-curve"+version = "0.13.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"+dependencies = [+ "base16ct",+ "crypto-bigint",+ "digest 0.10.7",+ "ff",+ "generic-array",+ "group",+ "hkdf",+ "pem-rfc7468",+ "pkcs8",+ "rand_core 0.6.4",+ "sec1",+ "subtle",+ "zeroize",+]+[[package]]name = "embed-resource"version = "3.0.8"@@ -2050,6 +2450,16 @@ dependencies = ["log",]+[[package]]+name = "ff"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"+dependencies = [+ "rand_core 0.6.4",+ "subtle",+]+[[package]]name = "field-offset"version = "0.3.6"@@ -2084,6 +2494,12 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"+[[package]]+name = "flagset"+version = "0.4.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"+[[package]]name = "flate2"version = "1.1.9"@@ -2113,6 +2529,15 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"+[[package]]+name = "foreign-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"+dependencies = [+ "foreign-types-shared 0.1.1",+]+[[package]]name = "foreign-types"version = "0.5.0"@@ -2120,7 +2545,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"dependencies = ["foreign-types-macros",- "foreign-types-shared",+ "foreign-types-shared 0.3.1",][[package]]@@ -2134,6 +2559,12 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "foreign-types-shared"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"+[[package]]name = "foreign-types-shared"version = "0.3.1"@@ -2401,8 +2832,10 @@ version = "0.14.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"dependencies = [+ "serde","typenum","version_check",+ "zeroize",][[package]]@@ -2623,6 +3056,17 @@ dependencies = ["uuid",]+[[package]]+name = "group"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"+dependencies = [+ "ff",+ "rand_core 0.6.4",+ "subtle",+]+[[package]]name = "gtk"version = "0.18.2"@@ -2694,6 +3138,17 @@ dependencies = ["tracing",]+[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "cfg-if",+ "crunchy",+ "zerocopy",+]+[[package]]name = "hash32"version = "0.2.1"@@ -2782,13 +3237,31 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hkdf"+version = "0.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"+dependencies = [+ "hmac 0.12.1",+]+[[package]]name = "hmac"version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"dependencies = [- "digest",+ "digest 0.10.7",+]++[[package]]+name = "hmac"+version = "0.13.0-rc.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef451d73f36d8a3f93ad32c332ea01146c9650e1ec821a9b0e46c01277d544f8"+dependencies = [+ "digest 0.11.0-rc.12",][[package]]@@ -2858,6 +3331,17 @@ version = "1.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"+[[package]]+name = "hybrid-array"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"+dependencies = [+ "serde",+ "typenum",+ "zeroize",+]+[[package]]name = "hyper"version = "1.9.0"@@ -3188,6 +3672,7 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"dependencies = [+ "block-padding","generic-array",]@@ -3274,7 +3759,7 @@ dependencies = ["macro_user_id","model_file_type","model_owner",- "nom",+ "nom 8.0.0","non_empty","notification_state","rootcause",@@ -3285,6 +3770,15 @@ dependencies = ["uuid",]+[[package]]+name = "itertools"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+dependencies = [+ "either",+]+[[package]]name = "itoa"version = "1.0.18"@@ -3314,6 +3808,20 @@ dependencies = ["system-deps",]+[[package]]+name = "jni"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec"+dependencies = [+ "cesu8",+ "combine",+ "jni-sys 0.3.1",+ "log",+ "thiserror 1.0.69",+ "walkdir",+]+[[package]]name = "jni"version = "0.21.1"@@ -3358,6 +3866,21 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "jni-utils"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "259e9f2c3ead61de911f147000660511f07ab00adeed1d84f5ac4d0386e7a6c4"+dependencies = [+ "dashmap 5.5.3",+ "futures",+ "jni 0.19.0",+ "log",+ "once_cell",+ "static_assertions",+ "uuid",+]+[[package]]name = "jobserver"version = "0.1.34"@@ -3414,6 +3937,15 @@ dependencies = ["serde_json",]+[[package]]+name = "kbkdf"+version = "0.1.0-rc.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90ac93c9768b8d587407881c98b0c3a5d3e3049daa73408ebe5bfb1ab1cb9c84"+dependencies = [+ "digest 0.11.0-rc.12",+]+[[package]]name = "keyboard-types"version = "0.7.0"@@ -3442,6 +3974,9 @@ name = "lazy_static"version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"+dependencies = [+ "spin",+][[package]]name = "lazycell"@@ -3644,7 +4179,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c60a23ffb90d527e23192f1246b14746e2f7f071cb84476dd879071696c18a4a"dependencies = ["crc",- "sha2",+ "sha2 0.10.9",][[package]]@@ -3661,7 +4196,7 @@ checksum = "29a16783dd1a47849b8c8133c9cd3eb2112cfbc6901670af3dba47c8bbfb07d3"dependencies = ["cc","objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2","time",]@@ -3678,9 +4213,9 @@ dependencies = [name = "macro_bundle_updater_plugin"version = "0.1.0"dependencies = [- "digest",+ "digest 0.10.7","futures",- "jni",+ "jni 0.21.1","ndk-context","objc2 0.5.2","reqwest",@@ -3688,7 +4223,7 @@ dependencies = ["semver","serde","serde_json",- "sha2",+ "sha2 0.10.9","specta","specta-serde","specta-typescript",@@ -3709,7 +4244,7 @@ version = "0.1.0"dependencies = ["cowlike","doppleganger",- "nom",+ "nom 8.0.0","serde","thiserror 2.0.18","tracing",@@ -3829,6 +4364,12 @@ dependencies = ["unicase",]+[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"+[[package]]name = "minisign-verify"version = "0.2.5"@@ -3890,7 +4431,7 @@ dependencies = ["objc2 0.6.4","objc2-app-kit","objc2-core-foundation",- "objc2-foundation",+ "objc2-foundation 0.3.2","once_cell","png 0.18.1","serde",@@ -3904,12 +4445,29 @@ version = "0.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bc0287524726960e07b119cebd01678f852f147742ae0d925e6a520dca956126"+[[package]]+name = "native-tls"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"+dependencies = [+ "libc",+ "log",+ "openssl",+ "openssl-probe",+ "openssl-sys",+ "schannel",+ "security-framework",+ "security-framework-sys",+ "tempfile",+]+[[package]]name = "navigation_plugin"version = "0.1.0"dependencies = ["logger",- "nom",+ "nom 8.0.0","rootcause","serde","serde_json",@@ -4064,6 +4622,16 @@ version = "0.1.14"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"+[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]+[[package]]name = "nom"version = "8.0.0"@@ -4129,12 +4697,39 @@ dependencies = ["num-traits",]+[[package]]+name = "num-bigint-dig"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"+dependencies = [+ "lazy_static",+ "libm",+ "num-integer",+ "num-iter",+ "num-traits",+ "rand 0.8.6",+ "smallvec",+ "zeroize",+]+[[package]]name = "num-conv"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967"+[[package]]+name = "num-derive"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "num-integer"version = "0.1.47"@@ -4144,6 +4739,16 @@ dependencies = ["num-traits",]+[[package]]+name = "num-iter"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"+dependencies = [+ "num-integer",+ "num-traits",+]+[[package]]name = "num-traits"version = "0.2.19"@@ -4151,6 +4756,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"dependencies = ["autocfg",+ "libm",][[package]]@@ -4217,10 +4823,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"dependencies = ["bitflags 2.11.1",- "block2",+ "block2 0.6.2","objc2 0.6.4","objc2-core-foundation",- "objc2-foundation",+ "objc2-foundation 0.3.2",][[package]]@@ -4231,7 +4837,18 @@ checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"dependencies = ["bitflags 2.11.1","objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2",+]++[[package]]+name = "objc2-core-bluetooth"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"+dependencies = [+ "bitflags 2.11.1",+ "objc2 0.5.2",+ "objc2-foundation 0.2.2",][[package]]@@ -4241,7 +4858,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"dependencies = ["objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2",][[package]]@@ -4275,7 +4892,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"dependencies = ["objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2",][[package]]@@ -4285,7 +4902,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"dependencies = ["objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2",][[package]]@@ -4315,6 +4932,18 @@ dependencies = ["cc",]+[[package]]+name = "objc2-foundation"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"+dependencies = [+ "bitflags 2.11.1",+ "block2 0.5.1",+ "libc",+ "objc2 0.5.2",+]+[[package]]name = "objc2-foundation"version = "0.3.2"@@ -4322,7 +4951,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"dependencies = ["bitflags 2.11.1",- "block2",+ "block2 0.6.2","libc","objc2 0.6.4","objc2-core-foundation",@@ -4334,9 +4963,9 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "80fac082e6de12282b24ea745e9707cd374363c7ae0b2f813bf1813cfc289325"dependencies = [- "block2",+ "block2 0.6.2","objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2",][[package]]@@ -4359,7 +4988,7 @@ dependencies = ["bitflags 2.11.1","objc2 0.6.4","objc2-app-kit",- "objc2-foundation",+ "objc2-foundation 0.3.2",][[package]]@@ -4371,7 +5000,7 @@ dependencies = ["bitflags 2.11.1","objc2 0.6.4","objc2-core-foundation",- "objc2-foundation",+ "objc2-foundation 0.3.2",][[package]]@@ -4381,7 +5010,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"dependencies = ["bitflags 2.11.1",- "block2",+ "block2 0.6.2","objc2 0.6.4","objc2-cloud-kit","objc2-core-data",@@ -4390,7 +5019,7 @@ dependencies = ["objc2-core-image","objc2-core-location","objc2-core-text",- "objc2-foundation",+ "objc2-foundation 0.3.2","objc2-quartz-core","objc2-user-notifications",]@@ -4402,9 +5031,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"dependencies = ["bitflags 2.11.1",- "block2",+ "block2 0.6.2","objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2",][[package]]@@ -4414,11 +5043,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"dependencies = ["bitflags 2.11.1",- "block2",+ "block2 0.6.2","objc2 0.6.4","objc2-app-kit","objc2-core-foundation",- "objc2-foundation",+ "objc2-foundation 0.3.2",+]++[[package]]+name = "oid-registry"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8d8034d9489cdaf79228eb9f6a3b8d7bb32ba00d6645ebd48eef4077ceb5bd9"+dependencies = [+ "asn1-rs",][[package]]@@ -4451,12 +5089,49 @@ dependencies = ["pathdiff",]+[[package]]+name = "openssl"+version = "0.10.81"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"+dependencies = [+ "bitflags 2.11.1",+ "cfg-if",+ "foreign-types 0.3.2",+ "libc",+ "openssl-macros",+ "openssl-sys",+]++[[package]]+name = "openssl-macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "openssl-probe"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"+[[package]]+name = "openssl-sys"+version = "0.9.117"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"+dependencies = [+ "cc",+ "libc",+ "pkg-config",+ "vcpkg",+]+[[package]]name = "option-ext"version = "0.2.0"@@ -4493,7 +5168,7 @@ dependencies = ["log","nix 0.30.1","objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2","objc2-ui-kit","serde","windows-sys 0.61.2",@@ -4506,7 +5181,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"dependencies = ["objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2","objc2-osa-kit","serde","serde_json",@@ -4519,6 +5194,44 @@ version = "3.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"+[[package]]+name = "p256"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"+dependencies = [+ "ecdsa",+ "elliptic-curve",+ "primeorder",+ "sha2 0.10.9",+]++[[package]]+name = "p384"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"+dependencies = [+ "ecdsa",+ "elliptic-curve",+ "primeorder",+ "sha2 0.10.9",+]++[[package]]+name = "p521"+version = "0.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fc9e2161f1f215afdfce23677034ae137bbd45016a880c2eb3ba8eb95f085b2"+dependencies = [+ "base16ct",+ "ecdsa",+ "elliptic-curve",+ "primeorder",+ "rand_core 0.6.4",+ "sha2 0.10.9",+]+[[package]]name = "pack1"version = "1.1.0"@@ -4582,6 +5295,17 @@ dependencies = ["windows-link 0.2.1",]+[[package]]+name = "password-hash"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"+dependencies = [+ "base64ct",+ "rand_core 0.6.4",+ "subtle",+]+[[package]]name = "paste"version = "1.0.15"@@ -4606,8 +5330,17 @@ version = "0.12.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"dependencies = [- "digest",- "hmac",+ "digest 0.10.7",+ "hmac 0.12.1",+]++[[package]]+name = "pem-rfc7468"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"+dependencies = [+ "base64ct",][[package]]@@ -4848,6 +5581,44 @@ dependencies = ["futures-io",]+[[package]]+name = "pkcs1"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"+dependencies = [+ "der",+ "pkcs8",+ "spki",+]++[[package]]+name = "pkcs5"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6"+dependencies = [+ "aes",+ "cbc",+ "der",+ "pbkdf2",+ "scrypt",+ "sha2 0.10.9",+ "spki",+]++[[package]]+name = "pkcs8"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"+dependencies = [+ "der",+ "pkcs5",+ "rand_core 0.6.4",+ "spki",+]+[[package]]name = "pkg-config"version = "0.3.33"@@ -4995,6 +5766,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "primeorder"+version = "0.13.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"+dependencies = [+ "elliptic-curve",+]+[[package]]name = "proc-macro-crate"version = "1.3.1"@@ -5501,6 +6281,16 @@ dependencies = ["web-sys",]+[[package]]+name = "rfc6979"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"+dependencies = [+ "hmac 0.12.1",+ "subtle",+]+[[package]]name = "ring"version = "0.17.14"@@ -5581,12 +6371,33 @@ dependencies = [name = "rowan"version = "0.16.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "417a3a9f582e349834051b8a10c8d71ca88da4211e4093528e36b9845f6b5f21"+checksum = "417a3a9f582e349834051b8a10c8d71ca88da4211e4093528e36b9845f6b5f21"+dependencies = [+ "countme",+ "hashbrown 0.14.5",+ "rustc-hash 1.1.0",+ "text-size",+]++[[package]]+name = "rsa"+version = "0.9.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"dependencies = [- "countme",- "hashbrown 0.14.5",- "rustc-hash 1.1.0",- "text-size",+ "const-oid",+ "digest 0.10.7",+ "num-bigint-dig",+ "num-integer",+ "num-traits",+ "pkcs1",+ "pkcs8",+ "rand_core 0.6.4",+ "sha2 0.10.9",+ "signature",+ "spki",+ "subtle",+ "zeroize",][[package]]@@ -5647,6 +6458,15 @@ dependencies = ["semver",]+[[package]]+name = "rusticata-macros"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"+dependencies = [+ "nom 7.1.3",+]+[[package]]name = "rustix"version = "1.1.4"@@ -5705,7 +6525,7 @@ checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784"dependencies = ["core-foundation 0.10.1","core-foundation-sys 0.8.7",- "jni",+ "jni 0.21.1","log","once_cell","rustls",@@ -5748,6 +6568,15 @@ version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"+[[package]]+name = "salsa20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"+dependencies = [+ "cipher",+]+[[package]]name = "same-file"version = "1.0.6"@@ -5829,12 +6658,37 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]+name = "scrypt"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f"+dependencies = [+ "pbkdf2",+ "salsa20",+ "sha2 0.10.9",+]+[[package]]name = "seahash"version = "4.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"+[[package]]+name = "sec1"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"+dependencies = [+ "base16ct",+ "der",+ "generic-array",+ "pkcs8",+ "subtle",+ "zeroize",+]+[[package]]name = "security-framework"version = "3.7.0"@@ -5927,6 +6781,38 @@ dependencies = ["typeid",]+[[package]]+name = "serde-xml-rs"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc2215ce3e6a77550b80a1c37251b7d294febaf42e36e21b7b411e0bf54d540d"+dependencies = [+ "log",+ "serde",+ "thiserror 2.0.18",+ "xml",+]++[[package]]+name = "serde_bytes"+version = "0.11.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"+dependencies = [+ "serde",+ "serde_core",+]++[[package]]+name = "serde_cbor_2"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34aec2709de9078e077090abd848e967abab63c9fb3fdb5d4799ad359d8d482c"+dependencies = [+ "half",+ "serde",+]+[[package]]name = "serde_core"version = "1.0.228"@@ -6107,7 +6993,7 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",][[package]]@@ -6124,7 +7010,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",+]++[[package]]+name = "sha2"+version = "0.11.0-rc.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c5f3b1e2dc8aad28310d8410bd4d7e180eca65fca176c52ab00d364475d0024"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest 0.11.0-rc.12",][[package]]@@ -6172,6 +7069,16 @@ dependencies = ["libc",]+[[package]]+name = "signature"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"+dependencies = [+ "digest 0.10.7",+ "rand_core 0.6.4",+]+[[package]]name = "simd-adler32"version = "0.3.9"@@ -6245,7 +7152,7 @@ dependencies = ["objc2 0.6.4","objc2-core-foundation","objc2-core-graphics",- "objc2-foundation",+ "objc2-foundation 0.3.2","objc2-quartz-core","raw-window-handle","redox_syscall",@@ -6364,6 +7271,16 @@ dependencies = ["lock_api",]+[[package]]+name = "spki"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"+dependencies = [+ "base64ct",+ "der",+]+[[package]]name = "stable_deref_trait"version = "1.2.1"@@ -6374,6 +7291,12 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"name = "staged_upload_constants"version = "0.1.0"+[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"+[[package]]name = "string_cache"version = "0.8.9"@@ -6625,7 +7548,7 @@ version = "0.37.0"source = "git+https://github.com/macro-inc/tao?rev=6cbc7628f91db2c5ce588719bf8ba6f2dd6fc1c8#6cbc7628f91db2c5ce588719bf8ba6f2dd6fc1c8"dependencies = ["bitflags 2.11.1",- "block2",+ "block2 0.6.2","core-foundation 0.10.1","core-graphics","crossbeam-channel",@@ -6636,7 +7559,7 @@ dependencies = ["gdkwayland-sys","gdkx11-sys","gtk",- "jni",+ "jni 0.21.1","libc","log","ndk",@@ -6644,7 +7567,7 @@ dependencies = ["ndk-sys","objc2 0.6.4","objc2-app-kit",- "objc2-foundation",+ "objc2-foundation 0.3.2","objc2-ui-kit","once_cell","parking_lot",@@ -6720,14 +7643,14 @@ dependencies = ["heck 0.5.0","http","http-range",- "jni",+ "jni 0.21.1","libc","log","mime","muda","objc2 0.6.4","objc2-app-kit",- "objc2-foundation",+ "objc2-foundation 0.3.2","objc2-ui-kit","objc2-web-kit","percent-encoding",@@ -6790,7 +7713,7 @@ dependencies = ["semver","serde","serde_json",- "sha2",+ "sha2 0.10.9","syn 2.0.117","tauri-utils","thiserror 2.0.18",@@ -6946,7 +7869,7 @@ dependencies = ["dunce","glob","log",- "objc2-foundation",+ "objc2-foundation 0.3.2","percent-encoding","schemars 0.8.22","serde",@@ -7016,7 +7939,7 @@ dependencies = ["fern","log","objc2 0.6.4",- "objc2-foundation",+ "objc2-foundation 0.3.2","serde","serde_json","serde_repr",@@ -7075,7 +7998,7 @@ dependencies = ["dunce","glob","objc2-app-kit",- "objc2-foundation",+ "objc2-foundation 0.3.2","open","schemars 0.8.22","serde",@@ -7202,7 +8125,7 @@ dependencies = ["tauri-plugin","thiserror 2.0.18","tokio",- "tokio-tungstenite",+ "tokio-tungstenite 0.29.0",][[package]]@@ -7229,7 +8152,7 @@ dependencies = ["dpi","gtk","http",- "jni",+ "jni 0.21.1","objc2 0.6.4","objc2-ui-kit","objc2-web-kit",@@ -7251,7 +8174,7 @@ source = "git+https://github.com/macro-inc/tauri?rev=957785f5#957785f52fa5c79c53dependencies = ["gtk","http",- "jni",+ "jni 0.21.1","log","objc2 0.6.4","objc2-app-kit",@@ -7488,6 +8411,27 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"+[[package]]+name = "tls_codec"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"+dependencies = [+ "tls_codec_derive",+ "zeroize",+]++[[package]]+name = "tls_codec_derive"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "tokio"version = "1.52.1"@@ -7516,6 +8460,16 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "tokio-native-tls"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"+dependencies = [+ "native-tls",+ "tokio",+]+[[package]]name = "tokio-rustls"version = "0.26.4"@@ -7526,6 +8480,32 @@ dependencies = ["tokio",]+[[package]]+name = "tokio-stream"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+ "tokio-util",+]++[[package]]+name = "tokio-tungstenite"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"+dependencies = [+ "futures-util",+ "log",+ "native-tls",+ "tokio",+ "tokio-native-tls",+ "tungstenite 0.28.0",+]+[[package]]name = "tokio-tungstenite"version = "0.29.0"@@ -7538,7 +8518,7 @@ dependencies = ["rustls-pki-types","tokio","tokio-rustls",- "tungstenite",+ "tungstenite 0.29.0","webpki-roots 0.26.11",]@@ -7818,7 +8798,7 @@ dependencies = ["objc2-app-kit","objc2-core-foundation","objc2-core-graphics",- "objc2-foundation",+ "objc2-foundation 0.3.2","once_cell","png 0.18.1","serde",@@ -7842,6 +8822,24 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "tungstenite"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442"+dependencies = [+ "bytes",+ "data-encoding",+ "http",+ "httparse",+ "log",+ "native-tls",+ "rand 0.9.4",+ "sha1",+ "thiserror 2.0.18",+ "utf-8",+]+[[package]]name = "tungstenite"version = "0.29.0"@@ -8082,6 +9080,15 @@ version = "1.0.24"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"+[[package]]+name = "unicode-normalization"+version = "0.1.26"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"+dependencies = [+ "tinyvec",+]+[[package]]name = "unicode-segmentation"version = "1.13.2"@@ -8112,7 +9119,7 @@ version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"dependencies = [- "crypto-common",+ "crypto-common 0.1.7","subtle",]@@ -8242,6 +9249,12 @@ version = "1.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"+[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"+[[package]]name = "version-compare"version = "0.2.1"@@ -8457,6 +9470,88 @@ dependencies = ["string_cache_codegen 0.6.1",]+[[package]]+name = "webauthn-attestation-ca"+version = "0.6.1-dev"+source = "git+https://github.com/beeper/webauthn-rs?rev=579f9144d37161bedf25ed1236d73486ce303de6#579f9144d37161bedf25ed1236d73486ce303de6"+dependencies = [+ "crypto-glue",+ "serde",+ "serde_with",+ "tracing",+ "uuid",+]++[[package]]+name = "webauthn-authenticator-rs"+version = "0.6.1-dev"+source = "git+https://github.com/beeper/webauthn-rs?rev=579f9144d37161bedf25ed1236d73486ce303de6#579f9144d37161bedf25ed1236d73486ce303de6"+dependencies = [+ "async-stream",+ "async-trait",+ "base64 0.21.7",+ "bitflags 1.3.2",+ "btleplug",+ "crypto-glue",+ "futures",+ "hex",+ "nom 7.1.3",+ "num-derive",+ "num-traits",+ "serde",+ "serde_bytes",+ "serde_cbor_2",+ "serde_json",+ "thiserror 1.0.69",+ "tokio",+ "tokio-stream",+ "tokio-tungstenite 0.28.0",+ "tracing",+ "unicode-normalization",+ "url",+ "uuid",+ "webauthn-rs-core",+ "webauthn-rs-proto",+ "windows 0.41.0",+]++[[package]]+name = "webauthn-rs-core"+version = "0.6.1-dev"+source = "git+https://github.com/beeper/webauthn-rs?rev=579f9144d37161bedf25ed1236d73486ce303de6#579f9144d37161bedf25ed1236d73486ce303de6"+dependencies = [+ "base64 0.21.7",+ "crypto-glue",+ "der-parser",+ "hex",+ "nom 7.1.3",+ "rand 0.9.4",+ "rand_chacha 0.9.0",+ "serde",+ "serde_cbor_2",+ "serde_json",+ "serde_with",+ "thiserror 1.0.69",+ "tracing",+ "url",+ "uuid",+ "webauthn-attestation-ca",+ "webauthn-rs-proto",+ "x509-parser",+]++[[package]]+name = "webauthn-rs-proto"+version = "0.6.1-dev"+source = "git+https://github.com/beeper/webauthn-rs?rev=579f9144d37161bedf25ed1236d73486ce303de6#579f9144d37161bedf25ed1236d73486ce303de6"+dependencies = [+ "base64 0.21.7",+ "serde",+ "serde_json",+ "serde_with",+ "url",+]+[[package]]name = "webkit2gtk"version = "2.0.2"@@ -8602,12 +9697,27 @@ dependencies = ["objc2 0.6.4","objc2-app-kit","objc2-core-foundation",- "objc2-foundation",+ "objc2-foundation 0.3.2","raw-window-handle","windows-sys 0.59.0","windows-version",]+[[package]]+name = "windows"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a3ed69de2c1f8d0524a8a3417a80a85dd316a071745fbfdf5eb028b310058ab"+dependencies = [+ "windows_aarch64_gnullvm 0.41.0",+ "windows_aarch64_msvc 0.41.0",+ "windows_i686_gnu 0.41.0",+ "windows_i686_msvc 0.41.0",+ "windows_x86_64_gnu 0.41.0",+ "windows_x86_64_gnullvm 0.41.0",+ "windows_x86_64_msvc 0.41.0",+]+[[package]]name = "windows"version = "0.48.0"@@ -9072,6 +10182,12 @@ dependencies = ["windows-link 0.2.1",]+[[package]]+name = "windows_aarch64_gnullvm"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "163d2761774f2278ecb4e6719e80b2b5e92e5a2be73a7bcd3ef624dd5e3091fd"+[[package]]name = "windows_aarch64_gnullvm"version = "0.42.2"@@ -9096,6 +10212,12 @@ version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"+[[package]]+name = "windows_aarch64_msvc"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef005ff2bceb00d3b84166a359cc19084f9459754fd3fe5a504dee3dddcd0a0c"+[[package]]name = "windows_aarch64_msvc"version = "0.42.2"@@ -9120,6 +10242,12 @@ version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"+[[package]]+name = "windows_i686_gnu"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02b4df2d51e32f03f8b4b228e487828c03bcb36d97b216fc5463bcea5bb1440b"+[[package]]name = "windows_i686_gnu"version = "0.42.2"@@ -9156,6 +10284,12 @@ version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"+[[package]]+name = "windows_i686_msvc"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "568a966834571f2f3267f07dd72b4d8507381f25e53d056808483b2637385ef7"+[[package]]name = "windows_i686_msvc"version = "0.42.2"@@ -9180,6 +10314,12 @@ version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"+[[package]]+name = "windows_x86_64_gnu"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc395dac1adf444e276d096d933ae7961361c8cda3245cffef7a9b3a70a8f994"+[[package]]name = "windows_x86_64_gnu"version = "0.42.2"@@ -9204,6 +10344,12 @@ version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"+[[package]]+name = "windows_x86_64_gnullvm"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90e8ec22b715d5b436e1d59c8adad6c744dc20cd984710121d5836b4e8dbb5e0"+[[package]]name = "windows_x86_64_gnullvm"version = "0.42.2"@@ -9228,6 +10374,12 @@ version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"+[[package]]+name = "windows_x86_64_msvc"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b9761f0216b669019df1512f6e25e5ee779bf61c5cdc43c7293858e7efd7926"+[[package]]name = "windows_x86_64_msvc"version = "0.42.2"@@ -9417,7 +10569,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0"dependencies = ["base64 0.22.1",- "block2",+ "block2 0.6.2","cookie","crossbeam-channel","dirs 7.0.0",@@ -9428,19 +10580,19 @@ dependencies = ["gtk","http","javascriptcore-rs",- "jni",+ "jni 0.21.1","libc","ndk","objc2 0.6.4","objc2-app-kit","objc2-core-foundation",- "objc2-foundation",+ "objc2-foundation 0.3.2","objc2-ui-kit","objc2-web-kit","once_cell","percent-encoding","raw-window-handle",- "sha2",+ "sha2 0.10.9","soup3","tao-macros 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)","thiserror 2.0.18",@@ -9484,6 +10636,37 @@ dependencies = ["pkg-config",]+[[package]]+name = "x509-cert"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"+dependencies = [+ "const-oid",+ "der",+ "sha1",+ "signature",+ "spki",+ "tls_codec",+]++[[package]]+name = "x509-parser"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fcbc162f30700d6f3f82a24bf7cc62ffe7caea42c0b2cba8bf7f3ae50cf51f69"+dependencies = [+ "asn1-rs",+ "data-encoding",+ "der-parser",+ "lazy_static",+ "nom 7.1.3",+ "oid-registry",+ "rusticata-macros",+ "thiserror 1.0.69",+ "time",+]+[[package]]name = "xattr"version = "1.6.1"@@ -9494,6 +10677,12 @@ dependencies = ["rustix",]+[[package]]+name = "xml"+version = "1.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f45bb2c13fec6a6cb4c0f76a7e94839e110a14ec803ec2940777a94c347bc52"+[[package]]name = "yansi"version = "1.0.1"@@ -9631,6 +10820,7 @@ version = "1.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"dependencies = [+ "serde","zeroize_derive",]@@ -9706,7 +10896,7 @@ dependencies = ["deflate64","flate2","getrandom 0.3.4",- "hmac",+ "hmac 0.12.1","indexmap 2.14.0","lzma-rust2","memchr",diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.tomlindex 0fa261d333..f732dfd304 100644--- a/apps/web/tauri/Cargo.toml+++ b/apps/web/tauri/Cargo.toml@@ -29,6 +29,10 @@ opt-level = 3debug-assertions = false[workspace.dependencies]+# Beeper's fork carries the caBLE (hybrid) fixes WhatsApp passkey pairing needs.+webauthn-authenticator-rs = { git = "https://github.com/beeper/webauthn-rs", rev = "579f9144d37161bedf25ed1236d73486ce303de6", default-features = false }+webauthn-rs-proto = { git = "https://github.com/beeper/webauthn-rs", rev = "579f9144d37161bedf25ed1236d73486ce303de6" }+pollster = "0.4"reqwest = "0.13"rootcause = "0.12"diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex d6bf5d701a..8b052c1cc5 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -82,6 +82,19 @@ tauri-plugin-updater = "=2.10.1"# 2.5 requires tauri 2.12; the pinned fork is 2.11.tauri-plugin-window-state = "=2.4.1"+# WhatsApp passkey pairing: caBLE (phone over Bluetooth) on macOS/Linux,+# native WebAuthn on Windows. See src/whatsapp_passkey.rs.+[target.'cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))'.dependencies]+base64 = "0.22"+sha2 = "0.10"+webauthn-rs-proto = { workspace = true }++[target.'cfg(any(target_os = "macos", target_os = "linux"))'.dependencies]+webauthn-authenticator-rs = { workspace = true, features = ["cable"] }++[target.'cfg(target_os = "windows")'.dependencies]+webauthn-authenticator-rs = { workspace = true, features = ["win10"] }+[target.'cfg(target_os = "linux")'.dependencies]futures-util = "0.3"gtk = "0.18"diff --git a/apps/web/tauri/src-tauri/gen/apple/NotificationServiceExtension/Info.plist b/apps/web/tauri/src-tauri/gen/apple/NotificationServiceExtension/Info.plistindex 20ecf02b15..99899b61e6 100644--- a/apps/web/tauri/src-tauri/gen/apple/NotificationServiceExtension/Info.plist+++ b/apps/web/tauri/src-tauri/gen/apple/NotificationServiceExtension/Info.plist@@ -19,7 +19,7 @@<key>CFBundleShortVersionString</key><string>2.0.11</string><key>CFBundleVersion</key>- <string>190</string>+ <string>191</string><key>NSExtension</key><dict><key>NSExtensionPointIdentifier</key>diff --git a/apps/web/tauri/src-tauri/gen/apple/ShareExtension/Info.plist b/apps/web/tauri/src-tauri/gen/apple/ShareExtension/Info.plistindex 33e5a09e4a..9cf592df90 100644--- a/apps/web/tauri/src-tauri/gen/apple/ShareExtension/Info.plist+++ b/apps/web/tauri/src-tauri/gen/apple/ShareExtension/Info.plist@@ -19,7 +19,7 @@<key>CFBundleShortVersionString</key><string>2.0.11</string><key>CFBundleVersion</key>- <string>190</string>+ <string>191</string><key>LSApplicationQueriesSchemes</key><array><string>macro</string>diff --git a/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plist b/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plistindex c4fb85da82..4079df52b6 100644--- a/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plist+++ b/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plist@@ -28,7 +28,7 @@</dict></array><key>CFBundleVersion</key>- <string>190</string>+ <string>191</string><key>ITSAppUsesNonExemptEncryption</key><false/><key>LSApplicationQueriesSchemes</key>diff --git a/apps/web/tauri/src-tauri/gen/apple/project.yml b/apps/web/tauri/src-tauri/gen/apple/project.ymlindex 08da265e2c..b5aca2b724 100644--- a/apps/web/tauri/src-tauri/gen/apple/project.yml+++ b/apps/web/tauri/src-tauri/gen/apple/project.yml@@ -59,7 +59,7 @@ targets:- UIInterfaceOrientationLandscapeLeft- UIInterfaceOrientationLandscapeRightCFBundleShortVersionString: 2.0.11- CFBundleVersion: "190"+ CFBundleVersion: "191"# Exempt encryption only (HTTPS / OS crypto): answers App Store# Connect's export-compliance questionnaire for every build. Keep in# sync with src-tauri/Info.ios.plist.@@ -146,7 +146,7 @@ targets:properties:CFBundleDisplayName: Share to MacroCFBundleShortVersionString: 2.0.11- CFBundleVersion: "190"+ CFBundleVersion: "191"LSApplicationQueriesSchemes:- macroNSExtension:@@ -181,7 +181,7 @@ targets:properties:CFBundleDisplayName: NotificationServiceExtensionCFBundleShortVersionString: 2.0.11- CFBundleVersion: "190"+ CFBundleVersion: "191"NSExtension:NSExtensionPointIdentifier: com.apple.usernotifications.serviceNSExtensionPrincipalClass: $(PRODUCT_MODULE_NAME).NotificationServicediff --git a/apps/web/tauri/src-tauri/icons/macos/Info.plist b/apps/web/tauri/src-tauri/icons/macos/Info.plistindex 9040487348..74116c781a 100644--- a/apps/web/tauri/src-tauri/icons/macos/Info.plist+++ b/apps/web/tauri/src-tauri/icons/macos/Info.plist@@ -14,5 +14,7 @@<string>Macro uses the camera for video calls.</string><key>NSMicrophoneUsageDescription</key><string>Macro uses the microphone for calls and dictation.</string>+ <key>NSBluetoothAlwaysUsageDescription</key>+ <string>Macro uses Bluetooth to securely authenticate a WhatsApp connection with your nearby phone.</string></dict></plist>diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex 2dc24919a2..1cc28fc691 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -45,6 +45,7 @@ mod logging;mod macos_notification_permission;mod share_target;mod staged_upload;+mod whatsapp_passkey;#[cfg(desktop)]mod window_state;@@ -366,6 +367,7 @@ pub fn run_with(builder: tauri::Builder<AppRuntime>) {.manage(graphql_cache_plugin::CacheState::default()).manage(IsIpad(is_ipad_device)).invoke_handler(tauri::generate_handler![+ whatsapp_passkey::whatsapp_passkey_authenticate,desktop_update::get_native_update_status,desktop_update::restart_native_update,diagnostics::read_desktop_diagnostics,diff --git a/apps/web/tauri/src-tauri/src/whatsapp_passkey.rs b/apps/web/tauri/src-tauri/src/whatsapp_passkey.rsnew file mode 100644index 0000000000..0c3ea2a7a6--- /dev/null+++ b/apps/web/tauri/src-tauri/src/whatsapp_passkey.rs@@ -0,0 +1,219 @@+//! Answers WhatsApp's passkey challenge during linked-device pairing.+//!+//! When WhatsApp protects pairing with a passkey, the session service stores+//! WhatsApp's WebAuthn request options on the pairing; the web app reads them+//! from DSS (as the signed-in owner) and hands them to this command, then+//! POSTs the returned assertion to `/meta/linked/pairing/{id}/passkey`. This is+//! an authentication handoff only: the hosted session stays the sole WhatsApp+//! endpoint.+//!+//! The command only signs for WhatsApp: the relying party must be WhatsApp's,+//! the origin is fixed to `https://web.whatsapp.com`, user verification is+//! forced on, and the returned assertion is checked against all three before+//! it leaves the process. macOS and Linux reach the phone over caBLE+//! (hybrid); Windows uses the native WebAuthn API; mobile is unsupported.++#[cfg(desktop)]+mod validation;++use serde::Serialize;+use tauri::ipc::Channel;+use uuid::Uuid;++/// What the pairing UI should show while the authenticator runs.+#[derive(Serialize, Clone, Debug, PartialEq, Eq)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum AuthenticationEvent {+ /// Show this `FIDO:/` URL as a QR code for the phone to scan.+ Qr { value: String },+ /// Ask the user to confirm on the authenticator.+ Touch,+ /// The authenticator is working.+ Processing,+ /// Hide the QR code.+ Dismiss,+}++#[derive(Debug, thiserror::Error, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum AuthenticationError {+ #[cfg(mobile)]+ #[error(+ "This device cannot complete WhatsApp authentication. Use Macro desktop with Bluetooth and your phone nearby."+ )]+ Unsupported,+ #[error("This connection request is no longer valid. Start connecting again.")]+ Invalid,+ #[error("WhatsApp authentication was cancelled or unavailable. Check Bluetooth and try again.")]+ Unavailable,+ #[error("Your phone did not verify you. Unlock your phone and try again.")]+ Unverified,+}++/// Sign WhatsApp's passkey challenge for pairing `pairing_id`.+///+/// `challenge` is the pairing's WebAuthn request options as DSS returns them+/// (`PairState.challenge`): `{ challenge, rpId, allowCredentials,+/// userVerification, timeout, extensions }`. Returns the assertion+/// (`PublicKeyCredential` JSON) for the passkey route.+#[tauri::command]+#[tracing::instrument(+ name = "whatsapp.passkey_authenticate",+ skip_all,+ err,+ fields(pairing_id = %pairing_id)+)]+pub async fn whatsapp_passkey_authenticate(+ pairing_id: Uuid,+ challenge: serde_json::Value,+ on_event: Channel<AuthenticationEvent>,+) -> Result<serde_json::Value, AuthenticationError> {+ #[cfg(desktop)]+ {+ desktop::authenticate(challenge, on_event).await+ }+ #[cfg(mobile)]+ {+ let _ = (challenge, on_event);+ Err(AuthenticationError::Unsupported)+ }+}++#[cfg(desktop)]+mod desktop {+ use super::validation::{WHATSAPP_ORIGIN, request_options, verify_assertion};+ use super::{AuthenticationError, AuthenticationEvent};+ use tauri::ipc::Channel;+ use webauthn_authenticator_rs::WebauthnAuthenticator;++ pub(super) async fn authenticate(+ challenge: serde_json::Value,+ on_event: Channel<AuthenticationEvent>,+ ) -> Result<serde_json::Value, AuthenticationError> {+ let options = request_options(challenge)?;+ let origin = url::Url::parse(WHATSAPP_ORIGIN).map_err(|_| AuthenticationError::Invalid)?;++ // Upstream trace output includes caBLE handshake material, so the whole+ // ceremony runs on its own thread (and current-thread runtime) with no+ // tracing subscriber.+ let (send, receive) = tokio::sync::oneshot::channel();+ std::thread::Builder::new()+ .name("whatsapp-passkey".into())+ .spawn(move || {+ let _quiet =+ tracing::subscriber::set_default(tracing::subscriber::NoSubscriber::default());+ let _ = send.send(+ run(origin, options.clone(), on_event).and_then(|credential| {+ verify_assertion(&options.public_key, &credential)?;+ serde_json::to_value(credential)+ .map_err(|_| AuthenticationError::Unavailable)+ }),+ );+ })+ .map_err(|_| AuthenticationError::Unavailable)?;+ receive+ .await+ .map_err(|_| AuthenticationError::Unavailable)?+ }++ #[cfg(target_os = "windows")]+ fn run(+ origin: url::Url,+ options: webauthn_rs_proto::RequestChallengeResponse,+ _on_event: Channel<AuthenticationEvent>,+ ) -> Result<webauthn_rs_proto::PublicKeyCredential, AuthenticationError> {+ // Windows shows its own WebAuthn dialog, phone (hybrid) included.+ webauthn_authenticator_rs::win10::Win10::default()+ .do_authentication(origin, options)+ .map_err(|_| AuthenticationError::Unavailable)+ }++ #[cfg(any(target_os = "macos", target_os = "linux"))]+ fn run(+ origin: url::Url,+ options: webauthn_rs_proto::RequestChallengeResponse,+ on_event: Channel<AuthenticationEvent>,+ ) -> Result<webauthn_rs_proto::PublicKeyCredential, AuthenticationError> {+ use webauthn_authenticator_rs::{+ cable::connect_cable_authenticator, types::CableRequestType,+ };++ /// How long the user has to scan the QR code and reach the phone.+ const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);++ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .map_err(|_| AuthenticationError::Unavailable)?;+ let ui = NativeUi(on_event);+ let mut authenticator = runtime+ .block_on(tokio::time::timeout(+ CONNECT_TIMEOUT,+ connect_cable_authenticator(CableRequestType::GetAssertion, &ui),+ ))+ .map_err(|_| AuthenticationError::Unavailable)?+ .map_err(|_| AuthenticationError::Unavailable)?;+ let _entered = runtime.enter();+ authenticator+ .do_authentication(origin, options)+ .map_err(|_| AuthenticationError::Unavailable)+ }++ /// Forwards the authenticator's UI requests to the pairing screen. Never+ /// answers a PIN prompt: the phone verifies the user itself.+ #[cfg(any(target_os = "macos", target_os = "linux"))]+ struct NativeUi(Channel<AuthenticationEvent>);++ #[cfg(any(target_os = "macos", target_os = "linux"))]+ impl std::fmt::Debug for NativeUi {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str("WhatsAppPasskeyUi")+ }+ }++ #[cfg(any(target_os = "macos", target_os = "linux"))]+ impl NativeUi {+ fn emit(&self, event: AuthenticationEvent) {+ // The window may be gone; the ceremony still ends on its timeout.+ let _ = self.0.send(event);+ }+ }++ #[cfg(any(target_os = "macos", target_os = "linux"))]+ impl webauthn_authenticator_rs::ui::UiCallback for NativeUi {+ fn request_pin(&self) -> Option<String> {+ None+ }++ fn request_touch(&self) {+ self.emit(AuthenticationEvent::Touch);+ }++ fn processing(&self) {+ self.emit(AuthenticationEvent::Processing);+ }++ fn fingerprint_enrollment_feedback(+ &self,+ _remaining_samples: u32,+ _feedback: Option<webauthn_authenticator_rs::types::EnrollSampleStatus>,+ ) {+ }++ fn cable_qr_code(+ &self,+ _request_type: webauthn_authenticator_rs::types::CableRequestType,+ url: String,+ ) {+ self.emit(AuthenticationEvent::Qr { value: url });+ }++ fn dismiss_qr_code(&self) {+ self.emit(AuthenticationEvent::Dismiss);+ }++ fn cable_status_update(&self, _state: webauthn_authenticator_rs::types::CableState) {+ self.emit(AuthenticationEvent::Processing);+ }+ }+}diff --git a/apps/web/tauri/src-tauri/src/whatsapp_passkey/validation.rs b/apps/web/tauri/src-tauri/src/whatsapp_passkey/validation.rsnew file mode 100644index 0000000000..211b27d8e6--- /dev/null+++ b/apps/web/tauri/src-tauri/src/whatsapp_passkey/validation.rs@@ -0,0 +1,105 @@+//! The WhatsApp boundary around the authenticator: what we agree to sign, and+//! what we agree to hand back.++use base64::Engine;+use base64::engine::general_purpose::URL_SAFE_NO_PAD;+use serde::Deserialize;+use sha2::{Digest, Sha256};+use webauthn_rs_proto::{+ PublicKeyCredential, PublicKeyCredentialRequestOptions, RequestChallengeResponse,+ UserVerificationPolicy,+};++use super::AuthenticationError;++/// The origin every assertion is made for, whatever the caller asks.+pub(super) const WHATSAPP_ORIGIN: &str = "https://web.whatsapp.com";+/// Relying-party ids WhatsApp may ask for; anything else is refused.+const RELYING_PARTY_IDS: [&str; 2] = ["whatsapp.com", "web.whatsapp.com"];+const MAX_CHALLENGE_BYTES: usize = 1024;+/// The authenticator library caps ceremonies at 60 seconds anyway.+const TIMEOUT_MS: u32 = 60_000;++/// Authenticator-data flag: user present.+const FLAG_USER_PRESENT: u8 = 0x01;+/// Authenticator-data flag: user verified.+const FLAG_USER_VERIFIED: u8 = 0x04;++/// Parse WhatsApp's request options and pin them to WhatsApp: refuse any other+/// relying party, force user verification, and drop extensions that would+/// widen what may answer (`appid`) or what comes back (`hmacGetSecret`).+pub(super) fn request_options(+ challenge: serde_json::Value,+) -> Result<RequestChallengeResponse, AuthenticationError> {+ let mut options: PublicKeyCredentialRequestOptions =+ serde_json::from_value(challenge).map_err(|_| AuthenticationError::Invalid)?;+ if !RELYING_PARTY_IDS.contains(&options.rp_id.as_str())+ || options.challenge.is_empty()+ || options.challenge.len() > MAX_CHALLENGE_BYTES+ {+ return Err(AuthenticationError::Invalid);+ }+ options.user_verification = UserVerificationPolicy::Required;+ options.timeout = Some(TIMEOUT_MS);+ if let Some(extensions) = options.extensions.as_mut() {+ extensions.appid = None;+ extensions.hmac_get_secret = None;+ }+ Ok(RequestChallengeResponse {+ public_key: options,+ mediation: None,+ })+}++#[derive(Deserialize)]+struct ClientData {+ #[serde(rename = "type")]+ kind: String,+ challenge: String,+ origin: String,+}++/// Check the assertion answers exactly the request: same challenge, WhatsApp's+/// origin and relying party, an allowed credential, and a verified user.+pub(super) fn verify_assertion(+ options: &PublicKeyCredentialRequestOptions,+ credential: &PublicKeyCredential,+) -> Result<(), AuthenticationError> {+ let client: ClientData = serde_json::from_slice(&credential.response.client_data_json)+ .map_err(|_| AuthenticationError::Unavailable)?;+ let signed_challenge = URL_SAFE_NO_PAD+ .decode(client.challenge.trim_end_matches('='))+ .map_err(|_| AuthenticationError::Unavailable)?;+ if credential.type_ != "public-key"+ || client.kind != "webauthn.get"+ || client.origin != WHATSAPP_ORIGIN+ || signed_challenge != options.challenge+ {+ return Err(AuthenticationError::Unavailable);+ }+ if !options.allow_credentials.is_empty()+ && !options+ .allow_credentials+ .iter()+ .any(|allowed| allowed.id == credential.raw_id)+ {+ return Err(AuthenticationError::Unavailable);+ }++ let authenticator_data = &credential.response.authenticator_data;+ let (Some(relying_party_hash), Some(&flags)) =+ (authenticator_data.get(..32), authenticator_data.get(32))+ else {+ return Err(AuthenticationError::Unavailable);+ };+ if relying_party_hash != Sha256::digest(options.rp_id.as_bytes()).as_slice() {+ return Err(AuthenticationError::Unavailable);+ }+ if flags & FLAG_USER_PRESENT == 0 || flags & FLAG_USER_VERIFIED == 0 {+ return Err(AuthenticationError::Unverified);+ }+ Ok(())+}++#[cfg(test)]+mod test;diff --git a/apps/web/tauri/src-tauri/src/whatsapp_passkey/validation/test.rs b/apps/web/tauri/src-tauri/src/whatsapp_passkey/validation/test.rsnew file mode 100644index 0000000000..f10acc3782--- /dev/null+++ b/apps/web/tauri/src-tauri/src/whatsapp_passkey/validation/test.rs@@ -0,0 +1,220 @@+use super::*;+use serde_json::json;++/// `challenge` = base64url("whatsapp-challenge"), credential id =+/// base64url("credential-1"), as whatsmeow serializes `WebAuthnPublicKey`.+fn whatsapp_request() -> serde_json::Value {+ json!({+ "challenge": "d2hhdHNhcHAtY2hhbGxlbmdl",+ "timeout": 300000,+ "rpId": "whatsapp.com",+ "allowCredentials": [+ { "id": "Y3JlZGVudGlhbC0x", "type": "public-key", "transports": ["hybrid", "internal"] }+ ],+ "userVerification": "preferred",+ "extensions": {}+ })+}++fn assertion(+ client_data: serde_json::Value,+ relying_party_id: &str,+ flags: u8,+ raw_id: &[u8],+) -> PublicKeyCredential {+ let mut authenticator_data = Sha256::digest(relying_party_id.as_bytes()).to_vec();+ authenticator_data.push(flags);+ authenticator_data.extend_from_slice(&[0, 0, 0, 1]);+ PublicKeyCredential {+ id: URL_SAFE_NO_PAD.encode(raw_id),+ raw_id: raw_id.to_vec(),+ response: webauthn_rs_proto::AuthenticatorAssertionResponseRaw {+ authenticator_data,+ client_data_json: serde_json::to_vec(&client_data).unwrap(),+ signature: vec![1, 2, 3],+ user_handle: None,+ },+ extensions: Default::default(),+ type_: "public-key".into(),+ }+}++fn whatsapp_client_data() -> serde_json::Value {+ json!({+ "type": "webauthn.get",+ "challenge": "d2hhdHNhcHAtY2hhbGxlbmdl",+ "origin": "https://web.whatsapp.com",+ "crossOrigin": false+ })+}++#[test]+fn whatsapp_request_is_pinned_to_required_verification() {+ let mut request = whatsapp_request();+ request["extensions"] = json!({ "appid": "https://evil.example", "uvm": true });++ let options = request_options(request).unwrap().public_key;++ assert_eq!(options.rp_id, "whatsapp.com");+ assert_eq!(options.challenge, b"whatsapp-challenge");+ assert_eq!(options.allow_credentials.len(), 1);+ assert_eq!(options.allow_credentials[0].id, b"credential-1");+ assert_eq!(options.user_verification, UserVerificationPolicy::Required);+ assert_eq!(options.timeout, Some(60_000));+ let extensions = options.extensions.unwrap();+ assert_eq!(extensions.appid, None);+ assert_eq!(extensions.uvm, Some(true));+}++#[test]+fn web_whatsapp_relying_party_is_accepted() {+ let mut request = whatsapp_request();+ request["rpId"] = json!("web.whatsapp.com");+ assert_eq!(+ request_options(request).unwrap().public_key.rp_id,+ "web.whatsapp.com"+ );+}++#[test]+fn other_relying_parties_are_rejected() {+ for relying_party_id in [+ "evil.example",+ "whatsapp.com.evil.example",+ "evilwhatsapp.com",+ "com",+ "",+ ] {+ let mut request = whatsapp_request();+ request["rpId"] = json!(relying_party_id);+ assert_eq!(+ request_options(request).unwrap_err(),+ AuthenticationError::Invalid,+ "{relying_party_id}"+ );+ }+}++#[test]+fn malformed_requests_are_rejected() {+ let mut missing_relying_party = whatsapp_request();+ missing_relying_party+ .as_object_mut()+ .unwrap()+ .remove("rpId");+ let mut missing_verification = whatsapp_request();+ missing_verification+ .as_object_mut()+ .unwrap()+ .remove("userVerification");+ let mut empty_challenge = whatsapp_request();+ empty_challenge["challenge"] = json!("");+ let mut not_base64_challenge = whatsapp_request();+ not_base64_challenge["challenge"] = json!("not base64!");+ let mut oversized_challenge = whatsapp_request();+ oversized_challenge["challenge"] = json!(URL_SAFE_NO_PAD.encode([7u8; 1025]));+ let mut wrapped = json!({});+ wrapped["publicKey"] = whatsapp_request();++ for request in [+ json!(null),+ json!("whatsapp.com"),+ json!([]),+ wrapped,+ missing_relying_party,+ missing_verification,+ empty_challenge,+ not_base64_challenge,+ oversized_challenge,+ ] {+ assert_eq!(+ request_options(request.clone()).unwrap_err(),+ AuthenticationError::Invalid,+ "{request}"+ );+ }+}++#[test]+fn verified_assertion_is_accepted() {+ let options = request_options(whatsapp_request()).unwrap().public_key;+ let credential = assertion(+ whatsapp_client_data(),+ "whatsapp.com",+ FLAG_USER_PRESENT | FLAG_USER_VERIFIED,+ b"credential-1",+ );+ assert_eq!(verify_assertion(&options, &credential), Ok(()));+}++#[test]+fn assertion_without_user_verification_is_rejected() {+ let options = request_options(whatsapp_request()).unwrap().public_key;+ for flags in [FLAG_USER_PRESENT, FLAG_USER_VERIFIED, 0] {+ let credential = assertion(+ whatsapp_client_data(),+ "whatsapp.com",+ flags,+ b"credential-1",+ );+ assert_eq!(+ verify_assertion(&options, &credential),+ Err(AuthenticationError::Unverified),+ "flags {flags:#x}"+ );+ }+}++#[test]+fn assertion_for_anything_else_is_rejected() {+ let options = request_options(whatsapp_request()).unwrap().public_key;+ let verified = FLAG_USER_PRESENT | FLAG_USER_VERIFIED;++ let mut other_origin = whatsapp_client_data();+ other_origin["origin"] = json!("https://evil.example");+ let mut other_challenge = whatsapp_client_data();+ other_challenge["challenge"] = json!("b3RoZXI");+ let mut registration = whatsapp_client_data();+ registration["type"] = json!("webauthn.create");++ let mut truncated = assertion(+ whatsapp_client_data(),+ "whatsapp.com",+ verified,+ b"credential-1",+ );+ truncated.response.authenticator_data.truncate(32);+ let mut garbled_client_data = assertion(+ whatsapp_client_data(),+ "whatsapp.com",+ verified,+ b"credential-1",+ );+ garbled_client_data.response.client_data_json = b"{".to_vec();++ for credential in [+ assertion(other_origin, "whatsapp.com", verified, b"credential-1"),+ assertion(other_challenge, "whatsapp.com", verified, b"credential-1"),+ assertion(registration, "whatsapp.com", verified, b"credential-1"),+ assertion(+ whatsapp_client_data(),+ "evil.example",+ verified,+ b"credential-1",+ ),+ assertion(+ whatsapp_client_data(),+ "whatsapp.com",+ verified,+ b"credential-2",+ ),+ truncated,+ garbled_client_data,+ ] {+ assert_eq!(+ verify_assertion(&options, &credential),+ Err(AuthenticationError::Unavailable),+ "{credential:?}"+ );+ }+}diff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.jsonindex 8236aef80c..c193de6350 100644--- a/apps/web/tauri/src-tauri/tauri.android.conf.json+++ b/apps/web/tauri/src-tauri/tauri.android.conf.json@@ -2,7 +2,7 @@"version": "2.5.0","bundle": {"android": {- "versionCode": 18+ "versionCode": 19}},"$schema": "https://schema.tauri.app/config/2",diff --git a/apps/web/tauri/src-tauri/tauri.ios.conf.json b/apps/web/tauri/src-tauri/tauri.ios.conf.jsonindex 9ff87160fe..428d028a01 100644--- a/apps/web/tauri/src-tauri/tauri.ios.conf.json+++ b/apps/web/tauri/src-tauri/tauri.ios.conf.json@@ -3,7 +3,7 @@"version": "2.0.11","bundle": {"iOS": {- "bundleVersion": "190"+ "bundleVersion": "191"}}}diff --git a/apps/web/tests/functional/whatsapp-linked.spec.ts b/apps/web/tests/functional/whatsapp-linked.spec.tsnew file mode 100644index 0000000000..91deac7d53--- /dev/null+++ b/apps/web/tests/functional/whatsapp-linked.spec.ts@@ -0,0 +1,667 @@+import { join } from 'node:path';+import { expect, type Page, test } from '@playwright/test';++const USER_ID = 'macro|[email protected]';++type Group = {+ jid: string;+ name: string;+ members: number;+ group: { id: string; name: string } | null;+};++/** Server state the mocked DSS `/meta/linked` routes answer from. */+type LinkedServer = {+ account: null | {+ id: string;+ user_id: string;+ authorization_generation: number;+ identity_jid: string | null;+ state: string;+ };+ pairingState: string;+ groups: Group[];+ requests: string[];+ adoptions: unknown[];+ passkeyAnswers: unknown[];+ canSend: boolean;+ sharedViewer: boolean;+ outgoing: unknown[];+ grants: { userId: string; accessLevel: string }[];+ permissionUpdates: unknown[];+ readMessages: string[];+};++function server(): LinkedServer {+ return {+ account: null,+ pairingState: 'qr',+ groups: [+ {+ jid: '[email protected]',+ name: 'Design Crit',+ members: 14,+ group: { id: GROUP_ID, name: 'design-crit' },+ },+ {+ jid: '[email protected]',+ name: 'Launch War Room',+ members: 23,+ group: null,+ },+ ],+ requests: [],+ adoptions: [],+ passkeyAnswers: [],+ canSend: true,+ sharedViewer: false,+ outgoing: [],+ grants: [],+ permissionUpdates: [],+ readMessages: [],+ };+}++const GROUP_ID = '019a061e-0000-7000-8000-000000000001';+const incomingMessage = {+ id: 'message-1',+ sender: { name: 'Ana Ruiz', user_id: null },+ body: 'The updated designs are ready for review.',+ sent_at: '2026-10-21T10:00:00Z',+ edited_at: null,+ deleted: false,+ reply_to: null,+ reactions: [{ emoji: '👍', count: 2, mine: false }],+ attachments: [+ {+ ordinal: 0,+ state: 'loading',+ file_name: 'design.pdf',+ document_id: null,+ },+ ],+ delivery_state: null,+};++/** Real client, queries and production adapter; the network is mocked here. */+async function mount(page: Page, state: LinkedServer, query = '') {+ const origin = test.info().project.use.baseURL;+ const unexpected: string[] = [];+ page.on('pageerror', (error) => unexpected.push(error.message));+ await page.addInitScript(() => localStorage.setItem('macro:login', 'true'));+ await page.routeWebSocket('**', (socket) => socket.close());+ await page.route('**/*', async (route) => {+ const url = new URL(route.request().url());+ if (url.origin !== origin) return route.abort();+ if (url.pathname === '/auth/user/legacy_user_permissions')+ return route.fulfill({+ json: {+ userId: USER_ID,+ email: '[email protected]',+ permissions: [],+ tutorialComplete: true,+ },+ });+ if (url.pathname.startsWith('/auth/user/get_names'))+ return route.fulfill({+ json: {+ names: [+ {+ id: 'macro|[email protected]',+ first_name: 'Group',+ last_name: 'Owner',+ },+ { id: USER_ID, first_name: 'Me' },+ ],+ },+ });+ if (url.pathname === '/auth/user/profile_pictures')+ return route.fulfill({ json: { pictures: [] } });+ if (url.pathname === '/auth/team/user')+ return route.fulfill({+ json: [+ {+ id: 'team-acme',+ name: 'Acme Inc',+ slug: 'acme',+ owner_id: USER_ID,+ allow_non_admin_invites: true,+ crm_enabled: false,+ enterprise: false,+ },+ ],+ });+ if (url.pathname.endsWith('/email/links'))+ return route.fulfill({ json: { links: [] } });+ if (url.pathname === '/auth/team')+ return route.fulfill({+ json: {+ team: { id: 'team-acme', name: 'Acme Inc', owner_id: USER_ID },+ members: [],+ },+ });+ if (url.pathname.startsWith(`/dss/entities/whatsapp_group/${GROUP_ID}`)) {+ if (url.pathname.includes('/direct-access/')) {+ state.grants.push({+ userId: decodeURIComponent(url.pathname.split('/').at(-1) ?? ''),+ accessLevel: route.request().postDataJSON().accessLevel,+ });+ return route.fulfill({ status: 204 });+ }+ if (url.pathname.endsWith('/direct-access'))+ return route.fulfill({ json: state.grants });+ return route.fulfill({+ json: {+ owner: state.sharedViewer ? 'macro|[email protected]' : USER_ID,+ canReview: !state.sharedViewer,+ accessLevel: state.sharedViewer ? 'view' : 'owner',+ supportedLevels: ['view'],+ requests: [],+ pendingCount: 0,+ mine: null,+ nextOffset: null,+ },+ });+ }+ if (url.pathname.startsWith('/dss/meta/linked/')) {+ const path = url.pathname.slice('/dss/meta/linked/'.length);+ const method = route.request().method();+ state.requests.push(`${method} ${path}`);+ if (path.startsWith(`whatsapp-groups/${GROUP_ID}`)) {+ const suffix = path.slice(`whatsapp-groups/${GROUP_ID}`.length);+ if (!suffix)+ return route.fulfill({+ json: {+ id: GROUP_ID,+ name: 'Design Crit',+ user_id: state.sharedViewer+ ? 'macro|[email protected]'+ : USER_ID,+ access_level: state.sharedViewer ? 'view' : 'owner',+ can_send: state.canSend,+ send_reason: state.canSend ? null : 'no_account',+ sending_identity: state.canSend+ ? '[email protected]'+ : null,+ unread_count: 1,+ roster: {+ participants: [+ {+ jid: '[email protected]',+ displayName: 'Ana Ruiz',+ admin: true,+ },+ ],+ },+ limits: {+ text_limit_bytes: 65536,+ attachment_limit_bytes: 33554432,+ mutation_window_seconds: 900,+ max_attachments: 1,+ mutations: ['reaction', 'edit', 'delete'],+ attachment_types: ['image/png', 'application/pdf', 'audio/ogg'],+ },+ },+ });+ if (suffix === '/messages')+ return route.fulfill({+ json: {+ next_cursor: url.searchParams.has('before')+ ? null+ : 'older-cursor',+ messages: url.searchParams.has('before')+ ? [+ {+ ...incomingMessage,+ id: 'message-0',+ body: 'Previous day discussion',+ sent_at: '2026-10-20T10:00:00Z',+ attachments: [],+ },+ ]+ : [+ incomingMessage,+ {+ ...incomingMessage,+ id: 'message-2',+ body: 'Looking now. Thanks, Ana!',+ sender: { name: 'Me', user_id: USER_ID },+ sent_at: new Date().toISOString(),+ reply_to: 'message-1',+ reactions: [],+ attachments: [],+ delivery_state: 'delivered',+ },+ ],+ },+ });+ 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());+ return route.fulfill({+ json: { id: 'new-send', state: 'pending', message_id: null },+ });+ }+ if (suffix === '/read') {+ state.readMessages.push(route.request().postDataJSON().message_id);+ return route.fulfill({ json: {} });+ }+ if (suffix === '/attachments')+ return route.fulfill({+ json: {+ upload_id: 'upload-1',+ filename: 'design.pdf',+ kind: 'document',+ },+ });+ if (suffix === '/permissions' && method === 'PATCH') {+ state.permissionUpdates.push(route.request().postDataJSON());+ return route.fulfill({ status: 204 });+ }+ if (suffix === '/permissions')+ return route.fulfill({+ json: {+ id: 'permissions-1',+ channelSharePermissions: [],+ linkShare: null,+ linkShareAccessLevel: null,+ teamShareAccessLevel: null,+ },+ });+ }+ if (url.pathname.startsWith(`/dss/entities/whatsapp_group/${GROUP_ID}`))+ return route.fulfill({ json: {} });+ if (path === 'configuration')+ return route.fulfill({+ json: { pairing: true, adoption: true, sending: true },+ });+ if (path === 'whatsapp-groups')+ return route.fulfill({+ json: state.groups+ .filter((item) => item.group)+ .map((item) => ({+ id: item.group?.id,+ name: item.group?.name,+ unread_count: 2,+ })),+ });+ if (path === 'account')+ return route.fulfill({ json: { account: state.account } });+ if (path === 'connect')+ return route.fulfill({+ json: {+ id: 'pairing-1',+ account_id: 'account-1',+ expires_at: new Date(Date.now() + 60_000).toISOString(),+ state: 'waiting',+ },+ });+ if (path === 'pairing/pairing-1' && method === 'DELETE')+ return route.fulfill({ status: 204 });+ if (path === 'pairing/pairing-1/passkey') {+ state.passkeyAnswers.push(route.request().postDataJSON());+ return route.fulfill({ status: 204 });+ }+ if (path === 'pairing/pairing-1') {+ if (state.pairingState === 'success')+ state.account = {+ id: 'account-1',+ user_id: USER_ID,+ authorization_generation: 4,+ identity_jid: '14155550142:[email protected]',+ state: 'connected',+ };+ return route.fulfill({+ headers: { 'Cache-Control': 'no-store' },+ json: {+ state: state.pairingState,+ qr: state.pairingState === 'qr' ? '2@ref,noise,identity,adv' : null,+ challenge:+ state.pairingState === 'passkey'+ ? { challenge: 'Y2hhbGxlbmdl', rpId: 'whatsapp.com' }+ : null,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ },+ });+ }+ if (path === 'groups' && method === 'GET')+ return route.fulfill({+ json: state.groups.map((group) => ({+ jid: group.jid,+ name: group.name,+ announce: false,+ community: false,+ disappearing: false,+ observedAt: '2026-10-20T12:00:00Z',+ group: group.group,+ participants: Array.from({ length: group.members }, (_, i) => ({+ jid: `1415555${String(i).padStart(4, '0')}@s.whatsapp.net`,+ admin: i === 0,+ })),+ })),+ });+ if (path === 'groups/adopt' && method === 'POST') {+ const body = route.request().postDataJSON() as {+ group_jid: string;+ name: string;+ };+ state.adoptions.push(body);+ const group = state.groups.find(({ jid }) => jid === body.group_jid);+ if (group) group.group = { id: 'group-new', name: body.name };+ return route.fulfill({+ json: {+ 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',+ state: 'active',+ },+ });+ }+ if (path === 'disconnect') {+ state.account = null;+ return route.fulfill({ json: { remote_unlink_requested: true } });+ }+ return route.fulfill({ status: 404, json: {} });+ }+ if (/^\/(auth|dss|notification|connection-gateway)\//.test(url.pathname))+ return route.fulfill({ json: {} });+ return route.fulfill({ response: await route.fetch() });+ });+ await page.goto(+ `${origin}/tests/functional/whatsapp-linked/index.html${query}`+ );+ return unexpected;+}++test('links WhatsApp by QR, then adds a shareable WhatsApp group', async ({+ page,+}) => {+ const state = server();+ const unexpected = await mount(page, state);++ await expect(page.getByText(/unofficial WhatsApp client/)).toBeVisible();+ await page.getByRole('button', { name: 'Connect' }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).toHaveClass(/ph-no-capture/);+ await expect(+ dialog.getByRole('img', {+ name: 'Scan this code with WhatsApp on your phone',+ })+ ).toBeVisible();+ await expect(dialog.getByText(/Expires in \d:\d\d/)).toBeVisible();++ state.pairingState = 'success';+ await expect(page.getByText('+14155550142')).toBeVisible();+ 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]);++ 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(+ groups.getByRole('button', { name: 'In Macro → Launch War Room' })+ ).toBeVisible();+ expect(state.adoptions).toEqual([+ {+ group_jid: '[email protected]',+ name: 'Launch War Room',+ },+ ]);+ expect(unexpected).toEqual([]);+});++test('cancelling a pairing tells the server and keeps the account unlinked', async ({+ page,+}) => {+ const state = server();+ await mount(page, state);++ await page.getByRole('button', { name: 'Connect' }).click();+ await expect(page.getByRole('img', { name: /Scan this code/ })).toBeVisible();+ await page+ .getByRole('dialog')+ .getByRole('button', { name: 'Cancel' })+ .click();+ await expect(page.getByRole('dialog')).toBeHidden();+ await expect.poll(() => state.requests).toContain('DELETE pairing/pairing-1');+ await expect(page.getByRole('button', { name: 'Connect' })).toBeVisible();+});++test('an expired pairing offers a new code', async ({ page }) => {+ const state = server();+ state.pairingState = 'expired';+ await mount(page, state);++ await page.getByRole('button', { name: 'Connect' }).click();+ await expect(+ page.getByText('This code expired before it was scanned.')+ ).toBeVisible();+ state.pairingState = 'qr';+ await page.getByRole('button', { name: 'Show a new code' }).click();+ await expect(page.getByRole('img', { name: /Scan this code/ })).toBeVisible();+ expect(+ state.requests.filter((request) => request === 'POST connect')+ ).toHaveLength(2);+});++test('a browser hands WhatsApp’s passkey step to Macro desktop by pairing id', async ({+ page,+}) => {+ const state = server();+ state.pairingState = 'passkey';+ await mount(page, state);++ await page.getByRole('button', { name: 'Connect' }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog.getByText('Confirm on your desktop')).toBeVisible();+ await expect(+ dialog.getByRole('link', { name: 'Continue in Macro desktop' })+ ).toHaveAttribute('href', 'macro:///external?whatsappPairing=pairing-1');+ expect(state.passkeyAnswers).toEqual([]);+});++test('Macro desktop shows its authenticator’s QR while the phone confirms', async ({+ page,+}) => {+ const state = server();+ state.pairingState = 'passkey';+ await mount(page, state, '?passkey=native');++ await page.getByRole('button', { name: 'Connect' }).click();+ const dialog = page.getByRole('dialog');+ await dialog.getByRole('button', { name: 'Confirm with passkey' }).click();+ await expect(+ dialog.getByRole('img', {+ name: "Scan this code with your phone's camera to confirm",+ })+ ).toBeVisible();+ await expect(+ dialog.getByRole('button', { name: 'Waiting for your phone…' })+ ).toBeDisabled();+});++test('an independent group reads, replies, reacts and pages without channel requests', async ({+ page,+}) => {+ const state = server();+ const unexpected = await mount(page, state, `?group=${GROUP_ID}`);+ await expect(+ page.getByRole('heading', { name: 'Design Crit' })+ ).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.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 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();+ await expect.poll(() => state.outgoing.length).toBe(2);+ expect(state.outgoing[1]).toMatchObject({+ message: {+ type: 'mutation',+ operation: 'reaction',+ message_id: 'message-1',+ text: '👍',+ },+ });+ await page.getByRole('button', { name: 'Load earlier messages' }).click();+ await expect(page.getByText('Previous day discussion')).toBeVisible();+ expect(state.requests.some((request) => request.includes('channels/'))).toBe(+ false+ );+ expect(unexpected).toEqual([]);+});++test('a shared viewer can read without connecting WhatsApp', async ({+ page,+}) => {+ const state = server();+ state.canSend = false;+ const unexpected = await mount(page, state, `?group=${GROUP_ID}`);+ await expect(+ page.getByText('The updated designs are ready for review.', { exact: true })+ ).toBeVisible();+ await expect(page.getByText('Connect your WhatsApp to reply')).toBeVisible();+ await expect(page.getByRole('textbox')).toHaveCount(0);+ await expect(+ page.getByRole('button', { name: 'Edit', exact: true })+ ).toHaveCount(0);+ expect(state.outgoing).toEqual([]);+ expect(unexpected).toEqual([]);+});++for (const mobile of [false, true]) {+ test.describe(`${mobile ? 'mobile' : 'desktop'} group`, () => {+ test.use({+ viewport: mobile+ ? { width: 390, height: 844 }+ : { width: 1440, height: 900 },+ isMobile: mobile,+ hasTouch: mobile,+ });+ for (const dark of [false, true]) {+ test(`presentation ${dark ? 'dark' : 'light'}`, async ({ page }) => {+ await page.emulateMedia({ colorScheme: dark ? 'dark' : 'light' });+ const state = server();+ 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 })+ ).toBeVisible();+ expect(await page.evaluate(() => innerWidth)).toBe(mobile ? 390 : 1440);+ expect(+ await page.evaluate(+ () => document.documentElement.scrollWidth > innerWidth+ )+ ).toBe(false);+ expect(+ await page.evaluate(() => document.documentElement.dataset.themeLight)+ ).toBe(String(!dark));+ const name = `group-${mobile ? 'mobile' : 'desktop'}-${dark ? 'dark' : 'light'}.png`;+ await page.screenshot({+ path: process.env.WHATSAPP_SCREENSHOT_DIR+ ? join(process.env.WHATSAPP_SCREENSHOT_DIR, name)+ : test.info().outputPath(name),+ fullPage: true,+ });+ expect(unexpected).toEqual([]);+ });+ }+ });+}++test('opens the standard share dialog for the independent group entity', async ({+ page,+}) => {+ const state = server();+ state.canSend = false;+ state.sharedViewer = true;+ const unexpected = await mount(page, state, `?group=${GROUP_ID}`);+ await page.getByRole('button', { name: 'Share', exact: true }).click();+ await expect(page.getByRole('dialog')).toBeVisible();+ await expect(+ page.getByRole('dialog').getByText('Design Crit', { exact: true })+ ).toBeVisible();+ await expect(+ page+ .getByRole('dialog')+ .getByText(/Only the owner can share access to this WhatsApp group/)+ ).toBeVisible();+ await expect(+ page.getByRole('dialog').getByRole('button', { name: 'Copy Link' })+ ).toBeVisible();+ expect(state.requests).toContain(+ `GET whatsapp-groups/${GROUP_ID}/permissions`+ );+ expect(unexpected).toEqual([]);+});++test('the owner shares through direct people access without creating a channel', async ({+ page,+}) => {+ const state = server();+ const unexpected = await mount(page, state, `?group=${GROUP_ID}`);+ await page.getByRole('button', { name: 'Share', exact: true }).click();+ const dialog = page.getByRole('dialog');+ await expect(+ dialog.getByRole('textbox', { name: 'Macro email address' })+ ).toBeVisible();+ await dialog+ .getByRole('textbox', { name: 'Macro email address' })+ .fill('[email protected]');+ await dialog.getByRole('button', { name: 'Add person' }).click();+ await expect+ .poll(() => state.grants)+ .toEqual([{ userId: 'macro|[email protected]', accessLevel: 'view' }]);+ await expect(dialog.getByText('View access added.')).toBeVisible();+ expect(state.permissionUpdates).toEqual([]);+ expect(state.requests.some((request) => request.includes('/channels/'))).toBe(+ false+ );+ expect(unexpected).toEqual([]);+});diff --git a/apps/web/tests/functional/whatsapp-linked/fixture.tsx b/apps/web/tests/functional/whatsapp-linked/fixture.tsxnew file mode 100644index 0000000000..9c89774e49--- /dev/null+++ b/apps/web/tests/functional/whatsapp-linked/fixture.tsx@@ -0,0 +1,148 @@+import { EmailLinksContextProvider } from '@core/context/emailLinks';+import { ImperativeDialogHost } from '@ui';+import '@fontsource-variable/inter';+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';+import { WhatsAppGroupView } from '@app/features/whatsapp-group/views/whatsapp-group-view';+import { getPermissions } from '@core/component/SharePermissions';+import { useShareModal } from '@core/component/TopBar/shareModal';+import { useUserId } from '@core/context/user';+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';+// The app's styles, so the page and its screenshots look like the app.+import '../../../src/index.css';+import {+ type PasskeyCapability,+ WhatsAppLinkedProvider,+} from '@app/features/whatsapp-linked/context/whatsapp-linked-context';+import { createWhatsAppLinkedCapabilities } from '@app/features/whatsapp-linked/queries/production-capabilities';+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 { UserContextProvider } from '@core/context/user';+import { queryClient } from '@queries/client';+import { QueryClientProvider } from '@tanstack/solid-query';+import { ResultAsync } from 'neverthrow';+import { render } from 'solid-js/web';++declare global {+ interface Window {+ openedGroups: string[];+ }+}+window.openedGroups = [];++/** The production adapter and real queries; only the network is the test's. */+/**+ * `?passkey=native` stands in for Macro desktop's authenticator, which a+ * browser can't run: it shows the caBLE QR event and waits for the phone.+ */+const nativePasskey: PasskeyCapability = {+ kind: 'native',+ authenticate: (_pairingId, _challenge, onEvent) => {+ onEvent({ type: 'qr', value: 'FIDO:/5103963548272401838013624816' });+ return new ResultAsync(new Promise(() => {}));+ },+};++function GroupHarness(props: { groupId: string }) {+ const userId = useUserId();+ const source = createWhatsAppGroupCapabilities(+ whatsappGroupApi,+ () => userId() ?? '',+ () => props.groupId+ );+ const share = useShareModal(() => {+ const group = source.group.data;+ if (!group) return;+ return {+ id: group.id,+ itemType: 'whatsapp_group',+ blockAlias: 'whatsapp_group',+ name: group.name,+ owner: group.ownerId,+ userPermissions: getPermissions(group.accessLevel),+ };+ });+ return (+ <div class="h-dvh">+ <WhatsAppGroupProvider value={source}>+ <WhatsAppGroupView+ userId={userId()}+ onShare={share}+ onConnect={() => {+ location.search = '';+ }}+ renderAttachment={(id) => <span>Document {id}</span>}+ />+ </WhatsAppGroupProvider>+ </div>+ );+}++function Page() {+ onMount(() => {+ const dark = matchMedia('(prefers-color-scheme: dark)').matches;+ for (const [key, token] of Object.entries(+ themeCssVars(dark ? macroDarkTheme : macroLightTheme)+ ))+ document.documentElement.style.setProperty(key, token);+ document.documentElement.style.colorScheme = dark ? 'dark' : 'light';+ document.documentElement.dataset.themeLight = String(!dark);+ });+ const groupId = new URLSearchParams(location.search).get('group');+ if (groupId)+ return (+ <Suspense fallback={<p>Loading group…</p>}>+ <GroupHarness groupId={groupId} />+ </Suspense>+ );+ const production = createWhatsAppLinkedCapabilities({+ openGroup: (groupId) => window.openedGroups.push(groupId),+ });+ const capabilities =+ new URLSearchParams(location.search).get('passkey') === 'native'+ ? { ...production, passkey: nativePasskey }+ : production;+ return (+ <WhatsAppLinkedProvider value={capabilities}>+ <main class="min-h-screen bg-panel p-4 text-ink">+ <WhatsAppPage />+ </main>+ </WhatsAppLinkedProvider>+ );+}++const root = document.getElementById('root');+if (!root) throw new Error('missing #root');+render(+ () => (+ <AnalyticsContextProvider>+ <PosthogProvider>+ <QueryClientProvider client={queryClient}>+ <UserContextProvider>+ <Suspense fallback={<p>Loading identity…</p>}>+ <EmailLinksContextProvider>+ <Router+ root={(props) => (+ <>+ {props.children}+ <ImperativeDialogHost />+ </>+ )}+ >+ <Route path="*" component={Page} />+ </Router>+ </EmailLinksContextProvider>+ </Suspense>+ </UserContextProvider>+ </QueryClientProvider>+ </PosthogProvider>+ </AnalyticsContextProvider>+ ),+ root+);diff --git a/apps/web/tests/functional/whatsapp-linked/index.html b/apps/web/tests/functional/whatsapp-linked/index.htmlnew file mode 100644index 0000000000..5ca12012ce--- /dev/null+++ b/apps/web/tests/functional/whatsapp-linked/index.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>WhatsApp linked devices functional tests</title></head>+ <body><div id="root"></div><script type="module" src="./fixture.tsx"></script></body>+</html>diff --git a/bun.lock b/bun.lockindex b6dbdbc3e5..cf9ddbf276 100644--- a/bun.lock+++ b/bun.lock@@ -166,6 +166,7 @@"tailwindcss": "^4.2.4","ts-pattern": "^5.9.0","unicode-emoji-json": "^0.8.0",+ "uqr": "0.1.3","uuid": "^10.0.0","virtua": "0.48.8","vite-plugin-wasm": "^3.5.0",@@ -3751,6 +3752,8 @@"update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],+ "uqr": ["[email protected]", "", {}, "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA=="],+"uri-js": ["[email protected]", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],"urijs": ["[email protected]", "", {}, "sha512-HXgFDgDommxn5/bIv0cnQZsPhHDA90NPHD6+c/v21U5+Sx5hoP8+dP9IZXBU1gIfvdRfhG8cel9QNPeionfcCQ=="],diff --git a/docs/agent-guide/README.md b/docs/agent-guide/README.mdindex ca06c1e37c..d74d0e998b 100644--- a/docs/agent-guide/README.md+++ b/docs/agent-guide/README.md@@ -26,6 +26,7 @@ verified live against a local stack (`just run_local`).| [pull-requests.md](pull-requests.md) | Pull request review || [activity.md](activity.md) | Activity || [notifications.md](notifications.md) | Notifications |+| [external.md](external.md) | External tab: linking WhatsApp by QR, adopting and sharing standalone groups, mocking `/meta/linked` || [settings.md](settings.md) | Settings sections, including Slack import and team membership || [onboarding.md](onboarding.md) | Onboarding resume links, bypass, and setup plan || [setup-cards.md](setup-cards.md) | Sidebar import and setup cards, the connector import dialog, and permanent dismissal |diff --git a/docs/agent-guide/external.md b/docs/agent-guide/external.mdnew file mode 100644index 0000000000..2382949677--- /dev/null+++ b/docs/agent-guide/external.md@@ -0,0 +1,72 @@+# External (linked WhatsApp)++`/app/external` lists outside messaging accounts a person links into Macro.+WhatsApp is the only entry. The view, its rail button, its More-views entry on+mobile and the `g x` shortcut exist only with the `enable-whatsapp-linked`+flag; a deep link with the flag off goes to Home once the flag resolves. Turn+it on locally with `VITE_ENABLE_WHATSAPP_LINKED=true`.++## Where it is++- Desktop: the **External** plug button on the sidebar rail (shown by default,+ 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.++## WhatsApp page states++| State | What shows |+| --- | --- |+| 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. |++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+Macro under Linked devices on their phone.++## Driving it without a WhatsApp backend++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+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`.+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.++The timeline pages newest-first from+`GET /meta/linked/whatsapp-groups/<id>/messages`, including verified sender names,+replies, grouped reactions, edit/delete flags, attachment states, and delivery+for the caller's own sends. Entering the view marks messages read through `/read`.+Ready attachments open their imported document; other states show loading,+unavailable or unsupported. The layout supports phone-width panes.++The composer shows the caller's own sending phone or the reason replies are+unavailable. Sending requires view access, the caller's own connected account,+and current membership that permits posting. A shared second member can send+from their number without owning or re-adopting the group. Text/media/replies,+reactions, and edits/deletes of the caller's own recent messages use+`POST /meta/linked/whatsapp-groups/<id>/sends`; files stage through `/attachments`.+The detail's `limits` supplies allowed MIME types, bytes and the edit window.+The owner may stop syncing with `DELETE` on the group; history remains readable.++Pending and uncertain sends are read from `GET .../sends`. An `unknown` outcome+may already have arrived and must never be resent automatically. Requests are+limited to one per second per user across groups; HTTP 429 carries+`Retry-After: 1`. Retain an intent key when retrying the same request.++Mock only `/meta/linked/*` for functional verification; never link a real account.+Soup/search integration is deferred.diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex b42907fbdc..913397a6de 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -158,6 +158,7 @@ successfully rather than hashing the empty JavaScript placeholder.| `/app/activity` | Activity heatmap + feed || `/app/calendar/<month-or-week-or-day>` | Calendar; the focused event, its occurrence, and the locator range use `sN.calendar.*` || `/app/scheduling` | Scheduling workspace: booking links, availability, bookings, insights, and booking page |+| `/app/external` | External: link a personal WhatsApp account and adopt independently shared WhatsApp groups (requires the `enable-whatsapp-linked` flag; see [External](external.md)) || `/app/<document-type>/<uuid>` | Legacy document URL (including `md`, `pdf`, `canvas`, `spreadsheet`, and the other Drive document types); redirects to `/app/drive/<document-type>/<uuid>` || `/app/database/<uuid>` | A database with table and board views (requires the Databases flag). Links and opens outside Drive stay at this URL; opened from Drive, it shows inline at `/app/drive/database/<uuid>` || `/app/documents`, `/app/files` | Legacy Files views; redirect to `/app/drive` |@@ -401,6 +402,8 @@ Showing Scheduling removes its duplicate from More; the choice survives reload.Activity appears in Customize sidebar only when the `enable-activity-feed` flagis on and, like Scheduling, starts hidden in More (also for existing preferences)until enabled on the rail.+External (plug icon, `g x`) appears on the rail only with the+`enable-whatsapp-linked` flag; it starts shown and can be hidden like other apps.- Top: buttons `Create` and `Search`. Clicking `Search` opens a menuwith `Command Menu` (⌘K on Mac / Ctrl+K elsewhere) and `Search everything`@@ -646,7 +649,8 @@ The inline `/app/debug/create-menu-demo` keeps all three layouts for comparisonwithout creating data. Mobile continues to use its create sheet.On mobile, the bottom dock defaults to Notifications, Calendar, Email, Channels,-Agents, Files, Tasks, Calls, CRM, Reviews, and Scheduling. Feature-gated views+Agents, Files, Tasks, Calls, CRM, Reviews, Scheduling,+and External. Feature-gated viewsappear only when enabled. The navigation island measures its width and fits asmany fixed-size app buttons as possible, reserving room for More. Search staysin its own island at the right edge and opens the persistent Search… input anddiff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.jsonindex c75ee5a1e7..16a701865c 100644--- a/nix-support/node_modules-hashes.json+++ b/nix-support/node_modules-hashes.json@@ -1,6 +1,6 @@{"nodeModules": {- "aarch64-darwin": "sha256-tNJC//qw4BonV/QtcKH7EWV/eAM7WyHlHxv3bmXcT/s=",- "x86_64-linux": "sha256-BelaxF0Nyjw8hD+Ko7vn3p9+kRom9xBA9WhlAA15ocs="+ "aarch64-darwin": "sha256-2kDPUYDJR2XAjg2Nqvq/2g25tiyf9KnFTlPFS2MbL28=",+ "x86_64-linux": "sha256-56UY+AcJzdWRd0vxnDbeL2UwZMwPkhQj+OckS4SjA/U="}}diff --git a/nix/tauri-desktop.nix b/nix/tauri-desktop.nixindex 3a95075e19..ca57ac2e17 100644--- a/nix/tauri-desktop.nix+++ b/nix/tauri-desktop.nix@@ -300,7 +300,20 @@tauriCargoVendorDir = craneLib.vendorCargoDeps {src = ../apps/web/tauri;cargoLock = ../apps/web/tauri/Cargo.lock;+ # The pinned fork lists an absent device-catalog README. Crane inspects+ # every workspace package while vendoring, including this unused one.+ overrideVendorGitCheckout = packages: drv:+ if lib.any (package: package.name == "webauthn-authenticator-rs") packages then+ drv.overrideAttrs (old: {+ postPatch = (old.postPatch or "") + ''+ cp README.md device-catalog/README.md+ '';+ })+ else+ drv;outputHashes = {+ "git+https://github.com/beeper/webauthn-rs?rev=579f9144d37161bedf25ed1236d73486ce303de6#579f9144d37161bedf25ed1236d73486ce303de6" =+ "sha256-0s6M8lB4EpY6FiUtRqsDXdrzqsfMxWkTBl/wVYvbV/I=";"git+https://github.com/macro-inc/tauri-plugins?rev=6ddd6600e20436388f169e936b610fe93944b7b0#6ddd6600e20436388f169e936b610fe93944b7b0" ="sha256-5ErLW2po5ZlTTuJjsCExwC//rHYcQo2tKXiyz3w/0kQ=";"git+https://github.com/macro-inc/plugins-workspace?rev=bc6ec3b8e80eed80ef4969f4463a357d46adb3b1#bc6ec3b8e80eed80ef4969f4463a357d46adb3b1" =