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
fix(ios): open channel notifications directly at their message (#8337)
gbirman5e396e36aa5e
diff --git a/.agents/rules/web/startup-bundle.md b/.agents/rules/web/startup-bundle.mdindex ec7ffe2924..80d416affc 100644--- a/.agents/rules/web/startup-bundle.md+++ b/.agents/rules/web/startup-bundle.md@@ -26,6 +26,9 @@ alwaysApply: falsebackground, the rail column, and the desktop app's content card — no appcontent. The first shell to mount dismisses it (`dismissBootShell`). Keep itsrail width and desktop inset in step with `SidebarRail` and `SplitLayout`.+- Read a supported iOS notification launch intent before mounting the router;+ keep startup payload validators in the generated compact push-schema entry+ rather than importing the full service schema bundle.- Do not register an asset-caching service worker. Keep `public/sw.js` at itsdeployed URL so existing workers can update, clear their shell and assetcaches, and unregister; it must not intercept requests.diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 4fee015c56..607021ba91 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -274,6 +274,29 @@ Follow [`docs/ios-releases.md`](docs/ios-releases.md) for App Store signing andprovisioning, including both extensions. The release script temporarily selectsmanual export when a distribution certificate path is supplied.+## Native notification navigation++Read iOS's durable pending tap before mounting the router, then choose its+destination only after the authenticated account matches `recipientId`. Keep+the native receipt pending until the destination route is applied; release the+resume cover for auth/retry UI without consuming the receipt. Use the existing+pending-notification intent for bootstrap and live taps so newer taps supersede+older work. Older native builds and pushes retain authenticated notification+lookup. The local bridge and native release requirement are documented in+[`docs/ios-releases.md`](docs/ios-releases.md).++Bound the pre-router bridge handoff to 1.5 seconds and release the native cover+on failure or timeout without consuming the pending tap. Late responses must+use normal account-checked navigation, never reset the mounted router's hash.+`notification.launch` records whether startup continued ready, failed, or timed out.++Generate APNs validators with `scripts/generate-api-schema.ts`; its compact+`generated/push.ts` entry avoids importing every notification-service schema+on the startup path. Carry known channel root IDs in push navigation (a null+`threadId` means the message itself is the root), prefetch the target window+alongside channel metadata, and keep the channel loading shell stable until+that target can be positioned.+## macOS notification activationCarry the notification ID through native delivery and the buffered `navigate`diff --git a/apps/web/docs/ios-releases.md b/apps/web/docs/ios-releases.mdindex c5b0158cb4..94799cfb36 100644--- a/apps/web/docs/ios-releases.md+++ b/apps/web/docs/ios-releases.md@@ -123,6 +123,24 @@ finish first (up to 25 minutes), and the release preconditions ignore it. For ato ship to the App Store, `just ios-bump --no-min` bumps the versions withoutraising the floor.+### Notification launch handoff compatibility++The local `tauri/ios_push_plugin` exposes+`window.__MACRO_IOS_NOTIFICATION_LAUNCH__` at document start. Web bundles use+the durable pending-intent, acknowledgment and native-cover commands only+when that capability exists; older iOS binaries keep their legacy push path.+New watchers pass `launchAware: true`. Older web bundles omit it, so the native+plugin delivers with the legacy contract and does not wait behind a cover for+an acknowledgment those bundles cannot send. This opt-in contract does not+require raising the OTA native floor; the improved cold-launch handoff still+requires shipping the new native binary.++Run `swift test --package-path tauri/ios_push_plugin/store` from `apps/web`+for persisted intent/acknowledgment regressions. A simulator build checks the+UIKit bridge; device verification must include notification launches after+termination/WebContent eviction and ordinary icon resume, as well as auth+failures, account switching, and rapid successive taps.+## What counts as native codeTwo things:diff --git a/apps/web/scripts/generate-api-schema.ts b/apps/web/scripts/generate-api-schema.tsindex 710b80e350..713a1bd41c 100644--- a/apps/web/scripts/generate-api-schema.ts+++ b/apps/web/scripts/generate-api-schema.ts@@ -175,6 +175,10 @@ const processService = async (await $`cd ${serviceClientsDir} && bun run orval --config orval.config.ts --project ${service.orvalKey}`;console.log(`[${service.name}] Orval finished (${elapsed(stepStart)})`);+ if (service.name === "notification-service") {+ await $`bun ${path.resolve(import.meta.dirname, "generate-push-schema.ts")}`;+ }+// Orval bug workaround: with input.filters, excluded schemas are not// generated, but the schemas barrel still re-exports them. Drop barrel// exports whose target file does not exist.diff --git a/apps/web/scripts/generate-push-schema.ts b/apps/web/scripts/generate-push-schema.tsnew file mode 100644index 0000000000..1474006d56--- /dev/null+++ b/apps/web/scripts/generate-push-schema.ts@@ -0,0 +1,57 @@+// Push data has no HTTP endpoint, so Orval only emits its TypeScript type.+// Generate runtime validators from the same Rust-owned OpenAPI components.+import $RefParser from '@apidevtools/json-schema-ref-parser';+import { jsonSchemaToZod } from 'json-schema-to-zod';+import { z } from 'zod';++const serviceDir = new URL(+ '../src/lib/service-clients/service-notification/',+ import.meta.url+);+const resolved = await $RefParser.dereference(+ await Bun.file(new URL('openapi.json', serviceDir)).json()+);+const { components } = z+ .object({+ components: z.object({+ schemas: z.record(z.string(), z.record(z.string(), z.unknown())),+ }),+ })+ .parse(resolved);++const validators = [+ ['PushNotificationNavigation', 'pushNotificationNavigation'],+ ['PushNotificationData', 'pushNotificationData'],+].map(([component, name]) => {+ const schema = components.schemas[component];+ if (!schema) throw new Error(`Missing push schema: ${component}`);+ return jsonSchemaToZod(schema, {+ module: 'esm',+ name,+ withoutDescribes: true,+ noImport: true,+ // Rust's Option<enum> is a oneOf(null, enum). Those branches are disjoint;+ // use a typed union instead of the converter's Zod 3-only oneOf refinement.+ parserOverride: (node) => {+ if (+ node.oneOf?.some(+ (branch) => typeof branch === 'object' && branch.type === 'null'+ )+ ) {+ return jsonSchemaToZod(+ { ...node, oneOf: undefined, anyOf: node.oneOf },+ { withoutDescribes: true }+ );+ }+ },+ });+});++await Bun.write(+ new URL('generated/push.ts', serviceDir),+ `/* Generated by scripts/generate-push-schema.ts. Do not edit manually. */+import { z } from 'zod';++${validators.join('\n\n')}+`+);diff --git a/apps/web/src/components/app/AppProviders.tsx b/apps/web/src/components/app/AppProviders.tsxindex c48619bdb9..0e79096bb0 100644--- a/apps/web/src/components/app/AppProviders.tsx+++ b/apps/web/src/components/app/AppProviders.tsx@@ -12,7 +12,7 @@ import { useReactiveFavicon } from '@components/app/useReactiveFavicon';import { useGlobalAttachableHistory } from '@core/component/AI/signal/globalAttachments';import { toast } from '@core/component/Toast/Toast';import { TeamContextProvider } from '@core/context/team';-import { useIsAuthenticated, useUserId } from '@core/context/user';+import { useIsAuthenticated, useUserId, useUserInfo } from '@core/context/user';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { createBlockOrchestrator } from '@core/orchestrator';import { fireAndForget } from '@core/util/fireAndForget';@@ -80,7 +80,11 @@ function ConfiguredGlobalAppStateProvider(props: ParentProps) {useReactiveFavicon(notificationSource);const blockOrchestrator = createBlockOrchestrator();- usePendingNotificationNavigationEffect(notificationSource);+ const userInfo = useUserInfo();+ usePendingNotificationNavigationEffect(+ notificationSource,+ () => userInfo()?.userId+ );return (<GlobalAppStateProviderdiff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsxindex 2a46054b7c..8c55d2338f 100644--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx@@ -21,6 +21,7 @@ import { getCallJoinTab } from '@channel/Call/call-tabs';import { useCall } from '@channel/Call/use-call';import { ChannelCallsTab } from '@channel/Calls/ChannelCallsTab';import type { MessageTimelineStateSnapshot } from '@channel/Channel/Channel';+import { ChannelLoading } from '@channel/Channel/ChannelLoading';import {ChannelMessages,ChannelSurface,@@ -562,9 +563,11 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {<div class="flex min-h-0 flex-1 flex-col" data-channel-tab-content><Switch><Match when={activeTab() === 'messages'}>- <ChannelMessages- autofocus={canAutofocusSplitContent && !navigatedFromJK()}- />+ <Suspense fallback={<ChannelLoading />}>+ <ChannelMessages+ autofocus={canAutofocusSplitContent && !navigatedFromJK()}+ />+ </Suspense></Match><Match when={activeTab() === 'attachments'}><ChannelAttachmentsTab channelId={channelId} />diff --git a/apps/web/src/features/block-channel/definition.ts b/apps/web/src/features/block-channel/definition.tsindex 9adc1f419c..33d2c5f251 100644--- a/apps/web/src/features/block-channel/definition.ts+++ b/apps/web/src/features/block-channel/definition.ts@@ -1,3 +1,4 @@+import { ChannelLoading } from '@channel/Channel/ChannelLoading';import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';import { ok } from 'neverthrow';import { lazy } from 'solid-js';@@ -5,6 +6,7 @@ import { lazy } from 'solid-js';export const definition = defineBlock({name: 'channel',description: '',+ loading: ChannelLoading,component: lazy(async () => ({default: (await import('./component/NewChannelBlockAdapter')).NewChannelBlockAdapter,diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsxindex b8e10c1664..1fe582cf3e 100644--- a/apps/web/src/features/channel/Channel/Channel.tsx+++ b/apps/web/src/features/channel/Channel/Channel.tsx@@ -115,6 +115,7 @@ import { CHANNEL_TOUR } from '../tour';import { isUnifiedInputMode } from '../unified-input-mode';import { ActiveCallMessage } from './ActiveCallMessage';import { ChannelDropZone } from './ChannelDropZone';+import { ChannelLoading } from './ChannelLoading';import { createChannelDragState } from './create-channel-drag-state';import { createChannelFindBar } from './create-channel-find-bar';import { createChannelHotkeys } from './create-channel-hotkeys';@@ -726,10 +727,11 @@ export function Channel(props: ChannelProps) {><EntityLoadGateresult={messagesLoadResult}+ loadingFallback={<ChannelLoading />}loadErrorTitle="Unable to load this channel"onRetry={() => fireAndForget(messagesQuery.refetch(), 'channel')}>- <DebugSuspense name="Channel.root">+ <DebugSuspense name="Channel.root" fallback={<ChannelLoading />}><deleteConfirmation.ConfirmationDialog /><StaticMarkdownContext host="channel"><SearchHighlightTermsProviderdiff --git a/apps/web/src/features/channel/Channel/ChannelDetail.tsx b/apps/web/src/features/channel/Channel/ChannelDetail.tsxindex 27276ba92e..514b8c7f7a 100644--- a/apps/web/src/features/channel/Channel/ChannelDetail.tsx+++ b/apps/web/src/features/channel/Channel/ChannelDetail.tsx@@ -49,6 +49,7 @@ import {Show,Switch,} from 'solid-js';+import { ChannelLoading } from './ChannelLoading';import {ChannelMessages,ChannelSurface,@@ -415,7 +416,10 @@ function ChannelDetailContent(props: ChannelDetailProps) {><Switch><Match when={activeTab() === 'messages'}>- <DebugSuspense name="ChannelDetail.messages">+ <DebugSuspense+ name="ChannelDetail.messages"+ fallback={<ChannelLoading />}+ ><ChannelMessages autofocus={props.autofocus ?? false} /></DebugSuspense></Match>diff --git a/apps/web/src/features/channel/Channel/ChannelLoading.tsx b/apps/web/src/features/channel/Channel/ChannelLoading.tsxnew file mode 100644index 0000000000..c4a0aaa927--- /dev/null+++ b/apps/web/src/features/channel/Channel/ChannelLoading.tsx@@ -0,0 +1,34 @@+import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';+import { For } from 'solid-js';++/** One conversation-shaped placeholder for target resolution and message loading. */+export function ChannelLoading() {+ return (+ <div+ role="status"+ aria-label="Loading conversation"+ class="flex min-h-0 flex-1 flex-col justify-center overflow-hidden px-5 py-6 touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)"+ >+ <span class="sr-only">Loading conversation</span>+ <div+ aria-hidden="true"+ class="mx-auto flex w-full max-w-160 flex-col gap-7"+ >+ <For each={[64, 86, 73]}>+ {(width) => (+ <div class="flex gap-3">+ <ListSkeleton.Bar class="size-7 shrink-0 rounded-full" />+ <div class="flex min-w-0 flex-1 flex-col gap-3">+ <ListSkeleton.Bar class="w-24" />+ <div style={{ width: `${width}%` }}>+ <ListSkeleton.Bar class="w-full" />+ </div>+ <ListSkeleton.Bar class="w-2/5" />+ </div>+ </div>+ )}+ </For>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/channel/Channel/ChannelSurface.tsx b/apps/web/src/features/channel/Channel/ChannelSurface.tsxindex 3407b74b51..ac5e1605c6 100644--- a/apps/web/src/features/channel/Channel/ChannelSurface.tsx+++ b/apps/web/src/features/channel/Channel/ChannelSurface.tsx@@ -1,4 +1,5 @@import { fireAndForget } from '@core/util/fireAndForget';+import { catchToResult } from '@core/util/result';import {fetchResolvedChannelMessage,findThreadIdInMessageTimeline,@@ -10,10 +11,12 @@ import {createComputed,createContext,createEffect,+ createMemo,createSignal,on,onCleanup,type ParentProps,+ Show,untrack,useContext,} from 'solid-js';@@ -22,6 +25,7 @@ import {type ChannelHandle,type MessageTimelineStateSnapshot,} from './Channel';+import { ChannelLoading } from './ChannelLoading';/*** A navigation intent for a channel. Hosts own this as state and pass it@@ -59,6 +63,7 @@ export type ChannelSurfaceProps = {type ChannelSurfaceContextValue = {channelId: Accessor<string>;resolvedTarget: Accessor<ChannelResolvedTarget | undefined>;+ isTargetResolving: Accessor<boolean>;};type ChannelSurfaceInternal = ChannelSurfaceContextValue & {@@ -133,6 +138,43 @@ function resolveSync(export function ChannelSurface(props: ParentProps<ChannelSurfaceProps>) {const [resolvedTarget, setResolvedTarget] =createSignal<ChannelResolvedTarget>();+ let disposed = false;+ onCleanup(() => {+ disposed = true;+ });++ async function resolveTarget(+ channelId: string,+ request: Extract<ChannelTargetRequest, { kind: 'message' }>+ ) {+ const result = await catchToResult(() =>+ fetchResolvedChannelMessage(+ { type: 'channel', id: channelId },+ request.messageId+ )+ );+ if (+ disposed ||+ props.channelId !== channelId ||+ props.targetRequest !== request+ )+ return;+ const resolved = result.isOk() ? result.value : undefined;+ setResolvedTarget(+ resolved?.kind === 'thread_reply'+ ? {+ kind: 'message',+ request,+ targetMessageId: resolved.thread_id,+ targetMessageReplyId: request.messageId,+ }+ : {+ kind: 'message',+ request,+ targetMessageId: request.messageId,+ }+ );+ }// Resolution runs once per request (not as a derived memo) so the resolved// object stays identity-stable while cache contents shift underneath, and@@ -153,30 +195,7 @@ export function ChannelSurface(props: ParentProps<ChannelSurfaceProps>) {}setResolvedTarget(undefined);if (request.kind !== 'message') return;- fireAndForget(- (async () => {- const resolved = await fetchResolvedChannelMessage(- { type: 'channel', id: channelId },- request.messageId- ).catch(() => undefined);- if (props.targetRequest !== request) return;- setResolvedTarget(- resolved?.kind === 'thread_reply'- ? {- kind: 'message',- request,- targetMessageId: resolved.thread_id,- targetMessageReplyId: request.messageId,- }- : {- kind: 'message',- request,- targetMessageId: request.messageId,- }- );- })(),- 'channel-surface'- );+ fireAndForget(resolveTarget(channelId, request), 'channel-surface');}));@@ -208,6 +227,8 @@ export function ChannelSurface(props: ParentProps<ChannelSurfaceProps>) {value={{channelId: () => props.channelId,resolvedTarget,+ isTargetResolving: () =>+ props.targetRequest?.kind === 'message' && !resolvedTarget(),// The messages part restores from here on every mount: the host's// initial state until the first cleanup stashes something fresher, so// leaving the messages pane and returning keeps scroll/thread/reply@@ -239,6 +260,21 @@ export type ChannelMessagesProps = {* restores the stashed timeline state instead.*/export function ChannelMessages(props: ChannelMessagesProps) {+ const surface = useChannelSurfaceInternal();+ // Wait only before the first timeline mounts. Later jumps keep the live+ // composer and scroll state while their destination is resolved.+ const canMount = createMemo(+ (mounted: boolean) => mounted || !surface.isTargetResolving(),+ false+ );+ return (+ <Show when={canMount()} fallback={<ChannelLoading />}>+ <MountedChannelMessages {...props} />+ </Show>+ );+}++function MountedChannelMessages(props: ChannelMessagesProps) {const surface = useChannelSurfaceInternal();const [handle, setHandle] = createSignal<ChannelHandle>();const mountTarget = untrack(surface.resolvedTarget);diff --git a/apps/web/src/features/channel/Channel/create-target-message-controller.ts b/apps/web/src/features/channel/Channel/create-target-message-controller.tsindex cc29f55143..76f9d244d8 100644--- a/apps/web/src/features/channel/Channel/create-target-message-controller.ts+++ b/apps/web/src/features/channel/Channel/create-target-message-controller.ts@@ -1,4 +1,5 @@import { createSolidMachine } from '@macro-inc/machine/solid';+import { markNotificationTargetVisible } from '@notifications/notification-open-trace';import { queryClient } from '@queries/client';import {getMessageTimelineQueryKey,@@ -117,10 +118,28 @@ export function createTargetMessageController(targetLoaded: untrack(() => options.messageKeys().includes(messageId)),ready: untrack(ready),}),- completePendingScroll: (messageId: string) =>- machine.dispatch({ t: 'root-scroll-done', messageId }),- completePendingReplyScroll: (messageId: string, replyId: string) =>- machine.dispatch({ t: 'reply-scroll-done', messageId, replyId }),+ completePendingScroll: (messageId: string) => {+ const before = state();+ machine.dispatch({ t: 'root-scroll-done', messageId });+ if (+ before.t === 'targeting' &&+ before.target.messageId === messageId &&+ !before.target.replyId &&+ state().t === 'flashing'+ )+ markNotificationTargetVisible(options.channelId(), messageId);+ },+ completePendingReplyScroll: (messageId: string, replyId: string) => {+ const before = state();+ machine.dispatch({ t: 'reply-scroll-done', messageId, replyId });+ if (+ before.t === 'targeting' &&+ before.target.messageId === messageId &&+ before.target.replyId === replyId &&+ state().t === 'flashing'+ )+ markNotificationTargetVisible(options.channelId(), replyId);+ },clearActiveTarget: (messageId: string) =>machine.dispatch({ t: 'release', messageId }),reset: () => machine.dispatch({ t: 'reset' }),diff --git a/apps/web/src/features/channel/Channel/tests/channel-surface-navigation.test.tsx b/apps/web/src/features/channel/Channel/tests/channel-surface-navigation.test.tsxnew file mode 100644index 0000000000..933ca1b29e--- /dev/null+++ b/apps/web/src/features/channel/Channel/tests/channel-surface-navigation.test.tsx@@ -0,0 +1,176 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal, onMount } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ChannelHandle } from '../Channel';+import {+ ChannelMessages,+ ChannelSurface,+ type ChannelTargetRequest,+} from '../ChannelSurface';++const mocks = vi.hoisted(() => ({+ resolve: vi.fn(),+ mount: vi.fn(),+ navigate: vi.fn(),+}));++vi.mock('@queries/messages/timeline', () => ({+ fetchResolvedChannelMessage: mocks.resolve,+ findThreadIdInMessageTimeline: () => undefined,+ findTopLevelMessageInMessageTimeline: () => undefined,+}));+vi.mock('../Channel', () => ({+ Channel: (props: {+ targetMessageId?: string;+ targetMessageReplyId?: string;+ onHandleReady: (handle: Partial<ChannelHandle>) => void;+ }) => {+ mocks.mount(props.targetMessageId, props.targetMessageReplyId);+ onMount(() =>+ props.onHandleReady({+ goToMessage: mocks.navigate,+ getMessagesStateSnapshot: () => undefined,+ })+ );+ return (+ <div>+ <p>{props.targetMessageReplyId ?? props.targetMessageId ?? 'Latest'}</p>+ <input aria-label="Message" />+ </div>+ );+ },+}));++beforeEach(() => vi.clearAllMocks());+afterEach(cleanup);++function deferredMessage() {+ let resolve!: (message: { kind: string; thread_id: string }) => void;+ const promise = new Promise<{ kind: string; thread_id: string }>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++describe('channel message link startup', () => {+ it('waits for an unknown reply before mounting its first message window', async () => {+ const message = deferredMessage();+ mocks.resolve.mockReturnValue(message.promise);+ render(() => (+ <ChannelSurface+ channelId="channel-1"+ targetRequest={{ kind: 'message', messageId: 'reply-1' }}+ >+ <ChannelMessages />+ </ChannelSurface>+ ));++ expect(screen.getByRole('status').textContent).toBe('Loading conversation');+ expect(mocks.mount).not.toHaveBeenCalled();+ expect(screen.queryByText('Latest')).toBeNull();++ message.resolve({ kind: 'thread_reply', thread_id: 'root-1' });+ await screen.findByText('reply-1');+ expect(mocks.mount).toHaveBeenCalledExactlyOnceWith('root-1', 'reply-1');+ expect(screen.queryByRole('status')).toBeNull();+ expect(mocks.navigate).not.toHaveBeenCalled();+ });++ it.each([+ { messageId: 'root-1', threadId: 'root-1', replyId: undefined },+ { messageId: 'reply-1', threadId: 'root-1', replyId: 'reply-1' },+ ])(+ 'opens a known target without a resolution request: $messageId',+ (target) => {+ render(() => (+ <ChannelSurface+ channelId="channel-1"+ targetRequest={{ kind: 'message', ...target }}+ >+ <ChannelMessages />+ </ChannelSurface>+ ));+ expect(mocks.resolve).not.toHaveBeenCalled();+ expect(mocks.mount).toHaveBeenCalledExactlyOnceWith(+ 'root-1',+ target.replyId+ );+ expect(screen.getByText(target.messageId)).toBeTruthy();+ }+ );++ it('lets a newer target replace an unresolved launch target', async () => {+ const oldMessage = deferredMessage();+ mocks.resolve.mockReturnValue(oldMessage.promise);+ render(() => {+ const [target, setTarget] = createSignal<ChannelTargetRequest>({+ kind: 'message',+ messageId: 'old-reply',+ });+ return (+ <>+ <button+ type="button"+ onClick={() =>+ setTarget({+ kind: 'message',+ messageId: 'new-root',+ threadId: 'new-root',+ })+ }+ >+ Open newer notification+ </button>+ <ChannelSurface channelId="channel-1" targetRequest={target()}>+ <ChannelMessages />+ </ChannelSurface>+ </>+ );+ });+ fireEvent.click(screen.getByRole('button'));+ expect(screen.getByText('new-root')).toBeTruthy();+ oldMessage.resolve({ kind: 'thread_reply', thread_id: 'old-root' });+ await oldMessage.promise;+ await Promise.resolve();+ expect(mocks.mount).toHaveBeenCalledExactlyOnceWith('new-root', undefined);+ expect(mocks.navigate).not.toHaveBeenCalled();+ });++ it('keeps a mounted composer while resolving another message link', async () => {+ const message = deferredMessage();+ mocks.resolve.mockReturnValue(message.promise);+ render(() => {+ const [target, setTarget] = createSignal<ChannelTargetRequest>({+ kind: 'message',+ messageId: 'root-1',+ threadId: 'root-1',+ });+ return (+ <>+ <button+ type="button"+ onClick={() => setTarget({ kind: 'message', messageId: 'reply-2' })}+ >+ Open another message+ </button>+ <ChannelSurface channelId="channel-1" targetRequest={target()}>+ <ChannelMessages />+ </ChannelSurface>+ </>+ );+ });+ const composer = screen.getByRole('textbox');+ fireEvent.input(composer, { target: { value: 'Unsent draft' } });+ fireEvent.click(screen.getByRole('button'));+ expect(screen.getByRole('textbox')).toBe(composer);+ expect(screen.queryByRole('status')).toBeNull();++ message.resolve({ kind: 'thread_reply', thread_id: 'root-2' });+ await message.promise;+ await Promise.resolve();+ expect(mocks.navigate).toHaveBeenCalledWith('root-2', 'reply-2');+ expect(mocks.mount).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('textbox')).toBe(composer);+ expect(composer).toHaveProperty('value', 'Unsent draft');+ });+});diff --git a/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts b/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.tsindex 0f8c139981..a4f819beed 100644--- a/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts+++ b/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts@@ -2,6 +2,11 @@ import { queryClient } from '@queries/client';import { createRoot, createSignal } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';+const notificationVisible = vi.hoisted(() => vi.fn());+vi.mock('@notifications/notification-open-trace', () => ({+ markNotificationTargetVisible: notificationVisible,+}));+vi.mock('@service-storage/client', () => ({storageServiceClient: {},}));@@ -21,6 +26,7 @@ import {afterEach(() => {queryClient.clear();+ notificationVisible.mockClear();vi.useRealTimers();});@@ -48,6 +54,33 @@ function mount(init?: { targetMessageId?: string; targetReplyId?: string }) {});}+describe('notification visibility', () => {+ it('acknowledges only the active root after its scroll completes', () => {+ const { controller, ready, dispose } = mount({ targetMessageId: 'm1' });+ ready(['m1', 'm2']);+ controller.completePendingScroll('m2');+ expect(notificationVisible).not.toHaveBeenCalled();+ controller.completePendingScroll('m1');+ controller.completePendingScroll('m1');+ expect(notificationVisible).toHaveBeenCalledExactlyOnceWith(CHANNEL, 'm1');+ dispose();+ });++ it('acknowledges a reply only when the reply itself is positioned', () => {+ const { controller, ready, dispose } = mount({+ targetMessageId: 'm1',+ targetReplyId: 'r1',+ });+ ready(['m1']);+ controller.completePendingScroll('m1');+ controller.completePendingReplyScroll('m1', 'r2');+ expect(notificationVisible).not.toHaveBeenCalled();+ controller.completePendingReplyScroll('m1', 'r1');+ expect(notificationVisible).toHaveBeenCalledExactlyOnceWith(CHANNEL, 'r1');+ dispose();+ });+});+describe('construction', () => {it('does not read ThreadList inputs during construct (Channel.tsx TDZ)', () => {createRoot((dispose) => {diff --git a/apps/web/src/features/channel/queries/prefetch-channel-target.test.ts b/apps/web/src/features/channel/queries/prefetch-channel-target.test.tsnew file mode 100644index 0000000000..c546c6cdfd--- /dev/null+++ b/apps/web/src/features/channel/queries/prefetch-channel-target.test.ts@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ timeline: vi.fn(),+ replies: vi.fn(),+}));+vi.mock('@queries/client', () => ({+ queryClient: {+ prefetchInfiniteQuery: mocks.timeline,+ prefetchQuery: mocks.replies,+ },+}));+vi.mock('@queries/messages/timeline', () => ({+ messageTimelineQueryOptions: (parent: unknown, messageId: string) => ({+ parent,+ messageId,+ }),+}));+vi.mock('@queries/messages/thread-replies', () => ({+ threadRepliesQueryOptions: (parent: unknown, threadId: string) => ({+ parent,+ threadId,+ }),+}));++import { prefetchChannelTarget } from './prefetch-channel-target';++beforeEach(() => {+ vi.clearAllMocks();+ mocks.timeline.mockResolvedValue(undefined);+ mocks.replies.mockResolvedValue(undefined);+});++describe('channel target prefetch', () => {+ it('starts the root window directly without resolving a known root', async () => {+ await prefetchChannelTarget('channel-1', {+ messageId: 'root-1',+ threadId: 'root-1',+ });+ expect(mocks.timeline).toHaveBeenCalledExactlyOnceWith({+ parent: { type: 'channel', id: 'channel-1' },+ messageId: 'root-1',+ });+ expect(mocks.replies).not.toHaveBeenCalled();+ });++ it('starts the root window and reply fetch together', async () => {+ let finishTimeline!: () => void;+ mocks.timeline.mockReturnValue(+ new Promise<void>((resolve) => {+ finishTimeline = resolve;+ })+ );+ const pending = prefetchChannelTarget('channel-1', {+ messageId: 'reply-1',+ threadId: 'root-1',+ });+ expect(mocks.timeline).toHaveBeenCalledExactlyOnceWith({+ parent: { type: 'channel', id: 'channel-1' },+ messageId: 'root-1',+ });+ expect(mocks.replies).toHaveBeenCalledExactlyOnceWith({+ parent: { type: 'channel', id: 'channel-1' },+ threadId: 'root-1',+ });+ finishTimeline();+ await pending;+ });++ it('leaves ambiguous links to the mounted surface instead of fetching latest', async () => {+ await prefetchChannelTarget('channel-1', { messageId: 'reply-1' });+ expect(mocks.timeline).not.toHaveBeenCalled();+ expect(mocks.replies).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/channel/queries/prefetch-channel-target.ts b/apps/web/src/features/channel/queries/prefetch-channel-target.tsnew file mode 100644index 0000000000..ff5699b714--- /dev/null+++ b/apps/web/src/features/channel/queries/prefetch-channel-target.ts@@ -0,0 +1,38 @@+import { Telemetry } from '@macro-inc/observability';+import { notificationTargetSpan } from '@notifications/notification-open-trace';+import { queryClient } from '@queries/client';+import { threadRepliesQueryOptions } from '@queries/messages/thread-replies';+import { messageTimelineQueryOptions } from '@queries/messages/timeline';++/** Warm the exact message window while the host resolves channel metadata. */+export async function prefetchChannelTarget(+ channelId: string,+ target: { messageId: string; threadId?: string }+): Promise<void> {+ // Bare links first need the surface's cancellable root/reply resolution.+ // Push destinations already identify the root, including roots themselves.+ const threadId = target.threadId;+ if (!threadId) return;+ const trace =+ notificationTargetSpan(channelId, target.messageId) ?? Telemetry;+ await trace.span('channel.target.prefetch', async (span) => {+ span.setAttr('channel.id', channelId);+ span.setAttr('message.id', target.messageId);+ const parent = { type: 'channel' as const, id: channelId };+ span.setAttr('thread.id', threadId);+ await Promise.all([+ queryClient.prefetchInfiniteQuery(+ messageTimelineQueryOptions(parent, threadId)+ ),+ ...(threadId !== target.messageId+ ? [+ queryClient.prefetchQuery(+ threadRepliesQueryOptions(parent, threadId)+ ),+ ]+ : []),+ ]);+ // TanStack prefetch owns error state; the mounted queries present failures.+ span.setAttr('channel.target.outcome', 'prefetch_settled');+ });+}diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsxindex bedf749839..830de4b3a3 100644--- a/apps/web/src/features/channels-view/channels-view.test.tsx+++ b/apps/web/src/features/channels-view/channels-view.test.tsx@@ -24,14 +24,23 @@ const mocks = vi.hoisted(() => ({active: (): boolean => true,searchOpen: (): boolean => false,searchText: (): string => '',+ authenticated: (): boolean | undefined => true,+ target: (): { messageId: string; threadId?: string } | undefined => undefined,sourceEnabled: (_scope: string): boolean => false,selectedQuery: vi.fn(),markRead: vi.fn(),resolveTarget: vi.fn(() => ({ kind: 'message', messageId: 'unread' })),refresh: vi.fn(async () => {}),+ prefetchTarget: vi.fn(async () => {}),favoriteIds: (): string[] => [],}));+vi.mock('@core/context/user', () => ({+ useIsAuthenticated: () => () => mocks.authenticated(),+}));+vi.mock('@channel/queries/prefetch-channel-target', () => ({+ prefetchChannelTarget: mocks.prefetchTarget,+}));vi.mock('./queries/channel-list-search-pool', () => ({useChannelListSearchPool: () => () => [],}));@@ -168,7 +177,11 @@ vi.mock('./channels-view-context', () => ({mobileLayout: () => mocks.mobileLayout(),selectedChannel: () =>mocks.selectedId()- ? { type: 'channel', id: mocks.selectedId() }+ ? {+ type: 'channel',+ id: mocks.selectedId(),+ target: mocks.target(),+ }: undefined,setAsideWidth: vi.fn(),}),@@ -246,6 +259,8 @@ beforeEach(() => {mocks.active = () => true;mocks.searchOpen = () => false;mocks.searchText = () => '';+ mocks.authenticated = () => true;+ mocks.target = () => undefined;[mocks.selectedId, setSelectedId] = createSignal<string | undefined>('one');[mocks.rows, setRows] = createSignal([row('one', 'new'), row('two')]);const [query, update] = createStore<QueryState>({@@ -326,6 +341,45 @@ describe('mobile dock search wiring', () => {});describe('channel selection loading and recovery', () => {+ it('prefetches an explicit target while uncached channel metadata is loading', () => {+ const target = { messageId: 'reply', threadId: 'root' };+ mocks.target = () => target;+ setRows([]);+ setQuery({ isLoading: true, isFetching: true, data: undefined });+ render(() => <ChannelsView />);+ expect(mocks.prefetchTarget).toHaveBeenCalledExactlyOnceWith('one', target);+ expect(+ screen.getByRole('status', { name: 'Loading conversation' })+ ).toBeTruthy();+ expect(screen.queryByTestId('channel-detail')).toBeNull();+ setQuery({+ isLoading: false,+ isFetching: false,+ data: { entities: [full('one', [])] },+ });+ expect(screen.getByTestId('channel-detail').textContent).toBe('one');+ expect(mocks.prefetchTarget).toHaveBeenCalledOnce();+ });++ it.each([false, undefined])(+ 'waits for confirmed authentication before prefetching a target from %s',+ (initial) => {+ const [authenticated, setAuthenticated] = createSignal<+ boolean | undefined+ >(initial);+ mocks.authenticated = authenticated;+ const target = { messageId: 'root', threadId: 'root' };+ mocks.target = () => target;+ render(() => <ChannelsView />);+ expect(mocks.prefetchTarget).not.toHaveBeenCalled();+ setAuthenticated(true);+ expect(mocks.prefetchTarget).toHaveBeenCalledExactlyOnceWith(+ 'one',+ target+ );+ }+ );+it.each(['pointerDown', 'keyDown', 'wheel'] as const)('stays at latest after %s and notification hydration',(event) => {diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsxindex b86dd0ce46..d55fa20dd5 100644--- a/apps/web/src/features/channels-view/channels-view.tsx+++ b/apps/web/src/features/channels-view/channels-view.tsx@@ -5,19 +5,25 @@ import { MaybeSoupEntityActionDrawerManager } from '@app/features/soup';import { withEntityNotifications } from '@app/features/soup/entity-notifications';import { ViewTour } from '@app/features/tours/ViewTour';import { SplitRouter } from '@app/lib/split-router';+import { ChannelLoading } from '@channel/Channel/ChannelLoading';import { useChannelByIdQuery } from '@channel/Channel/channel-entity';import { DebugSuspense } from '@channel/DebugSuspense';+import { prefetchChannelTarget } from '@channel/queries/prefetch-channel-target';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { SplitPanel } from '@components/app/split-panel';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { useIsAuthenticated } from '@core/context/user';+import { fireAndForget } from '@core/util/fireAndForget';import { ListEntityMetadataQueryProvider } from '@entity';import SpinnerIcon from '@phosphor/spinner.svg';import { useFavoritesData } from '@queries/favorites/favorites';import {createContext,+ createEffect,createMemo,createSignal,+ on,onMount,Show,useContext,@@ -263,6 +269,17 @@ function ChannelDetailRouteContent() {const { selectedChannel } = useChannelsView();const notificationSource = useGlobalNotificationSource();const channelId = createMemo(() => selectedChannel()?.id);+ const authenticated = useIsAuthenticated();+ const target = createMemo(() => selectedChannel()?.target);+ createEffect(+ on([channelId, target, authenticated], ([id, destination, signedIn]) => {+ if (!id || !destination || signedIn !== true) return;+ fireAndForget(+ prefetchChannelTarget(id, destination),+ 'channel-target-prefetch'+ );+ })+ );const sources = useContext(ChannelSourcesContext);const loaded = createMemo(() =>resolveSelectedChannel(@@ -311,7 +328,10 @@ function ChannelDetailRouteContent() {};return (- <DebugSuspense name="ChannelsView.detail-content">+ <DebugSuspense+ name="ChannelsView.detail-content"+ fallback={<ChannelLoading />}+ ><Showwhen={visibleChannel()}fallback={@@ -321,21 +341,17 @@ function ChannelDetailRouteContent() {{loaded()?.name ?? 'Conversation'}</span></ViewShell.TopBar>- <div- class="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 text-ink-muted"- role="status"- >- <h2>- {unavailable()- ? 'Conversation unavailable'- : 'Loading conversation'}- </h2>- <Show when={unavailable()}>+ <Show when={unavailable()} fallback={<ChannelLoading />}>+ <div+ class="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 text-ink-muted"+ role="status"+ >+ <h2>Conversation unavailable</h2><button type="button" onClick={retry}>Retry</button>- </Show>- </div>+ </div>+ </Show></>}>@@ -351,7 +367,10 @@ function ChannelDetailRouteContent() {export function ChannelDetailRouteView() {return (- <DebugSuspense name="ChannelsView.detail-route">+ <DebugSuspense+ name="ChannelsView.detail-route"+ fallback={<ChannelLoading />}+ ><ChannelDetailRouteContent /></DebugSuspense>);diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.tsindex bd58f3b99f..6c1a56fe44 100644--- a/apps/web/src/features/next-soup/utils.test.ts+++ b/apps/web/src/features/next-soup/utils.test.ts@@ -1617,7 +1617,7 @@ describe('getChannelEntityTarget', () => {expect(getChannelEntityTarget(entity)).toEqual({kind: 'message',messageId: 'notif-msg',- threadId: undefined,+ threadId: 'notif-msg',});});@@ -2058,9 +2058,9 @@ describe('getChannelEntityTarget', () => {} else {expect(search).toMatchObject({messageId: ['message'],+ threadId: ['message'],seek: [expect.any(String)],});- expect(search?.threadId).toBeUndefined();}expect(bulkMarkAsRead).toHaveBeenCalledExactlyOnceWith([parentNotification,@@ -2115,7 +2115,7 @@ describe('getChannelEntityTarget', () => {expect(getChannelEntityTarget(entity)).toEqual({kind: 'message',messageId: 'unread-older-msg',- threadId: undefined,+ threadId: 'unread-older-msg',});});diff --git a/apps/web/src/features/notifications/PendingNotificationNavigationEffect.test.tsx b/apps/web/src/features/notifications/PendingNotificationNavigationEffect.test.tsxindex 300af7e849..b54ef64577 100644--- a/apps/web/src/features/notifications/PendingNotificationNavigationEffect.test.tsx+++ b/apps/web/src/features/notifications/PendingNotificationNavigationEffect.test.tsx@@ -20,6 +20,7 @@ import { batch, createRoot, createSignal } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {pendingNotificationNavigationId,+ receiveNotificationTap,setPendingNotificationNavigationId,} from './notification-navigation-intent';import type { NotificationSource } from './notification-source';@@ -94,7 +95,10 @@ describe('usePendingNotificationNavigationEffect', () => {function mount(source = {} as NotificationSource) {dispose = createRoot((rootDispose) => {- usePendingNotificationNavigationEffect(source);+ usePendingNotificationNavigationEffect(+ source,+ () => 'macro|[email protected]'+ );return rootDispose;});return source;@@ -128,6 +132,69 @@ describe('usePendingNotificationNavigationEffect', () => {expect(pendingNotificationNavigationId()).toBeUndefined();});+ it('passes an account-bound destination without waiting for notification hydration', async () => {+ const host = managerHarness(true);+ const source = mount();+ const acknowledge = vi.fn(async () => {});+ setGlobalSplitManager(host.manager);+ const navigation = {+ type: 'channel',+ channelId: '11111111-1111-4111-8111-111111111111',+ messageId: '22222222-2222-4222-8222-222222222222',+ threadId: null,+ };+ receiveNotificationTap(+ {+ type: 'BACKGROUND_TAP',+ deliveryId: 'native-tap',+ payload: {+ notificationId: 'notification-1',+ recipientId: 'macro|[email protected]',+ navigation,+ },+ },+ acknowledge+ );+ await Promise.resolve();+ expect(mocks.openNotificationFromId).toHaveBeenCalledWith(+ 'notification-1',+ host.manager,+ source,+ {+ canOpen: expect.any(Function),+ onApplied: expect.any(Function),+ target: navigation,+ }+ );+ expect(acknowledge).not.toHaveBeenCalled();+ attempts[0]?.onApplied();+ await Promise.resolve();+ expect(acknowledge).toHaveBeenCalledWith('native-tap');+ expect(pendingNotificationNavigationId()).toBeUndefined();+ });++ it('discards another account’s tap without opening or fetching it', async () => {+ const host = managerHarness(true);+ mount();+ setGlobalSplitManager(host.manager);+ const acknowledge = vi.fn(async () => {});+ receiveNotificationTap(+ {+ type: 'BACKGROUND_TAP',+ deliveryId: 'wrong-account',+ payload: {+ notificationId: 'private-notification',+ recipientId: 'macro|[email protected]',+ },+ },+ acknowledge+ );+ await Promise.resolve();+ expect(mocks.openNotificationFromId).not.toHaveBeenCalled();+ expect(acknowledge).toHaveBeenCalledWith('wrong-account');+ expect(pendingNotificationNavigationId()).toBeUndefined();+ });+it('retries a settled but aborted request after layout reconciliation', async () => {const host = managerHarness(true);mount();diff --git a/apps/web/src/features/notifications/PendingNotificationNavigationEffect.tsx b/apps/web/src/features/notifications/PendingNotificationNavigationEffect.tsxindex a2edfa6605..1beabd561d 100644--- a/apps/web/src/features/notifications/PendingNotificationNavigationEffect.tsx+++ b/apps/web/src/features/notifications/PendingNotificationNavigationEffect.tsx@@ -8,21 +8,28 @@ import { fireAndForget } from '@core/util/fireAndForget';import {type NotificationSource,openNotificationFromId,- pendingNotificationNavigationId,- setPendingNotificationNavigationId,} from '@notifications';-import { createEffect, createSignal, onCleanup } from 'solid-js';+import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';+import {+ finishNotificationNavigation,+ type NotificationNavigationIntent,+ pendingNotificationNavigation,+} from './notification-navigation-intent';+import { notificationOpenSpan } from './notification-open-trace';type NavigationAttempt = {notificationId: string;+ intent: NotificationNavigationIntent;layoutManager: SplitManager;navigationVersion: number;eventAtStart: SplitEventWithType | undefined;settled: boolean;+ applied: boolean;};export function usePendingNotificationNavigationEffect(- notificationSource: NotificationSource+ notificationSource: NotificationSource,+ recipientId: Accessor<string | undefined>) {const [retryRevision, setRetryRevision] = createSignal(0);let disposed = false;@@ -35,25 +42,39 @@ export function usePendingNotificationNavigationEffect(createEffect(() => {retryRevision();- const notificationId = pendingNotificationNavigationId();+ const intent = pendingNotificationNavigation();+ const notificationId = intent?.notificationId;+ const account = recipientId();const layoutManager = globalSplitManager();const navigationReady = layoutManager?.contentNavigationReady() ?? false;const navigationVersion = layoutManager?.contentNavigationVersion() ?? 0;const currentEvent = layoutManager?.events();- if (!notificationId || !layoutManager || !navigationReady) {+ if (intent?.recipientId && account && intent.recipientId !== account) {+ activeAttempt = undefined;+ finishNotificationNavigation(intent, 'account_mismatch');+ return;+ }+ if (+ !intent ||+ !notificationId ||+ !layoutManager ||+ !navigationReady ||+ (intent.recipientId && !account)+ ) {activeAttempt = undefined;return;}if (- activeAttempt?.notificationId === notificationId &&+ activeAttempt?.intent === intent &&activeAttempt.layoutManager === layoutManager &&activeAttempt.navigationVersion === navigationVersion) {// Do not overlap a fetch/open. Once it settles without being applied,// retry only after reconciliation changes the live layout.if (+ activeAttempt.applied ||!activeAttempt.settled ||activeAttempt.eventAtStart === currentEvent) {@@ -63,36 +84,48 @@ export function usePendingNotificationNavigationEffect(const attempt: NavigationAttempt = {notificationId,+ intent,layoutManager,navigationVersion,eventAtStart: currentEvent,settled: false,+ applied: false,};activeAttempt = attempt;const isCurrentAttempt = () =>!disposed &&activeAttempt === attempt &&- pendingNotificationNavigationId() === notificationId &&+ pendingNotificationNavigation() === intent &&+ (!intent.recipientId || recipientId() === intent.recipientId) &&globalSplitManager() === layoutManager &&layoutManager.contentNavigationReady() &&layoutManager.contentNavigationVersion() === navigationVersion;const onApplied = () => {if (!isCurrentAttempt()) return;- activeAttempt = undefined;- setPendingNotificationNavigationId(undefined);+ // Keep the attempt in flight until native confirms receipt, so another+ // layout event cannot start a second navigation during that handshake.+ attempt.applied = true;+ finishNotificationNavigation(intent);};- fireAndForget(+ const open = () =>openNotificationFromId(notificationId,layoutManager,notificationSource,- { canOpen: isCurrentAttempt, onApplied }- ).match(+ {+ canOpen: isCurrentAttempt,+ onApplied,+ ...(intent.target ? { target: intent.target } : {}),+ }+ );+ const span = notificationOpenSpan(notificationId);+ fireAndForget(+ (span ? span.run(open) : open()).match(() => {- if (!isCurrentAttempt()) return;+ if (!isCurrentAttempt() || attempt.applied) return;attempt.settled = true;if (layoutManager.events() !== attempt.eventAtStart) {setRetryRevision((revision) => revision + 1);@@ -104,13 +137,13 @@ export function usePendingNotificationNavigationEffect(if (error.tag === 'NavigationDeferredError') return;if (disposed ||- pendingNotificationNavigationId() !== notificationId ||+ pendingNotificationNavigation() !== intent ||globalSplitManager() !== layoutManager ||layoutManager.contentNavigationVersion() !== navigationVersion) {return;}- setPendingNotificationNavigationId(undefined);+ finishNotificationNavigation(intent, 'failed');toast.failure('Failed to open notification.');}),diff --git a/apps/web/src/features/notifications/notification-navigation-intent.test.ts b/apps/web/src/features/notifications/notification-navigation-intent.test.tsnew file mode 100644index 0000000000..ea34695774--- /dev/null+++ b/apps/web/src/features/notifications/notification-navigation-intent.test.ts@@ -0,0 +1,171 @@+import { afterEach, expect, it, vi } from 'vitest';+import {+ finishNotificationNavigation,+ notificationIntentFromPayload,+ notificationLaunchPath,+ pendingNotificationNavigation,+ receiveNotificationTap,+ setPendingNotificationNavigationId,+} from './notification-navigation-intent';+import { endNotificationOpen } from './notification-open-trace';++const navigation = {+ type: 'channel',+ channelId: '11111111-1111-4111-8111-111111111111',+ messageId: '22222222-2222-4222-8222-222222222222',+ threadId: null,+};+const payload = {+ notificationId: 'notification-1',+ recipientId: 'macro|[email protected]',+ navigation,+};++afterEach(() => {+ setPendingNotificationNavigationId(undefined);+ endNotificationOpen('test_complete');+});++it('decodes nested APNs routing metadata and retains known top-level identity', () => {+ expect(+ notificationIntentFromPayload({+ ...payload,+ navigation: JSON.stringify(navigation),+ })?.target+ ).toEqual(navigation);+ receiveNotificationTap({ type: 'BACKGROUND_TAP', payload }, vi.fn());+ expect(notificationLaunchPath(payload.recipientId)).toBe(+ '/channel/11111111-1111-4111-8111-111111111111?channel_message_id=22222222-2222-4222-8222-222222222222&channel_thread_id=22222222-2222-4222-8222-222222222222'+ );+ expect(notificationLaunchPath('macro|[email protected]')).toBeUndefined();+});++it.each([+ { notificationId: 'old-notification' },+ { ...payload, recipientId: undefined },+ { ...payload, navigation: '{broken' },+ {+ ...payload,+ navigation: {+ type: 'channel',+ channelId: navigation.channelId,+ messageId: navigation.messageId,+ },+ },+ { ...payload, navigation: { ...navigation, channelId: '../../login' } },+])(+ 'retains the authenticated lookup for legacy or malformed routing: %j',+ (value) => {+ expect(notificationIntentFromPayload(value)?.notificationId).toBe(+ value.notificationId+ );+ expect(notificationIntentFromPayload(value)?.target).toBeUndefined();+ }+);++it('never navigates for delivery without an explicit tap', () => {+ expect(+ receiveNotificationTap({ type: 'FOREGROUND_DELIVERY', payload }, vi.fn())+ ).toBe(false);+ expect(pendingNotificationNavigation()).toBeUndefined();+});++it('keeps a tap durable until navigation acknowledgment and ignores duplicate delivery', async () => {+ let acknowledge!: () => void;+ const ack = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ acknowledge = resolve;+ })+ );+ const event = { type: 'BACKGROUND_TAP', payload, deliveryId: 'delivery-1' };+ receiveNotificationTap(event, ack);+ const intent = pendingNotificationNavigation()!;+ receiveNotificationTap(event, ack);+ expect(pendingNotificationNavigation()).toBe(intent);+ expect(ack).not.toHaveBeenCalled();+ finishNotificationNavigation(intent);+ expect(ack).toHaveBeenCalledWith('delivery-1');+ expect(pendingNotificationNavigation()).toBe(intent);+ acknowledge();+ await Promise.resolve();+ expect(pendingNotificationNavigation()).toBeUndefined();+ expect(receiveNotificationTap(event, ack)).toBe(false);+});++it('a late acknowledgment or startup snapshot cannot replace a newer tap', async () => {+ let acknowledge!: () => void;+ const firstAck = () =>+ new Promise<void>((resolve) => {+ acknowledge = resolve;+ });+ const first = {+ type: 'BACKGROUND_TAP',+ payload,+ deliveryId: 'old',+ receivedAtMs: 10,+ };+ const second = {+ ...first,+ payload: { ...payload, notificationId: 'notification-2' },+ deliveryId: 'new',+ receivedAtMs: 20,+ };+ receiveNotificationTap(first, firstAck);+ finishNotificationNavigation(pendingNotificationNavigation()!);+ receiveNotificationTap(second, vi.fn());+ receiveNotificationTap(first, firstAck);+ acknowledge();+ await Promise.resolve();+ expect(pendingNotificationNavigation()?.notificationId).toBe(+ 'notification-2'+ );+});++it('a late acknowledgment cannot reopen the newer completed delivery', async () => {+ let acknowledgeFirst!: () => void;+ const firstAck = () =>+ new Promise<void>((resolve) => {+ acknowledgeFirst = resolve;+ });+ const first = {+ type: 'BACKGROUND_TAP',+ payload,+ deliveryId: 'old',+ receivedAtMs: 10,+ };+ const second = {+ ...first,+ payload: { ...payload, notificationId: 'notification-2' },+ deliveryId: 'new',+ receivedAtMs: 20,+ };+ receiveNotificationTap(first, firstAck);+ finishNotificationNavigation(pendingNotificationNavigation()!);+ receiveNotificationTap(second, async () => {});+ finishNotificationNavigation(pendingNotificationNavigation()!);+ await Promise.resolve();+ expect(pendingNotificationNavigation()).toBeUndefined();+ acknowledgeFirst();+ await Promise.resolve();+ expect(receiveNotificationTap(second, vi.fn())).toBe(false);+ expect(pendingNotificationNavigation()).toBeUndefined();+});++it('retries a failed receipt acknowledgment without navigating again', async () => {+ const ack = vi+ .fn<() => Promise<void>>()+ .mockRejectedValueOnce(new Error('bridge unavailable'))+ .mockResolvedValueOnce();+ const event = { type: 'BACKGROUND_TAP', payload, deliveryId: 'retry' };+ receiveNotificationTap(event, ack);+ const intent = pendingNotificationNavigation()!;+ finishNotificationNavigation(intent);+ await Promise.resolve();+ expect(pendingNotificationNavigation()).toBe(intent);+ receiveNotificationTap(event, ack);+ expect(pendingNotificationNavigation()).toBe(intent);+ await Promise.resolve();+ expect(ack).toHaveBeenCalledTimes(2);+ expect(pendingNotificationNavigation()).toBeUndefined();+});diff --git a/apps/web/src/features/notifications/notification-navigation-intent.ts b/apps/web/src/features/notifications/notification-navigation-intent.tsindex e29c39298c..1ad310fd22 100644--- a/apps/web/src/features/notifications/notification-navigation-intent.ts+++ b/apps/web/src/features/notifications/notification-navigation-intent.ts@@ -1,10 +1,171 @@+import { getChannelParams } from '@channel/Channel/link';+import { fireAndForget } from '@core/util/fireAndForget';+import { pushNotificationNavigation } from '@service-notification/generated/push';+import type { PushNotificationNavigation } from '@service-notification/generated/schemas/pushNotificationNavigation';import { createSignal } from 'solid-js';+import {+ endNotificationOpen,+ notificationOpenSpan,+ startNotificationOpen,+} from './notification-open-trace';-export const [- pendingNotificationNavigationId,- setPendingNotificationNavigationId,-] = createSignal<string | undefined>();+export type NotificationNavigationIntent = {+ notificationId: string;+ recipientId?: string;+ target?: PushNotificationNavigation;+ deliveryId?: string;+ receivedAtMs?: number;+ acknowledge?: () => Promise<void>;+};-export function triggerNotificationNavigation(notificationId: string) {+export const [pendingNotificationNavigation, setPendingNotificationNavigation] =+ createSignal<NotificationNavigationIntent>();+let acknowledgedDeliveryId: string | undefined;+let latestReceiptMs: number | undefined;+let completing: NotificationNavigationIntent | undefined;+let completion:+ | { intent: NotificationNavigationIntent; outcome: string }+ | undefined;++export const pendingNotificationNavigationId = () =>+ pendingNotificationNavigation()?.notificationId;++export function setPendingNotificationNavigationId(+ notificationId: string | undefined+): void {+ if (!notificationId) {+ latestReceiptMs = undefined;+ acknowledgedDeliveryId = undefined;+ completion = undefined;+ }+ setPendingNotificationNavigation(+ notificationId ? { notificationId } : undefined+ );+}++export function triggerNotificationNavigation(notificationId: string): void {+ startNotificationOpen(notificationId);setPendingNotificationNavigationId(notificationId);}++/** The native iOS bridge JSON-encodes nested APNs values; Android can send objects. */+export function notificationIntentFromPayload(+ payload: Record<string, unknown>+): NotificationNavigationIntent | undefined {+ const notificationId = payload.notificationId;+ if (typeof notificationId !== 'string' || !notificationId) return;+ const recipientId =+ typeof payload.recipientId === 'string' && payload.recipientId+ ? payload.recipientId+ : undefined;+ let navigation = payload.navigation;+ if (typeof navigation === 'string') {+ try {+ navigation = JSON.parse(navigation);+ } catch {+ navigation = undefined;+ }+ }+ const parsed = pushNotificationNavigation.safeParse(navigation);+ // Direct destinations must be bound to an account. Old/malformed pushes+ // still use the authenticated notification lookup.+ return {+ notificationId,+ recipientId,+ target: recipientId && parsed.success ? parsed.data : undefined,+ };+}++/** Return true when receipt acknowledgment belongs to navigation, not delivery. */+export function receiveNotificationTap(+ event: {+ type: string;+ payload: Record<string, unknown>;+ deliveryId?: string;+ receivedAtMs?: number;+ },+ acknowledge: (deliveryId: string) => Promise<void>+): boolean {+ if (event.type !== 'BACKGROUND_TAP' && event.type !== 'FOREGROUND_TAP')+ return false;+ const intent = notificationIntentFromPayload(event.payload);+ if (!intent) return false;+ if (event.deliveryId && event.deliveryId === acknowledgedDeliveryId)+ return false;+ if (+ event.deliveryId &&+ event.deliveryId === pendingNotificationNavigation()?.deliveryId+ ) {+ if (completion)+ finishNotificationNavigation(completion.intent, completion.outcome);+ return true;+ }+ if (+ event.receivedAtMs !== undefined &&+ latestReceiptMs !== undefined &&+ event.receivedAtMs < latestReceiptMs+ )+ return false;+ latestReceiptMs = event.receivedAtMs ?? latestReceiptMs;+ completion = undefined;+ const deliveryId = event.deliveryId;+ startNotificationOpen(+ intent.notificationId,+ intent.target,+ event.receivedAtMs,+ deliveryId+ );+ setPendingNotificationNavigation({+ ...intent,+ deliveryId,+ receivedAtMs: event.receivedAtMs,+ acknowledge: deliveryId ? () => acknowledge(deliveryId) : undefined,+ });+ return true;+}++/** Select the first route only after the session's actual account is known. */+export function notificationLaunchPath(+ recipientId: string+): string | undefined {+ const intent = pendingNotificationNavigation();+ if (!intent?.target || intent.recipientId !== recipientId) return;+ const { channelId, messageId, threadId } = intent.target;+ const params = new URLSearchParams(+ getChannelParams(messageId, threadId ?? messageId)+ );+ return `/channel/${encodeURIComponent(channelId)}?${params}`;+}++export function finishNotificationNavigation(+ intent: NotificationNavigationIntent,+ outcome = 'applied'+): void {+ if (pendingNotificationNavigation() !== intent) return;+ if (completing === intent) return;+ completion = { intent, outcome };+ const complete = () => {+ if (pendingNotificationNavigation() !== intent) return;+ acknowledgedDeliveryId = intent.deliveryId;+ notificationOpenSpan(intent.notificationId)?.event(+ 'notification.route_applied'+ );+ if (outcome !== 'applied' || !intent.target) endNotificationOpen(outcome);+ setPendingNotificationNavigation(undefined);+ completion = undefined;+ };+ if (!intent.acknowledge) {+ complete();+ return;+ }+ const finish = async () => {+ completing = intent;+ try {+ await intent.acknowledge?.();+ complete();+ } finally {+ if (completing === intent) completing = undefined;+ }+ };+ fireAndForget(finish(), 'notification-navigation');+}diff --git a/apps/web/src/features/notifications/notification-navigation.ts b/apps/web/src/features/notifications/notification-navigation.tsindex 1ebe03f8a2..5dca066a22 100644--- a/apps/web/src/features/notifications/notification-navigation.ts+++ b/apps/web/src/features/notifications/notification-navigation.ts@@ -5,6 +5,7 @@ import {getChannelParams,navigateToChannelMessage,} from '@block-channel/utils/link';+import { prefetchChannelTarget } from '@channel/queries/prefetch-channel-target';import { contentReference } from '@components/app/split-layout/content-reference';import type {OpenSplitResult,@@ -24,10 +25,12 @@ import {import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';import { isTouchDevice } from '@core/mobile/isTouchDevice';import type { NotificationType } from '@core/types';+import { fireAndForget } from '@core/util/fireAndForget';import { catchToResult } from '@core/util/result';import { openExternalUrl } from '@core/util/url';import { Telemetry } from '@macro-inc/observability';import { getNotificationById } from '@queries/notification/user-notifications';+import type { PushNotificationNavigation } from '@service-notification/generated/schemas/pushNotificationNavigation';import { errAsync, ResultAsync } from 'neverthrow';import { match, P } from 'ts-pattern';import { shareEntity } from '../access-requests/core/types';@@ -119,7 +122,7 @@ export function getChannelNotificationParams(})).with({ tag: 'channel_message_send' }, (m) => ({messageId: m.content.messageId,- threadId: undefined,+ threadId: m.content.messageId,})).with({ tag: 'channel_message_reaction' }, (m) => ({messageId: m.content.messageId,@@ -655,8 +658,34 @@ export function openNotificationFromId(notificationId: string,layoutManager: SplitManager,notificationSource: NotificationSource,- options: { canOpen?: () => boolean; onApplied?: VoidFunction } = {}+ options: {+ canOpen?: () => boolean;+ onApplied?: VoidFunction;+ target?: PushNotificationNavigation;+ } = {}): ResultAsync<void, OpenNotificationFromIdError> {+ if (options.target) {+ if (options.canOpen && !options.canOpen()) {+ return errAsync({ tag: 'NavigationDeferredError', notificationId });+ }+ const { channelId, messageId, threadId } = options.target;+ fireAndForget(+ prefetchChannelTarget(channelId, {+ messageId,+ threadId: threadId ?? messageId,+ }),+ 'notification-navigation'+ );+ return ResultAsync.fromSafePromise(+ navigateToChannelMessage(+ layoutManager.getOrchestrator(),+ channelId,+ messageId,+ threadId ?? messageId,+ { splitManager: layoutManager, onApplied: options.onApplied }+ )+ );+ }const openIfReady = (notification: UnifiedNotification) => {if (options.canOpen && !options.canOpen()) {return errAsync({diff --git a/apps/web/src/features/notifications/notification-open-trace.ts b/apps/web/src/features/notifications/notification-open-trace.tsnew file mode 100644index 0000000000..ed5f7164fb--- /dev/null+++ b/apps/web/src/features/notifications/notification-open-trace.ts@@ -0,0 +1,61 @@+import { type Span, Telemetry } from '@macro-inc/observability';++type Target = { channelId: string; messageId: string };+let active: { notificationId: string; target?: Target; span: Span } | undefined;+let timeout: ReturnType<typeof setTimeout> | undefined;++/** A notification open outlives the native callback and ends at target positioning. */+export function startNotificationOpen(+ notificationId: string,+ target?: Target,+ receivedAtMs?: number,+ deliveryId?: string+): void {+ endNotificationOpen('superseded');+ const span = Telemetry.span('notification.open');+ span.setAttr('notification.id', notificationId);+ span.setAttr('notification.direct_target', !!target);+ if (deliveryId) span.setAttr('notification.delivery_id', deliveryId);+ if (target) {+ span.setAttr('channel.id', target.channelId);+ span.setAttr('message.id', target.messageId);+ }+ if (receivedAtMs !== undefined) {+ span.setAttr(+ 'notification.native_handoff_ms',+ Math.max(0, Date.now() - receivedAtMs)+ );+ }+ active = { notificationId, target, span };+ timeout = setTimeout(() => endNotificationOpen('target_not_visible'), 60_000);+}++export function notificationOpenSpan(notificationId: string): Span | undefined {+ return active?.notificationId === notificationId ? active.span : undefined;+}++export function notificationTargetSpan(+ channelId: string,+ messageId: string+): Span | undefined {+ return active?.target?.channelId === channelId &&+ active.target.messageId === messageId+ ? active.span+ : undefined;+}++export function markNotificationTargetVisible(+ channelId: string,+ messageId: string+): void {+ if (!notificationTargetSpan(channelId, messageId)) return;+ active?.span.event('notification.target_visible');+ endNotificationOpen('visible');+}++export function endNotificationOpen(outcome: string): void {+ clearTimeout(timeout);+ active?.span.setAttr('notification.outcome', outcome);+ active?.span.end();+ active = undefined;+}diff --git a/apps/web/src/features/notifications/tests/calendar-join-request-navigation.test.ts b/apps/web/src/features/notifications/tests/calendar-join-request-navigation.test.tsindex 80d90403d2..274d5204ae 100644--- a/apps/web/src/features/notifications/tests/calendar-join-request-navigation.test.ts+++ b/apps/web/src/features/notifications/tests/calendar-join-request-navigation.test.ts@@ -33,6 +33,9 @@ vi.mock('@block-channel/utils/link', () => ({getChannelParams: vi.fn(),navigateToChannelMessage: vi.fn(),}));+vi.mock('@channel/queries/prefetch-channel-target', () => ({+ prefetchChannelTarget: vi.fn(async () => {}),+}));vi.mock('@core/constant/allBlocks', () => ({itemToBlockName: (value: { fileType: string }) => value.fileType,resolveBlockAlias: (type: string) => type,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 23aa645c89..dc701e4da5 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,9 +1,14 @@import { createRoutedSplitLayout } from '@components/app/split-layout/tests/fixtures';import { toast } from '@core/component/Toast/Toast';import type { BlockOrchestrator } from '@core/orchestrator';+import { getNotificationById } from '@queries/notification/user-notifications';import { createRoot } from 'solid-js';import { beforeEach, expect, it, onTestFinished, vi } from 'vitest';-import { openNotification } from '../notification-navigation';+import {+ openNotification,+ openNotificationFromId,+} from '../notification-navigation';+import type { NotificationSource } from '../notification-source';import type { UnifiedNotification } from '../types';vi.mock('@app/signal/splitLayout', () => ({@@ -41,6 +46,9 @@ vi.mock('@core/util/url', () => ({ openExternalUrl: vi.fn() }));vi.mock('@queries/notification/user-notifications', () => ({getNotificationById: vi.fn(),}));+vi.mock('@channel/queries/prefetch-channel-target', () => ({+ prefetchChannelTarget: vi.fn(async () => {}),+}));vi.mock('@queries/reminders/reminders', () => ({ getReminderById: vi.fn() }));vi.mock('../notification-resolvers', () => ({DefaultNotificationBlockNameResolver: vi.fn(),@@ -128,7 +136,7 @@ it.each([expect(navigate).toHaveBeenCalledWith({channel_message_id: 'message',...(tag === 'channel_message_send'- ? {}+ ? { channel_thread_id: 'message' }: { channel_thread_id: 'thread' }),});@@ -138,6 +146,30 @@ it.each([});+it('opens a direct push target without looking up the notification or loading the feed', async () => {+ const { layout, navigate } = setup('closed');+ const notifications = vi.fn();+ const source = { notifications } as unknown as NotificationSource;+ const onApplied = vi.fn();+ const result = await openNotificationFromId('notification', layout, source, {+ target: {+ type: 'channel',+ channelId: 'channel',+ messageId: 'message',+ threadId: null,+ },+ onApplied,+ });+ expect(result.isOk()).toBe(true);+ expect(notifications).not.toHaveBeenCalled();+ expect(getNotificationById).not.toHaveBeenCalled();+ expect(navigate).toHaveBeenCalledWith({+ channel_message_id: 'message',+ channel_thread_id: 'message',+ });+ expect(onApplied).toHaveBeenCalledOnce();+});+it.each(['channel_invite', 'call_started'] as const)('activates the existing preview for %s without opening a split',async (tag) => {@@ -196,6 +228,9 @@ it.each(['split', 'closed'] as const)(expect(createBlockInstance).toHaveBeenCalledOnce();if (location === 'split') expect(layout.activeSplitId()).toBe(first.id);expect(toast.alert).not.toHaveBeenCalled();- expect(navigate).toHaveBeenCalledWith({ channel_message_id: 'message' });+ expect(navigate).toHaveBeenCalledWith({+ channel_message_id: 'message',+ channel_thread_id: 'message',+ });});diff --git a/apps/web/src/features/notifications/tests/crm-discussion-navigation.test.ts b/apps/web/src/features/notifications/tests/crm-discussion-navigation.test.tsindex a0af3dd82e..833a2bb48d 100644--- a/apps/web/src/features/notifications/tests/crm-discussion-navigation.test.ts+++ b/apps/web/src/features/notifications/tests/crm-discussion-navigation.test.ts@@ -146,3 +146,6 @@ it.each(records)();});+vi.mock('@channel/queries/prefetch-channel-target', () => ({+ prefetchChannelTarget: vi.fn(async () => {}),+}));diff --git a/apps/web/src/features/notifications/tests/reminder-navigation.test.ts b/apps/web/src/features/notifications/tests/reminder-navigation.test.tsindex d5cfa72b50..376ef679ed 100644--- a/apps/web/src/features/notifications/tests/reminder-navigation.test.ts+++ b/apps/web/src/features/notifications/tests/reminder-navigation.test.ts@@ -137,3 +137,6 @@ describe('reminder notification navigation', () => {expect(openWithSplit).not.toHaveBeenCalled();});});+vi.mock('@channel/queries/prefetch-channel-target', () => ({+ prefetchChannelTarget: vi.fn(async () => {}),+}));diff --git a/apps/web/src/features/notifications/tests/spreadsheet-comment-navigation.test.ts b/apps/web/src/features/notifications/tests/spreadsheet-comment-navigation.test.tsindex 3b8c71f4cd..13fa070149 100644--- a/apps/web/src/features/notifications/tests/spreadsheet-comment-navigation.test.ts+++ b/apps/web/src/features/notifications/tests/spreadsheet-comment-navigation.test.ts@@ -316,3 +316,6 @@ it('does not open project notifications when the rollout is disabled', async ()expect(open).not.toHaveBeenCalled();expect(activate).not.toHaveBeenCalled();});+vi.mock('@channel/queries/prefetch-channel-target', () => ({+ prefetchChannelTarget: vi.fn(async () => {}),+}));diff --git a/apps/web/src/index.tsx b/apps/web/src/index.tsxindex 0896a009bf..cca523bcdf 100644--- a/apps/web/src/index.tsx+++ b/apps/web/src/index.tsx@@ -15,6 +15,7 @@ import { Telemetry } from '@macro-inc/observability';import { initMonochromeIcons } from '@ui/utils/monochromeIcons';import { ErrorBoundary, render } from 'solid-js/web';import { FatalError } from './components/app/FatalError';+import { prepareNotificationLaunch } from './lib/tauri/notification-launch';import { perfMark } from './observability/perf-marks';import { Root } from './routes/Root';@@ -105,6 +106,11 @@ async function main() {perfMark('boot.main');await initializeBrowserObservability();perfMark('boot.observability-ready');+ try {+ await prepareNotificationLaunch();+ } catch (error) {+ Telemetry.error(error, { surface: 'notification-launch' });+ }console.log('App Version ', import.meta.env.__APP_VERSION__);diff --git a/apps/web/src/lib/core/component/EntityLoadGate.test.tsx b/apps/web/src/lib/core/component/EntityLoadGate.test.tsxindex e1b5b3f919..3252279304 100644--- a/apps/web/src/lib/core/component/EntityLoadGate.test.tsx+++ b/apps/web/src/lib/core/component/EntityLoadGate.test.tsx@@ -3,6 +3,7 @@*/import { ThrownResultError } from '@core/util/result';+import { createSignal, type JSX } from 'solid-js';import { render } from 'solid-js/web';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -41,12 +42,15 @@ import {let dispose: (() => void) | undefined;-function renderGate<Data>(result: EntityLoadResult<Data>): HTMLElement {+function renderGate<Data>(+ result: EntityLoadResult<Data>,+ loadingFallback?: JSX.Element+): HTMLElement {const container = document.createElement('div');document.body.appendChild(container);const disposeRender = render(() => (- <EntityLoadGate result={result}>+ <EntityLoadGate result={result} loadingFallback={loadingFallback}><div>Loaded</div></EntityLoadGate>),@@ -67,6 +71,23 @@ afterEach(() => {});describe('EntityLoadGate', () => {+ it('uses the conversation placeholder while pending without masking access failures', () => {+ const [pending, setPending] = createSignal(true);+ const [error, setError] = createSignal<EntityLoadErrorCode>();+ const container = renderGate(+ {+ data: () => undefined,+ error,+ isPending: pending,+ },+ <div>Conversation placeholder</div>+ );+ expect(container.textContent).toBe('Conversation placeholder');+ setPending(false);+ setError('FORBIDDEN');+ expect(container.textContent).toBe('Unauthorized');+ });+it('renders its child after data loads', () => {const container = renderGate({data: () => 'channel data',diff --git a/apps/web/src/lib/core/component/EntityLoadGate.tsx b/apps/web/src/lib/core/component/EntityLoadGate.tsxindex dfbd6404ef..a56961de6d 100644--- a/apps/web/src/lib/core/component/EntityLoadGate.tsx+++ b/apps/web/src/lib/core/component/EntityLoadGate.tsx@@ -46,6 +46,8 @@ type EntityLoadGateProps<Data> = {onRetry?: () => void;/** Entity-specific title for the `LOAD_FAILED` state. */loadErrorTitle?: string;+ /** Keep an entity's loading geometry consistent across its data boundaries. */+ loadingFallback?: JSX.Element;children: JSX.Element;};@@ -132,7 +134,7 @@ export function EntityLoadGate<Data>(props: EntityLoadGateProps<Data>) {const hasData = () => props.result.data() !== undefined;return (- <Suspense fallback={<LoadingBlock />}>+ <Suspense fallback={props.loadingFallback ?? <LoadingBlock />}><Switchfallback={<div class="flex flex-col items-center justify-center h-full text-lg">@@ -166,7 +168,7 @@ export function EntityLoadGate<Data>(props: EntityLoadGateProps<Data>) {/></Match><Match when={props.result.isPending()}>- <LoadingBlock />+ {props.loadingFallback ?? <LoadingBlock />}</Match><Match when={hasData()}>{props.children}</Match></Switch>diff --git a/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx b/apps/web/src/lib/core/component/TopBar/shareModal.test.tsxindex 46441ac7b2..40a5bff75d 100644--- a/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx+++ b/apps/web/src/lib/core/component/TopBar/shareModal.test.tsx@@ -51,6 +51,7 @@ vi.mock('@core/context/team', () => ({}));vi.mock('@core/context/user', () => ({useUserId: () => () => 'test-user',+ useUserInfo: () => () => ({ userId: 'test-user' }),useIsAuthenticated: () => () => true,}));vi.mock('@core/orchestrator', () => ({diff --git a/apps/web/src/lib/service-clients/service-notification/generated/push.ts b/apps/web/src/lib/service-clients/service-notification/generated/push.tsnew file mode 100644index 0000000000..3ec508b09e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/push.ts@@ -0,0 +1,26 @@+/* Generated by scripts/generate-push-schema.ts. Do not edit manually. */+import { z } from 'zod';++export const pushNotificationNavigation = z.object({+ channelId: z.string().uuid(),+ messageId: z.string().uuid(),+ threadId: z.union([z.string().uuid(), z.null()]),+ type: z.literal('channel'),+});++export const pushNotificationData = z.object({+ navigation: z+ .union([+ z.null(),+ z.object({+ channelId: z.string().uuid(),+ messageId: z.string().uuid(),+ threadId: z.union([z.string().uuid(), z.null()]),+ type: z.literal('channel'),+ }),+ ])+ .optional(),+ notificationId: z.string().uuid(),+ recipientId: z.union([z.string(), z.null()]).optional(),+ senderProfilePictureUrl: z.union([z.string(), z.null()]).optional(),+});diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.tsindex 59c01fae98..eb759dc091 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts@@ -226,7 +226,13 @@ export * from './notificationServiceApiVersion';export * from './notificationState';export * from './notificationTypeName';export * from './pushNotificationData';+export * from './pushNotificationDataNavigation';+export * from './pushNotificationDataRecipientId';export * from './pushNotificationDataSenderProfilePictureUrl';+export * from './pushNotificationNavigation';+export * from './pushNotificationNavigationOneOf';+export * from './pushNotificationNavigationOneOfThreadId';+export * from './pushNotificationNavigationOneOfType';export * from './realtimeNotifTaggedContentValue';export * from './realtimeNotifTaggedContentValueAllOf';export * from './realtimeNotifTaggedContentValueAllOfDeletedAt';diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationData.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationData.tsindex 1bf352672e..8028007d79 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationData.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationData.ts@@ -4,11 +4,20 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { PushNotificationDataNavigation } from './pushNotificationDataNavigation';+import type { PushNotificationDataRecipientId } from './pushNotificationDataRecipientId';import type { PushNotificationDataSenderProfilePictureUrl } from './pushNotificationDataSenderProfilePictureUrl';+/**+ * the value we send as the payload in the ios notification+This data is accessible to the client+ */export interface PushNotificationData {+ navigation?: PushNotificationDataNavigation;/** The id of the notification record (UserNotification.id) */notificationId: string;+ /** Account that owns the receiving device, set during per-recipient delivery. */+ recipientId?: PushNotificationDataRecipientId;/** The sender's profile picture URL, used by the Notification Service Extensionto download and attach as a rich notification image. */senderProfilePictureUrl?: PushNotificationDataSenderProfilePictureUrl;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationDataNavigation.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationDataNavigation.tsnew file mode 100644index 0000000000..538935160d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationDataNavigation.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { PushNotificationNavigation } from './pushNotificationNavigation';++export type PushNotificationDataNavigation = null | PushNotificationNavigation;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationDataRecipientId.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationDataRecipientId.tsnew file mode 100644index 0000000000..ab0a71ea7f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationDataRecipientId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Account that owns the receiving device, set during per-recipient delivery.+ */+export type PushNotificationDataRecipientId = string | null;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigation.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigation.tsnew file mode 100644index 0000000000..cf0a2d2add--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigation.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { PushNotificationNavigationOneOf } from './pushNotificationNavigationOneOf';++/**+ * A destination carried by a push notification. Access is checked when opened.+ */+export type PushNotificationNavigation = PushNotificationNavigationOneOf;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigationOneOf.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigationOneOf.tsnew file mode 100644index 0000000000..fc8bda7db3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigationOneOf.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { PushNotificationNavigationOneOfThreadId } from './pushNotificationNavigationOneOfThreadId';+import type { PushNotificationNavigationOneOfType } from './pushNotificationNavigationOneOfType';++/**+ * Open a channel at a specific message.+ */+export type PushNotificationNavigationOneOf = {+ /** Channel containing the message. */+ channelId: string;+ /** Message to highlight. */+ messageId: string;+ /** Root of the message's thread; null identifies a top-level message. */+ threadId: PushNotificationNavigationOneOfThreadId;+ type: PushNotificationNavigationOneOfType;+};diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigationOneOfThreadId.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigationOneOfThreadId.tsnew file mode 100644index 0000000000..f65fffa5f2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigationOneOfThreadId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Root of the message's thread; null identifies a top-level message.+ */+export type PushNotificationNavigationOneOfThreadId = string | null;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigationOneOfType.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigationOneOfType.tsnew file mode 100644index 0000000000..0cf1f9d03a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/pushNotificationNavigationOneOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type PushNotificationNavigationOneOfType =+ (typeof PushNotificationNavigationOneOfType)[keyof typeof PushNotificationNavigationOneOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const PushNotificationNavigationOneOfType = {+ channel: 'channel',+} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.jsonindex 568262bb75..8499efa7db 100644--- a/apps/web/src/lib/service-clients/service-notification/openapi.json+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json@@ -2982,19 +2982,66 @@},"PushNotificationData": {"type": "object",+ "description": "the value we send as the payload in the ios notification\nThis data is accessible to the client","required": ["notificationId"],"properties": {+ "navigation": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/PushNotificationNavigation",+ "description": "Destination to open without fetching the notification record first."+ }+ ]+ },"notificationId": {"type": "string","format": "uuid","description": "The id of the notification record (UserNotification.id)"},+ "recipientId": {+ "type": ["string", "null"],+ "description": "Account that owns the receiving device, set during per-recipient delivery."+ },"senderProfilePictureUrl": {"type": ["string", "null"],"description": "The sender's profile picture URL, used by the Notification Service Extension\nto download and attach as a rich notification image."}}},+ "PushNotificationNavigation": {+ "oneOf": [+ {+ "type": "object",+ "description": "Open a channel at a specific message.",+ "required": ["channelId", "messageId", "threadId", "type"],+ "properties": {+ "channelId": {+ "type": "string",+ "format": "uuid",+ "description": "Channel containing the message."+ },+ "messageId": {+ "type": "string",+ "format": "uuid",+ "description": "Message to highlight."+ },+ "threadId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Root of the message's thread; null identifies a top-level message."+ },+ "type": {+ "type": "string",+ "enum": ["channel"]+ }+ }+ }+ ],+ "description": "A destination carried by a push notification. Access is checked when opened."+ },"RealtimeNotif_TaggedContent_Value": {"allOf": [{diff --git a/apps/web/src/lib/tauri/PushNotification.test.tsx b/apps/web/src/lib/tauri/PushNotification.test.tsxindex 62a8d4c21b..17fa1913dd 100644--- a/apps/web/src/lib/tauri/PushNotification.test.tsx+++ b/apps/web/src/lib/tauri/PushNotification.test.tsx@@ -1,7 +1,11 @@import {+ finishNotificationNavigation,+ pendingNotificationNavigation,pendingNotificationNavigationId,setPendingNotificationNavigationId,} from '@notifications/notification-navigation-intent';+import { endNotificationOpen } from '@notifications/notification-open-trace';+import { waitFor } from '@solidjs/testing-library';import { createRoot } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { MaybePushNotificationRegistration } from './PushNotification';@@ -10,11 +14,18 @@ import type { PushEvent } from './push-api';const registration = vi.hoisted(() => ({os: 'android',version: '16',+ signedIn: true,sync: undefined as (() => Promise<void>) | undefined,+ logout: undefined as (() => Promise<void>) | undefined,+ onEvent: undefined as ((event: PushEvent) => void) | undefined,register: vi.fn(async () => ({ isErr: () => false })),+ configureRecipient: vi.fn(async (_recipientId: string | null) => {}),+ acknowledge: vi.fn(async (_deliveryId: string) => {}),+ clearPending: vi.fn(async () => {}),+ releaseCover: vi.fn(async () => {}),+ removeAllActive: vi.fn(async () => {}),receive: undefined as ((event: PushEvent) => void) | undefined,buffered: undefined as PushEvent | undefined,- acknowledge: vi.fn(async (_deliveryId: string) => {}),}));vi.mock('@core/constant/featureFlags', () => ({ ENABLE_CALLKIT: true }));vi.mock('@core/util/platform', () => ({@@ -24,12 +35,16 @@ vi.mock('@core/util/platform', () => ({vi.mock('@tauri-apps/plugin-os', () => ({version: () => registration.version,}));-vi.mock('@core/util/cookies', () => ({ hasLoginCookie: () => true }));+vi.mock('@core/util/cookies', () => ({+ hasLoginCookie: () => registration.signedIn,+}));vi.mock('@core/auth/push-registration-lifecycle', () => ({registerPushRegistrationLifecycle: (hooks: {syncRegistration: () => Promise<void>;+ unregisterForLogout: () => Promise<void>;}) => {registration.sync = hooks.syncRegistration;+ registration.logout = hooks.unregisterForLogout;return () => {};},syncPushRegistrations: async () => {},@@ -43,7 +58,7 @@ vi.mock('@solid-primitives/storage', () => ({makePersisted: (signal: unknown) => signal,}));vi.mock('@tauri-apps/plugin-notification', () => ({- removeAllActive: async () => {},+ removeAllActive: registration.removeAllActive,}));vi.mock('@notifications', async () => ({PlatformNotificationProvider: () => null,@@ -59,22 +74,28 @@ vi.mock('./push-api', () => ({createPushApi: () => ({checkPermissions: async () => ({ status: 'granted' }),register: async () => ({ token: 'test-device-token' }),- configureRecipient: async () => {},+ configureRecipient: registration.configureRecipient,watch: async (callback: (event: PushEvent) => void) => {+ registration.onEvent = callback;registration.receive = callback;if (registration.buffered) callback(registration.buffered);},unwatch: async () => {},acknowledge: registration.acknowledge,+ clearPending: registration.clearPending,}),+ releaseNotificationCover: registration.releaseCover,}));let dispose: (() => void) | undefined;beforeEach(() => {registration.os = 'android';registration.version = '16';+ registration.signedIn = true;registration.sync = undefined;- registration.register.mockClear();+ registration.logout = undefined;+ registration.onEvent = undefined;+ vi.clearAllMocks();registration.receive = undefined;registration.buffered = undefined;registration.acknowledge.mockClear();@@ -85,6 +106,7 @@ afterEach(() => {dispose?.();dispose = undefined;setPendingNotificationNavigationId(undefined);+ endNotificationOpen('test_complete');delete window.__MACRO_ANDROID_CALL_KIT__;});@@ -108,6 +130,8 @@ describe.each(['ios', 'android'])('%s push notification navigation', (os) => {deliveryId: 'mobile-delivery',});expect(pendingNotificationNavigationId()).toBe('mobile-notification');+ expect(registration.acknowledge).not.toHaveBeenCalled();+ finishNotificationNavigation(pendingNotificationNavigation()!);expect(registration.acknowledge).toHaveBeenCalledExactlyOnceWith('mobile-delivery');@@ -169,6 +193,13 @@ describe.each(['ios', 'android'])('%s push notification navigation', (os) => {});});+function mountRegistration() {+ createRoot((cleanup) => {+ dispose = cleanup;+ MaybePushNotificationRegistration({ children: null });+ });+}+describe('push registration native-call capability', () => {it.each([{ os: 'android', version: '16', binary: true, expected: true },@@ -181,10 +212,7 @@ describe('push registration native-call capability', () => {registration.os = os;registration.version = version;if (binary) window.__MACRO_ANDROID_CALL_KIT__ = true;- createRoot((cleanup) => {- dispose = cleanup;- MaybePushNotificationRegistration({ children: null });- });+ mountRegistration();expect(registration.sync).toBeDefined();await registration.sync!();expect(registration.register).toHaveBeenCalledExactlyOnceWith({@@ -195,3 +223,96 @@ describe('push registration native-call capability', () => {});});++describe('iOS notification launch integration', () => {+ const tap: PushEvent = {+ type: 'BACKGROUND_TAP',+ deliveryId: 'delivery-1',+ receivedAtMs: 123,+ payload: {+ notificationId: 'notification-1',+ recipientId: 'macro|[email protected]',+ navigation: JSON.stringify({+ type: 'channel',+ channelId: '11111111-1111-4111-8111-111111111111',+ messageId: '22222222-2222-4222-8222-222222222222',+ threadId: null,+ }),+ },+ };++ beforeEach(() => {+ registration.os = 'ios';+ });++ it('binds the iOS receiver to the actual registered recipient', async () => {+ mountRegistration();+ await registration.sync!();+ expect(registration.configureRecipient).toHaveBeenCalledExactlyOnceWith(+ 'macro|[email protected]'+ );+ });++ it('retains a delivered tap until navigation and native acknowledgment finish', async () => {+ let completeAcknowledgment!: () => void;+ registration.acknowledge.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ completeAcknowledgment = resolve;+ })+ );+ mountRegistration();+ await waitFor(() => expect(registration.onEvent).toBeDefined());+ registration.onEvent!(tap);+ const intent = pendingNotificationNavigation();+ expect(intent).toMatchObject({+ notificationId: 'notification-1',+ deliveryId: 'delivery-1',+ target: { messageId: '22222222-2222-4222-8222-222222222222' },+ });+ expect(registration.acknowledge).not.toHaveBeenCalled();++ finishNotificationNavigation(intent!);+ expect(registration.acknowledge).toHaveBeenCalledExactlyOnceWith(+ 'delivery-1'+ );+ expect(pendingNotificationNavigation()).toBe(intent);+ completeAcknowledgment();+ await waitFor(() =>+ expect(pendingNotificationNavigation()).toBeUndefined()+ );+ });++ it('retains a signed-out tap and reveals the sign-in UI', async () => {+ registration.signedIn = false;+ mountRegistration();+ await waitFor(() => expect(registration.onEvent).toBeDefined());+ registration.onEvent!(tap);+ await waitFor(() =>+ expect(registration.releaseCover).toHaveBeenCalledOnce()+ );+ expect(pendingNotificationNavigation()).toMatchObject({+ notificationId: 'notification-1',+ deliveryId: 'delivery-1',+ });+ expect(registration.acknowledge).not.toHaveBeenCalled();+ expect(registration.clearPending).not.toHaveBeenCalled();+ expect(registration.configureRecipient).not.toHaveBeenCalled();+ });++ it('clears the pending tap and disarms the receiver on explicit logout', async () => {+ mountRegistration();+ await waitFor(() => expect(registration.onEvent).toBeDefined());+ registration.onEvent!(tap);+ expect(pendingNotificationNavigation()).toBeDefined();+ registration.signedIn = false;+ await registration.logout!();+ expect(pendingNotificationNavigation()).toBeUndefined();+ expect(registration.clearPending).toHaveBeenCalledOnce();+ expect(registration.configureRecipient).toHaveBeenCalledExactlyOnceWith(+ null+ );+ expect(registration.removeAllActive).toHaveBeenCalledOnce();+ expect(registration.acknowledge).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/tauri/PushNotification.tsx b/apps/web/src/lib/tauri/PushNotification.tsxindex d533810933..46bba54609 100644--- a/apps/web/src/lib/tauri/PushNotification.tsx+++ b/apps/web/src/lib/tauri/PushNotification.tsx@@ -5,15 +5,16 @@ import {} from '@core/auth/push-registration-lifecycle';import { hasLoginCookie } from '@core/util/cookies';import { fireAndForget } from '@core/util/fireAndForget';-import type {- NotificationEvent,- NotificationRegistrationResult,-} from '@inkibra/tauri-plugins/packages/tauri-plugin-notifications';+import type { NotificationRegistrationResult } from '@inkibra/tauri-plugins/packages/tauri-plugin-notifications';import {type PlatformNotificationInterface,PlatformNotificationProvider,- triggerNotificationNavigation,} from '@notifications';+import {+ receiveNotificationTap,+ setPendingNotificationNavigationId,+} from '@notifications/notification-navigation-intent';+import { endNotificationOpen } from '@notifications/notification-open-trace';import {fetchPushRecipient,registerPushDevice,@@ -30,17 +31,19 @@ import {onCleanup,} from 'solid-js';import { createTauriNotificationInterface } from './notification';-import { createPushApi, type PushEvent } from './push-api';+import {+ createPushApi,+ type PushEvent,+ releaseNotificationCover,+} from './push-api';import { useExpectTauri } from './TauriProvider';-function getNotificationId(payload: Record<string, unknown>) {- const value = payload.notificationId;- return typeof value === 'string' && value.length > 0 ? value : undefined;-}-function usePushNotifications(deviceType: 'android' | 'ios',- onPushNotification?: (event: NotificationEvent) => void+ onPushNotification?: (+ event: PushEvent,+ acknowledge: (deliveryId: string) => Promise<void>+ ) => boolean) {const api = createPushApi(deviceType);// Bumped by every registration-changing action so an in-flight one can@@ -139,10 +142,8 @@ function usePushNotifications(if (res.isErr()) throw new Error('failed to unregister device for push');}- // The native receiver only displays pushes addressed to this account, so- // Android needs the user id before it can be armed. iOS has no such gate.+ // Bind both native receivers to the account that owns the registration.async function fetchRecipient(): Promise<string | null | undefined> {- if (deviceType !== 'android') return null;try {return await fetchPushRecipient();} catch (error) {@@ -261,11 +262,14 @@ function usePushNotifications(}async function unregisterForLogout() {+ setPendingNotificationNavigationId(undefined);+ endNotificationOpen('logout');// The logged-out account's already-delivered notifications must not// linger in the system notification center for the next account to see.await Promise.all([clearDisplayedNotifications(),unregisterPushNotifications(false),+ api.clearPending(),]);}@@ -306,7 +310,13 @@ function usePushNotifications(async function reconcileOnLaunch() {const epoch = registrationEpoch;try {- if (!hasLoginCookie() || pushDisabledByUser()) {+ if (!hasLoginCookie()) {+ // A tapped destination may still be awaiting sign-in. Explicit logout+ // clears it through unregisterForLogout; startup must not discard it.+ setPermission(undefined);+ return;+ }+ if (pushDisabledByUser()) {setPermission(undefined);await configureRecipient(null, epoch);return;@@ -355,14 +365,20 @@ function usePushNotifications(}async function handlePushEvent(event: PushEvent) {- if (disposed || !hasLoginCookie()) return;+ if (disposed) return;try {+ if (!hasLoginCookie()) {+ onPushNotification?.(event, api.acknowledge);+ await releaseNotificationCover();+ return;+ }if (event.type === 'TOKEN_REFRESH' || event.type === 'RESUME') {await syncPushRegistrations('resume');return;}- onPushNotification?.(event);- if (event.deliveryId) await api.acknowledge(event.deliveryId);+ const pendingNavigation = onPushNotification?.(event, api.acknowledge);+ if (event.deliveryId && !pendingNavigation)+ await api.acknowledge(event.deliveryId);} catch (error) {console.error('push event handling failed', error);}@@ -401,18 +417,7 @@ export function MaybePushNotificationRegistration(props: {);}- const push = usePushNotifications(os, (event) => {- const notificationId = getNotificationId(event.payload);-- const tapped =- event.type === 'BACKGROUND_TAP' || event.type === 'FOREGROUND_TAP';-- // Only navigate on explicit user interaction.- if (!tapped) return;- if (!notificationId) return;-- triggerNotificationNavigation(notificationId);- });+ const push = usePushNotifications(os, receiveNotificationTap);// now we compose the standard tauri notif plugin with the push notification pluginfunction curriedTauriPushNotification(diff --git a/apps/web/src/lib/tauri/notification-launch.test.ts b/apps/web/src/lib/tauri/notification-launch.test.tsnew file mode 100644index 0000000000..d82a0e999d--- /dev/null+++ b/apps/web/src/lib/tauri/notification-launch.test.ts@@ -0,0 +1,149 @@+import {+ pendingNotificationNavigation,+ setPendingNotificationNavigationId,+} from '@notifications/notification-navigation-intent';+import { endNotificationOpen } from '@notifications/notification-open-trace';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { prepareNotificationLaunch } from './notification-launch';+import type { PushEvent } from './push-api';++const bridge = vi.hoisted(() => ({+ supported: true,+ watch: vi.fn(),+ pending: vi.fn(),+ acknowledge: vi.fn(),+ releaseCover: vi.fn(),+}));+vi.mock('./push-api', () => ({+ supportsNotificationLaunch: () => bridge.supported,+ createPushApi: () => bridge,+ releaseNotificationCover: bridge.releaseCover,+}));++beforeEach(() => {+ vi.useFakeTimers();+ bridge.supported = true;+ bridge.watch.mockResolvedValue(undefined);+ bridge.pending.mockResolvedValue(null);+ bridge.acknowledge.mockResolvedValue(undefined);+ bridge.releaseCover.mockResolvedValue(undefined);+ window.history.replaceState(null, '', '/app/#/channels/previous-channel');+});+afterEach(() => {+ vi.resetAllMocks();+ setPendingNotificationNavigationId(undefined);+ endNotificationOpen('test_complete');+ vi.useRealTimers();+});++it('captures a cold-launch tap before the router restores the previous channel', async () => {+ bridge.pending.mockResolvedValue({+ type: 'BACKGROUND_TAP',+ payload: { notificationId: 'notification' },+ deliveryId: 'cold-launch',+ });+ await prepareNotificationLaunch();+ expect(bridge.watch.mock.invocationCallOrder[0]).toBeLessThan(+ bridge.pending.mock.invocationCallOrder[0]+ );+ expect(window.location.hash).toBe('#/');+ expect(pendingNotificationNavigation()?.notificationId).toBe('notification');+ expect(bridge.acknowledge).not.toHaveBeenCalled();+});++it('keeps ordinary icon launches on their restored route', async () => {+ await prepareNotificationLaunch();+ expect(window.location.hash).toBe('#/channels/previous-channel');+ expect(vi.getTimerCount()).toBe(0);+ expect(bridge.releaseCover).not.toHaveBeenCalled();+});++it('does not call new native commands on older iOS binaries', async () => {+ bridge.supported = false;+ await prepareNotificationLaunch();+ expect(bridge.watch).not.toHaveBeenCalled();+ expect(bridge.pending).not.toHaveBeenCalled();+});++it.each(['watch', 'pending'] as const)(+ 'releases startup after a stalled %s and queues late taps without resetting the live route',+ async (phase) => {+ let release!: () => void;+ const stalled = new Promise<void>((resolve) => {+ release = resolve;+ });+ const tap: PushEvent = {+ type: 'BACKGROUND_TAP',+ payload: { notificationId: 'late-notification' },+ deliveryId: 'late-delivery',+ };+ bridge.watch.mockImplementation(async () => {+ if (phase === 'watch') await stalled;+ });+ bridge.pending.mockImplementation(async () => {+ if (phase === 'pending') await stalled;+ return tap;+ });+ // A stalled cover-release command must not become a second startup gate.+ bridge.releaseCover.mockImplementation(() => new Promise(() => {}));+ const finished = vi.fn();+ const launch = (async () => {+ await prepareNotificationLaunch();+ finished();+ })();+ await vi.advanceTimersByTimeAsync(1499);+ expect(finished).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(finished).toHaveBeenCalledOnce();+ await launch;+ expect(bridge.releaseCover).toHaveBeenCalledOnce();+ expect(window.location.hash).toBe('#/channels/previous-channel');++ window.history.replaceState(null, '', '/app/#/channels/current-channel');+ release();+ await vi.advanceTimersByTimeAsync(0);+ expect(pendingNotificationNavigation()?.notificationId).toBe(+ 'late-notification'+ );+ expect(window.location.hash).toBe('#/channels/current-channel');+ expect(bridge.acknowledge).not.toHaveBeenCalled();+ }+);++it('preserves a buffered tap when the pending snapshot stalls', async () => {+ bridge.watch.mockImplementation(+ async (receive: (event: PushEvent) => void) => {+ receive({+ type: 'BACKGROUND_TAP',+ payload: { notificationId: 'buffered-notification' },+ deliveryId: 'buffered-delivery',+ });+ }+ );+ bridge.pending.mockImplementation(() => new Promise(() => {}));+ const finished = vi.fn();+ const launch = (async () => {+ await prepareNotificationLaunch();+ finished();+ })();+ await vi.advanceTimersByTimeAsync(1500);+ expect(finished).toHaveBeenCalledOnce();+ await launch;+ expect(window.location.hash).toBe('#/');+ expect(pendingNotificationNavigation()?.notificationId).toBe(+ 'buffered-notification'+ );+ expect(bridge.acknowledge).not.toHaveBeenCalled();+});++it.each(['watch', 'pending'] as const)(+ 'releases the native cover when %s rejects',+ async (phase) => {+ bridge[phase].mockRejectedValue(new Error('bridge unavailable'));+ await prepareNotificationLaunch();+ expect(bridge.releaseCover).toHaveBeenCalledOnce();+ expect(window.location.hash).toBe('#/channels/previous-channel');+ expect(vi.getTimerCount()).toBe(0);+ expect(bridge.acknowledge).not.toHaveBeenCalled();+ }+);diff --git a/apps/web/src/lib/tauri/notification-launch.ts b/apps/web/src/lib/tauri/notification-launch.tsnew file mode 100644index 0000000000..9b3d229e77--- /dev/null+++ b/apps/web/src/lib/tauri/notification-launch.ts@@ -0,0 +1,60 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { Telemetry } from '@macro-inc/observability';+import {+ pendingNotificationNavigation,+ receiveNotificationTap,+} from '@notifications/notification-navigation-intent';+import {+ createPushApi,+ releaseNotificationCover,+ supportsNotificationLaunch,+} from './push-api';++/** Read the native launch intent before the hash router can restore another page. */+export async function prepareNotificationLaunch(): Promise<void> {+ if (!supportsNotificationLaunch()) return;+ const api = createPushApi('ios');+ const span = Telemetry.span('notification.launch');+ let timeout: ReturnType<typeof setTimeout> | undefined;++ async function readPending(): Promise<'ready' | 'failed'> {+ try {+ await api.watch((event) => {+ receiveNotificationTap(event, api.acknowledge);+ });+ const pending = await api.pending();+ if (pending) receiveNotificationTap(pending, api.acknowledge);+ return 'ready';+ } catch (error) {+ // This can reject after startup has continued; still report the failure.+ Telemetry.error(error, { surface: 'notification-launch' });+ return 'failed';+ }+ }++ try {+ const outcome = await Promise.race([+ readPending(),+ new Promise<'timeout'>((resolve) => {+ timeout = setTimeout(() => resolve('timeout'), 1500);+ }),+ ]);+ span.setAttr('notification.launch.outcome', outcome);+ if (outcome !== 'ready') {+ // Revealing the app must not wait on another potentially stalled invoke.+ fireAndForget(releaseNotificationCover(), 'notification-launch');+ }+ } finally {+ clearTimeout(timeout);+ span.end();+ }++ // Only startup may reset the initial location. If the bridge settles after+ // the deadline, its tap stays in the normal account-checked navigation flow.+ if (!pendingNotificationNavigation()) return;+ const url = new URL(window.location.href);+ // BasePath verifies the account and chooses the notification route. Do not+ // restore a previous page while that identity is still unknown.+ url.hash = '/';+ window.history.replaceState(window.history.state, '', url);+}diff --git a/apps/web/src/lib/tauri/push-api.ts b/apps/web/src/lib/tauri/push-api.tsindex 7767ca1aa3..f8991118dc 100644--- a/apps/web/src/lib/tauri/push-api.ts+++ b/apps/web/src/lib/tauri/push-api.ts@@ -9,10 +9,26 @@ type LifecycleEvent<Type extends 'TOKEN_REFRESH' | 'RESUME'> = {// One member per lifecycle type so a handler that returns early on them// narrows the rest to NotificationEvent.export type PushEvent =- | (ios.NotificationEvent & { deliveryId?: string })+ | (ios.NotificationEvent & { deliveryId?: string; receivedAtMs?: number })| LifecycleEvent<'TOKEN_REFRESH'>| LifecycleEvent<'RESUME'>;+declare global {+ interface Window {+ __MACRO_IOS_NOTIFICATION_LAUNCH__?: boolean;+ }+}++export function supportsNotificationLaunch(): boolean {+ return window.__MACRO_IOS_NOTIFICATION_LAUNCH__ === true;+}++/** Reveal auth/retry UI without discarding the durable tapped destination. */+export async function releaseNotificationCover(): Promise<void> {+ if (supportsNotificationLaunch())+ await invoke('plugin:notifications|release_notification_cover');+}+/** Keep the Android bridge separate from the existing iOS plugin contract. */export function createPushApi(platform: 'android' | 'ios') {const android = platform === 'android';@@ -40,24 +56,54 @@ export function createPushApi(platform: 'android' | 'ios') {await invoke('plugin:android-push|configure', {payload: { recipientId },});+ else if (supportsNotificationLaunch())+ await invoke('plugin:notifications|configure_recipient', {+ payload: { recipientId },+ });},watch: async (callback: (event: PushEvent) => void) => {- if (!android) {+ if (!android && !supportsNotificationLaunch()) {await ios.watchNotifications(callback);return;}const channel = new Channel<PushEvent>();channel.onmessage = callback;- await invoke('plugin:android-push|watch', { channel });+ await invoke(+ android+ ? 'plugin:android-push|watch'+ : 'plugin:notifications|watch_notifications',+ {+ channel,+ ...(!android ? { launchAware: true } : {}),+ }+ );},unwatch: async () => {if (android) await invoke('plugin:android-push|unwatch');+ else if (supportsNotificationLaunch())+ await invoke('plugin:notifications|unwatch_notifications');},acknowledge: async (deliveryId: string) => {if (android)await invoke('plugin:android-push|acknowledge', {payload: { deliveryId },});+ else if (supportsNotificationLaunch()) {+ // Let the destination's route/loading shell draw before native removes+ // its resume cover. In the background this waits until the next frame.+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => resolve())+ );+ await invoke('plugin:notifications|acknowledge_notification', {+ deliveryId,+ });+ }+ },+ pending: () =>+ invoke<PushEvent | null>('plugin:notifications|get_pending_notification'),+ clearPending: async () => {+ if (supportsNotificationLaunch())+ await invoke('plugin:notifications|clear_pending_notification');},};}diff --git a/apps/web/src/routes/BasePath.test.tsx b/apps/web/src/routes/BasePath.test.tsxindex 0d0dbb9058..0b463ea9f3 100644--- a/apps/web/src/routes/BasePath.test.tsx+++ b/apps/web/src/routes/BasePath.test.tsx@@ -105,6 +105,15 @@ vi.mock('@ui', () => ({),}));+vi.mock('@channel/queries/prefetch-channel-target', () => ({+ prefetchChannelTarget: vi.fn(async () => {}),+}));++import {+ receiveNotificationTap,+ setPendingNotificationNavigationId,+} from '@notifications/notification-navigation-intent';+import { endNotificationOpen } from '@notifications/notification-open-trace';import { queryClient } from '@queries/client';import { BasePathComponent } from './BasePath';@@ -161,9 +170,50 @@ beforeEach(() => {afterEach(() => {dispose?.();dispose = undefined;+ setPendingNotificationNavigationId(undefined);+ endNotificationOpen('test_complete');});describe('BasePathComponent', () => {+ it('chooses the tapped message before Home or a saved destination after authentication', async () => {+ mocks.nativeMobile = true;+ setPostLoginRedirect('/channels/previous');+ const recipientId = 'macro|[email protected]';+ receiveNotificationTap(+ {+ type: 'BACKGROUND_TAP',+ payload: {+ notificationId: 'notification-1',+ recipientId,+ navigation: {+ type: 'channel',+ channelId: '11111111-1111-4111-8111-111111111111',+ messageId: '22222222-2222-4222-8222-222222222222',+ threadId: null,+ },+ },+ },+ vi.fn()+ );+ let resolveIdentity!: (identity: {+ authenticated: true;+ userId: string;+ }) => void;+ mocks.fetchUserInfo.mockReturnValue(+ new Promise((resolve) => {+ resolveIdentity = resolve;+ })+ );+ renderRoute();+ expect(mocks.navigate).not.toHaveBeenCalled();+ resolveIdentity({ authenticated: true, userId: recipientId });+ await vi.waitFor(() =>+ expect(mocks.navigate).toHaveBeenCalledExactlyOnceWith(+ '/channel/11111111-1111-4111-8111-111111111111?channel_message_id=22222222-2222-4222-8222-222222222222&channel_thread_id=22222222-2222-4222-8222-222222222222',+ { replace: true }+ )+ );+ });it.each([true, false])('preserves a late native root query while authentication resolves (%s)',async (authenticated) => {diff --git a/apps/web/src/routes/BasePath.tsx b/apps/web/src/routes/BasePath.tsxindex 6c6a785d5e..40ae20999b 100644--- a/apps/web/src/routes/BasePath.tsx+++ b/apps/web/src/routes/BasePath.tsx@@ -1,17 +1,31 @@import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';import { useCheckoutCompletionListener } from '@app/features/paywall/use-checkout-completion-listener';+import { prefetchChannelTarget } from '@channel/queries/prefetch-channel-target';import {getCurrentQueryString,SessionExpiredRedirect,} from '@components/app/SessionExpiredRedirect';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { hasLoginCookie } from '@core/util/cookies';+import { fireAndForget } from '@core/util/fireAndForget';import { consumePostLoginRedirect } from '@core/util/postLoginRedirect';import { thrownResultErrorHasCode } from '@core/util/result';+import { releaseNotificationCover } from '@macro/tauri/push-api';+import {+ notificationLaunchPath,+ pendingNotificationNavigation,+} from '@notifications/notification-navigation-intent';import { useUserInfoQuery } from '@queries/auth/user-info';import { Navigate, useLocation, useSearchParams } from '@solidjs/router';import { Button } from '@ui';-import { createEffect, createSignal, Match, on, Switch } from 'solid-js';+import {+ createEffect,+ createSignal,+ Match,+ on,+ onMount,+ Switch,+} from 'solid-js';function shouldShowNativeSessionVerificationFallback(userInfoQuery: ReturnType<typeof useUserInfoQuery>@@ -28,6 +42,9 @@ function shouldShowNativeSessionVerificationFallback(function SessionVerificationFallback(props: {onRetry: () => Promise<unknown>;}) {+ onMount(() =>+ fireAndForget(releaseNotificationCover(), 'notification-launch')+ );const [retrying, setRetrying] = createSignal(false);const handleRetry = async () => {@@ -54,9 +71,23 @@ function SessionVerificationFallback(props: {);}-function AuthenticatedDestination(props: { fallback: string }) {+function AuthenticatedDestination(props: {+ fallback: string;+ recipientId: string;+}) {const pending = isNativeMobilePlatform() ? consumePostLoginRedirect() : null;- return <Navigate href={pending ?? props.fallback} />;+ const notificationPath = notificationLaunchPath(props.recipientId);+ const target = pendingNotificationNavigation()?.target;+ if (notificationPath && target) {+ fireAndForget(+ prefetchChannelTarget(target.channelId, {+ messageId: target.messageId,+ threadId: target.threadId ?? target.messageId,+ }),+ 'notification-navigation'+ );+ }+ return <Navigate href={notificationPath ?? pending ?? props.fallback} />;}export function BasePathComponent() {@@ -105,7 +136,10 @@ export function BasePathComponent() {<SessionExpiredRedirect /></Match><Match when={userInfoQuery.data?.authenticated}>- <AuthenticatedDestination fallback={redirectPath()} />+ <AuthenticatedDestination+ fallback={redirectPath()}+ recipientId={userInfoQuery.data!.userId}+ /></Match>{/* A failed remote check does not make an authenticated cached sessionunusable: the data branch above enters the local app first. Block onlydiff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsxindex 7fb40e606d..d14f035c96 100644--- a/apps/web/src/routes/Root.tsx+++ b/apps/web/src/routes/Root.tsx@@ -33,6 +33,7 @@ import { isTauri } from '@core/util/platform';import { transformShortIdInUrlPathname } from '@core/util/url';import { EntityProvider } from '@entity';import { MaybeTauriProvider } from '@macro/tauri';+import { releaseNotificationCover } from '@macro/tauri/push-api';import { TauriRouteListener } from '@macro/tauri/TauriProvider';import { Telemetry } from '@macro-inc/observability';import { BrowserNotificationModal } from '@notifications';@@ -180,7 +181,10 @@ function AppRouteFrame(props: RouteSectionProps) {useUserInfoSideEffects();useSessionWebsockets();onMount(() => {- const cap = setTimeout(dismissBootShell, BOOT_SHELL_MAX_WAIT_MS);+ const cap = setTimeout(() => {+ dismissBootShell();+ fireAndForget(releaseNotificationCover(), 'notification-launch');+ }, BOOT_SHELL_MAX_WAIT_MS);onCleanup(() => clearTimeout(cap));});return <RootFrame>{props.children}</RootFrame>;diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsxindex 8a18d12fa9..66cd98031a 100644--- a/apps/web/src/routes/app-router-view.tsx+++ b/apps/web/src/routes/app-router-view.tsx@@ -22,6 +22,7 @@ import {useSolidRouterHistory,} from '@app/lib/split-router';import { globalSplitManager } from '@app/signal/splitLayout';+import { ChannelLoading } from '@channel/Channel/ChannelLoading';import { createAppSplitRouterMiddleware } from '@components/app/split-layout/split-router/app-middleware';import { createAppPanePolicy } from '@components/app/split-layout/split-router/app-pane-policy';import {@@ -396,6 +397,7 @@ export function AppRouterView() {<Routedefinition={channelDetailRoute}component={ChannelDetailRouteView}+ loading={ChannelLoading}/></Route><Route definition={callsRoute} component={CallsRouteView}>diff --git a/apps/web/src/routes/shells.tsx b/apps/web/src/routes/shells.tsxindex 037f8d9d33..d21453f999 100644--- a/apps/web/src/routes/shells.tsx+++ b/apps/web/src/routes/shells.tsx@@ -8,6 +8,8 @@ import {SplitLayoutProvider,} from '@components/app/split-layout/SplitLayout';import { useIsAuthenticated } from '@core/auth';+import { fireAndForget } from '@core/util/fireAndForget';+import { releaseNotificationCover } from '@macro/tauri/push-api';import { ImperativeDialogHost } from '@ui';import { type JSX, onCleanup, onMount, type ParentProps, Show } from 'solid-js';import { LIKELY_NEXT_VIEWS } from './lazy-route-views';@@ -21,6 +23,9 @@ function useDismissBootShell() {/** Sign-in, onboarding, invite, and handoff pages: the page alone. */export function AuthShell(): JSX.Element {useDismissBootShell();+ onMount(() =>+ fireAndForget(releaseNotificationCover(), 'notification-launch')+ );return (<PageContent><ImperativeDialogHost />diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex a34ad904f4..2a624d67ee 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -7059,12 +7059,11 @@ dependencies = [[[package]]name = "tauri-plugin-notifications"version = "0.1.0"-source = "git+https://github.com/macro-inc/tauri-plugins?rev=6ddd6600e20436388f169e936b610fe93944b7b0#6ddd6600e20436388f169e936b610fe93944b7b0"dependencies = ["serde",+ "serde_json","tauri","tauri-plugin",- "thiserror 1.0.69",][[package]]diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.tomlindex 61d722d0f3..0fa261d333 100644--- a/apps/web/tauri/Cargo.toml+++ b/apps/web/tauri/Cargo.toml@@ -8,6 +8,7 @@ members = ["file_export_plugin","graphql_cache_plugin","input_accessory_plugin",+ "ios_push_plugin","logger","macro_bundle_updater_plugin","navigation_plugin",diff --git a/apps/web/tauri/ios_push_plugin/.gitignore b/apps/web/tauri/ios_push_plugin/.gitignorenew file mode 100644index 0000000000..ac43fdc8dd--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/.gitignore@@ -0,0 +1,3 @@+/.tauri/+/ios/.build/+/store/.build/diff --git a/apps/web/tauri/ios_push_plugin/AGENTS.md b/apps/web/tauri/ios_push_plugin/AGENTS.mdnew file mode 100644index 0000000000..30ce0c0374--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/AGENTS.md@@ -0,0 +1,46 @@+# iOS push notifications++## What it is++The local iOS replacement for `macro-inc/tauri-plugins`' notifications crate.+It preserves the `notifications` command namespace and APNs registration API,+and owns durable notification-tap delivery across cold launches/WebView reloads.++## Start here++- `ios/Sources/NotificationsPlugin.swift`: APNs delegate, JS bridge, native cover.+- `store/Sources/PendingPushStore/PendingPushStore.swift`: atomic pending intent,+ expiration, duplicate suppression, account changes, and matching acknowledgment.+- `src/ios.rs`: Tauri command arguments; the frontend bridge is+ `../../src/lib/tauri/notification-launch.ts`.++## Boundaries++- Persist only notification ID, recipient ID and navigation metadata; never notification bodies.+- Keep store access and UI operations on the main thread. Sending to a Tauri+ channel does not acknowledge delivery; only a matching frontend ack consumes it.+- Keep only the latest tap; old callbacks and acknowledgments cannot replace or+ clear it. Expire unacknowledged intents after 24 hours.+- Let the authenticated frontend validate the payload recipient and access.+ `configure_recipient` clears stale intents on logout/account changes.+- A neutral view covers the WebView while inactive and during notification+ navigation. Auth/error screens use `release_notification_cover` without+ consuming the intent. A hidden bootstrap must never wait for foregrounding.+ Failed tap delivery releases the cover only after frontend bootstrap; keep+ the intent available for a replacement listener.+- Gate new frontend commands on `__MACRO_IOS_NOTIFICATION_LAUNCH__`; older native+ binaries retain the existing push behavior when receiving an OTA web bundle.+ Pass `launchAware: true` when watching. Older web bundles omit that flag and+ retain legacy delivery without a native cover or required acknowledgment.++## Checks++- `swift test --package-path apps/web/tauri/ios_push_plugin/store` (Foundation only).+- `nix develop .#tauri-linux --command cargo check --manifest-path apps/web/tauri/Cargo.toml -p tauri-plugin-notifications` validates host plugin registration/build metadata.+- A full iOS simulator build validates the Swift/UIKit bridge and iOS Rust+ commands; exercise warm resume, terminated launch, WebContent eviction, rapid+ successive taps, offline/auth failures, and ordinary icon resume on a device.++## Related++- [iOS release guide](../../docs/ios-releases.md): native builds and OTA compatibility.diff --git a/apps/web/tauri/ios_push_plugin/CLAUDE.md b/apps/web/tauri/ios_push_plugin/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/apps/web/tauri/ios_push_plugin/Cargo.toml b/apps/web/tauri/ios_push_plugin/Cargo.tomlnew file mode 100644index 0000000000..dbc9ff8ce5--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "tauri-plugin-notifications"+version = "0.1.0"+edition.workspace = true+links = "tauri-plugin-notifications"+license = "MIT"++[build-dependencies]+tauri-plugin = { version = "2.4", features = ["build"] }++[dependencies]+tauri = { workspace = true }++[target.'cfg(target_os = "ios")'.dependencies]+serde = { workspace = true, features = ["derive"] }+serde_json = "1"diff --git a/apps/web/tauri/ios_push_plugin/LICENSE-MIT b/apps/web/tauri/ios_push_plugin/LICENSE-MITnew file mode 100644index 0000000000..4d75472566--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/LICENSE-MIT@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2017 - Present Tauri Apps Contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.\ No newline at end of filediff --git a/apps/web/tauri/ios_push_plugin/build.rs b/apps/web/tauri/ios_push_plugin/build.rsnew file mode 100644index 0000000000..7f70813399--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/build.rs@@ -0,0 +1,17 @@+const COMMANDS: &[&str] = &[+ "check_permissions",+ "request_permissions",+ "check_registration_status",+ "register_for_remote_notifications",+ "watch_notifications",+ "unwatch_notifications",+ "get_pending_notification",+ "acknowledge_notification",+ "clear_pending_notification",+ "release_notification_cover",+ "configure_recipient",+];++fn main() {+ tauri_plugin::Builder::new(COMMANDS).ios_path("ios").build();+}diff --git a/apps/web/tauri/ios_push_plugin/ios/Package.swift b/apps/web/tauri/ios_push_plugin/ios/Package.swiftnew file mode 100644index 0000000000..4b5b23bbbe--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/ios/Package.swift@@ -0,0 +1,19 @@+// swift-tools-version:5.9+import PackageDescription++let package = Package(+ name: "tauri-plugin-notifications",+ platforms: [.iOS(.v15)],+ products: [.library(name: "tauri-plugin-notifications", type: .static, targets: ["tauri-plugin-notifications"])],+ dependencies: [+ .package(name: "Tauri", path: "../.tauri/tauri-api"),+ .package(path: "../store"),+ ],+ targets: [+ .target(+ name: "tauri-plugin-notifications",+ dependencies: [.byName(name: "Tauri"), .product(name: "PendingPushStore", package: "store")],+ path: "Sources"+ ),+ ]+)diff --git a/apps/web/tauri/ios_push_plugin/ios/Sources/NotificationsPlugin.swift b/apps/web/tauri/ios_push_plugin/ios/Sources/NotificationsPlugin.swiftnew file mode 100644index 0000000000..25f7ac3830--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/ios/Sources/NotificationsPlugin.swift@@ -0,0 +1,425 @@+// Adapted from macro-inc/tauri-plugins 6ddd6600 (MIT); see LICENSE-MIT.+import Foundation+import PendingPushStore+import SwiftRs+import Tauri+import UIKit+import UserNotifications+import WebKit++private struct PermissionStatus: Encodable { let status: String }+private struct RegistrationStatus: Encodable { let isRegistered: Bool; let token: String? }+private struct RegistrationResult: Encodable { let success: Bool; let token: String?; let error: String? }+private struct WatchArgs: Decodable { let channel: Channel; let launchAware: Bool? }+private struct WatchResult: Encodable { let success: Bool }+private struct AcknowledgeArgs: Decodable { let deliveryId: String }+private struct ConfigureArgs: Decodable { let recipientId: String? }+private struct PendingResult: Encodable { let event: PendingPush? }+private struct DeliveryEvent: Encodable { let type: String; let payload: [String: String] }++final class NotificationsPlugin: Plugin, UNUserNotificationCenterDelegate {+ private var registrationInvoke: Invoke?+ private var notificationChannel: Channel?+ private var originalDelegate: UIApplicationDelegate?+ private var pendingStore: PendingPushStore?+ private var pendingStoreError: Error?+ private var lifecycleObservers: [NSObjectProtocol] = []+ private var loadObservation: NSKeyValueObservation?+ private weak var appWebview: WKWebView?+ private var cover: UIView?+ private var frontendReady = false+ private var launchAware = false+ private var suppressPendingCover = false++ override init() {+ super.init()+ do {+ let directory = try FileManager.default.url(+ for: .applicationSupportDirectory, in: .userDomainMask,+ appropriateFor: nil, create: true+ )+ pendingStore = try PendingPushStore(+ fileURL: directory.appendingPathComponent("notification-navigation/pending.json")+ )+ } catch {+ pendingStoreError = error+ Logger.error("[notification-open] phase=store_init outcome=failed")+ }+ UNUserNotificationCenter.current().delegate = self+ }++ @objc override public func load(webview: WKWebView) {+ super.load(webview: webview)+ appWebview = webview+ loadObservation = webview.observe(\.isLoading, options: [.new]) { [weak self] _, change in+ guard change.newValue == true, let self else { return }+ // A retained native channel belongs to the previous JavaScript+ // realm. New and old OTA bundles explicitly choose their contract.+ self.notificationChannel = nil+ self.launchAware = false+ self.frontendReady = false+ self.suppressPendingCover = false+ self.reveal()+ }+ let app = UIApplication.shared+ originalDelegate = app.delegate+ app.delegate = self+ for name in [UIApplication.willResignActiveNotification, UIScene.willDeactivateNotification] {+ lifecycleObservers.append(NotificationCenter.default.addObserver(+ forName: name, object: nil, queue: .main+ ) { [weak self] _ in self?.showCover() })+ }+ for name in [UIApplication.didBecomeActiveNotification, UIScene.didActivateNotification] {+ lifecycleObservers.append(NotificationCenter.default.addObserver(+ forName: name, object: nil, queue: .main+ ) { [weak self] _ in+ // Let launch response callbacks already queued on the main+ // thread run before deciding this is an ordinary icon resume.+ DispatchQueue.main.async { self?.didBecomeActive() }+ })+ }+ }++ deinit {+ for observer in lifecycleObservers { NotificationCenter.default.removeObserver(observer) }+ }++ private static var nowMs: Int64 { Int64(Date().timeIntervalSince1970 * 1000) }++ private func store() throws -> PendingPushStore {+ if let pendingStore { return pendingStore }+ throw pendingStoreError ?? NSError(domain: "MacroPush", code: 1)+ }++ private func showCover() {+ guard launchAware, let webview = appWebview else { return }+ let surface = cover ?? UIView(frame: webview.bounds)+ surface.backgroundColor = .systemBackground+ surface.autoresizingMask = [.flexibleWidth, .flexibleHeight]+ surface.isUserInteractionEnabled = true+ surface.accessibilityIdentifier = "notification-navigation-cover"+ if surface.superview !== webview {+ webview.addSubview(surface)+ }+ surface.frame = webview.bounds+ webview.bringSubviewToFront(surface)+ cover = surface+ }++ private func reveal() {+ // Keep the app-switcher/launch snapshot neutral while backgrounded.+ guard UIApplication.shared.applicationState == .active else { return }+ cover?.removeFromSuperview()+ cover = nil+ }++ private func didBecomeActive() {+ // Auth/retry UI can release the cover without consuming the intent.+ // Keep retrying delivery after sign-in even while that UI stays visible.+ if suppressPendingCover { reveal() }+ guard launchAware, frontendReady else {+ if !launchAware { reveal() }+ return+ }+ do {+ guard let event = try store().pending(at: Self.nowMs) else {+ reveal()+ return+ }+ // A previous route may have committed while its durable ack failed.+ // Re-delivery lets the live frontend retry that same delivery ID.+ deliverTap(event)+ Logger.info("[notification-open] phase=resume_retry delivery_id=\(event.deliveryId) timestamp_ms=\(Self.nowMs)")+ } catch {+ reveal()+ Logger.error("[notification-open] phase=resume_retry outcome=failed")+ }+ }++ @objc public func getPendingNotification(_ invoke: Invoke) {+ DispatchQueue.main.async {+ // Watch is installed first. A response that arrives after this+ // snapshot still reaches that listener, including hidden reloads.+ self.resolvePending(invoke)+ }+ }++ private func resolvePending(_ invoke: Invoke) {+ do {+ let event = try store().pending(at: Self.nowMs)+ launchAware = true+ frontendReady = true+ if event == nil || suppressPendingCover { reveal() } else { showCover() }+ invoke.resolve(PendingResult(event: event))+ Logger.info("[notification-open] phase=bootstrap pending=\(event != nil) timestamp_ms=\(Self.nowMs)")+ } catch {+ frontendReady = true+ reveal()+ invoke.reject("Unable to read pending notification navigation")+ }+ }++ @objc public func acknowledgeNotification(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(AcknowledgeArgs.self)+ DispatchQueue.main.async {+ do {+ if try self.store().acknowledge(deliveryId: args.deliveryId) {+ DispatchQueue.main.async {+ if (try? self.store().pending(at: Self.nowMs)) == nil { self.reveal() }+ }+ Logger.info("[notification-open] phase=ack delivery_id=\(args.deliveryId) timestamp_ms=\(Self.nowMs)")+ }+ invoke.resolve()+ } catch {+ // The route already rendered. A persistence failure must not+ // trap it behind the cover; retain the intent for a later retry.+ self.reveal()+ invoke.reject("Unable to acknowledge notification navigation")+ }+ }+ }++ @objc public func clearPendingNotification(_ invoke: Invoke) {+ DispatchQueue.main.async {+ do {+ try self.store().clear()+ self.reveal()+ invoke.resolve()+ } catch {+ invoke.reject("Unable to clear notification navigation")+ }+ }+ }++ @objc public func releaseNotificationCover(_ invoke: Invoke) {+ DispatchQueue.main.async {+ self.suppressPendingCover = true+ self.frontendReady = true+ self.reveal()+ invoke.resolve()+ }+ }++ @objc public func watchNotifications(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(WatchArgs.self)+ DispatchQueue.main.async {+ self.notificationChannel = args.channel+ self.launchAware = args.launchAware == true+ if !self.launchAware {+ self.frontendReady = true+ self.reveal()+ }+ do {+ if let event = try self.store().pending(at: Self.nowMs) {+ if !self.suppressPendingCover { self.showCover() }+ self.deliverTap(event)+ }+ invoke.resolve(WatchResult(success: true))+ } catch {+ invoke.reject("Unable to watch pending notification navigation")+ }+ }+ }++ @objc public func configureRecipient(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(ConfigureArgs.self)+ DispatchQueue.main.async {+ do {+ try self.store().configureRecipient(args.recipientId)+ if try self.store().pending(at: Self.nowMs) == nil { self.reveal() }+ invoke.resolve()+ } catch {+ invoke.reject("Unable to configure notification recipient")+ }+ }+ }++ @objc public func unwatchNotifications(_ invoke: Invoke) {+ DispatchQueue.main.async {+ self.notificationChannel = nil+ invoke.resolve()+ }+ }++ @discardableResult+ private func send<T: Encodable>(_ event: T) -> Bool {+ // Channel.send does not acknowledge receipt. The persisted intent stays+ // available to a new JS context even when this call returns successfully.+ guard let channel = notificationChannel else { return false }+ do {+ try channel.send(event)+ return true+ } catch {+ notificationChannel = nil+ Logger.error("[notification-open] phase=delivery outcome=failed")+ return false+ }+ }++ private func deliverTap(_ event: PendingPush) {+ guard send(event) else {+ // A live frontend may lose its listener without remounting. Keep+ // the intent for reconnect, but do not leave its UI covered. A new+ // WebView still waits for bootstrap before revealing any content.+ if frontendReady { reveal() }+ return+ }+ if !launchAware {+ // Older frontend bundles cannot acknowledge. Preserve their+ // historical delivery contract without leaving a native cover up.+ do { try store().acknowledge(deliveryId: event.deliveryId) }+ catch { Logger.error("[notification-open] phase=legacy_ack outcome=failed") }+ }+ }++ public func userNotificationCenter(+ _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,+ withCompletionHandler completionHandler: @escaping () -> Void+ ) {+ guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else {+ completionHandler()+ return+ }+ DispatchQueue.main.async {+ defer { completionHandler() }+ let notification = response.notification+ let payload = Self.stringPayload(notification.request.content.userInfo)+ .filter { ["notificationId", "recipientId", "navigation"].contains($0.key) }+ guard let notificationId = payload["notificationId"], !notificationId.isEmpty else { return }+ let event = PendingPush(+ type: UIApplication.shared.applicationState == .active ? "FOREGROUND_TAP" : "BACKGROUND_TAP",+ payload: payload, deliveryId: UUID().uuidString, receivedAtMs: Self.nowMs+ )+ let sourceId = "\(notification.request.identifier):\(notification.date.timeIntervalSince1970)"+ do {+ guard let captured = try self.store().capture(sourceId: sourceId, event: event) else { return }+ self.suppressPendingCover = false+ self.showCover()+ self.deliverTap(captured)+ Logger.info("[notification-open] phase=capture delivery_id=\(captured.deliveryId) timestamp_ms=\(captured.receivedAtMs)")+ } catch {+ self.reveal()+ self.send(event)+ Logger.error("[notification-open] phase=capture outcome=failed")+ }+ }+ }++ public func userNotificationCenter(+ _ center: UNUserNotificationCenter, willPresent notification: UNNotification,+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void+ ) {+ DispatchQueue.main.async {+ self.send(DeliveryEvent(type: "FOREGROUND_DELIVERY", payload: Self.stringPayload(notification.request.content.userInfo)))+ completionHandler([.banner, .sound, .badge, .list])+ }+ }++ private static func stringPayload(_ userInfo: [AnyHashable: Any]) -> [String: String] {+ userInfo.reduce(into: [:]) { result, pair in+ guard let key = pair.key as? String else { return }+ if let value = pair.value as? String {+ result[key] = value+ } else if JSONSerialization.isValidJSONObject(pair.value),+ let data = try? JSONSerialization.data(withJSONObject: pair.value),+ let value = String(data: data, encoding: .utf8) {+ result[key] = value+ } else {+ result[key] = String(describing: pair.value)+ }+ }+ }++ @objc override public func checkPermissions(_ invoke: Invoke) {+ UNUserNotificationCenter.current().getNotificationSettings { settings in+ let status: String+ switch settings.authorizationStatus {+ case .notDetermined: status = "prompt"+ case .denied: status = "denied"+ case .authorized, .provisional, .ephemeral: status = "granted"+ @unknown default: status = "prompt"+ }+ invoke.resolve(PermissionStatus(status: status))+ }+ }++ @objc override public func requestPermissions(_ invoke: Invoke) {+ UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in+ invoke.resolve(PermissionStatus(status: granted ? "granted" : "denied"))+ }+ }++ @objc public func checkRegistrationStatus(_ invoke: Invoke) {+ DispatchQueue.main.async {+ invoke.resolve(RegistrationStatus(+ isRegistered: UIApplication.shared.isRegisteredForRemoteNotifications,+ token: UserDefaults.standard.string(forKey: "deviceToken")+ ))+ }+ }++ @objc public func registerForRemoteNotifications(_ invoke: Invoke) {+ UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in+ DispatchQueue.main.async {+ guard granted else {+ invoke.resolve(RegistrationResult(success: false, token: nil, error: error?.localizedDescription ?? "Push notifications are not authorized"))+ return+ }+ if let token = UserDefaults.standard.string(forKey: "deviceToken") {+ invoke.resolve(RegistrationResult(success: true, token: token, error: nil))+ UIApplication.shared.registerForRemoteNotifications()+ return+ }+ self.registrationInvoke = invoke+ UIApplication.shared.registerForRemoteNotifications()+ DispatchQueue.main.asyncAfter(deadline: .now() + 10) {+ guard self.registrationInvoke === invoke else { return }+ self.registrationInvoke = nil+ invoke.resolve(RegistrationResult(success: false, token: nil, error: "Push registration timed out"))+ }+ }+ }+ }+}++extension NotificationsPlugin: UIApplicationDelegate {+ public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {+ let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()+ UserDefaults.standard.set(token, forKey: "deviceToken")+ registrationInvoke?.resolve(RegistrationResult(success: true, token: token, error: nil))+ registrationInvoke = nil+ }++ public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {+ registrationInvoke?.resolve(RegistrationResult(success: false, token: nil, error: error.localizedDescription))+ registrationInvoke = nil+ }++ public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {+ if application.applicationState != .active {+ send(DeliveryEvent(type: "BACKGROUND_DELIVERY", payload: Self.stringPayload(userInfo)))+ }+ completionHandler(.newData)+ }++ public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {+ originalDelegate?.application?(application, didFinishLaunchingWithOptions: launchOptions) ?? false+ }++ public func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {+ originalDelegate?.application?(application, open: url, options: options) ?? false+ }++ public func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {+ originalDelegate?.application?(application, continue: userActivity, restorationHandler: restorationHandler) ?? false+ }++ public func applicationDidBecomeActive(_ application: UIApplication) { originalDelegate?.applicationDidBecomeActive?(application) }+ public func applicationWillResignActive(_ application: UIApplication) { originalDelegate?.applicationWillResignActive?(application) }+ public func applicationWillEnterForeground(_ application: UIApplication) { originalDelegate?.applicationWillEnterForeground?(application) }+ public func applicationDidEnterBackground(_ application: UIApplication) { originalDelegate?.applicationDidEnterBackground?(application) }+ public func applicationWillTerminate(_ application: UIApplication) { originalDelegate?.applicationWillTerminate?(application) }+}++@_cdecl("init_plugin_notifications")+func initPlugin() -> Plugin { NotificationsPlugin() }diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/acknowledge_notification.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/acknowledge_notification.tomlnew file mode 100644index 0000000000..fa2380dd6e--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/acknowledge_notification.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-acknowledge-notification"+description = "Enables the acknowledge_notification command without any pre-configured scope."+commands.allow = ["acknowledge_notification"]++[[permission]]+identifier = "deny-acknowledge-notification"+description = "Denies the acknowledge_notification command without any pre-configured scope."+commands.deny = ["acknowledge_notification"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/check_permissions.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/check_permissions.tomlnew file mode 100644index 0000000000..f5af08b137--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/check_permissions.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-check-permissions"+description = "Enables the check_permissions command without any pre-configured scope."+commands.allow = ["check_permissions"]++[[permission]]+identifier = "deny-check-permissions"+description = "Denies the check_permissions command without any pre-configured scope."+commands.deny = ["check_permissions"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/check_registration_status.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/check_registration_status.tomlnew file mode 100644index 0000000000..76c31ad4bd--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/check_registration_status.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-check-registration-status"+description = "Enables the check_registration_status command without any pre-configured scope."+commands.allow = ["check_registration_status"]++[[permission]]+identifier = "deny-check-registration-status"+description = "Denies the check_registration_status command without any pre-configured scope."+commands.deny = ["check_registration_status"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/clear_pending_notification.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/clear_pending_notification.tomlnew file mode 100644index 0000000000..5596a2c567--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/clear_pending_notification.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-clear-pending-notification"+description = "Enables the clear_pending_notification command without any pre-configured scope."+commands.allow = ["clear_pending_notification"]++[[permission]]+identifier = "deny-clear-pending-notification"+description = "Denies the clear_pending_notification command without any pre-configured scope."+commands.deny = ["clear_pending_notification"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/configure_recipient.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/configure_recipient.tomlnew file mode 100644index 0000000000..d4f548db1d--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/configure_recipient.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-configure-recipient"+description = "Enables the configure_recipient command without any pre-configured scope."+commands.allow = ["configure_recipient"]++[[permission]]+identifier = "deny-configure-recipient"+description = "Denies the configure_recipient command without any pre-configured scope."+commands.deny = ["configure_recipient"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/get_pending_notification.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/get_pending_notification.tomlnew file mode 100644index 0000000000..65b4555193--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/get_pending_notification.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-pending-notification"+description = "Enables the get_pending_notification command without any pre-configured scope."+commands.allow = ["get_pending_notification"]++[[permission]]+identifier = "deny-get-pending-notification"+description = "Denies the get_pending_notification command without any pre-configured scope."+commands.deny = ["get_pending_notification"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/register_for_remote_notifications.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/register_for_remote_notifications.tomlnew file mode 100644index 0000000000..220a78d38e--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/register_for_remote_notifications.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-register-for-remote-notifications"+description = "Enables the register_for_remote_notifications command without any pre-configured scope."+commands.allow = ["register_for_remote_notifications"]++[[permission]]+identifier = "deny-register-for-remote-notifications"+description = "Denies the register_for_remote_notifications command without any pre-configured scope."+commands.deny = ["register_for_remote_notifications"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/release_notification_cover.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/release_notification_cover.tomlnew file mode 100644index 0000000000..9631bf56d5--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/release_notification_cover.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-release-notification-cover"+description = "Enables the release_notification_cover command without any pre-configured scope."+commands.allow = ["release_notification_cover"]++[[permission]]+identifier = "deny-release-notification-cover"+description = "Denies the release_notification_cover command without any pre-configured scope."+commands.deny = ["release_notification_cover"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/request_permissions.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/request_permissions.tomlnew file mode 100644index 0000000000..02dcd62718--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/request_permissions.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-request-permissions"+description = "Enables the request_permissions command without any pre-configured scope."+commands.allow = ["request_permissions"]++[[permission]]+identifier = "deny-request-permissions"+description = "Denies the request_permissions command without any pre-configured scope."+commands.deny = ["request_permissions"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/unwatch_notifications.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/unwatch_notifications.tomlnew file mode 100644index 0000000000..85507b7727--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/unwatch_notifications.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-unwatch-notifications"+description = "Enables the unwatch_notifications command without any pre-configured scope."+commands.allow = ["unwatch_notifications"]++[[permission]]+identifier = "deny-unwatch-notifications"+description = "Denies the unwatch_notifications command without any pre-configured scope."+commands.deny = ["unwatch_notifications"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/watch_notifications.toml b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/watch_notifications.tomlnew file mode 100644index 0000000000..7df25359af--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/commands/watch_notifications.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-watch-notifications"+description = "Enables the watch_notifications command without any pre-configured scope."+commands.allow = ["watch_notifications"]++[[permission]]+identifier = "deny-watch-notifications"+description = "Denies the watch_notifications command without any pre-configured scope."+commands.deny = ["watch_notifications"]diff --git a/apps/web/tauri/ios_push_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/reference.mdnew file mode 100644index 0000000000..b4b5fde080--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/autogenerated/reference.md@@ -0,0 +1,313 @@+## Default Permission++iOS push registration and acknowledged notification navigation.++#### This default permission set includes the following:++- `allow-check-permissions`+- `allow-request-permissions`+- `allow-check-registration-status`+- `allow-register-for-remote-notifications`+- `allow-watch-notifications`+- `allow-unwatch-notifications`+- `allow-get-pending-notification`+- `allow-acknowledge-notification`+- `allow-clear-pending-notification`+- `allow-release-notification-cover`+- `allow-configure-recipient`++## Permission Table++<table>+<tr>+<th>Identifier</th>+<th>Description</th>+</tr>+++<tr>+<td>++`notifications:allow-acknowledge-notification`++</td>+<td>++Enables the acknowledge_notification command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-acknowledge-notification`++</td>+<td>++Denies the acknowledge_notification command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-check-permissions`++</td>+<td>++Enables the check_permissions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-check-permissions`++</td>+<td>++Denies the check_permissions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-check-registration-status`++</td>+<td>++Enables the check_registration_status command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-check-registration-status`++</td>+<td>++Denies the check_registration_status command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-clear-pending-notification`++</td>+<td>++Enables the clear_pending_notification command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-clear-pending-notification`++</td>+<td>++Denies the clear_pending_notification command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-configure-recipient`++</td>+<td>++Enables the configure_recipient command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-configure-recipient`++</td>+<td>++Denies the configure_recipient command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-get-pending-notification`++</td>+<td>++Enables the get_pending_notification command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-get-pending-notification`++</td>+<td>++Denies the get_pending_notification command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-register-for-remote-notifications`++</td>+<td>++Enables the register_for_remote_notifications command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-register-for-remote-notifications`++</td>+<td>++Denies the register_for_remote_notifications command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-release-notification-cover`++</td>+<td>++Enables the release_notification_cover command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-release-notification-cover`++</td>+<td>++Denies the release_notification_cover command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-request-permissions`++</td>+<td>++Enables the request_permissions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-request-permissions`++</td>+<td>++Denies the request_permissions command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-unwatch-notifications`++</td>+<td>++Enables the unwatch_notifications command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-unwatch-notifications`++</td>+<td>++Denies the unwatch_notifications command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:allow-watch-notifications`++</td>+<td>++Enables the watch_notifications command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`notifications:deny-watch-notifications`++</td>+<td>++Denies the watch_notifications command without any pre-configured scope.++</td>+</tr>+</table>diff --git a/apps/web/tauri/ios_push_plugin/permissions/default.toml b/apps/web/tauri/ios_push_plugin/permissions/default.tomlnew file mode 100644index 0000000000..be86f73c3f--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/default.toml@@ -0,0 +1,15 @@+[default]+description = "iOS push registration and acknowledged notification navigation."+permissions = [+ "allow-check-permissions",+ "allow-request-permissions",+ "allow-check-registration-status",+ "allow-register-for-remote-notifications",+ "allow-watch-notifications",+ "allow-unwatch-notifications",+ "allow-get-pending-notification",+ "allow-acknowledge-notification",+ "allow-clear-pending-notification",+ "allow-release-notification-cover",+ "allow-configure-recipient",+]diff --git a/apps/web/tauri/ios_push_plugin/permissions/schemas/schema.json b/apps/web/tauri/ios_push_plugin/permissions/schemas/schema.jsonnew file mode 100644index 0000000000..4819ed35a5--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/permissions/schemas/schema.json@@ -0,0 +1,438 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "PermissionFile",+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",+ "type": "object",+ "properties": {+ "default": {+ "description": "The default permission set for the plugin",+ "anyOf": [+ {+ "$ref": "#/definitions/DefaultPermission"+ },+ {+ "type": "null"+ }+ ]+ },+ "set": {+ "description": "A list of permissions sets defined",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionSet"+ }+ },+ "permission": {+ "description": "A list of inlined permissions",+ "default": [],+ "type": "array",+ "items": {+ "$ref": "#/definitions/Permission"+ }+ }+ },+ "definitions": {+ "DefaultPermission": {+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",+ "type": "object",+ "required": [+ "permissions"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "PermissionSet": {+ "description": "A set of direct permissions grouped together under a new name.",+ "type": "object",+ "required": [+ "description",+ "identifier",+ "permissions"+ ],+ "properties": {+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does.",+ "type": "string"+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionKind"+ }+ }+ }+ },+ "Permission": {+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",+ "type": "object",+ "required": [+ "identifier"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "commands": {+ "description": "Allowed or denied commands when using this permission.",+ "default": {+ "allow": [],+ "deny": []+ },+ "allOf": [+ {+ "$ref": "#/definitions/Commands"+ }+ ]+ },+ "scope": {+ "description": "Allowed or denied scoped when using this permission.",+ "allOf": [+ {+ "$ref": "#/definitions/Scopes"+ }+ ]+ },+ "platforms": {+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Target"+ }+ }+ }+ },+ "Commands": {+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Allowed command.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "deny": {+ "description": "Denied command, which takes priority.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "Scopes": {+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Data that defines what is allowed by the scope.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ "deny": {+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ }+ }+ },+ "Value": {+ "description": "All supported ACL values.",+ "anyOf": [+ {+ "description": "Represents a null JSON value.",+ "type": "null"+ },+ {+ "description": "Represents a [`bool`].",+ "type": "boolean"+ },+ {+ "description": "Represents a valid ACL [`Number`].",+ "allOf": [+ {+ "$ref": "#/definitions/Number"+ }+ ]+ },+ {+ "description": "Represents a [`String`].",+ "type": "string"+ },+ {+ "description": "Represents a list of other [`Value`]s.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ {+ "description": "Represents a map of [`String`] keys to [`Value`]s.",+ "type": "object",+ "additionalProperties": {+ "$ref": "#/definitions/Value"+ }+ }+ ]+ },+ "Number": {+ "description": "A valid ACL number.",+ "anyOf": [+ {+ "description": "Represents an [`i64`].",+ "type": "integer",+ "format": "int64"+ },+ {+ "description": "Represents a [`f64`].",+ "type": "number",+ "format": "double"+ }+ ]+ },+ "Target": {+ "description": "Platform target.",+ "oneOf": [+ {+ "description": "MacOS.",+ "type": "string",+ "enum": [+ "macOS"+ ]+ },+ {+ "description": "Windows.",+ "type": "string",+ "enum": [+ "windows"+ ]+ },+ {+ "description": "Linux.",+ "type": "string",+ "enum": [+ "linux"+ ]+ },+ {+ "description": "Android.",+ "type": "string",+ "enum": [+ "android"+ ]+ },+ {+ "description": "iOS.",+ "type": "string",+ "enum": [+ "iOS"+ ]+ }+ ]+ },+ "PermissionKind": {+ "type": "string",+ "oneOf": [+ {+ "description": "Enables the acknowledge_notification command without any pre-configured scope.",+ "type": "string",+ "const": "allow-acknowledge-notification",+ "markdownDescription": "Enables the acknowledge_notification command without any pre-configured scope."+ },+ {+ "description": "Denies the acknowledge_notification command without any pre-configured scope.",+ "type": "string",+ "const": "deny-acknowledge-notification",+ "markdownDescription": "Denies the acknowledge_notification command without any pre-configured scope."+ },+ {+ "description": "Enables the check_permissions command without any pre-configured scope.",+ "type": "string",+ "const": "allow-check-permissions",+ "markdownDescription": "Enables the check_permissions command without any pre-configured scope."+ },+ {+ "description": "Denies the check_permissions command without any pre-configured scope.",+ "type": "string",+ "const": "deny-check-permissions",+ "markdownDescription": "Denies the check_permissions command without any pre-configured scope."+ },+ {+ "description": "Enables the check_registration_status command without any pre-configured scope.",+ "type": "string",+ "const": "allow-check-registration-status",+ "markdownDescription": "Enables the check_registration_status command without any pre-configured scope."+ },+ {+ "description": "Denies the check_registration_status command without any pre-configured scope.",+ "type": "string",+ "const": "deny-check-registration-status",+ "markdownDescription": "Denies the check_registration_status command without any pre-configured scope."+ },+ {+ "description": "Enables the clear_pending_notification command without any pre-configured scope.",+ "type": "string",+ "const": "allow-clear-pending-notification",+ "markdownDescription": "Enables the clear_pending_notification command without any pre-configured scope."+ },+ {+ "description": "Denies the clear_pending_notification command without any pre-configured scope.",+ "type": "string",+ "const": "deny-clear-pending-notification",+ "markdownDescription": "Denies the clear_pending_notification command without any pre-configured scope."+ },+ {+ "description": "Enables the configure_recipient command without any pre-configured scope.",+ "type": "string",+ "const": "allow-configure-recipient",+ "markdownDescription": "Enables the configure_recipient command without any pre-configured scope."+ },+ {+ "description": "Denies the configure_recipient command without any pre-configured scope.",+ "type": "string",+ "const": "deny-configure-recipient",+ "markdownDescription": "Denies the configure_recipient command without any pre-configured scope."+ },+ {+ "description": "Enables the get_pending_notification command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-pending-notification",+ "markdownDescription": "Enables the get_pending_notification command without any pre-configured scope."+ },+ {+ "description": "Denies the get_pending_notification command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-pending-notification",+ "markdownDescription": "Denies the get_pending_notification command without any pre-configured scope."+ },+ {+ "description": "Enables the register_for_remote_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "allow-register-for-remote-notifications",+ "markdownDescription": "Enables the register_for_remote_notifications command without any pre-configured scope."+ },+ {+ "description": "Denies the register_for_remote_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "deny-register-for-remote-notifications",+ "markdownDescription": "Denies the register_for_remote_notifications command without any pre-configured scope."+ },+ {+ "description": "Enables the release_notification_cover command without any pre-configured scope.",+ "type": "string",+ "const": "allow-release-notification-cover",+ "markdownDescription": "Enables the release_notification_cover command without any pre-configured scope."+ },+ {+ "description": "Denies the release_notification_cover command without any pre-configured scope.",+ "type": "string",+ "const": "deny-release-notification-cover",+ "markdownDescription": "Denies the release_notification_cover command without any pre-configured scope."+ },+ {+ "description": "Enables the request_permissions command without any pre-configured scope.",+ "type": "string",+ "const": "allow-request-permissions",+ "markdownDescription": "Enables the request_permissions command without any pre-configured scope."+ },+ {+ "description": "Denies the request_permissions command without any pre-configured scope.",+ "type": "string",+ "const": "deny-request-permissions",+ "markdownDescription": "Denies the request_permissions command without any pre-configured scope."+ },+ {+ "description": "Enables the unwatch_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "allow-unwatch-notifications",+ "markdownDescription": "Enables the unwatch_notifications command without any pre-configured scope."+ },+ {+ "description": "Denies the unwatch_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "deny-unwatch-notifications",+ "markdownDescription": "Denies the unwatch_notifications command without any pre-configured scope."+ },+ {+ "description": "Enables the watch_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "allow-watch-notifications",+ "markdownDescription": "Enables the watch_notifications command without any pre-configured scope."+ },+ {+ "description": "Denies the watch_notifications command without any pre-configured scope.",+ "type": "string",+ "const": "deny-watch-notifications",+ "markdownDescription": "Denies the watch_notifications command without any pre-configured scope."+ },+ {+ "description": "iOS push registration and acknowledged notification navigation.\n#### This default permission set includes:\n\n- `allow-check-permissions`\n- `allow-request-permissions`\n- `allow-check-registration-status`\n- `allow-register-for-remote-notifications`\n- `allow-watch-notifications`\n- `allow-unwatch-notifications`\n- `allow-get-pending-notification`\n- `allow-acknowledge-notification`\n- `allow-clear-pending-notification`\n- `allow-release-notification-cover`\n- `allow-configure-recipient`",+ "type": "string",+ "const": "default",+ "markdownDescription": "iOS push registration and acknowledged notification navigation.\n#### This default permission set includes:\n\n- `allow-check-permissions`\n- `allow-request-permissions`\n- `allow-check-registration-status`\n- `allow-register-for-remote-notifications`\n- `allow-watch-notifications`\n- `allow-unwatch-notifications`\n- `allow-get-pending-notification`\n- `allow-acknowledge-notification`\n- `allow-clear-pending-notification`\n- `allow-release-notification-cover`\n- `allow-configure-recipient`"+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/apps/web/tauri/ios_push_plugin/src/ios.rs b/apps/web/tauri/ios_push_plugin/src/ios.rsnew file mode 100644index 0000000000..aa59b3bbdf--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/src/ios.rs@@ -0,0 +1,155 @@+use serde::{Deserialize, Serialize};+use serde_json::Value;+use tauri::{AppHandle, Manager, Runtime, ipc::Channel, plugin::PluginHandle};++pub(crate) struct Push<R: Runtime>(pub PluginHandle<R>);++#[derive(Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct ConfigureArgs {+ recipient_id: Option<String>,+}++#[tauri::command]+pub(crate) async fn configure_recipient<R: Runtime>(+ app: AppHandle<R>,+ payload: ConfigureArgs,+) -> Result<(), String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async("configureRecipient", payload)+ .await+ .map_err(|error| error.to_string())+}++#[tauri::command]+pub(crate) async fn check_permissions<R: Runtime>(app: AppHandle<R>) -> Result<Value, String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async("checkPermissions", ())+ .await+ .map_err(|error| error.to_string())+}++#[tauri::command]+pub(crate) async fn request_permissions<R: Runtime>(app: AppHandle<R>) -> Result<Value, String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async("requestPermissions", ())+ .await+ .map_err(|error| error.to_string())+}++#[tauri::command]+pub(crate) async fn check_registration_status<R: Runtime>(+ app: AppHandle<R>,+) -> Result<Value, String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async("checkRegistrationStatus", ())+ .await+ .map_err(|error| error.to_string())+}++#[tauri::command]+pub(crate) async fn register_for_remote_notifications<R: Runtime>(+ app: AppHandle<R>,+) -> Result<Value, String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async("registerForRemoteNotifications", ())+ .await+ .map_err(|error| error.to_string())+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct WatchArgs {+ channel: Channel<Value>,+ launch_aware: bool,+}++#[tauri::command]+pub(crate) async fn watch_notifications<R: Runtime>(+ app: AppHandle<R>,+ channel: Channel<Value>,+ launch_aware: Option<bool>,+) -> Result<Value, String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async(+ "watchNotifications",+ WatchArgs {+ channel,+ launch_aware: launch_aware.unwrap_or(false),+ },+ )+ .await+ .map_err(|error| error.to_string())+}++#[tauri::command]+pub(crate) async fn unwatch_notifications<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async("unwatchNotifications", ())+ .await+ .map_err(|error| error.to_string())+}++#[derive(Deserialize)]+struct PendingResult {+ event: Option<Value>,+}++#[tauri::command]+pub(crate) async fn get_pending_notification<R: Runtime>(+ app: AppHandle<R>,+) -> Result<Option<Value>, String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async::<PendingResult>("getPendingNotification", ())+ .await+ .map(|result| result.event)+ .map_err(|error| error.to_string())+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct AcknowledgeArgs {+ delivery_id: String,+}++#[tauri::command]+pub(crate) async fn acknowledge_notification<R: Runtime>(+ app: AppHandle<R>,+ delivery_id: String,+) -> Result<(), String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async("acknowledgeNotification", AcknowledgeArgs { delivery_id })+ .await+ .map_err(|error| error.to_string())+}++#[tauri::command]+pub(crate) async fn clear_pending_notification<R: Runtime>(+ app: AppHandle<R>,+) -> Result<(), String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async("clearPendingNotification", ())+ .await+ .map_err(|error| error.to_string())+}++#[tauri::command]+pub(crate) async fn release_notification_cover<R: Runtime>(+ app: AppHandle<R>,+) -> Result<(), String> {+ app.state::<Push<R>>()+ .0+ .run_mobile_plugin_async("releaseNotificationCover", ())+ .await+ .map_err(|error| error.to_string())+}diff --git a/apps/web/tauri/ios_push_plugin/src/lib.rs b/apps/web/tauri/ios_push_plugin/src/lib.rsnew file mode 100644index 0000000000..848aff575e--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/src/lib.rs@@ -0,0 +1,40 @@+//! iOS remote notifications with a durable, acknowledged navigation handoff.+#![deny(missing_docs)]++use tauri::{+ Runtime,+ plugin::{Builder, TauriPlugin},+};++#[cfg(target_os = "ios")]+mod ios;++/// Register the iOS APNs bridge under the existing notifications namespace.+pub fn init<R: Runtime>() -> TauriPlugin<R> {+ let builder = Builder::new("notifications");+ #[cfg(target_os = "ios")]+ let builder = builder+ .js_init_script("window.__MACRO_IOS_NOTIFICATION_LAUNCH__ = true;")+ .invoke_handler(tauri::generate_handler![+ ios::check_permissions,+ ios::request_permissions,+ ios::check_registration_status,+ ios::register_for_remote_notifications,+ ios::watch_notifications,+ ios::unwatch_notifications,+ ios::get_pending_notification,+ ios::acknowledge_notification,+ ios::clear_pending_notification,+ ios::release_notification_cover,+ ios::configure_recipient,+ ])+ .setup(|app, api| {+ use tauri::Manager;+ tauri::ios_plugin_binding!(init_plugin_notifications);+ app.manage(ios::Push(+ api.register_ios_plugin(init_plugin_notifications)?,+ ));+ Ok(())+ });+ builder.build()+}diff --git a/apps/web/tauri/ios_push_plugin/store/Package.swift b/apps/web/tauri/ios_push_plugin/store/Package.swiftnew file mode 100644index 0000000000..72d2d8edb2--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/store/Package.swift@@ -0,0 +1,11 @@+// swift-tools-version:5.9+import PackageDescription++let package = Package(+ name: "PendingPushStore",+ products: [.library(name: "PendingPushStore", targets: ["PendingPushStore"])],+ targets: [+ .target(name: "PendingPushStore"),+ .testTarget(name: "PendingPushStoreTests", dependencies: ["PendingPushStore"]),+ ]+)diff --git a/apps/web/tauri/ios_push_plugin/store/Sources/PendingPushStore/PendingPushStore.swift b/apps/web/tauri/ios_push_plugin/store/Sources/PendingPushStore/PendingPushStore.swiftnew file mode 100644index 0000000000..74bb7f3bc2--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/store/Sources/PendingPushStore/PendingPushStore.swift@@ -0,0 +1,119 @@+import Foundation++/// Only routing metadata is persisted; notification bodies and images stay in APNs.+public struct PendingPush: Codable, Equatable {+ public let type: String+ public let payload: [String: String]+ public let deliveryId: String+ public let receivedAtMs: Int64++ public init(type: String, payload: [String: String], deliveryId: String, receivedAtMs: Int64) {+ self.type = type+ self.payload = payload+ self.deliveryId = deliveryId+ self.receivedAtMs = receivedAtMs+ }+}++/// Confine this store to the main thread. A successful write precedes delivery to JS.+public final class PendingPushStore {+ private struct Receipt: Codable {+ let sourceId: String+ let receivedAtMs: Int64+ }++ private struct State: Codable {+ var pending: PendingPush?+ var receipts: [Receipt] = []+ var recipientId: String?+ }++ private let fileURL: URL+ private let lifetimeMs: Int64+ private var state: State++ public init(fileURL: URL, lifetimeMs: Int64 = 24 * 60 * 60 * 1000) throws {+ self.fileURL = fileURL+ self.lifetimeMs = lifetimeMs+ if FileManager.default.fileExists(atPath: fileURL.path) {+ let data = try Data(contentsOf: fileURL)+ // Unreadable navigation state must not disable all future taps.+ // I/O errors still propagate; only an invalid persisted record is+ // discarded and replaced by the next atomic capture.+ state = (try? JSONDecoder().decode(State.self, from: data)) ?? State()+ } else {+ state = State()+ }+ }++ /// Repeated native callbacks never replace a newer explicit user intent.+ public func capture(sourceId: String, event: PendingPush) throws -> PendingPush? {+ var next = pruned(at: event.receivedAtMs)+ if next.receipts.contains(where: { $0.sourceId == sourceId }) {+ return nil+ }+ next.pending = event+ next.receipts.append(Receipt(sourceId: sourceId, receivedAtMs: event.receivedAtMs))+ next.receipts = Array(next.receipts.suffix(32))+ try save(next)+ return event+ }++ /// Reading or sending an event never consumes it; a reload may retry it.+ public func pending(at nowMs: Int64) throws -> PendingPush? {+ let next = pruned(at: nowMs)+ if next.pending != state.pending || next.receipts.count != state.receipts.count {+ try save(next)+ }+ return next.pending+ }++ /// A late acknowledgment for A cannot clear a more recent tap B.+ @discardableResult+ public func acknowledge(deliveryId: String) throws -> Bool {+ guard state.pending?.deliveryId == deliveryId else { return false }+ var next = state+ next.pending = nil+ try save(next)+ return true+ }++ public func clear() throws {+ var next = state+ next.pending = nil+ try save(next)+ }++ private func pruned(at nowMs: Int64) -> State {+ var next = state+ if let pending = next.pending, !isFresh(pending.receivedAtMs, nowMs: nowMs) {+ next.pending = nil+ }+ next.receipts.removeAll { !isFresh($0.receivedAtMs, nowMs: nowMs) }+ return next+ }++ /// Account changes discard legacy/unmatched intents; a tap explicitly+ /// addressed to the newly authenticated account survives login bootstrap.+ public func configureRecipient(_ recipientId: String?) throws {+ var next = state+ if recipientId == nil || (next.recipientId != recipientId && next.pending?.payload["recipientId"] != recipientId) {+ next.pending = nil+ }+ next.recipientId = recipientId+ try save(next)+ }++ private func isFresh(_ receivedAtMs: Int64, nowMs: Int64) -> Bool {+ // A clock jump into the past must not retain an intent indefinitely.+ receivedAtMs <= nowMs && nowMs - receivedAtMs < lifetimeMs+ }++ private func save(_ next: State) throws {+ try FileManager.default.createDirectory(+ at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true+ )+ try JSONEncoder().encode(next).write(to: fileURL, options: .atomic)+ state = next+ }+}diff --git a/apps/web/tauri/ios_push_plugin/store/Tests/PendingPushStoreTests/PendingPushStoreTests.swift b/apps/web/tauri/ios_push_plugin/store/Tests/PendingPushStoreTests/PendingPushStoreTests.swiftnew file mode 100644index 0000000000..0f668ab83a--- /dev/null+++ b/apps/web/tauri/ios_push_plugin/store/Tests/PendingPushStoreTests/PendingPushStoreTests.swift@@ -0,0 +1,95 @@+import Foundation+import XCTest+@testable import PendingPushStore++final class PendingPushStoreTests: XCTestCase {+ private var directory: URL!+ private var fileURL: URL { directory.appendingPathComponent("pending.json") }++ override func setUpWithError() throws {+ directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ }++ override func tearDownWithError() throws {+ if FileManager.default.fileExists(atPath: directory.path) {+ try FileManager.default.removeItem(at: directory)+ }+ }++ func testPendingTapSurvivesStoreRecreationAndRepeatedReadsUntilAcknowledgment() throws {+ let event = PendingPush(type: "BACKGROUND_TAP", payload: ["notificationId": "notification-a"], deliveryId: "delivery-a", receivedAtMs: 100)+ let store = try PendingPushStore(fileURL: fileURL)+ XCTAssertEqual(try store.capture(sourceId: "apns-a", event: event), event)+ XCTAssertEqual(try store.pending(at: 101), event)+ let reloaded = try PendingPushStore(fileURL: fileURL)+ XCTAssertEqual(try reloaded.pending(at: 102), event)+ XCTAssertEqual(try reloaded.pending(at: 103), event)+ XCTAssertTrue(try reloaded.acknowledge(deliveryId: "delivery-a"))+ XCTAssertNil(try PendingPushStore(fileURL: fileURL).pending(at: 104))+ XCTAssertNil(try reloaded.capture(sourceId: "apns-a", event: event))+ }++ func testLatestTapWinsAndOldAcknowledgmentOrRedeliveryCannotClearIt() throws {+ let first = PendingPush(type: "BACKGROUND_TAP", payload: ["notificationId": "a"], deliveryId: "first", receivedAtMs: 100)+ let second = PendingPush(type: "FOREGROUND_TAP", payload: ["notificationId": "b"], deliveryId: "second", receivedAtMs: 101)+ let store = try PendingPushStore(fileURL: fileURL)+ _ = try store.capture(sourceId: "apns-a", event: first)+ _ = try store.capture(sourceId: "apns-b", event: second)+ XCTAssertFalse(try store.acknowledge(deliveryId: "first"))+ let duplicate = PendingPush(type: first.type, payload: first.payload, deliveryId: "duplicate", receivedAtMs: 102)+ XCTAssertNil(try store.capture(sourceId: "apns-a", event: duplicate))+ XCTAssertEqual(try store.pending(at: 103), second)+ }++ func testExpiredIntentAndClockRollbackDoNotReopenAnOldConversation() throws {+ let event = PendingPush(type: "BACKGROUND_TAP", payload: ["notificationId": "a"], deliveryId: "first", receivedAtMs: 100)+ let store = try PendingPushStore(fileURL: fileURL, lifetimeMs: 10)+ _ = try store.capture(sourceId: "apns-a", event: event)+ XCTAssertNil(try store.pending(at: 110))+ _ = try store.capture(sourceId: "apns-a", event: event)+ XCTAssertNil(try store.pending(at: 99))+ }++ func testAccountClearPersistsAndDoesNotAllowNativeRedeliveryToReopenIt() throws {+ let event = PendingPush(type: "BACKGROUND_TAP", payload: ["recipientId": "old-account"], deliveryId: "first", receivedAtMs: 100)+ let store = try PendingPushStore(fileURL: fileURL)+ _ = try store.capture(sourceId: "apns-a", event: event)+ try store.clear()+ let reloaded = try PendingPushStore(fileURL: fileURL)+ XCTAssertNil(try reloaded.pending(at: 101))+ XCTAssertNil(try reloaded.capture(sourceId: "apns-a", event: event))+ }++ func testFailedPersistenceDoesNotConsumePreviousIntent() throws {+ let event = PendingPush(type: "BACKGROUND_TAP", payload: ["notificationId": "a"], deliveryId: "first", receivedAtMs: 100)+ let store = try PendingPushStore(fileURL: fileURL)+ _ = try store.capture(sourceId: "apns-a", event: event)+ try FileManager.default.removeItem(at: fileURL)+ try FileManager.default.createDirectory(at: fileURL, withIntermediateDirectories: true)+ XCTAssertThrowsError(try store.acknowledge(deliveryId: "first"))+ XCTAssertEqual(try store.pending(at: 101), event)+ }++ func testAccountConfigurationPreservesMatchingLaunchAndClearsOnSwitchOrLogout() throws {+ let event = PendingPush(type: "BACKGROUND_TAP", payload: ["recipientId": "account-a"], deliveryId: "first", receivedAtMs: 100)+ let store = try PendingPushStore(fileURL: fileURL)+ _ = try store.capture(sourceId: "apns-a", event: event)+ try store.configureRecipient("account-a")+ XCTAssertEqual(try store.pending(at: 101), event)+ try store.configureRecipient("account-b")+ XCTAssertNil(try store.pending(at: 102))+ _ = try store.capture(sourceId: "apns-b", event: event)+ try store.configureRecipient(nil)+ XCTAssertNil(try store.pending(at: 103))+ }++ func testMalformedPersistedStateDoesNotDisableFutureTaps() throws {+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ try Data("invalid json".utf8).write(to: fileURL)+ let store = try PendingPushStore(fileURL: fileURL)+ XCTAssertNil(try store.pending(at: 100))+ let event = PendingPush(type: "BACKGROUND_TAP", payload: ["notificationId": "a"], deliveryId: "first", receivedAtMs: 100)+ _ = try store.capture(sourceId: "apns-a", event: event)+ XCTAssertEqual(try PendingPushStore(fileURL: fileURL).pending(at: 101), event)+ }+}diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex 52d5a94f9e..b6ab1a8f20 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -71,7 +71,7 @@ graphql_cache_plugin = { path = "../graphql_cache_plugin" }macro_bundle_updater_plugin = { path = "../macro_bundle_updater_plugin" }navigation_plugin = { path = "../navigation_plugin" }tauri-plugin-device-info = "1.0.1"-tauri-plugin-notifications = { git = "https://github.com/macro-inc/tauri-plugins", rev = "6ddd6600e20436388f169e936b610fe93944b7b0" }+tauri-plugin-notifications = { path = "../ios_push_plugin" }tauri-plugin-os = "2"diff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.jsonindex 76aaa41cef..8236aef80c 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": 17+ "versionCode": 18}},"$schema": "https://schema.tauri.app/config/2",diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rsindex 73dc573997..037bcaded8 100644--- a/crates/call/src/domain/service.rs+++ b/crates/call/src/domain/service.rs@@ -640,6 +640,8 @@ impl NotificationExtIos for CallStartedNotification {push_notification_data: PushNotificationData {notification_id,sender_profile_picture_url: self.sender_profile_picture_url.clone(),+ recipient_id: None,+ navigation: None,},})}diff --git a/crates/invite_email/src/lib.rs b/crates/invite_email/src/lib.rsindex 753ed88342..93f8cb5906 100644--- a/crates/invite_email/src/lib.rs+++ b/crates/invite_email/src/lib.rs@@ -257,6 +257,8 @@ impl NotificationExtIos for ChannelInviteMetadata {push_notification_data: PushNotificationData {notification_id,sender_profile_picture_url: self.sender_profile_picture_url.clone(),+ recipient_id: None,+ navigation: None,},})}diff --git a/crates/model_notifications/AGENTS.md b/crates/model_notifications/AGENTS.mdindex 3b8711fad1..a04d58f107 100644--- a/crates/model_notifications/AGENTS.md+++ b/crates/model_notifications/AGENTS.md@@ -12,6 +12,8 @@ types.metadata types — the fastest way to see every notification kind that exists.- `src/metadata.rs` + `src/metadata/`: one metadata struct per notificationkind (channel, CRM discussion, initiative discussion, GitHub PR, reminder, …).+- `src/metadata/channel_push.rs`: channel push destinations, including the known+ thread root so clients can open directly without fetching notification metadata.- `src/digest_state.rs`: the digest batching state machine.- `src/device.rs`, `src/unsubscribe.rs`: device type and per-user unsubscribe.diff --git a/crates/model_notifications/src/metadata.rs b/crates/model_notifications/src/metadata.rsindex e607c52829..4eac47c574 100644--- a/crates/model_notifications/src/metadata.rs+++ b/crates/model_notifications/src/metadata.rs@@ -1,5 +1,6 @@mod access_request;mod calendar_join_request;+mod channel_push;pub use access_request::{EntityAccessGrantedMetadata, EntityAccessRequestedMetadata, RequestedAccessLevel,};@@ -1056,6 +1057,8 @@ fn alert_apns<T: NotificationTitle>(push_notification_data: PushNotificationData {notification_id,sender_profile_picture_url,+ recipient_id: None,+ navigation: None,},})}@@ -1102,11 +1105,19 @@ impl NotificationExtIos for ChannelMessageSendMetadata {fn as_apns<'a>(&self,sender_id: Option<MacroUserIdStr<'a>>,- _entity: &Entity<'_>,+ entity: &Entity<'_>,notification_id: Uuid,) -> Option<APNSPushNotification<Self::NotifData>> {let profile_pic = self.sender_profile_picture_url.clone();- alert_apns(self, sender_id, notification_id, profile_pic).ok()+ channel_push::channel_apns(+ self,+ sender_id,+ notification_id,+ profile_pic,+ entity,+ &self.message_id,+ None,+ )}}@@ -1120,16 +1131,18 @@ impl NotificationExtIos for ChannelMessageReactionMetadata {fn as_apns<'a>(&self,sender_id: Option<MacroUserIdStr<'a>>,- _entity: &Entity<'_>,+ entity: &Entity<'_>,notification_id: Uuid,) -> Option<APNSPushNotification<Self::NotifData>> {- alert_apns(+ channel_push::channel_apns(self,sender_id,notification_id,self.sender_profile_picture_url.clone(),+ entity,+ &self.message_id,+ self.thread_id.as_deref(),)- .ok()}}@@ -1143,11 +1156,19 @@ impl NotificationExtIos for ChannelMentionMetadata {fn as_apns<'a>(&self,sender_id: Option<MacroUserIdStr<'a>>,- _entity: &Entity<'_>,+ entity: &Entity<'_>,notification_id: Uuid,) -> Option<APNSPushNotification<Self::NotifData>> {let profile_pic = self.sender_profile_picture_url.clone();- alert_apns(self, sender_id, notification_id, profile_pic).ok()+ channel_push::channel_apns(+ self,+ sender_id,+ notification_id,+ profile_pic,+ entity,+ &self.message_id,+ self.thread_id.as_deref(),+ )}}@@ -1161,11 +1182,19 @@ impl NotificationExtIos for ChannelReplyMetadata {fn as_apns<'a>(&self,sender_id: Option<MacroUserIdStr<'a>>,- _entity: &Entity<'_>,+ entity: &Entity<'_>,notification_id: Uuid,) -> Option<APNSPushNotification<Self::NotifData>> {let profile_pic = self.sender_profile_picture_url.clone();- alert_apns(self, sender_id, notification_id, profile_pic).ok()+ channel_push::channel_apns(+ self,+ sender_id,+ notification_id,+ profile_pic,+ entity,+ &self.message_id,+ Some(&self.thread_id),+ )}}@@ -1179,11 +1208,19 @@ impl NotificationExtIos for DocumentMentionMetadata {fn as_apns<'a>(&self,sender_id: Option<MacroUserIdStr<'a>>,- _entity: &Entity<'_>,+ entity: &Entity<'_>,notification_id: Uuid,) -> Option<APNSPushNotification<Self::NotifData>> {let profile_pic = self.channel.sender_profile_picture_url.clone();- alert_apns(self, sender_id, notification_id, profile_pic).ok()+ channel_push::channel_apns(+ self,+ sender_id,+ notification_id,+ profile_pic,+ entity,+ &self.channel.message_id,+ self.channel.thread_id.as_deref(),+ )}}diff --git a/crates/model_notifications/src/metadata/channel_push.rs b/crates/model_notifications/src/metadata/channel_push.rsnew file mode 100644index 0000000000..d4e455349d--- /dev/null+++ b/crates/model_notifications/src/metadata/channel_push.rs@@ -0,0 +1,41 @@+use super::{NotificationTitle, alert_apns};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};+use notification::domain::models::apple::{+ APNSPushNotification, PushNotificationData, PushNotificationNavigation,+};+use uuid::Uuid;++#[cfg(test)]+mod test;++pub(super) fn channel_apns<T: NotificationTitle>(+ notification: &T,+ sender_id: Option<MacroUserIdStr<'_>>,+ notification_id: Uuid,+ sender_profile_picture_url: Option<String>,+ entity: &Entity<'_>,+ message_id: &str,+ thread_id: Option<&str>,+) -> Option<APNSPushNotification<PushNotificationData>> {+ let mut apns = alert_apns(+ notification,+ sender_id,+ notification_id,+ sender_profile_picture_url,+ )+ .ok()?;+ // Old persisted metadata can contain invalid IDs. Keep its alert and let the+ // client resolve the notification record instead of emitting a broken route.+ apns.push_notification_data.navigation = (|| {+ if entity.entity_type != EntityType::Channel {+ return None;+ }+ Some(PushNotificationNavigation::Channel {+ channel_id: Uuid::parse_str(&entity.entity_id).ok()?,+ message_id: Uuid::parse_str(message_id).ok()?,+ thread_id: thread_id.map(Uuid::parse_str).transpose().ok()?,+ })+ })();+ Some(apns)+}diff --git a/crates/model_notifications/src/metadata/channel_push/test.rs b/crates/model_notifications/src/metadata/channel_push/test.rsnew file mode 100644index 0000000000..bb981d2f66--- /dev/null+++ b/crates/model_notifications/src/metadata/channel_push/test.rs@@ -0,0 +1,130 @@+use crate::metadata::{ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata};+use model_entity::EntityType;+use notification::domain::models::{NotificationExtIos, apple::PushNotificationData};+use serde_json::json;+use uuid::Uuid;++#[test]+fn top_level_message_push_contains_the_destination_before_notification_fetch() {+ let metadata: ChannelMessageSendMetadata = serde_json::from_value(json!({+ "senderDisplayName": "Macro Bot",+ "messageId": "019a0000-0000-7000-8000-000000000002",+ "messageContent": "Hello",+ "channelType": "directMessage",+ "channelName": "General"+ }))+ .unwrap();+ let apns = metadata+ .as_apns(+ None,+ &EntityType::Channel.with_entity_str("019a0000-0000-7000-8000-000000000001"),+ Uuid::nil(),+ )+ .unwrap();+ let payload = serde_json::to_value(apns).unwrap();+ assert_eq!(payload["notificationId"], Uuid::nil().to_string());+ assert_eq!(payload["aps"]["alert"]["body"], "Hello");+ assert_eq!(+ payload["navigation"],+ json!({+ "type": "channel",+ "channelId": "019a0000-0000-7000-8000-000000000001",+ "messageId": "019a0000-0000-7000-8000-000000000002",+ "threadId": null+ })+ );+ // Recipients are attached at delivery, never copied from the sender.+ assert!(payload.get("recipientId").is_none());+}++#[test]+fn reply_push_includes_the_thread_root() {+ let metadata: ChannelReplyMetadata = serde_json::from_value(json!({+ "senderDisplayName": "Macro Bot",+ "threadId": "019a0000-0000-7000-8000-000000000002",+ "messageId": "019a0000-0000-7000-8000-000000000003",+ "messageContent": "Reply",+ "channelType": "public",+ "channelName": "General"+ }))+ .unwrap();+ let apns = metadata+ .as_apns(+ None,+ &EntityType::Channel.with_entity_str("019a0000-0000-7000-8000-000000000001"),+ Uuid::nil(),+ )+ .unwrap();+ assert_eq!(+ serde_json::to_value(apns).unwrap()["navigation"],+ json!({+ "type": "channel",+ "channelId": "019a0000-0000-7000-8000-000000000001",+ "messageId": "019a0000-0000-7000-8000-000000000003",+ "threadId": "019a0000-0000-7000-8000-000000000002"+ })+ );+}++#[test]+fn channel_mentions_distinguish_top_level_messages_from_replies() {+ for thread_id in [None, Some("019a0000-0000-7000-8000-000000000002")] {+ let metadata: ChannelMentionMetadata = serde_json::from_value(json!({+ "senderDisplayName": "Macro Bot",+ "threadId": thread_id,+ "messageId": "019a0000-0000-7000-8000-000000000003",+ "messageContent": "Mention",+ "channelType": "private",+ "channelName": "General"+ }))+ .unwrap();+ let apns = metadata+ .as_apns(+ None,+ &EntityType::Channel.with_entity_str("019a0000-0000-7000-8000-000000000001"),+ Uuid::nil(),+ )+ .unwrap();+ assert_eq!(+ serde_json::to_value(apns).unwrap()["navigation"],+ json!({+ "type": "channel",+ "channelId": "019a0000-0000-7000-8000-000000000001",+ "messageId": "019a0000-0000-7000-8000-000000000003",+ "threadId": thread_id+ })+ );+ }+}++#[test]+fn malformed_legacy_ids_keep_alerts_without_a_broken_destination() {+ let metadata: ChannelMessageSendMetadata = serde_json::from_value(json!({+ "senderDisplayName": "Macro Bot",+ "messageId": "legacy-message",+ "messageContent": "Hello",+ "channelType": "public",+ "channelName": "General"+ }))+ .unwrap();+ let apns = metadata+ .as_apns(+ None,+ &EntityType::Channel.with_entity_str("019a0000-0000-7000-8000-000000000001"),+ Uuid::nil(),+ )+ .unwrap();+ let payload = serde_json::to_value(apns).unwrap();+ assert!(payload.get("navigation").is_none());+ assert_eq!(payload["aps"]["alert"]["body"], "Hello");+}++#[test]+fn queued_legacy_push_data_does_not_require_navigation_or_recipient() {+ let payload: PushNotificationData = serde_json::from_value(json!({+ "notificationId": "019a0000-0000-7000-8000-000000000004"+ }))+ .unwrap();+ assert!(payload.navigation.is_none());+ assert!(payload.recipient_id.is_none());+}diff --git a/crates/notification/AGENTS.md b/crates/notification/AGENTS.mdindex bde6a00065..6018d2cda4 100644--- a/crates/notification/AGENTS.md+++ b/crates/notification/AGENTS.md@@ -83,6 +83,9 @@ through the same service.stale/unknown measurements from zero; they are not client-delivery ACKs.- Notification payloads must not be logged on tracing spans (see the`fix(notification): stop recording notification payloads` history).+- iOS egress binds `recipientId` to each receiving account; channel pushes carry+ an optional typed `navigation` destination, with `threadId: null` for a root+ message. Preserve older payloads that omit these fields.## Relateddiff --git a/crates/notification/src/domain/models/apple.rs b/crates/notification/src/domain/models/apple.rsindex 4078abcf0e..3acea5a791 100644--- a/crates/notification/src/domain/models/apple.rs+++ b/crates/notification/src/domain/models/apple.rs@@ -1,10 +1,11 @@//! Apple Push Notification Service (APNS) payload models.+use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize};use uuid::Uuid;/// The APNS payload container.-#[derive(Serialize, Debug, Deserialize)]+#[derive(Serialize, Debug, Deserialize, Clone)]#[serde(rename_all = "kebab-case")]pub struct Aps {/// The alert content.@@ -62,7 +63,7 @@ impl Default for Aps {}/// The alert content of an APNS notification.-#[derive(Serialize, Debug, Deserialize)]+#[derive(Serialize, Debug, Deserialize, Clone)]#[serde(untagged)]pub enum Alert {/// A simple string alert.@@ -72,7 +73,7 @@ pub enum Alert {}/// Dictionary-based alert with structured fields.-#[derive(Serialize, Debug, Default, Deserialize)]+#[derive(Serialize, Debug, Default, Deserialize, Clone)]#[serde(rename_all = "kebab-case")]pub struct AlertDictionary {/// The title of the notification.@@ -109,7 +110,7 @@ pub struct AlertDictionary {}/// Notification sound configuration.-#[derive(Serialize, Debug, Deserialize)]+#[derive(Serialize, Debug, Deserialize, Clone)]#[serde(untagged)]pub enum Sound {/// Default sound (usually "default").@@ -119,7 +120,7 @@ pub enum Sound {}/// Critical sound configuration with volume control.-#[derive(Serialize, Debug, Deserialize)]+#[derive(Serialize, Debug, Deserialize, Clone)]pub struct CriticalSound {/// Set to 1 for critical sound.pub critical: u8,@@ -130,7 +131,7 @@ pub struct CriticalSound {}/// The interruption level of a notification.-#[derive(Serialize, Debug, Deserialize)]+#[derive(Serialize, Debug, Deserialize, Clone)]#[serde(rename_all = "kebab-case")]pub enum InterruptionLevel {/// Delivered silently.@@ -144,7 +145,7 @@ pub enum InterruptionLevel {}/// A complete APNS push notification with custom data.-#[derive(Serialize, Debug, Deserialize)]+#[derive(Serialize, Debug, Deserialize, Clone)]#[serde(rename_all = "camelCase")]pub struct APNSPushNotification<T> {/// The APNS payload.@@ -197,6 +198,7 @@ pub struct VoipPushPayload {/// the value we send as the payload in the ios notification/// This data is accessible to the client#[derive(Serialize, Deserialize, Debug, Clone)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]#[serde(rename_all = "camelCase")]pub struct PushNotificationData {/// The id of the notification record (UserNotification.id)@@ -206,4 +208,31 @@ pub struct PushNotificationData {#[serde(skip_serializing_if = "Option::is_none")]#[serde(default)]pub sender_profile_picture_url: Option<String>,+ /// Account that owns the receiving device, set during per-recipient delivery.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[cfg_attr(feature = "schema", schema(value_type = Option<String>))]+ pub recipient_id: Option<MacroUserIdStr<'static>>,+ /// Destination to open without fetching the notification record first.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub navigation: Option<PushNotificationNavigation>,+}++/// A destination carried by a push notification. Access is checked when opened.+#[derive(Serialize, Deserialize, Debug, Clone)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(tag = "type", rename_all = "camelCase")]+pub enum PushNotificationNavigation {+ /// Open a channel at a specific message.+ Channel {+ /// Channel containing the message.+ #[serde(rename = "channelId")]+ channel_id: Uuid,+ /// Message to highlight.+ #[serde(rename = "messageId")]+ message_id: Uuid,+ /// Root of the message's thread; null identifies a top-level message.+ #[serde(rename = "threadId")]+ #[cfg_attr(feature = "schema", schema(required = true))]+ thread_id: Option<Uuid>,+ },}diff --git a/crates/notification/src/domain/service/egress.rs b/crates/notification/src/domain/service/egress.rsindex 060cf037f6..52af59a7e1 100644--- a/crates/notification/src/domain/service/egress.rs+++ b/crates/notification/src/domain/service/egress.rs@@ -112,6 +112,17 @@ fn android_notification(FCMMessage::notification(title, body, identifier, data, recipient_id)}+fn ios_notification(+ apns: &APNSPushNotification<serde_json::Value>,+ recipient_id: &MacroUserIdStr<'_>,+) -> APNSPushNotification<serde_json::Value> {+ let mut notification = apns.clone();+ if let Some(data) = notification.push_notification_data.as_object_mut() {+ data.insert("recipientId".into(), recipient_id.as_ref().into());+ }+ notification+}+#[cfg(test)]mod test;@@ -237,6 +248,7 @@ wherelet mut out = Vec::with_capacity(total);for (user_id, user_apns) in &apns.ios_device_endpoints {+ let ios = ios_notification(&apns.notif, user_id);let android = (!user_apns.android_endpoints.is_empty()).then(|| android_notification(apns, user_id.clone()));let checkers: Vec<_> = user_apns@@ -245,7 +257,7 @@ where.map(|endpoint| MobilePushSend {mobile: &self.mobile,endpoint_arn: endpoint,- notif: MobilePayload::Ios(&apns.notif),+ notif: MobilePayload::Ios(&ios),attributes: &apns.attributes,}).chain(android.iter().flat_map(|android| {diff --git a/crates/notification/src/domain/service/egress/test.rs b/crates/notification/src/domain/service/egress/test.rsindex 454ea67e78..fbede326db 100644--- a/crates/notification/src/domain/service/egress/test.rs+++ b/crates/notification/src/domain/service/egress/test.rs@@ -2,6 +2,40 @@ use super::*;use crate::domain::models::apple::{AlertDictionary, Aps};use serde_json::json;+#[test]+fn ios_delivery_binds_the_destination_to_each_receiving_account() {+ let template = APNSPushNotification {+ aps: Aps::default(),+ push_notification_data: json!({+ "notificationId": "019a0000-0000-7000-8000-000000000004",+ "recipientId": "macro|[email protected]",+ "navigation": {+ "type": "channel",+ "channelId": "019a0000-0000-7000-8000-000000000001",+ "messageId": "019a0000-0000-7000-8000-000000000002",+ "threadId": null+ }+ }),+ };+ for email in ["[email protected]", "[email protected]"] {+ let recipient = MacroUserIdStr::try_from_email(email).unwrap();+ let payload = serde_json::to_value(ios_notification(&template, &recipient)).unwrap();+ assert_eq!(payload["recipientId"], recipient.as_ref());+ assert_eq!(+ payload["navigation"],+ template.push_notification_data["navigation"]+ );+ assert_eq!(+ payload["notificationId"],+ template.push_notification_data["notificationId"]+ );+ }+ assert_eq!(+ template.push_notification_data["recipientId"],+ "macro|[email protected]"+ );+}+fn notification(alert: Option<Alert>, push_type: PushType) -> FCMMessage<serde_json::Value> {android_notification(&APNSTargets {diff --git a/crates/notification/src/domain/service/test.rs b/crates/notification/src/domain/service/test.rsindex 5715b6cd5d..2727dac597 100644--- a/crates/notification/src/domain/service/test.rs+++ b/crates/notification/src/domain/service/test.rs@@ -2,6 +2,7 @@mod access_request_delivery;mod android;+mod ios_navigation;mod status_updates;use crate::domain::models::apple::APNSPushNotification;diff --git a/crates/notification/src/domain/service/test/ios_navigation.rs b/crates/notification/src/domain/service/test/ios_navigation.rsnew file mode 100644index 0000000000..3b05d50174--- /dev/null+++ b/crates/notification/src/domain/service/test/ios_navigation.rs@@ -0,0 +1,91 @@+use super::*;+use crate::domain::models::android::FCMMessage;+use crate::domain::models::mobile::MessageAttributes;++#[derive(Default)]+struct CaptureIos {+ payloads: Mutex<HashMap<String, serde_json::Value>>,+}++impl NotificationSender for CaptureIos {+ async fn send_ios_push_notification<T: Serialize + Send + Sync>(+ &self,+ endpoint: &str,+ notification: &APNSPushNotification<T>,+ _: &MessageAttributes,+ ) -> Result<String, Report> {+ self.payloads.lock().unwrap().insert(+ endpoint.to_owned(),+ serde_json::to_value(notification).unwrap(),+ );+ Ok("message-id".into())+ }++ async fn send_android_push_notification<T: Serialize + Send + Sync>(+ &self,+ _: &str,+ _: &FCMMessage<T>,+ _: &MessageAttributes,+ ) -> Result<String, Report> {+ panic!("this notification only targets iOS devices")+ }+}++#[tokio::test]+async fn one_queued_push_gets_the_correct_account_for_each_ios_recipient() {+ let service = NotificationEgressService {+ queue: MockQueue::new(),+ repository: MockRepository::new(),+ realtime: MockRealtimeSender,+ mobile: CaptureIos::default(),+ email: MockEmailSender,+ rate_limiter: allowing_rate_limiter(),+ state_machine: MockEgressStateMachine,+ digest_batcher: MockDigestBatcher,+ };+ let message = serde_json::from_value(json!({+ "message_type": "channel_message_send",+ "content": {+ "Ios": {+ "notif": {+ "aps": {"alert": "Hello"},+ "notificationId": "019a0000-0000-7000-8000-000000000004",+ "navigation": {+ "type": "channel",+ "channelId": "019a0000-0000-7000-8000-000000000001",+ "messageId": "019a0000-0000-7000-8000-000000000002",+ "threadId": null+ }+ },+ "attributes": {"push_type": "Alert", "collapse_key": "message"},+ "ios_device_endpoints": {+ "macro|[email protected]": {"endpoints": ["alice-phone"]},+ "macro|[email protected]": {"endpoints": ["bob-phone"]}+ }+ }+ }+ }))+ .unwrap();+ let outcomes = service.deliver_notification(message).await;+ assert_eq!(outcomes.len(), 2);+ assert!(outcomes.iter().all(Result::is_ok));+ let payloads = service.mobile.payloads.lock().unwrap();+ assert_eq!(+ payloads["alice-phone"]["recipientId"],+ "macro|[email protected]"+ );+ assert_eq!(+ payloads["bob-phone"]["recipientId"],+ "macro|[email protected]"+ );+ for payload in payloads.values() {+ assert_eq!(+ payload["navigation"]["messageId"],+ "019a0000-0000-7000-8000-000000000002"+ );+ assert_eq!(+ payload["notificationId"],+ "019a0000-0000-7000-8000-000000000004"+ );+ }+}diff --git a/crates/notification/src/outbound/mobile/payload/test.rs b/crates/notification/src/outbound/mobile/payload/test.rsindex a73f9d5fa7..b4f79080db 100644--- a/crates/notification/src/outbound/mobile/payload/test.rs+++ b/crates/notification/src/outbound/mobile/payload/test.rs@@ -13,6 +13,8 @@ fn android_alert_uses_sns_fcm_v1_with_string_data() {PushNotificationData {notification_id: id,sender_profile_picture_url: Some("https://example.com/avatar.png".into()),+ recipient_id: None,+ navigation: None,},macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").unwrap(),);diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 32274aa362..2bcef1f456 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -589,6 +589,14 @@ Press `Escape` to clear selection; the parent Home shortcut is then availableagain. Typing `e` in the composer or inline editor should still enter text.Verify a message link in a fresh browser tab as well as inside an open channel:the initial page should center the requested message, including older history.+On a cold notification open, the destination shows one conversation placeholder+while channel metadata and the targeted message window load in parallel. It+must not briefly fetch or display the latest messages before resolving an+uncached message link. Explicit thread replies load their parent window and+replies together; known root messages skip the message-kind lookup. Throttle+these requests and verify the placeholder transitions directly to the target,+without a blank body or Macro spinner. A newer link supersedes an unresolved+one, while a jump inside an already-mounted conversation preserves its composer.Returning through split navigation restores the saved message position and expandedthreads. Switching channel tabs and returning restores the Messages position,expanded threads, and pending reply from when the tab was left. The `Scroll to bottom` control appears when scrolling down through history;diff --git a/docs/agent-guide/notifications.md b/docs/agent-guide/notifications.mdindex 73dfc704eb..8b1ab83d8d 100644--- a/docs/agent-guide/notifications.md+++ b/docs/agent-guide/notifications.md@@ -47,6 +47,15 @@ supported while the app process is running, not after quitting it. The isolatedLinux WebKit/D-Bus regression is `bun run native:e2e:notifications`; compositorfocus behavior still needs a real Wayland/X11 desktop check.+On iOS builds with durable push navigation, a tapped channel push chooses the+first route after verifying its recipient account. A failed or stalled native+bridge must release startup within 1.5 seconds; the app can show its auth or+retry UI while retaining the tap. If the bridge recovers later, the tap uses+normal navigation without resetting the current page to the app root. Check+both listener attachment and pending-intent reads, including a tap delivered+before the pending read stalls. Receiving a push without tapping it must not+navigate.+On native Android, enable notifications in Settings while signed in. Android 13+also asks for system permission; the system's **Activity** notification channelmust be enabled. Remote push owns system notification display after registration,diff --git a/docs/guides/add-notification-kind.md b/docs/guides/add-notification-kind.mdindex e166e19b7e..62da9556d7 100644--- a/docs/guides/add-notification-kind.md+++ b/docs/guides/add-notification-kind.md@@ -208,9 +208,17 @@ consumer matches on `notification_metadata.tag`.5. Settings: if blockable, add an entry to `NOTIFICATION_EVENT_GROUPS` in`apps/web/src/features/notifications/notification-event-catalog.ts`. It mustmatch `BLOCKABLE_NOTIFICATIONS`; no test checks that.-6. Mobile push taps carry only the notification id; the app loads the- notification and routes through `notification-navigation.ts`, so step 3 covers- phones too.+6. Mobile push taps retain the notification id for authenticated lookup through+ `notification-navigation.ts`. iOS channel pushes also carry typed `navigation`+ data (channel, message, and nullable thread-root IDs) plus a per-recipient+ `recipientId`, allowing a matching signed-in account to open the destination+ before notification hydration. Add channel destinations in+ `crates/model_notifications/src/metadata/channel_push.rs` and the metadata's+ `NotificationExtIos` implementation; regenerate the service OpenAPI and the+ web push validators with `scripts/generate-api-schema.ts`. Older pushes and+ other notification kinds still follow the lookup path, so step 3 covers+ phones too. Never infer a root from an absent thread ID: the direct payload+ requires `threadId: null` for a known top-level message.Mark done and mute act on the notification's entity, so an existing entity typeneeds nothing more. Copy `.otherwise` arms rather than throwing: older tabs ignorediff --git a/packages/sdk-docs/reference/generated/notification/types.gen/README.md b/packages/sdk-docs/reference/generated/notification/types.gen/README.mdindex 4f624f80bd..da33dd8485 100644--- a/packages/sdk-docs/reference/generated/notification/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/notification/types.gen/README.md@@ -128,6 +128,7 @@- [NotificationState](type-aliases/NotificationState.md)- [NotificationTypeName](type-aliases/NotificationTypeName.md)- [PushNotificationData](type-aliases/PushNotificationData.md)+- [PushNotificationNavigation](type-aliases/PushNotificationNavigation.md)- [RealtimeNotifTaggedContentValue](type-aliases/RealtimeNotifTaggedContentValue.md)- [ReminderMetadata](type-aliases/ReminderMetadata.md)- [RemoveUnsubscribeAllData](type-aliases/RemoveUnsubscribeAllData.md)diff --git a/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/PushNotificationData.md b/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/PushNotificationData.mdindex 15352b3105..4ed080d44b 100644--- a/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/PushNotificationData.md+++ b/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/PushNotificationData.md@@ -1,10 +1,15 @@# Type Alias: PushNotificationData-> **PushNotificationData** = \{ `notificationId`: `string`; `senderProfilePictureUrl?`: `string` \| `null`; \}+> **PushNotificationData** = \{ `navigation?`: `null` \| [`PushNotificationNavigation`](PushNotificationNavigation.md); `notificationId`: `string`; `recipientId?`: `string` \| `null`; `senderProfilePictureUrl?`: `string` \| `null`; \}++the value we send as the payload in the ios notification+This data is accessible to the client## Properties| Property | Type | Description || ------ | ------ | ------ |+| <a id="property-navigation"></a> `navigation?` | `null` \| [`PushNotificationNavigation`](PushNotificationNavigation.md) | - || <a id="property-notificationid"></a> `notificationId` | `string` | The id of the notification record (UserNotification.id) |+| <a id="property-recipientid"></a> `recipientId?` | `string` \| `null` | Account that owns the receiving device, set during per-recipient delivery. || <a id="property-senderprofilepictureurl"></a> `senderProfilePictureUrl?` | `string` \| `null` | The sender's profile picture URL, used by the Notification Service Extension to download and attach as a rich notification image. |diff --git a/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/PushNotificationNavigation.md b/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/PushNotificationNavigation.mdnew file mode 100644index 0000000000..681bf00a5d--- /dev/null+++ b/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/PushNotificationNavigation.md@@ -0,0 +1,14 @@+# Type Alias: PushNotificationNavigation++> **PushNotificationNavigation** = \{ `channelId`: `string`; `messageId`: `string`; `threadId`: `string` \| `null`; `type`: `"channel"`; \}++Open a channel at a specific message.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-channelid"></a> `channelId` | `string` | Channel containing the message. |+| <a id="property-messageid"></a> `messageId` | `string` | Message to highlight. |+| <a id="property-threadid"></a> `threadId` | `string` \| `null` | Root of the message's thread; null identifies a top-level message. |+| <a id="property-type"></a> `type` | `"channel"` | - |diff --git a/packages/sdk/generated/notification/index.ts b/packages/sdk/generated/notification/index.tsindex 4a732864ba..515e8e3fc3 100644--- a/packages/sdk/generated/notification/index.ts+++ b/packages/sdk/generated/notification/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AgentSessionMentionedMetadata, AgentSessionNotificationRef, AgentSessionOriginParent, AgentSessionSettledMetadata, AgentSessionWaitingForInputMetadata, AiResponseMetadata, ApiUserNotification, BulkDeleteUserNotificationsV2Data, BulkDeleteUserNotificationsV2Error, BulkDeleteUserNotificationsV2Errors, BulkDeleteUserNotificationsV2Responses, BulkGetByEventItemIdsRequest, BulkGetTypedNotificationsByEventItemIdsData, BulkGetTypedNotificationsByEventItemIdsError, BulkGetTypedNotificationsByEventItemIdsErrors, BulkGetTypedNotificationsByEventItemIdsResponse, BulkGetTypedNotificationsByEventItemIdsResponses, BulkMarkNotificationsDoneData, BulkMarkNotificationsDoneError, BulkMarkNotificationsDoneErrors, BulkMarkNotificationsDoneResponses, BulkMarkNotificationsSeenData, BulkMarkNotificationsSeenError, BulkMarkNotificationsSeenErrors, BulkMarkNotificationsSeenResponses, BulkMarkNotificationsUndoneData, BulkMarkNotificationsUndoneError, BulkMarkNotificationsUndoneErrors, BulkMarkNotificationsUndoneResponses, CalendarEventJoinRequestMetadata, CalendarEventReminderMetadata, CallStartedMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageReactionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType, ClientOptions, CommentedOnDocumentMetadata, CommentRef, CommonChannelMetadata, ConnGatewayNotificationPayload, CreateNotification, CrmDiscussionMetadata, CrmDiscussionReason, DeleteUserNotificationV2Data, DeleteUserNotificationV2Error, DeleteUserNotificationV2Errors, DeleteUserNotificationV2Responses, DeviceRequest, DeviceType, DisableNotificationTypeData, DisableNotificationTypeError, DisableNotificationTypeErrors, DisableNotificationTypeResponses, DocumentMentionMetadata, EmptyResponse, EnableNotificationTypeData, EnableNotificationTypeError, EnableNotificationTypeErrors, EnableNotificationTypeResponses, Entity, EntityAccessGrantedMetadata, EntityAccessRequestedMetadata, EntityType, ErrorResponse, GetAllUserNotificationsResponse, GetNotificationTypePreferencesData, GetNotificationTypePreferencesError, GetNotificationTypePreferencesErrors, GetNotificationTypePreferencesResponse, GetNotificationTypePreferencesResponse2, GetNotificationTypePreferencesResponses, GetTypedNotificationByIdData, GetTypedNotificationByIdError, GetTypedNotificationByIdErrors, GetTypedNotificationByIdResponse, GetTypedNotificationByIdResponses, GetTypedNotificationsByEventItemIdData, GetTypedNotificationsByEventItemIdError, GetTypedNotificationsByEventItemIdErrors, GetTypedNotificationsByEventItemIdResponse, GetTypedNotificationsByEventItemIdResponses, GetUnsubscribesData, GetUnsubscribesError, GetUnsubscribesErrors, GetUnsubscribesResponse, GetUnsubscribesResponses, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment, GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InboxReauthRequiredMetadata, InitiativeDiscussionMetadata, InitiativeDiscussionReason, InviteePlan, InviteToTeamMetadata, ItemSharedMetadata, ListTypedNotificationsData, ListTypedNotificationsError, ListTypedNotificationsErrors, ListTypedNotificationsResponse, ListTypedNotificationsResponses, MacroUserIdStr, MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent, NotificationBulkRequest, NotificationDocumentSubType, NotificationServiceApiVersion, NotificationState, NotificationTypeName, PushNotificationData, RealtimeNotifTaggedContentValue, ReminderMetadata, RemoveUnsubscribeAllData, RemoveUnsubscribeAllError, RemoveUnsubscribeAllErrors, RemoveUnsubscribeAllResponse, RemoveUnsubscribeAllResponses, RemoveUnsubscribeItemData, RemoveUnsubscribeItemError, RemoveUnsubscribeItemErrors, RemoveUnsubscribeItemResponse, RemoveUnsubscribeItemResponses, RepliedToDocumentCommentThreadMetadata, RequestedAccessLevel, TaskAssignedMetadata, UnsubscribeAllData, UnsubscribeAllError, UnsubscribeAllErrors, UnsubscribeAllResponse, UnsubscribeAllResponses, UnsubscribeEmailData, UnsubscribeEmailError, UnsubscribeEmailErrors, UnsubscribeEmailResponse, UnsubscribeEmailResponses, UnsubscribeItemData, UnsubscribeItemError, UnsubscribeItemErrors, UnsubscribeItemPathParams, UnsubscribeItemResponse, UnsubscribeItemResponses, UserUnsubscribe } from './types.gen';+export type { AgentSessionMentionedMetadata, AgentSessionNotificationRef, AgentSessionOriginParent, AgentSessionSettledMetadata, AgentSessionWaitingForInputMetadata, AiResponseMetadata, ApiUserNotification, BulkDeleteUserNotificationsV2Data, BulkDeleteUserNotificationsV2Error, BulkDeleteUserNotificationsV2Errors, BulkDeleteUserNotificationsV2Responses, BulkGetByEventItemIdsRequest, BulkGetTypedNotificationsByEventItemIdsData, BulkGetTypedNotificationsByEventItemIdsError, BulkGetTypedNotificationsByEventItemIdsErrors, BulkGetTypedNotificationsByEventItemIdsResponse, BulkGetTypedNotificationsByEventItemIdsResponses, BulkMarkNotificationsDoneData, BulkMarkNotificationsDoneError, BulkMarkNotificationsDoneErrors, BulkMarkNotificationsDoneResponses, BulkMarkNotificationsSeenData, BulkMarkNotificationsSeenError, BulkMarkNotificationsSeenErrors, BulkMarkNotificationsSeenResponses, BulkMarkNotificationsUndoneData, BulkMarkNotificationsUndoneError, BulkMarkNotificationsUndoneErrors, BulkMarkNotificationsUndoneResponses, CalendarEventJoinRequestMetadata, CalendarEventReminderMetadata, CallStartedMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageReactionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType, ClientOptions, CommentedOnDocumentMetadata, CommentRef, CommonChannelMetadata, ConnGatewayNotificationPayload, CreateNotification, CrmDiscussionMetadata, CrmDiscussionReason, DeleteUserNotificationV2Data, DeleteUserNotificationV2Error, DeleteUserNotificationV2Errors, DeleteUserNotificationV2Responses, DeviceRequest, DeviceType, DisableNotificationTypeData, DisableNotificationTypeError, DisableNotificationTypeErrors, DisableNotificationTypeResponses, DocumentMentionMetadata, EmptyResponse, EnableNotificationTypeData, EnableNotificationTypeError, EnableNotificationTypeErrors, EnableNotificationTypeResponses, Entity, EntityAccessGrantedMetadata, EntityAccessRequestedMetadata, EntityType, ErrorResponse, GetAllUserNotificationsResponse, GetNotificationTypePreferencesData, GetNotificationTypePreferencesError, GetNotificationTypePreferencesErrors, GetNotificationTypePreferencesResponse, GetNotificationTypePreferencesResponse2, GetNotificationTypePreferencesResponses, GetTypedNotificationByIdData, GetTypedNotificationByIdError, GetTypedNotificationByIdErrors, GetTypedNotificationByIdResponse, GetTypedNotificationByIdResponses, GetTypedNotificationsByEventItemIdData, GetTypedNotificationsByEventItemIdError, GetTypedNotificationsByEventItemIdErrors, GetTypedNotificationsByEventItemIdResponse, GetTypedNotificationsByEventItemIdResponses, GetUnsubscribesData, GetUnsubscribesError, GetUnsubscribesErrors, GetUnsubscribesResponse, GetUnsubscribesResponses, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment, GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InboxReauthRequiredMetadata, InitiativeDiscussionMetadata, InitiativeDiscussionReason, InviteePlan, InviteToTeamMetadata, ItemSharedMetadata, ListTypedNotificationsData, ListTypedNotificationsError, ListTypedNotificationsErrors, ListTypedNotificationsResponse, ListTypedNotificationsResponses, MacroUserIdStr, MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent, NotificationBulkRequest, NotificationDocumentSubType, NotificationServiceApiVersion, NotificationState, NotificationTypeName, PushNotificationData, PushNotificationNavigation, RealtimeNotifTaggedContentValue, ReminderMetadata, RemoveUnsubscribeAllData, RemoveUnsubscribeAllError, RemoveUnsubscribeAllErrors, RemoveUnsubscribeAllResponse, RemoveUnsubscribeAllResponses, RemoveUnsubscribeItemData, RemoveUnsubscribeItemError, RemoveUnsubscribeItemErrors, RemoveUnsubscribeItemResponse, RemoveUnsubscribeItemResponses, RepliedToDocumentCommentThreadMetadata, RequestedAccessLevel, TaskAssignedMetadata, UnsubscribeAllData, UnsubscribeAllError, UnsubscribeAllErrors, UnsubscribeAllResponse, UnsubscribeAllResponses, UnsubscribeEmailData, UnsubscribeEmailError, UnsubscribeEmailErrors, UnsubscribeEmailResponse, UnsubscribeEmailResponses, UnsubscribeItemData, UnsubscribeItemError, UnsubscribeItemErrors, UnsubscribeItemPathParams, UnsubscribeItemResponse, UnsubscribeItemResponses, UserUnsubscribe } from './types.gen';diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.tsindex 3d158ba5c9..84ec13c5c5 100644--- a/packages/sdk/generated/notification/types.gen.ts+++ b/packages/sdk/generated/notification/types.gen.ts@@ -1285,11 +1285,20 @@ export type NotificationState = 'unseen' | 'seen' | 'done';*/export type NotificationTypeName = string;+/**+ * the value we send as the payload in the ios notification+ * This data is accessible to the client+ */export type PushNotificationData = {+ navigation?: null | PushNotificationNavigation;/*** The id of the notification record (UserNotification.id)*/notificationId: string;+ /**+ * Account that owns the receiving device, set during per-recipient delivery.+ */+ recipientId?: string | null;/*** The sender's profile picture URL, used by the Notification Service Extension* to download and attach as a rich notification image.@@ -1297,6 +1306,25 @@ export type PushNotificationData = {senderProfilePictureUrl?: string | null;};+/**+ * Open a channel at a specific message.+ */+export type PushNotificationNavigation = {+ /**+ * Channel containing the message.+ */+ channelId: string;+ /**+ * Message to highlight.+ */+ messageId: string;+ /**+ * Root of the message's thread; null identifies a top-level message.+ */+ threadId: string | null;+ type: 'channel';+};+/*** the value of the inner payload inside [ConnGatewayNotification]*/diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.jsonindex 568262bb75..8499efa7db 100644--- a/packages/sdk/specs/notification.json+++ b/packages/sdk/specs/notification.json@@ -2982,19 +2982,66 @@},"PushNotificationData": {"type": "object",+ "description": "the value we send as the payload in the ios notification\nThis data is accessible to the client","required": ["notificationId"],"properties": {+ "navigation": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/PushNotificationNavigation",+ "description": "Destination to open without fetching the notification record first."+ }+ ]+ },"notificationId": {"type": "string","format": "uuid","description": "The id of the notification record (UserNotification.id)"},+ "recipientId": {+ "type": ["string", "null"],+ "description": "Account that owns the receiving device, set during per-recipient delivery."+ },"senderProfilePictureUrl": {"type": ["string", "null"],"description": "The sender's profile picture URL, used by the Notification Service Extension\nto download and attach as a rich notification image."}}},+ "PushNotificationNavigation": {+ "oneOf": [+ {+ "type": "object",+ "description": "Open a channel at a specific message.",+ "required": ["channelId", "messageId", "threadId", "type"],+ "properties": {+ "channelId": {+ "type": "string",+ "format": "uuid",+ "description": "Channel containing the message."+ },+ "messageId": {+ "type": "string",+ "format": "uuid",+ "description": "Message to highlight."+ },+ "threadId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Root of the message's thread; null identifies a top-level message."+ },+ "type": {+ "type": "string",+ "enum": ["channel"]+ }+ }+ }+ ],+ "description": "A destination carried by a push notification. Access is checked when opened."+ },"RealtimeNotif_TaggedContent_Value": {"allOf": [{diff --git a/services/notification_service/AGENTS.md b/services/notification_service/AGENTS.mdindex 350bc184fe..01c6caf71f 100644--- a/services/notification_service/AGENTS.md+++ b/services/notification_service/AGENTS.md@@ -16,6 +16,8 @@ worker that sends email/mobile-push/websocket notifications.- `src/api.rs` + `src/api/context.rs`: HTTP routes — `user_notification.rs`(list/read), `unsubscribe.rs`, `health.rs`.- `src/model/notification.rs`: service-local request/response shapes.+- Push payload schemas come from `notification::domain::models::apple`; keep the+ frontend push validators generated from those same OpenAPI components.- `README.md`: local DB setup (`sqlx database setup` from`crates/notification_db_client`).diff --git a/services/notification_service/src/notification/send/push.rs b/services/notification_service/src/notification/send/push.rsindex e5364fda11..71844eb505 100644--- a/services/notification_service/src/notification/send/push.rs+++ b/services/notification_service/src/notification/send/push.rs@@ -1,24 +1 @@-use serde::{Deserialize, Serialize};-use utoipa::ToSchema;-use uuid::Uuid;--#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct PushNotificationData {- /// The id of the notification record (UserNotification.id)- pub notification_id: Uuid,- /// The sender's profile picture URL, used by the Notification Service Extension- /// to download and attach as a rich notification image.- #[serde(skip_serializing_if = "Option::is_none")]- #[serde(default)]- pub sender_profile_picture_url: Option<String>,-}--impl PushNotificationData {- pub fn new_from_inner(val: notification::domain::models::apple::PushNotificationData) -> Self {- Self {- notification_id: val.notification_id,- sender_profile_picture_url: val.sender_profile_picture_url,- }- }-}+pub use notification::domain::models::apple::PushNotificationData;