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(mobile): better offline support (#5971)
Peter Chinmanf41d24736ca7
diff --git a/apps/web/src/components/ui/components/EmptyStatePanel.tsx b/apps/web/src/components/ui/components/EmptyStatePanel.tsxindex 0ec0d6ddd0..9558ef09cf 100644--- a/apps/web/src/components/ui/components/EmptyStatePanel.tsx+++ b/apps/web/src/components/ui/components/EmptyStatePanel.tsx@@ -45,7 +45,11 @@ export function EmptyStatePanel(props: EmptyStatePanelProps) {// too tight, so we widen the padding and let the centered column keep// comfortable space from the split's edges (content stays left-aligned).'flex size-full flex-col overflow-y-auto px-10 pb-8 @4xl:px-2',- props.centered && 'items-center text-center',+ // Centered states can span full-bleed mobile panels (e.g. the entity+ // load gate), where the panel extends behind the floating top chrome+ // — inset the content below it like other full-bleed content.+ props.centered &&+ 'items-center text-center touch:pt-(--mobile-content-inset-top)',props.class)}>diff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsxindex aacbde0427..100725266a 100644--- a/apps/web/src/features/block-agent/component/Block.tsx+++ b/apps/web/src/features/block-agent/component/Block.tsx@@ -1,8 +1,10 @@import { SidePanel } from '@components/app/side-panel';import { SplitPanelContext } from '@components/app/split-layout/context';import { useBlockId } from '@core/block';+import { LoadErrorPanel } from '@core/component/EntityLoadGate';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { LinkedConversationDrawer } from '@core/linked-conversation';+import { nativeNetworkStatus } from '@core/mobile/native-network-status';import { Show, useContext } from 'solid-js';import {@@ -20,39 +22,60 @@ import { AgentSidePanelSections } from './sidepanel/AgentSidePanelSections';import { Transcript } from './Transcript';function AgentBlockContent() {- const { session, metadata } = useAgentSession();+ const { session, metadata, loadFailed, loadRetryable, pending, retryLoad } =+ useAgentSession();++ // Nothing loaded and no way forward: the load failed outright, or the+ // device is offline and the pending load cannot complete until+ // connectivity returns (that one resumes by itself, so no Retry). Gating+ // the whole block — like the other entity blocks — keeps the composer and+ // header from rendering against a session that never loaded.+ const loadUnavailable = () =>+ loadFailed() ||+ (nativeNetworkStatus() === 'offline' && !session() && !pending());return (- // One shared static-markdown editor for every text part, rather than one- // per part — the same scoping the channel does around its message tree.- <StaticMarkdownContext>- <div class="size-full overflow-hidden flex">- {/* Collapsed by default, like the other conversation-shaped blocks —+ <Show+ when={!loadUnavailable()}+ fallback={+ <LoadErrorPanel+ title="Unable to load this document"+ onRetry={loadRetryable() ? retryLoad : undefined}+ />+ }+ >+ {/* One shared static-markdown editor for every text part, rather than+ one per part — the same scoping the channel does around its message+ tree. */}+ <StaticMarkdownContext>+ <div class="size-full overflow-hidden flex">+ {/* Collapsed by default, like the other conversation-shaped blocks —the transcript wants the width; `]` or the header button opens it. */}- <SidePanel.Layout defaultOpen={false}>- <AgentSidePanelSections />- <AgentSplitHeader- session={session()}- title={metadata()?.title ?? undefined}- />- <div class="size-full min-w-0 flex flex-col">- <Transcript />- <div class="shrink-0 w-full max-w-3xl mx-auto px-4 pb-4">- <AgentComposer />+ <SidePanel.Layout defaultOpen={false}>+ <AgentSidePanelSections />+ <AgentSplitHeader+ session={session()}+ title={metadata()?.title ?? undefined}+ />+ <div class="size-full min-w-0 flex flex-col">+ <Transcript />+ <div class="shrink-0 w-full max-w-3xl mx-auto px-4 pb-4">+ <AgentComposer />+ </div></div>- </div>- <Show when={sessionOriginThread(session())}>- {(origin) => (- <LinkedConversationDrawer- id={ORIGIN_THREAD_DRAWER_ID}- channelId={origin().channelId}- messageId={origin().messageId}- />- )}- </Show>- </SidePanel.Layout>- </div>- </StaticMarkdownContext>+ <Show when={sessionOriginThread(session())}>+ {(origin) => (+ <LinkedConversationDrawer+ id={ORIGIN_THREAD_DRAWER_ID}+ channelId={origin().channelId}+ messageId={origin().messageId}+ />+ )}+ </Show>+ </SidePanel.Layout>+ </div>+ </StaticMarkdownContext>+ </Show>);}diff --git a/apps/web/src/features/block-agent/component/Transcript.tsx b/apps/web/src/features/block-agent/component/Transcript.tsxindex 16d74ebb57..891c49f9d7 100644--- a/apps/web/src/features/block-agent/component/Transcript.tsx+++ b/apps/web/src/features/block-agent/component/Transcript.tsx@@ -20,7 +20,7 @@import { ScrollToBottomOverlay } from '@channel/Channel/ScrollToBottomOverlay';import type { ThreadListScrollState } from '@channel/Channel/ThreadList';import { Scroll } from '@ui';-import { createSignal, onCleanup, Show } from 'solid-js';+import { createSignal, onCleanup } from 'solid-js';import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';import { useAgentSession } from '../context/AgentSessionContext';import { Message } from './AgentMessage';@@ -33,7 +33,7 @@ const SETTLE_MS = 1000;const ITEM_SIZE = 96;export function Transcript() {- const { messages, loadFailed } = useAgentSession();+ const { messages } = useAgentSession();let scrollRef: HTMLDivElement | undefined;let handle: VirtualizerHandle | undefined;@@ -165,11 +165,6 @@ export function Transcript() {>{/* Bottom-align short transcripts, chat-style. */}<div aria-hidden style={{ 'flex-grow': 1 }} />- <Show when={loadFailed()}>- <div class="w-full max-w-3xl mx-auto px-4 py-4 text-sm text-ink-muted">- Couldn't load this agent session.- </div>- </Show><div ref={observeGrowth}><Virtualizerref={(virtualizer) => {diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsxindex 151f87ccc4..f8351df4cf 100644--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx@@ -55,6 +55,13 @@ export type AgentSessionState = {/** The folded transcript, ordered by turn, live-following the session. */messages: Accessor<FoldedMessage[]>;loadFailed: Accessor<boolean>;+ /**+ * Retry can re-run the failed load. False when the create itself failed —+ * there is no session to refetch, so offering Retry would do nothing.+ */+ loadRetryable: Accessor<boolean>;+ /** Re-runs a failed load. */+ retryLoad: () => void;/*** The block's one answer to "is the agent working": the fold's* turn-in-flight signal, cut off when the runtime is known to be gone.@@ -130,6 +137,8 @@ export function AgentSessionProvider(// A create that failed leaves the block with nothing to load, which// is the same dead end for the reader as a load that failed.loadFailed: () => feed.loadFailed() || failed(),+ loadRetryable: feed.loadFailed,+ retryLoad: feed.retry,working,status: status.status,resuming,diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.tsindex 66c08e9786..e226d113d5 100644--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.ts@@ -44,6 +44,8 @@ export type AgentSessionFeed = {/** The folded transcript, ordered by turn (prompt before reply). */messages: Accessor<FoldedMessage[]>;loadFailed: Accessor<boolean>;+ /** Re-runs a failed load. */+ retry: () => void;/** The newest turn has no stop reason yet — the agent is working. */working: Accessor<boolean>;};@@ -113,46 +115,49 @@ export function createAgentSessionFeed(release = undefined;});- const [resource, { mutate }] = createResource(sessionId, async (id) => {- const run = ++generation;- const renameRefreshAtStart = renameRefresh;- const superseded = () => closed || generation !== run;-- release?.();- release = undefined;- batch(() => {- setList(reconcile([]));- setBot(undefined);- setMetadata(undefined);- });-- const session = await agentHarnessServiceClient.get(id);- if (session.isErr()) {- throw new Error(`agent session could not be fetched: ${id}`);- }- if (superseded()) return session.value;-- const fold = await acquireAgentSessionFold({- agentSessionId: id,- onChange: upsert,- onMetadata: setMetadata,- });- if (superseded()) {- fold.release();- return session.value;+ const [resource, { mutate, refetch }] = createResource(+ sessionId,+ async (id) => {+ const run = ++generation;+ const renameRefreshAtStart = renameRefresh;+ const superseded = () => closed || generation !== run;++ release?.();+ release = undefined;+ batch(() => {+ setList(reconcile([]));+ setBot(undefined);+ setMetadata(undefined);+ });++ const session = await agentHarnessServiceClient.get(id);+ if (session.isErr()) {+ throw new Error(`agent session could not be fetched: ${id}`);+ }+ if (superseded()) return session.value;++ const fold = await acquireAgentSessionFold({+ agentSessionId: id,+ onChange: upsert,+ onMetadata: setMetadata,+ });+ if (superseded()) {+ fold.release();+ return session.value;+ }+ release = fold.release;+ batch(() => {+ setBot(fold.bot);+ setMetadata(fold.metadata);+ upsert(fold.messages);+ });++ return renameRefresh > renameRefreshAtStart &&+ latestRename?.agentSessionId === id+ ? { ...session.value, name: latestRename.name }+ : session.value;}- release = fold.release;- batch(() => {- setBot(fold.bot);- setMetadata(fold.metadata);- upsert(fold.messages);- });-- return renameRefresh > renameRefreshAtStart &&- latestRename?.agentSessionId === id- ? { ...session.value, name: latestRename.name }- : session.value;- });+ );onCleanup(subscribeAgentSessionRenamed((event) => {@@ -221,6 +226,7 @@ export function createAgentSessionFeed(metadata,messages,loadFailed: () => resource.error !== undefined,+ retry: () => void refetch(),working,};}diff --git a/apps/web/src/features/block-email/component/BaseInput.tsx b/apps/web/src/features/block-email/component/BaseInput.tsxindex d5e89f0814..2a6dc32523 100644--- a/apps/web/src/features/block-email/component/BaseInput.tsx+++ b/apps/web/src/features/block-email/component/BaseInput.tsx@@ -26,6 +26,7 @@ import {ENABLE_EMAIL_SCHEDULED_SEND,ENABLE_EMAIL_SIGNATURES_FLAG,ENABLE_EMAIL_SIGNATURES_OVERRIDE,+ ENABLE_GRAPHQL_SOUP,} from '@core/constant/featureFlags';import { useEmail } from '@core/context/user';import { fileFolderDrop } from '@core/directive/fileFolderDrop';@@ -70,10 +71,11 @@ import {usePrimaryEmailLinkId,} from '@queries/email/link';import {+ fetchAndCacheThread,useSendMessageMutation,useUnscheduleMessageMutation,} from '@queries/email/thread';-import { invalidateSoupEntity, refetchSoupEntity } from '@queries/soup/cache';+import { refetchSoupEntity } from '@queries/soup/cache';import type { UndoHandle } from '@queries/undo';import { emailClient } from '@service-email/client';import type {@@ -107,7 +109,6 @@ import {clearEmailBody,hasDraftContent,prepareEmailBody,- prepareEmailBodyFromHtml,prepareMacroBody,registerToggleAppendedThread,TOGGLE_APPEND_EMAIL_THREAD_COMMAND,@@ -116,9 +117,9 @@ import { convertEmailRecipientToContactInfo } from '../util/recipientConversion'import { getReplyTypeFromDraft } from '../util/replyType';import {endUndoSend,- tryBeginUndoSend,- unscheduleWithRetry,-} from '../util/undoSendGuard';+ restoreDraftBodyAfterUndo,+ runUndoSend,+} from '../util/undoSend';import { SignaturePreview } from './compose/SignaturePreview';import {type EmailRecipient,@@ -274,6 +275,15 @@ export function BaseInput(props: {draft?: ApiMessage;preloadedBody?: string;preloadedHtml?: string;+ /** Seed identity of the draft this composer mounted from — becomes part of+ * the form-state cache key so a remount on a newer draft version gets a+ * freshly seeded form. See EmailInput's seed key. */+ formSeed?: string;+ /** Reports the composer gaining local state worth keeping — a first edit+ * or save (every modification funnels through scheduleDraftSave) or an+ * undo-send restore. The parent latches the seed key on it so the input+ * stops remounting on later draft versions. */+ onEngaged?: () => void;sideEffectOnSend?: (newMessageId: ApiDraftOutputDbId | null) => void;onMarkDone?: (opts?: {silent?: boolean;@@ -304,6 +314,7 @@ export function BaseInput(props: {return getOrInitEmailFormContext({type: 'replying_to',messageID: replyingTo.db_id,+ seed: props.formSeed,});}@@ -313,6 +324,7 @@ export function BaseInput(props: {return getOrInitEmailFormContext({type: 'draft',messageID: props.draft.db_id,+ seed: props.formSeed,});}@@ -387,15 +399,18 @@ export function BaseInput(props: {recipient: EmailRecipient;sourceField: 'to' | 'cc' | 'bcc';} | null>(null);+ // A pending undo-send restore that belongs to this thread (inline reply+ // remount case). It carries a just-undone send. Consumed below.+ const restoredSnapshot =+ undoReplySnapshot?.threadId === ctx.thread()?.db_id+ ? undoReplySnapshot+ : null;++ // The draft row this composer upserts into: the server draft when one+ // exists, else the one the undone send restores.const [savedDraftId, setSavedDraftId] = createSignal<ApiDraftOutputDbId | undefined- >(- props.draft?.db_id ??- (undoReplySnapshot?.threadId === ctx.thread()?.db_id- ? undoReplySnapshot?.draftId- : undefined) ??- undefined- );+ >(props.draft?.db_id ?? restoredSnapshot?.draftId ?? undefined);const editorConfig = createConfiguredEmailMarkdownEditor({namespace: 'email-base-input-markdown',@@ -430,15 +445,14 @@ export function BaseInput(props: {const markdownHandle = editorConfig.buildHandle();const editor = () => markdownHandle.lexical;- // Consume undo-send snapshot if one exists and belongs to this thread (inline reply remount case).- // Use bodyHtml as initialHtml for the editor, restore attachments on mount.- const restoredSnapshot =- undoReplySnapshot?.threadId === ctx.thread()?.db_id- ? undoReplySnapshot- : null;+ // Consume the undo-send snapshot so a later composer mount doesn't restore+ // it again. Use bodyHtml as initialHtml for the editor, restore attachments+ // on mount.if (restoredSnapshot) {undoReplySnapshot = null;onMount(() => {+ // Restored content is local state worth keeping — latch the seed.+ props.onEngaged?.();for (const attachment of restoredSnapshot.attachments) {form().attachments.add(attachment);}@@ -452,6 +466,7 @@ export function BaseInput(props: {// Register a callback so stale undoSend closures from a previous mount can// restore state into this (the live) component instance.restoreUndoCallback = (snapshot, draftId) => {+ props.onEngaged?.();setSavedDraftId(draftId);const currentEditor = editor();if (currentEditor && snapshot.bodyHtml) {@@ -492,129 +507,101 @@ export function BaseInput(props: {let markDoneUndoHandle: UndoHandle | undefined;let pendingMarkDoneNavigationTargetId: string | undefined;- // linkId is the X-Email-Link-Id header value the send itself used, resolved- // at send time. Undo can fire after navigation has disposed this component's- // reactive state (mark-done navigates away).- const undoSend = async (draftId: string, linkId: string | undefined) => {- if (!tryBeginUndoSend(draftId)) return;- try {- const result = await unscheduleWithRetry(draftId, linkId);- // A non-2xx response comes back as an Err Result (it doesn't throw), so- // bail before reverting the send appearance in the UI.- if (result.isErr()) {- endUndoSend(draftId);- Telemetry.error(- new Error(- `Failed to undo send for draft ${draftId}: ${result.error- .map((e) => `${e.code}: ${e.message}`)- .join(', ')}`- )- );- // 400 is the backend's "already sent" — the undo window has passed.- const alreadySent = result.error.some(- (e) => e.code === 'HTTP_ERROR' && e.message.includes('status: 400')- );- toast.failure(- alreadySent- ? 'Too late to undo — the email was already sent'- : 'Failed to undo send'- );- return;- }- queryClient.invalidateQueries({- queryKey: emailKeys.previews._def,- });-- let snapshot: UndoReplySnapshot | null = null;- if (undoSendSnapshot?.draftId === draftId) {- snapshot = undoSendSnapshot;- undoSendSnapshot = null;- }-- // Remove the sent message from the thread cache so it disappears from- // the list. Prefer the snapshot's threadId (send-time captured value), survives navigation; the context- // read covers snapshotless undos in a still-mounted thread.- const threadId = snapshot?.threadId ?? ctx.thread()?.db_id;- if (threadId) {- queryClient.setQueryData(- emailKeys.threadMessages(threadId).queryKey,- (old: any) => {- if (!old?.pages) return old;- return {- ...old,- pages: old.pages.map((page: any) => ({- ...page,- messages: page.messages.filter((m: any) => m.db_id !== draftId),- })),- };- }- );- // Wipe the thread cache on unmount so the next visit fetches fresh- // data (with the restored draft). Deferred to avoid Suspense DOM- // detach while the thread is open.- markThreadDraftSaved(threadId);- }+ // Everything that follows a successful unschedule: consume the send+ // snapshot, scrub the sent message from the thread cache, restore the+ // server-side draft and the composer, and reverse the send's mark-done.+ const restoreAfterUndoSend = async (+ draftId: string,+ linkId: string | undefined+ ) => {+ let snapshot: UndoReplySnapshot | null = null;+ if (undoSendSnapshot?.draftId === draftId) {+ snapshot = undoSendSnapshot;+ undoSendSnapshot = null;+ }- // The unscheduled message still carries the sent body — appended reply- // chain and injected signature included — so overwrite the server-side- // draft with the pre-send content before anything loads it into a- // composer (thread revisit, refetch, next session).- if (snapshot) {- const prepared = prepareEmailBodyFromHtml(snapshot.bodyHtml);- const saveResult = await emailClient.createDraft(- {- draft: { ...snapshot.draftRestore, body_html: prepared.bodyHtml },- },- linkId- );- if (saveResult.isErr()) {- // Non-fatal: the composer restores from the snapshot either way,- // and the next draft autosave overwrites the stale body.- Telemetry.error(- new Error('Failed to restore draft body after undo-send')- );+ // Remove the sent message from the thread cache so it disappears from+ // the list. Prefer the snapshot's threadId — captured at send time, it+ // survives navigation — while the context read covers snapshotless undos+ // in a still-mounted thread.+ const threadId = snapshot?.threadId ?? ctx.thread()?.db_id;+ if (threadId && !ENABLE_GRAPHQL_SOUP()) {+ queryClient.setQueryData(+ emailKeys.threadMessages(threadId).queryKey,+ (old: any) => {+ if (!old?.pages) return old;+ return {+ ...old,+ pages: old.pages.map((page: any) => ({+ ...page,+ messages: page.messages.filter((m: any) => m.db_id !== draftId),+ })),+ };}- }+ );+ // Wipe the thread cache on unmount so the next visit fetches fresh+ // data (with the restored draft). Deferred to avoid Suspense DOM+ // detach while the thread is open.+ markThreadDraftSaved(threadId);+ }- if (snapshot && restoreUndoCallback) {- // A live BaseInput is mounted — restore after reactive updates from- // setQueryData have settled (form may have re-keyed).- const cb = restoreUndoCallback;- setTimeout(() => cb(snapshot, draftId), 0);- } else if (snapshot) {- // No live component (e.g. inline reply was unmounted).- // Stash for mount-time restore.- undoReplySnapshot = snapshot;- props.setShowReply?.(true);- }+ // Overwrite the server-side draft with the pre-send content before+ // anything loads it into a composer (thread revisit, refetch, next+ // session).+ if (snapshot) {+ await restoreDraftBodyAfterUndo(+ snapshot.draftRestore,+ snapshot.bodyHtml,+ linkId+ );+ }- // Reverse the mark-done this send triggered (restores the soup rows,- // notification state, and unarchives), then refresh the thread's soup- // item the same way a send does so inbox views show the restored draft.- const doneHandle = markDoneUndoHandle;- markDoneUndoHandle = undefined;- if (doneHandle) {- await doneHandle.undo({- onError: () => toast.failure('Failed to restore thread to inbox'),- });- }- if (threadId) {- void refetchSoupEntity(threadId, 'emailThread');- }+ // GraphQL mode renders the thread from the normalized cache, which the+ // setQueryData surgery above can't reach — refetch through it instead.+ // After the draft-body restore, so the single fetch returns the message+ // as a draft with the pre-send content, dropping it from the message+ // list and re-seeding the draft map in one pass.+ if (threadId && ENABLE_GRAPHQL_SOUP()) {+ void fetchAndCacheThread(threadId);+ }- toast.success('Send cancelled');- invalidateSoupEntity(draftId);- } catch (e) {- endUndoSend(draftId);- Telemetry.error(- e instanceof Error- ? e- : new Error(`Failed to undo send for draft ${draftId}`)- );- toast.failure('Failed to undo send');+ if (snapshot && restoreUndoCallback) {+ // A live BaseInput is mounted — restore after reactive updates from+ // setQueryData have settled (form may have re-keyed).+ const cb = restoreUndoCallback;+ setTimeout(() => cb(snapshot, draftId), 0);+ } else if (snapshot) {+ // No live component (e.g. inline reply was unmounted).+ // Stash for mount-time restore.+ undoReplySnapshot = snapshot;+ props.setShowReply?.(true);+ }++ // Reverse the mark-done this send triggered (restores the soup rows,+ // notification state, and unarchives), then refresh the thread's soup+ // item the same way a send does so inbox views show the restored draft.+ const doneHandle = markDoneUndoHandle;+ markDoneUndoHandle = undefined;+ if (doneHandle) {+ await doneHandle.undo({+ onError: () => toast.failure('Failed to restore thread to inbox'),+ });+ }+ if (threadId) {+ void refetchSoupEntity(threadId, 'emailThread');}};+ // linkId is the X-Email-Link-Id header value the send itself used, resolved+ // at send time. Undo can fire after navigation has disposed this component's+ // reactive state (mark-done navigates away).+ const undoSend = (draftId: string, linkId: string | undefined) =>+ runUndoSend({+ draftId,+ linkId,+ onUndone: () => restoreAfterUndoSend(draftId, linkId),+ });+const sendMutation = useSendMessageMutation({onSuccess: async ({ message }, vars) => {// Cancel the post-reset save scheduled by sendEmail's resetState() and@@ -894,21 +881,58 @@ export function BaseInput(props: {}}+ // The reply target the pending debounced save was scheduled against.+ // Captured at schedule time — a live interactive context — because the+ // unmount flush below cannot trust props during disposal.+ let pendingSaveReplyingToId: string | undefined;+function scheduleDraftSave() {+ props.onEngaged?.();+ pendingSaveReplyingToId = untrack(() => props.replyingTo()?.db_id);if (draftSaveTimer) window.clearTimeout(draftSaveTimer);draftSaveTimer = window.setTimeout(() => {+ draftSaveTimer = undefined;void executeSaveDraft();}, DRAFT_DEBOUNCE_MS);}onCleanup(() => {- if (draftSaveTimer) window.clearTimeout(draftSaveTimer);+ const flushPending = draftSaveTimer !== undefined;+ if (draftSaveTimer) {+ window.clearTimeout(draftSaveTimer);+ draftSaveTimer = undefined;+ }+ // A send or discard already owns this composer's state; saving here+ // would resurrect content those flows just cleared.+ if (pendingSend || pendingDeletion) return;++ // Flush the pending debounced save so dismissal doesn't drop the last+ // edits server-side; a failure surfaces through the mutation's toast.+ if (flushPending) {+ try {+ // Only while the reply target still reads as the one the save was+ // scheduled against — mid-disposal it can come back empty or stale,+ // and a save without replying_to_id would unlink the server draft+ // from its message.+ if (+ untrack(() => props.replyingTo()?.db_id) === pendingSaveReplyingToId+ ) {+ // The mutation's own onError reports the failure (toast + console);+ // this catch only keeps the post-disposal rejection from surfacing+ // as unhandled.+ executeSaveDraft().catch(() => {});+ }+ } catch {+ // Props already disposed; the next mount's autosave persists it.+ }+ }});// Persist the draft immediately when the user switches the sending inbox, even// without a text edit, so it moves to the new inbox and the choice survives a// refresh. Driven by the explicit switch (below) rather than inbox reactivity.const persistDraftOnSenderSwitch = (linkId: string) => {+ props.onEngaged?.();form().setSelectedFromLink(linkId);if (draftSaveTimer) window.clearTimeout(draftSaveTimer);void executeSaveDraft();@@ -2157,7 +2181,12 @@ export function BaseInput(props: {{(html) => (<SignaturePreviewhtml={html()}- onDismiss={() => setIncludeSignature(false)}+ onDismiss={() => {+ // Dismissal is composer-local state worth keeping — latch+ // the seed so a draft upgrade can't remount it away.+ props.onEngaged?.();+ setIncludeSignature(false);+ }}/>)}</Show>@@ -2219,7 +2248,12 @@ export function BaseInput(props: {{(html) => (<SignaturePreviewhtml={html()}- onDismiss={() => setIncludeSignature(false)}+ onDismiss={() => {+ // Dismissal is composer-local state worth keeping — latch+ // the seed so a draft upgrade can't remount it away.+ props.onEngaged?.();+ setIncludeSignature(false);+ }}/>)}</Show>diff --git a/apps/web/src/features/block-email/component/Block.tsx b/apps/web/src/features/block-email/component/Block.tsxindex 936e6d1636..c8fee83e57 100644--- a/apps/web/src/features/block-email/component/Block.tsx+++ b/apps/web/src/features/block-email/component/Block.tsx@@ -3,24 +3,33 @@ import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { useBlockId } from '@core/block';import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';+import {+ EntityLoadGate,+ toEntityLoadError,+} from '@core/component/EntityLoadGate';import { buildEntityData } from '@entity';import { EmailDebouncedReadMarker } from '@notifications';import { useThreadQuery } from '@queries/email/thread';import { createMemo, Show, Suspense } from 'solid-js';-import { blockDataSignal } from '../signal/emailBlockData';import { displaySubject } from '../util/subjectText';import { EmailView } from './Email';export default function BlockEmail() {- const blockData = blockDataSignal.get;const blockId = useBlockId();+ const threadId = () => blockId;++ const threadQuery = useThreadQuery(threadId, () => ({+ enabled: !!threadId(),+ }));+// Email threads are absent from quick access, so the entity the block-level- // commands act on has to come from here. Built off the block's loaded data- // rather than `threadQuery` because command-menu conditions read it outside a- // Suspense boundary.+ // commands act on has to come from here. Gated on isSuccess so the+ // command-menu conditions, which read this outside a Suspense boundary,+ // never touch pending query data.const commandEntity = createMemo(() => {- const thread = blockData()?.thread;+ if (!threadQuery.isSuccess) return undefined;+ const thread = threadQuery.data?.thread;if (!thread) return undefined;return buildEntityData({id: thread.db_id,@@ -32,17 +41,24 @@ export default function BlockEmail() {});useBlockEntityCommands(commandEntity);++ // The gate owns the load policy: structural errors are authoritative even+ // over cached data, a transport failure over cached data still renders the+ // thread, and an offline load with nothing cached gates as the retryable+ // state. Loader-level errors (e.g. an invalid source) still reach+ // DocumentBlockContainer through blockErrorSignal.+ const threadLoadResult = {+ data: () => threadQuery.data,+ error: () =>+ threadQuery.isError ? toEntityLoadError(threadQuery.error) : undefined,+ isPending: () => threadQuery.isLoading,+ };+const notificationSource = useGlobalNotificationSource();// A Preview Pair Viewer shows the thread passively — wait longer before// marking it seen so scanning/previewing doesn't clear unread state.const isPreview = !!useSplitPanel()?.handle.isViewerSplit();- const threadId = () => blockId;-- const threadQuery = useThreadQuery(threadId, () => ({- enabled: !!threadId(),- }));-const title = () => {const data = threadQuery.data;if (!data || !data.thread || data.thread.messages.length === 0) return '';@@ -53,7 +69,11 @@ export default function BlockEmail() {<Suspense><DocumentBlockContainer title={title() ?? 'Email'}><div class="size-full" tabIndex={-1}>- <Show when={blockData()}>+ <EntityLoadGate+ result={threadLoadResult}+ loadErrorTitle="Unable to load this email"+ onRetry={() => void threadQuery.refetch()}+ ><Show when={threadId()}>{(id) => (<>@@ -69,7 +89,7 @@ export default function BlockEmail() {</>)}</Show>- </Show>+ </EntityLoadGate></div></DocumentBlockContainer></Suspense>diff --git a/apps/web/src/features/block-email/component/BottomReplyButtons.tsx b/apps/web/src/features/block-email/component/BottomReplyButtons.tsxindex d8c26f005a..6361406c98 100644--- a/apps/web/src/features/block-email/component/BottomReplyButtons.tsx+++ b/apps/web/src/features/block-email/component/BottomReplyButtons.tsx@@ -13,7 +13,6 @@ import { Button, cn } from '@ui';import { type Component, Show } from 'solid-js';import type { ReplyType } from '../util/replyType';import { useEmailContext } from './EmailContext';-import { getEmailFormRegistry } from './EmailFormContext';import { openEmailReplyComposerForMessage } from './emailReplyActions';function ReplyActionButton(props: {@@ -47,7 +46,6 @@ function ReplyActionButton(props: {export function BottomReplyButtons(props: { lastMessage: ApiMessage }) {const ctx = useEmailContext();- const formRegistry = getEmailFormRegistry();const currentUserEmail = useEmail();const open = (type: ReplyType) =>@@ -56,7 +54,6 @@ export function BottomReplyButtons(props: { lastMessage: ApiMessage }) {if (!messageId) return;openEmailReplyComposerForMessage({ctx,- formRegistry,message: props.lastMessage,replyType: type,isLastMessage: true,diff --git a/apps/web/src/features/block-email/component/EmailContext.tsx b/apps/web/src/features/block-email/component/EmailContext.tsxindex 6fd501e2d3..34e98e9a9d 100644--- a/apps/web/src/features/block-email/component/EmailContext.tsx+++ b/apps/web/src/features/block-email/component/EmailContext.tsx@@ -22,7 +22,6 @@ import {useContacts,type WithCustomUserInput,} from '@core/user';-import { whenSettled } from '@core/util/whenSettled';import {compositeEntity,createEffectOnEntityTypeNotification,@@ -287,31 +286,55 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {},});- const [messageDraftMap, setMessageDraftMap] = createStore<- Record<string, ApiMessage | undefined>+ // The newest version of each reply draft seen across query snapshots,+ // keyed by the replied-to message id. A cached snapshot populates this the+ // moment it's available (the composer must not wait on the network), and a+ // later fetch upgrades an entry only when its updated_at is newer — so the+ // revalidation of a stale cache wins, but an out-of-order response can't+ // downgrade a draft. Entries missing from a fetch are kept: deletes are+ // handled locally below, and dropping one would collapse an open composer.+ const serverDrafts = createMemo<+ { threadDbId: string; map: Record<string, ApiMessage> } | undefined+ >((prev) => {+ const data = threadQuery.data;+ if (!data) return undefined;+ const next = data.draftMap;+ if (!prev || prev.threadDbId !== data.db_id) {+ return { threadDbId: data.db_id, map: next };+ }+ const map: Record<string, ApiMessage> = { ...next };+ for (const [messageId, prevDraft] of Object.entries(prev.map)) {+ const nextDraft = map[messageId];+ if (+ !nextDraft ||+ new Date(nextDraft.updated_at).getTime() <+ new Date(prevDraft.updated_at).getTime()+ ) {+ map[messageId] = prevDraft;+ }+ }+ return { threadDbId: data.db_id, map };+ });++ // Drafts the user discarded this session. Kept apart from the server map so+ // a fetch that still contains the deleted draft (delete propagation lag)+ // can't resurrect it.+ const [deletedDraftIds, setDeletedDraftIds] = createStore<+ Record<string, true>>({});const deleteDraftForMessage = (messageID: string) => {- setMessageDraftMap(messageID, undefined!);+ setDeletedDraftIds(messageID, true);};const getDraftForMessage = (messageID: string) => {- return messageDraftMap[messageID];+ if (deletedDraftIds[messageID]) return undefined;+ return serverDrafts()?.map[messageID];};- const [draftsSettled, setDraftsSettled] = createSignal(false);-- whenSettled(- threadQuery,- (data) => {- setMessageDraftMap(data.draftMap);- setDraftsSettled(true);- },- (error) => {- console.error('Failed to load thread data:', error);- toast.failure('Failed to load email thread. Please try again.');- }- );+ // Drafts derive straight from the query, so "settled" is simply "we have a+ // thread snapshot" — cached or fresh, revalidating or not.+ const initialDraftsSettled = () => serverDrafts() !== undefined;const contacts = useContacts();@@ -933,7 +956,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {drafts: {deleteDraftForMessage,getDraftForMessage,- initialDraftsSettled: draftsSettled,+ initialDraftsSettled,},messages: {focusedID: focusedMessageId,diff --git a/apps/web/src/features/block-email/component/EmailFormContext.tsx b/apps/web/src/features/block-email/component/EmailFormContext.tsxindex 11d2eac3a8..b6085da304 100644--- a/apps/web/src/features/block-email/component/EmailFormContext.tsx+++ b/apps/web/src/features/block-email/component/EmailFormContext.tsx@@ -7,11 +7,14 @@ import {type EmailFormContextValue = ReturnType<typeof createEmailFormState>;type FormAccessKey =- | { type: 'replying_to'; messageID: string }- | { type: 'draft'; messageID: string };+ | { type: 'replying_to'; messageID: string; seed?: string }+ | { type: 'draft'; messageID: string; seed?: string };+// `seed` identifies the draft version the form seeds from (see EmailInput's+// seed key), so a composer remounting on a newer draft version gets a+// freshly derived form instead of the cached one.const stringifyKey = (key: FormAccessKey) => {- return `${key.type}_${key.messageID}`;+ return `${key.type}_${key.messageID}_${key.seed ?? ''}`;};type RegistryApi = {diff --git a/apps/web/src/features/block-email/component/EmailInput.tsx b/apps/web/src/features/block-email/component/EmailInput.tsxindex cc558e577d..30be3bef1c 100644--- a/apps/web/src/features/block-email/component/EmailInput.tsx+++ b/apps/web/src/features/block-email/component/EmailInput.tsx@@ -4,7 +4,13 @@ import type {ApiMessage,} from '@service-email/generated/schemas';import { Layer } from '@ui';-import { type Accessor, createMemo, type Setter, Show } from 'solid-js';+import {+ type Accessor,+ createMemo,+ createSignal,+ type Setter,+ Show,+} from 'solid-js';import { decodeBase64Utf8 } from '../util/decodeBase64';import { plainTextToHtml } from '../util/plainTextToHtml';import { BaseInput } from './BaseInput';@@ -23,6 +29,23 @@ interface EmailInputProps {export function EmailInput(props: EmailInputProps) {const ctx = useEmailContext();+ // The seed identity of this composer: which version of which draft it+ // mounts from. When the server sends a newer save of that draft (a thread+ // opened from a cached snapshot revalidates, or the draft was edited on+ // another device), the key changes and the input remounts, seeding from+ // the newer draft through the ordinary mount path — but only until the+ // user engages with the composer. From then on the mounted instance is+ // authoritative (later fetches are typically echoes of its own saves), so+ // the key latches and the input never remounts underneath the user.+ const [engaged, setEngaged] = createSignal(false);+ const seedKey = createMemo<string>((prev) =>+ engaged() && prev !== undefined+ ? prev+ : props.draft+ ? `${props.draft.db_id}:${props.draft.updated_at}`+ : 'no-draft'+ );+const draftHTML = createMemo(() => {const encoded = props.draft?.body_html_sanitized;if (!encoded) {@@ -47,20 +70,28 @@ export function EmailInput(props: EmailInputProps) {return (<Show when={ctx.drafts.initialDraftsSettled()}>- <Layer depth={props.mobileDrawer ? 0 : 2}>- <BaseInput- replyingTo={props.replyingTo}- draft={props.draft}- preloadedHtml={draftHTML()}- sideEffectOnSend={afterSend}- onMarkDone={ctx.archiveThread}- setShowReply={props.setShowReply}- markdownDomRef={props.markdownDomRef}- unframed={props.unframed}- mobileDrawer={props.mobileDrawer}- isEditingExisting={props.replyingTo() == null && props.draft != null}- />- </Layer>+ <Show when={seedKey()} keyed>+ {(seed) => (+ <Layer depth={props.mobileDrawer ? 0 : 2}>+ <BaseInput+ replyingTo={props.replyingTo}+ draft={props.draft}+ preloadedHtml={draftHTML()}+ formSeed={seed}+ onEngaged={() => setEngaged(true)}+ sideEffectOnSend={afterSend}+ onMarkDone={ctx.archiveThread}+ setShowReply={props.setShowReply}+ markdownDomRef={props.markdownDomRef}+ unframed={props.unframed}+ mobileDrawer={props.mobileDrawer}+ isEditingExisting={+ props.replyingTo() == null && props.draft != null+ }+ />+ </Layer>+ )}+ </Show></Show>);}diff --git a/apps/web/src/features/block-email/component/MessageActions.tsx b/apps/web/src/features/block-email/component/MessageActions.tsxindex 92bdb78eff..c21c940ef8 100644--- a/apps/web/src/features/block-email/component/MessageActions.tsx+++ b/apps/web/src/features/block-email/component/MessageActions.tsx@@ -6,7 +6,6 @@ import { createCallback } from '@solid-primitives/rootless';import { Button } from '@ui';import { type Setter, Show } from 'solid-js';import { useEmailContext } from './EmailContext';-import { getEmailFormRegistry } from './EmailFormContext';import { openEmailReplyComposerForMessage } from './emailReplyActions';const EMAIL_MESSAGE_ACTIONS = ['reply', 'reply-all', 'forward'] as const;@@ -20,7 +19,6 @@ export function MessageActions(props: {hiddenActions?: EmailMessageAction[];}) {const ctx = useEmailContext();- const formRegistry = getEmailFormRegistry();const canShowActions = () => {if (!props.showActions) return false;@@ -36,7 +34,6 @@ export function MessageActions(props: {return createCallback(() => {openEmailReplyComposerForMessage({ctx,- formRegistry,message: props.message,replyType: type,isLastMessage: props.isLastMessage,diff --git a/apps/web/src/features/block-email/component/compose/Compose.tsx b/apps/web/src/features/block-email/component/compose/Compose.tsxindex fc97249153..7170c3f028 100644--- a/apps/web/src/features/block-email/component/compose/Compose.tsx+++ b/apps/web/src/features/block-email/component/compose/Compose.tsx@@ -15,14 +15,13 @@ import {clearEmailBody,hasDraftContent,prepareEmailBody,- prepareEmailBodyFromHtml,} from '@block-email/util/prepareEmailBody';import { convertEmailRecipientToContactInfo } from '@block-email/util/recipientConversion';import {endUndoSend,- tryBeginUndoSend,- unscheduleWithRetry,-} from '@block-email/util/undoSendGuard';+ restoreDraftBodyAfterUndo,+ runUndoSend,+} from '@block-email/util/undoSend';import { MobileDrawer } from '@components/app/mobile/MobileDrawer';import { useSplitBackInterceptor } from '@components/app/split-layout/back-interceptor';import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';@@ -38,6 +37,7 @@ import { toast } from '@core/component/Toast/Toast';import {ENABLE_EMAIL_SIGNATURES_FLAG,ENABLE_EMAIL_SIGNATURES_OVERRIDE,+ ENABLE_GRAPHQL_SOUP,} from '@core/constant/featureFlags';import { isMobile } from '@core/mobile/isMobile';import { WrapUnlessMobile } from '@core/mobile/WrapUnlessMobile';@@ -58,7 +58,6 @@ import {import { Telemetry } from '@macro-inc/observability';import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';-import { queryClient } from '@queries/client';import {useRemoveDraftAttachmentMutation,useRemoveForwardedAttachmentMutation,@@ -68,7 +67,6 @@ import {useDeleteDraftMutation,useSaveDraftMutation,} from '@queries/email/draft';-import { emailKeys } from '@queries/email/keys';import {useEmailLinksQuery,useEmailSignature,@@ -76,6 +74,7 @@ import {usePrimaryEmailLinkId,} from '@queries/email/link';import {+ fetchAndCacheThread,useSendMessageMutation,useUnscheduleMessageMutation,} from '@queries/email/thread';@@ -404,104 +403,70 @@ export function EmailCompose(props: EmailComposeProps) {const [validationError, setValidationError] =createSignal<ComposeValidationError | null>(null);- // `linkId` is the X-Email-Link-Id header value the send itself used, resolved- // at send time.- const undoSend = async (+ // Everything that follows a successful unschedule: scrub the new thread's+ // cache, restore the server-side draft, and remount the compose view so it+ // restores the form from the undo snapshot.+ const restoreAfterUndoSend = async (draftId: string,threadId: string | undefined,linkId: string | undefined) => {- if (!tryBeginUndoSend(draftId)) return;- try {- const result = await unscheduleWithRetry(draftId, linkId);- // A non-2xx response comes back as an Err Result (it doesn't throw), so- // bail before reverting the send appearance in the UI.- if (result.isErr()) {- endUndoSend(draftId);- Telemetry.error(- new Error(- `Failed to undo send for draft ${draftId}: ${result.error- .map((e) => `${e.code}: ${e.message}`)- .join(', ')}`- )- );- // 400 is the backend's "already sent" — the undo window has passed.- const alreadySent = result.error.some(- (e) => e.code === 'HTTP_ERROR' && e.message.includes('status: 400')- );- toast.failure(- alreadySent- ? 'Too late to undo — the email was already sent'- : 'Failed to undo send'- );- return;- }- queryClient.invalidateQueries({- queryKey: emailKeys.previews._def,- });- // Wipe the new thread's cache when its view unmounts (replaceSplit- // below) so the next visit fetches fresh data without the sent message.- if (threadId) markThreadDraftSaved(threadId);-- // The unscheduled message still carries the sent body (watermark and- // injected signature baked in), so overwrite the server-side draft with- // the pre-send content. The snapshot itself stays for the compose- // remount below to restore the form from.- const snapshot =- undoComposeSnapshot?.draftId === draftId ? undoComposeSnapshot : null;- if (snapshot) {- const prepared = prepareEmailBodyFromHtml(snapshot.bodyHtml);- const saveResult = await emailClient.createDraft(- {- draft: {- bcc: snapshot.recipients.bcc.map(- convertEmailRecipientToContactInfo- ),- body_html: prepared.bodyHtml,- cc: snapshot.recipients.cc.map(- convertEmailRecipientToContactInfo- ),- db_id: draftId,- subject: snapshot.subject,- to: snapshot.recipients.to.map(- convertEmailRecipientToContactInfo- ),- },- },- linkId- );- if (saveResult.isErr()) {- // Non-fatal: the compose remount restores from the snapshot either- // way, and the next draft autosave overwrites the stale body.- Telemetry.error(- new Error('Failed to restore draft body after undo-send')- );- }- }-- replaceSplit({- content: {- type: 'component',- id: 'email-compose',- params: { draftID: draftId },- // reattach() strips params by default; keep draftID so the compose- // remount can restore the undo snapshot.- preserveParams: true,+ // Wipe the new thread's cache when its view unmounts (replaceSplit+ // below) so the next visit fetches fresh data without the sent message.+ if (threadId && !ENABLE_GRAPHQL_SOUP()) markThreadDraftSaved(threadId);++ // Overwrite the server-side draft with the pre-send content. The+ // snapshot itself stays for the compose remount below to restore the+ // form from.+ const snapshot =+ undoComposeSnapshot?.draftId === draftId ? undoComposeSnapshot : null;+ if (snapshot) {+ await restoreDraftBodyAfterUndo(+ {+ bcc: snapshot.recipients.bcc.map(convertEmailRecipientToContactInfo),+ cc: snapshot.recipients.cc.map(convertEmailRecipientToContactInfo),+ db_id: draftId,+ subject: snapshot.subject,+ to: snapshot.recipients.to.map(convertEmailRecipientToContactInfo),},- });- toast.success('Send cancelled');- invalidateSoupEntity(draftId);- } catch (e) {- endUndoSend(draftId);- Telemetry.error(- e instanceof Error- ? e- : new Error(`Failed to undo send for draft ${draftId}`)+ snapshot.bodyHtml,+ linkId);- toast.failure('Failed to undo send');}++ // GraphQL mode renders threads from the normalized cache, which+ // markThreadDraftSaved's TanStack cleanup can't reach — refetch through+ // it (after the draft-body restore) so a revisit doesn't replay the+ // undone message from cache.+ if (threadId && ENABLE_GRAPHQL_SOUP()) {+ void fetchAndCacheThread(threadId);+ }++ replaceSplit({+ content: {+ type: 'component',+ id: 'email-compose',+ params: { draftID: draftId },+ // reattach() strips params by default; keep draftID so the compose+ // remount can restore the undo snapshot.+ preserveParams: true,+ },+ });};+ // `linkId` is the X-Email-Link-Id header value the send itself used, resolved+ // at send time.+ const undoSend = (+ draftId: string,+ threadId: string | undefined,+ linkId: string | undefined+ ) =>+ runUndoSend({+ draftId,+ linkId,+ onUndone: () => restoreAfterUndoSend(draftId, threadId, linkId),+ });+const sendMutation = useSendMessageMutation({onSuccess: (data, vars) => {const draftId = data.message.db_id;diff --git a/apps/web/src/features/block-email/component/emailReplyActions.ts b/apps/web/src/features/block-email/component/emailReplyActions.tsindex 34d36087fa..5eb60c7b9d 100644--- a/apps/web/src/features/block-email/component/emailReplyActions.ts+++ b/apps/web/src/features/block-email/component/emailReplyActions.ts@@ -3,11 +3,9 @@ import type { ApiMessage } from '@service-email/generated/schemas';import type { Setter } from 'solid-js';import type { ReplyType } from '../util/replyType';import type { useEmailContext } from './EmailContext';-import type { getEmailFormRegistry } from './EmailFormContext';export function openEmailReplyComposerForMessage(args: {ctx: ReturnType<typeof useEmailContext>;- formRegistry?: ReturnType<typeof getEmailFormRegistry>;message: ApiMessage;replyType: ReplyType;isLastMessage?: boolean;@@ -16,17 +14,12 @@ export function openEmailReplyComposerForMessage(args: {const messageId = args.message.db_id;if (!messageId) return false;+ // The reply type and focus land through the reply request: the mounted+ // composer's effect applies them to its own (seed-keyed) form instance.+ // Writing to the form registry from here would target the wrong entry —+ // the registry key includes a seed only the composer knows.args.ctx.replyRequest.set(messageId, args.replyType);- if (args.formRegistry) {- const form = args.formRegistry.getOrInit({- type: 'replying_to',- messageID: messageId,- });- form.setReplyType(args.replyType);- form.setShouldFocusInput(true);- }-if (isMobile()) {args.ctx.mobileReplyComposer.openForMessage(messageId);return true;diff --git a/apps/web/src/features/block-email/definition.ts b/apps/web/src/features/block-email/definition.tsindex 09555de1c1..a8e6493277 100644--- a/apps/web/src/features/block-email/definition.ts+++ b/apps/web/src/features/block-email/definition.ts@@ -1,5 +1,4 @@-import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';-import { fetchAndCacheThread } from '@queries/email/thread';+import { defineBlock, LoadErrors } from '@core/block';import { ok } from 'neverthrow';import EmailBlock from './component/Block';@@ -11,41 +10,13 @@ export const definition = defineBlock({syncServiceEnabled: false,defaultFilename: '[No subject]',+ // The thread itself is fetched by the block component (useThreadQuery),+ // which owns loading, offline fallback, and error states — see Block.tsx.async load(source) {if (source.type === 'dss') {- let email = await fetchAndCacheThread(source.id);-- if (!email) {- return LoadErrors.MISSING;- }-- if (email.isErr()) {- if (email.error.some((error) => error.code === 'NOT_FOUND')) {- return LoadErrors.MISSING;- } else if (- email.isErr() &&- email.error.some((error) => error.code === 'UNAUTHORIZED')- ) {- return LoadErrors.UNAUTHORIZED;- } else if (- email.isErr() &&- email.error.some((error) => error.code === 'GONE')- ) {- return LoadErrors.GONE;- } else {- return LoadErrors.INVALID;- }- }-- const emailData = email.value;-- return ok({- ...emailData,- });+ return ok({ id: source.id });}return LoadErrors.INVALID;},accepted: {},});--export type EmailData = ExtractLoadType<(typeof definition)['load']>;diff --git a/apps/web/src/features/block-email/signal/emailBlockData.ts b/apps/web/src/features/block-email/signal/emailBlockData.tsdeleted file mode 100644index ab1f5d44c2..0000000000--- a/apps/web/src/features/block-email/signal/emailBlockData.ts+++ /dev/null@@ -1,4 +0,0 @@-import { blockDataSignalAs } from '@core/block';-import type { EmailData } from '../definition';--export const blockDataSignal = blockDataSignalAs<EmailData>('email');diff --git a/apps/web/src/features/block-email/util/undoSend.ts b/apps/web/src/features/block-email/util/undoSend.tsnew file mode 100644index 0000000000..12fc4f6a22--- /dev/null+++ b/apps/web/src/features/block-email/util/undoSend.ts@@ -0,0 +1,137 @@+import { toast } from '@core/component/Toast/Toast';+import { Telemetry } from '@macro-inc/observability';+import { queryClient } from '@queries/client';+import { emailKeys } from '@queries/email/keys';+import { invalidateSoupEntity } from '@queries/soup/cache';+import { emailClient } from '@service-email/client';+import type { ApiDraftInput } from '@service-email/generated/schemas';+import { prepareEmailBodyFromHtml } from './prepareEmailBody';++/**+ * Guards undo-send against duplicate invocations. The undo toast stays+ * clickable during its dismiss animation, so a double-click fires undoSend+ * twice; the second unschedule 404s (the scheduled row is already gone) and+ * flashes a false "Failed to undo send".+ *+ * An id stays claimed after a successful undo so late clicks stay inert; a+ * failed undo releases it (retry allowed), and a new send of the same draft+ * releases it to open the next undo cycle.+ */+const claimedDraftIds = new Set<string>();++/** Claim an undo for this draft. Returns false if one is in flight or done. */+export function tryBeginUndoSend(draftId: string): boolean {+ if (claimedDraftIds.has(draftId)) return false;+ claimedDraftIds.add(draftId);+ return true;+}++/** Release a claim — after a failed undo, or when the draft is sent again. */+export function endUndoSend(draftId: string) {+ claimedDraftIds.delete(draftId);+}++/**+ * Unschedule with one retry on transient failures (network errors, 5xx from a+ * redeploy or proxy blip). Retrying is safe: the endpoint treats an+ * already-undone send as success. 400 (already sent — the undo window passed)+ * and 404 (not found) are definitive and not retried.+ */+export async function unscheduleWithRetry(+ draftId: string,+ linkId: string | undefined+) {+ const first = await emailClient.unscheduleMessage(+ { draftID: draftId },+ linkId+ );+ if (first.isOk()) return first;+ const definitive = first.error.some(+ (e) =>+ e.code === 'NOT_FOUND' ||+ (e.code === 'HTTP_ERROR' && e.message.includes('status: 400'))+ );+ if (definitive) return first;+ await new Promise((resolve) => setTimeout(resolve, 500));+ return emailClient.unscheduleMessage({ draftID: draftId }, linkId);+}++/**+ * The shared undo-send flow: claims the guard, unschedules with retry,+ * surfaces failures (including the definitive "already sent" 400), and on+ * success invalidates the previews then runs the surface-specific `onUndone`+ * work — cache edits, snapshot restore, navigation — before announcing the+ * cancellation. Callers keep only what genuinely differs per surface.+ */+export async function runUndoSend(options: {+ draftId: string;+ /** The X-Email-Link-Id header value the send itself used. */+ linkId: string | undefined;+ onUndone: () => Promise<void> | void;+}): Promise<void> {+ const { draftId, linkId } = options;+ if (!tryBeginUndoSend(draftId)) return;+ try {+ const result = await unscheduleWithRetry(draftId, linkId);+ // A non-2xx response comes back as an Err Result (it doesn't throw), so+ // bail before reverting the send appearance in the UI.+ if (result.isErr()) {+ endUndoSend(draftId);+ Telemetry.error(+ new Error(+ `Failed to undo send for draft ${draftId}: ${result.error+ .map((e) => `${e.code}: ${e.message}`)+ .join(', ')}`+ )+ );+ // 400 is the backend's "already sent" — the undo window has passed.+ const alreadySent = result.error.some(+ (e) => e.code === 'HTTP_ERROR' && e.message.includes('status: 400')+ );+ toast.failure(+ alreadySent+ ? 'Too late to undo — the email was already sent'+ : 'Failed to undo send'+ );+ return;+ }+ queryClient.invalidateQueries({+ queryKey: emailKeys.previews._def,+ });++ await options.onUndone();++ toast.success('Send cancelled');+ invalidateSoupEntity(draftId);+ } catch (e) {+ endUndoSend(draftId);+ Telemetry.error(+ e instanceof Error+ ? e+ : new Error(`Failed to undo send for draft ${draftId}`)+ );+ toast.failure('Failed to undo send');+ }+}++/**+ * Overwrites the server-side draft with the pre-send content — the+ * unscheduled message still carries the sent body (appended reply chain /+ * watermark and injected signature baked in). A failure is non-fatal: the+ * composer restores from its snapshot either way, and the next draft+ * autosave overwrites the stale body.+ */+export async function restoreDraftBodyAfterUndo(+ draft: Omit<ApiDraftInput, 'body_html'>,+ bodyHtml: string,+ linkId: string | undefined+): Promise<void> {+ const prepared = prepareEmailBodyFromHtml(bodyHtml);+ const saveResult = await emailClient.createDraft(+ { draft: { ...draft, body_html: prepared.bodyHtml } },+ linkId+ );+ if (saveResult.isErr()) {+ Telemetry.error(new Error('Failed to restore draft body after undo-send'));+ }+}diff --git a/apps/web/src/features/block-email/util/undoSendGuard.ts b/apps/web/src/features/block-email/util/undoSendGuard.tsdeleted file mode 100644index 2e900b74cd..0000000000--- a/apps/web/src/features/block-email/util/undoSendGuard.ts+++ /dev/null@@ -1,50 +0,0 @@-import { emailClient } from '@service-email/client';--/**- * Guards undo-send against duplicate invocations. The undo toast stays- * clickable during its dismiss animation, so a double-click fires undoSend- * twice; the second unschedule 404s (the scheduled row is already gone) and- * flashes a false "Failed to undo send".- *- * An id stays claimed after a successful undo so late clicks stay inert; a- * failed undo releases it (retry allowed), and a new send of the same draft- * releases it to open the next undo cycle.- */-const claimedDraftIds = new Set<string>();--/** Claim an undo for this draft. Returns false if one is in flight or done. */-export function tryBeginUndoSend(draftId: string): boolean {- if (claimedDraftIds.has(draftId)) return false;- claimedDraftIds.add(draftId);- return true;-}--/** Release a claim — after a failed undo, or when the draft is sent again. */-export function endUndoSend(draftId: string) {- claimedDraftIds.delete(draftId);-}--/**- * Unschedule with one retry on transient failures (network errors, 5xx from a- * redeploy or proxy blip). Retrying is safe: the endpoint treats an- * already-undone send as success. 400 (already sent — the undo window passed)- * and 404 (not found) are definitive and not retried.- */-export async function unscheduleWithRetry(- draftId: string,- linkId: string | undefined-) {- const first = await emailClient.unscheduleMessage(- { draftID: draftId },- linkId- );- if (first.isOk()) return first;- const definitive = first.error.some(- (e) =>- e.code === 'NOT_FOUND' ||- (e.code === 'HTTP_ERROR' && e.message.includes('status: 400'))- );- if (definitive) return first;- await new Promise((resolve) => setTimeout(resolve, 500));- return emailClient.unscheduleMessage({ draftID: draftId }, linkId);-}diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsxindex 5612e8ca7b..1fd82cc6d3 100644--- a/apps/web/src/features/channel/Channel/Channel.tsx+++ b/apps/web/src/features/channel/Channel/Channel.tsx@@ -707,7 +707,11 @@ export function Channel(props: ChannelProps) {);return (- <EntityLoadGate result={messagesLoadResult}>+ <EntityLoadGate+ result={messagesLoadResult}+ loadErrorTitle="Unable to load this channel"+ onRetry={() => void messagesQuery.refetch()}+ ><DebugSuspense name="Channel.root"><deleteConfirmation.ConfirmationDialog /><StaticMarkdownContext>diff --git a/apps/web/src/features/next-soup/soup-view/empty-states.test.tsx b/apps/web/src/features/next-soup/soup-view/empty-states.test.tsxnew file mode 100644index 0000000000..0fe72989b8--- /dev/null+++ b/apps/web/src/features/next-soup/soup-view/empty-states.test.tsx@@ -0,0 +1,51 @@+/**+ * @vitest-environment jsdom+ */++import { describe, expect, it, vi } from 'vitest';+import { shouldShowLoadError } from './empty-states';++vi.mock('@app/features/command/Launcher', () => ({+ runCreateAction: vi.fn(),+}));+vi.mock('@channel/CreateChannelModal', () => ({+ openNewChannelModal: vi.fn(),+}));+vi.mock('@core/constant/SettingsState', () => ({+ useSettingsState: () => ({ openSettings: vi.fn() }),+}));+vi.mock('@core/email-link', () => ({+ useAddInboxFlow: () => vi.fn(),+ useEmailLinksStatus: () => () => false,+}));+vi.mock('@queries/team/teams', () => ({+ useCurrentTeamQuery: () => ({ data: undefined }),+ useIsTeamAdmin: () => () => false,+}));+vi.mock('./FolderDropZone', () => ({ FolderDropZone: () => null }));+vi.mock('./soup-view-context', () => ({+ useSoupView: () => ({ activeTab: () => undefined, searchText: () => '' }),+}));++describe('shouldShowLoadError', () => {+ it('replaces stale rendered rows when the active query has no data', () => {+ expect(+ shouldShowLoadError({+ hasData: false,+ forceEmptyState: false,+ })+ ).toBe(true);+ expect(+ shouldShowLoadError({+ hasData: true,+ forceEmptyState: false,+ })+ ).toBe(false);+ expect(+ shouldShowLoadError({+ hasData: false,+ forceEmptyState: true,+ })+ ).toBe(false);+ });+});diff --git a/apps/web/src/features/next-soup/soup-view/empty-states.tsx b/apps/web/src/features/next-soup/soup-view/empty-states.tsxindex caff19e0ff..1f1a6f07af 100644--- a/apps/web/src/features/next-soup/soup-view/empty-states.tsx+++ b/apps/web/src/features/next-soup/soup-view/empty-states.tsx@@ -45,6 +45,14 @@ type FallbackContent = {documentationUrl?: string;};+/** Whether a failed request has no trustworthy local result to render. */+export function shouldShowLoadError(options: {+ hasData: boolean;+ forceEmptyState: boolean;+}): boolean {+ return !options.hasData && !options.forceEmptyState;+}+const FALLBACK_CONTENT: Partial<Record<ListView, FallbackContent>> = {documents: {plural: 'documents',diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsxindex 1b1518fd9b..3ca95516ea 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx@@ -59,6 +59,10 @@ import {} from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';+import {+ NATIVE_OFFLINE_ERROR_MESSAGE,+ nativeNetworkStatus,+} from '@core/mobile/native-network-status';import { idToDisplayName } from '@core/user/util';import {COMPANY_STAGE_OPTIONS,@@ -103,6 +107,10 @@ import { unwrap } from 'solid-js/store';type DataSource<T> = {data: Accessor<T[]>;+ error: Accessor<Error | null>;+ /** True when the active request has local or network data, including an+ * intentionally empty result. */+ hasData: Accessor<boolean>;isLoading: Accessor<boolean>;isFetching: Accessor<boolean>;/**@@ -282,6 +290,15 @@ type EntityWithRawNotifications = EntityData & {notifications?: Notification[];};+const NATIVE_OFFLINE_LOAD_ERROR = new Error(NATIVE_OFFLINE_ERROR_MESSAGE);++/** Retryable load error for a data-less view once iOS reports no network path. */+function nativeOfflineLoadError(hasData: () => boolean): Error | null {+ return nativeNetworkStatus() === 'offline' && !hasData()+ ? NATIVE_OFFLINE_LOAD_ERROR+ : null;+}+function rawEntityNotifications(entity: EntityData): Notification[] | undefined {@@ -986,9 +1003,15 @@ export const SoupViewContextProvider: FlowComponent<// Read loading first so REST fallback leaves the view shell rendered.const itemsQueryData = () =>itemsQuery.isLoading ? undefined : itemsQuery.data;+ const itemsQueryHasData = () =>+ itemsQueryData() !== undefined && !itemsQuery.isPlaceholderData;+ const itemsQueryError = () =>+ itemsQuery.error ?? nativeOfflineLoadError(itemsQueryHasData);const itemsSource = {data: itemsQueryData,+ error: itemsQueryError,+ hasData: itemsQueryHasData,isLoading: () => itemsQuery.isLoading,isFetching: () => itemsQuery.isFetching,isPlaceholderData: () => itemsQuery.isPlaceholderData,@@ -1006,21 +1029,27 @@ export const SoupViewContextProvider: FlowComponent<if (!searching) {const data = itemsSource.data();-- if (!data || data.groups) return prev;-- const base = data.entities.map((e) =>+ const extras = config().additionalEntities?.() ?? [];+ const extraEntities = extras.map((e) =>isWithNotification(e) ? e : attachNotifications(e)) as SoupEntity[];- const extras = config().additionalEntities?.() ?? [];-- if (extras.length === 0) return base;+ if (!data) {+ // Query rebinding can temporarily produce no data without an+ // error; keep the previous rows to avoid a flash on back+ // navigation. Once the active query fails, those rows belong to+ // the previous query and must go so the load-error state can+ // render — only client-local rows remain valid.+ return itemsSource.error() ? extraEntities : prev;+ }+ if (data.groups) return prev;- const extraEntities = extras.map((e) =>+ const base = data.entities.map((e) =>isWithNotification(e) ? e : attachNotifications(e)) as SoupEntity[];+ if (extraEntities.length === 0) return base;+return [...extraEntities, ...base];}@@ -1416,12 +1445,30 @@ export const SoupViewContextProvider: FlowComponent<});const { searchQuery } = search;+ const searchSourceHasData = () =>+ (searchQuery.data !== undefined && !searchQuery.isPlaceholderData) ||+ (!searchQuery.isPlaceholderData && entities().length > 0);+ const searchSourceError = () =>+ (searchQuery.error as Error | null) ??+ nativeOfflineLoadError(searchSourceHasData);const context = {soup,initialize,source: {data: entities,+ error: () =>+ search.isSearching() ? searchSourceError() : itemsSource.error(),+ hasData: () =>+ search.isSearching()+ ? searchSourceHasData()+ : itemsSource.hasData() ||+ // Rows retained across a query rebind count as data so the view+ // doesn't flash, but once the query errors only client-local+ // rows remain and must not suppress the load-error state.+ (!itemsSource.error() &&+ !itemsSource.isPlaceholderData() &&+ entities().length > 0),isLoading: () => itemsSource.isLoading(),isFetching: () => itemsSource.isFetching() || searchQuery.isFetching,isPlaceholderData: () =>diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsxindex e29712a11b..285482abc2 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx@@ -16,7 +16,10 @@ import type { SetPredicatesInput } from '@app/features/next-soup/filters/filter-import { VIEW_TAB_PRESETS } from '@app/features/next-soup/sidebar/soup-filter-presets';import { useSoup } from '@app/features/next-soup/soup-context';import { registerDocumentsFilterSplit } from '@app/features/next-soup/soup-view/documents-filter-controllers';-import { EmptyState } from '@app/features/next-soup/soup-view/empty-states';+import {+ EmptyState,+ shouldShowLoadError,+} from '@app/features/next-soup/soup-view/empty-states';import { InboxSelector } from '@app/features/next-soup/soup-view/filters-bar/inbox-selector';import { SoupFiltersBar } from '@app/features/next-soup/soup-view/filters-bar/soup-filters-bar';import { SoupSearchbar } from '@app/features/next-soup/soup-view/filters-bar/soup-view-search-bar';@@ -71,6 +74,7 @@ import {} from '@components/app/split-layout/components/SplitHeader';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { CustomScrollbar } from '@core/component/CustomScrollbar';+import { LoadErrorPanel } from '@core/component/EntityLoadGate';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { LoadingBlock } from '@core/component/LoadingBlock';import { ENABLE_UNIFIED_LIST_AI_INPUT } from '@core/constant/featureFlags';@@ -1140,6 +1144,17 @@ const SoupViewListContent = (props: SoupViewListProps) => {((!source.isFetching() || isPullRefreshing()) && !rows().length) ||forceEmptyState();+ const showLoadError = () =>+ !!source.error() &&+ shouldShowLoadError({+ hasData: source.hasData(),+ forceEmptyState: forceEmptyState(),+ });++ const retryLoad = () => {+ void source.refresh().catch(() => undefined);+ };+const entityById = createMemo(() => {const list = rows() ?? [];@@ -1252,7 +1267,11 @@ const SoupViewListContent = (props: SoupViewListProps) => {><SoupViewFileDropzone><div class="@container/u-list size-full unified-list-root flex flex-col relative no-select-children">- <Show when={isTouchDevice() && source.isPlaceholderData()}>+ <Show+ when={+ isTouchDevice() && source.isPlaceholderData() && !source.error()+ }+ ><MobileTabLoadingBar /></Show><Show when={isTouchDevice()}>@@ -1265,6 +1284,14 @@ const SoupViewListContent = (props: SoupViewListProps) => {</Show><StaticMarkdownContext><Switch>+ <Match when={showLoadError()}>+ <div+ ref={setEmptyStateRef}+ class="flex-1 min-h-0 flex flex-col touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)"+ >+ <LoadErrorPanel onRetry={retryLoad} />+ </div>+ </Match><Matchwhen={source.isFetching() && !rows().length && !isPullRefreshing()diff --git a/apps/web/src/lib/core/component/DocumentBlockContainer.tsx b/apps/web/src/lib/core/component/DocumentBlockContainer.tsxindex 46633b6095..d962612a00 100644--- a/apps/web/src/lib/core/component/DocumentBlockContainer.tsx+++ b/apps/web/src/lib/core/component/DocumentBlockContainer.tsx@@ -1,10 +1,12 @@import { BlockContainer } from '@core/component/BlockContainer';import { blockDataSignal } from '@core/internal/BlockLoader';-import { blockErrorSignal } from '@core/signal/load';+import { nativeNetworkStatus } from '@core/mobile/native-network-status';+import { blockErrorSignal, blockLoadRetrySignal } from '@core/signal/load';import { type FlowProps, Match, Show, Switch, splitProps } from 'solid-js';import Gone from './AccessErrorViews/Gone';import NotFound from './AccessErrorViews/NotFound';import Unauthorized from './AccessErrorViews/Unauthorized';+import { LoadErrorPanel } from './EntityLoadGate';import { LoadingPanel } from './LoadingSpinner';export function DocumentBlockContainer(@@ -12,6 +14,8 @@ export function DocumentBlockContainer() {const blockData = blockDataSignal.get;const blockError = blockErrorSignal.get;+ const setLoadRetry = blockLoadRetrySignal.set;+ const retryLoad = () => setLoadRetry((count) => (count ?? 0) + 1);const hasBlockData = () => blockData() != null;const [local, others] = splitProps(props, ['usesCenterBar']);@@ -23,13 +27,23 @@ export function DocumentBlockContainer(when={hasBlockData() && !blockError()}fallback={<ContainerWithTopBar {...local}>+ {/* The fallback is every non-structural failure (`INVALID`,+ `UNKNOWN`): retryable, like EntityLoadGate's LOAD_FAILED. */}<Switchfallback={- <div class="flex flex-col items-center justify-center h-full text-lg">- Sorry, an unexpected error has occurred.- </div>+ <LoadErrorPanel+ title="Unable to load this document"+ onRetry={retryLoad}+ />}>+ {/* An offline load with nothing to show would otherwise spin+ forever — its pending fetch resumes once connectivity+ returns, so no Retry (a second concurrent load could leak+ the first one's sync source). */}+ <Match when={isLoading() && nativeNetworkStatus() === 'offline'}>+ <LoadErrorPanel title="Unable to load this document" />+ </Match><Match when={isLoading()}><LoadingPanel /></Match>diff --git a/apps/web/src/lib/core/component/EntityLoadGate.test.tsx b/apps/web/src/lib/core/component/EntityLoadGate.test.tsxindex 2f32833e1b..e1b5b3f919 100644--- a/apps/web/src/lib/core/component/EntityLoadGate.test.tsx+++ b/apps/web/src/lib/core/component/EntityLoadGate.test.tsx@@ -19,6 +19,19 @@ vi.mock('./LoadingBlock', () => ({LoadingBlock: () => <div>Loading</div>,}));+// A real signal so components reacting to connectivity changes re-run.+const network = vi.hoisted(() => ({+ set: (_status: 'unknown' | 'online' | 'offline') => {},+}));+vi.mock('@core/mobile/native-network-status', async () => {+ const { createSignal } = await import('solid-js');+ const [status, setStatus] = createSignal<'unknown' | 'online' | 'offline'>(+ 'unknown'+ );+ network.set = setStatus;+ return { nativeNetworkStatus: status };+});+import {type EntityLoadErrorCode,EntityLoadGate,@@ -49,6 +62,8 @@ function renderGate<Data>(result: EntityLoadResult<Data>): HTMLElement {afterEach(() => {dispose?.();dispose = undefined;+ network.set('unknown');+ vi.useRealTimers();});describe('EntityLoadGate', () => {@@ -132,16 +147,216 @@ describe('EntityLoadGate', () => {expect(container.textContent).toBe(expected);});- it('renders an unexpected-error fallback for other failures', () => {+ it('renders the retryable load-error state for other failures', () => {const container = renderGate({data: () => undefined,- error: () => 'UNEXPECTED',+ error: () => 'LOAD_FAILED',isPending: () => false,});+ expect(container.textContent).toContain('Unable to load this view');expect(container.textContent).toContain(- 'Sorry, an unexpected error has occurred.'+ 'Check your internet connection and try again.'+ );+ });++ it('renders loaded content over a LOAD_FAILED error', () => {+ const container = renderGate({+ data: () => 'cached entity',+ error: () => 'LOAD_FAILED',+ isPending: () => false,+ });++ expect(container.textContent).toBe('Loaded');+ });++ it('renders the structural error view even over loaded content', () => {+ const container = renderGate({+ data: () => 'cached entity',+ error: () => 'UNAUTHORIZED',+ isPending: () => false,+ });++ expect(container.textContent).toBe('Unauthorized');+ });++ it('renders the retryable load-error state when offline with nothing to show', () => {+ network.set('offline');+ const container = renderGate({+ data: () => undefined,+ error: () => undefined,+ isPending: () => true,+ });++ expect(container.textContent).toContain('Unable to load this view');+ });++ it('renders loaded content while offline', () => {+ network.set('offline');+ const container = renderGate({+ data: () => 'cached entity',+ error: () => undefined,+ isPending: () => false,+ });++ expect(container.textContent).toBe('Loaded');+ });++ it('hides the Retry action while the device is offline', () => {+ network.set('offline');+ const onRetry = vi.fn();+ const container = document.createElement('div');+ document.body.appendChild(container);+ const disposeRender = render(+ () => (+ <EntityLoadGate+ result={{+ data: () => undefined,+ error: () => 'LOAD_FAILED',+ isPending: () => false,+ }}+ onRetry={onRetry}+ >+ <div>Loaded</div>+ </EntityLoadGate>+ ),+ container+ );+ dispose = () => {+ disposeRender();+ container.remove();+ };++ expect(container.textContent).toContain('Unable to load this view');+ expect(container.querySelector('button')).toBeNull();++ network.set('online');+ expect(container.querySelector('button')?.textContent).toContain('Retry');+ });++ it('auto-retries shortly after connectivity returns', () => {+ vi.useFakeTimers();+ network.set('offline');+ const onRetry = vi.fn();+ const container = document.createElement('div');+ document.body.appendChild(container);+ const disposeRender = render(+ () => (+ <EntityLoadGate+ result={{+ data: () => undefined,+ error: () => 'LOAD_FAILED',+ isPending: () => false,+ }}+ onRetry={onRetry}+ >+ <div>Loaded</div>+ </EntityLoadGate>+ ),+ container+ );+ dispose = () => {+ disposeRender();+ container.remove();+ };++ network.set('online');+ expect(onRetry).not.toHaveBeenCalled();+ vi.advanceTimersByTime(2_000);+ expect(onRetry).toHaveBeenCalledOnce();+ });++ it('does not auto-retry when mounted while already online', () => {+ vi.useFakeTimers();+ network.set('online');+ const onRetry = vi.fn();+ const container = document.createElement('div');+ document.body.appendChild(container);+ const disposeRender = render(+ () => (+ <EntityLoadGate+ result={{+ data: () => undefined,+ error: () => 'LOAD_FAILED',+ isPending: () => false,+ }}+ onRetry={onRetry}+ >+ <div>Loaded</div>+ </EntityLoadGate>+ ),+ container);+ dispose = () => {+ disposeRender();+ container.remove();+ };++ vi.advanceTimersByTime(10_000);+ expect(onRetry).not.toHaveBeenCalled();+ });++ it('cancels the pending auto-retry when connectivity drops again', () => {+ vi.useFakeTimers();+ network.set('offline');+ const onRetry = vi.fn();+ const container = document.createElement('div');+ document.body.appendChild(container);+ const disposeRender = render(+ () => (+ <EntityLoadGate+ result={{+ data: () => undefined,+ error: () => 'LOAD_FAILED',+ isPending: () => false,+ }}+ onRetry={onRetry}+ >+ <div>Loaded</div>+ </EntityLoadGate>+ ),+ container+ );+ dispose = () => {+ disposeRender();+ container.remove();+ };++ network.set('online');+ vi.advanceTimersByTime(1_000);+ network.set('offline');+ vi.advanceTimersByTime(10_000);+ expect(onRetry).not.toHaveBeenCalled();+ });++ it('invokes onRetry from the load-error state', () => {+ const onRetry = vi.fn();+ const container = document.createElement('div');+ document.body.appendChild(container);+ const disposeRender = render(+ () => (+ <EntityLoadGate+ result={{+ data: () => undefined,+ error: () => 'LOAD_FAILED',+ isPending: () => false,+ }}+ onRetry={onRetry}+ >+ <div>Loaded</div>+ </EntityLoadGate>+ ),+ container+ );+ dispose = () => {+ disposeRender();+ container.remove();+ };++ const retryButton = container.querySelector('button');+ expect(retryButton?.textContent).toContain('Retry');+ retryButton?.click();+ expect(onRetry).toHaveBeenCalledOnce();});it('normalizes query errors into gate errors', () => {@@ -153,7 +368,7 @@ describe('EntityLoadGate', () => {)).toBe('NOT_FOUND');expect(toEntityLoadError(new Error('network unavailable'))).toBe(- 'UNEXPECTED'+ 'LOAD_FAILED');});});diff --git a/apps/web/src/lib/core/component/EntityLoadGate.tsx b/apps/web/src/lib/core/component/EntityLoadGate.tsxindex cd97f06f88..dfbd6404ef 100644--- a/apps/web/src/lib/core/component/EntityLoadGate.tsx+++ b/apps/web/src/lib/core/component/EntityLoadGate.tsx@@ -1,5 +1,16 @@+import { nativeNetworkStatus } from '@core/mobile/native-network-status';import { ThrownResultError } from '@core/util/result';-import { type Accessor, type JSX, Match, Suspense, Switch } from 'solid-js';+import { EmptyStatePanel } from '@ui';+import {+ type Accessor,+ createEffect,+ type JSX,+ Match,+ on,+ onCleanup,+ Suspense,+ Switch,+} from 'solid-js';import Gone from './AccessErrorViews/Gone';import NotFound from './AccessErrorViews/NotFound';import Unauthorized from './AccessErrorViews/Unauthorized';@@ -11,7 +22,17 @@ export type EntityLoadErrorCode =| 'NOT_FOUND'| 'GONE';-export type EntityLoadError = EntityLoadErrorCode | 'UNEXPECTED';+/**+ * `LOAD_FAILED` is any non-structural failure — a transport error or an+ * offline load with nothing cached. Unlike the structural codes it is+ * retryable, so the gate renders it with a Retry action when the consumer+ * provides `onRetry` — and loaded content outranks it: when `data` is+ * available the gate renders the content instead, so consumers can pass the+ * normalized error of a failed background refresh without unmounting an+ * already-rendered entity. The structural codes stay authoritative even over+ * loaded data (a revoked entity must not keep rendering its cached copy).+ */+export type EntityLoadError = EntityLoadErrorCode | 'LOAD_FAILED';export type EntityLoadResult<Data> = {data: Accessor<Data | undefined>;@@ -21,6 +42,10 @@ export type EntityLoadResult<Data> = {type EntityLoadGateProps<Data> = {result: EntityLoadResult<Data>;+ /** Refetch handler for the `LOAD_FAILED` state's Retry action. */+ onRetry?: () => void;+ /** Entity-specific title for the `LOAD_FAILED` state. */+ loadErrorTitle?: string;children: JSX.Element;};@@ -42,15 +67,69 @@ export function toEntityLoadError(error: unknown): EntityLoadError | undefined {if (error instanceof ThrownResultError) {return (error.errors.map(({ code }) => code).find(isEntityLoadErrorCode) ??- 'UNEXPECTED'+ 'LOAD_FAILED');}- return 'UNEXPECTED';+ return 'LOAD_FAILED';+}++/** Delay between regaining native connectivity and the automatic retry. */+const RECONNECT_AUTO_RETRY_DELAY_MS = 2_000;++/**+ * The retryable load-failure panel. While it is on screen, regaining native+ * connectivity retries automatically shortly after the reconnect — the moment+ * a retry is most likely to succeed — instead of waiting for the button. The+ * Retry action is hidden while the device is offline: a manual retry can't+ * succeed, a paused load resumes by itself on reconnect, and a failed one is+ * covered by the automatic retry.+ */+export function LoadErrorPanel(props: {+ title?: string;+ onRetry?: () => void;+}) {+ let retryTimer: ReturnType<typeof setTimeout> | undefined;+ const clearRetryTimer = () => {+ if (retryTimer !== undefined) clearTimeout(retryTimer);+ retryTimer = undefined;+ };+ // Deferred: only a transition observed while this panel is showing counts+ // as a reconnect. Mounting while already online means the failure wasn't+ // connectivity (e.g. a server error), which must not self-retry.+ createEffect(+ on(+ nativeNetworkStatus,+ (status) => {+ clearRetryTimer();+ if (status !== 'online') return;+ retryTimer = setTimeout(+ () => props.onRetry?.(),+ RECONNECT_AUTO_RETRY_DELAY_MS+ );+ },+ { defer: true }+ )+ );+ onCleanup(clearRetryTimer);++ return (+ <EmptyStatePanel+ centered+ title={props.title ?? 'Unable to load this view'}+ description="Check your internet connection and try again."+ primaryAction={+ props.onRetry && nativeNetworkStatus() !== 'offline'+ ? { label: 'Retry', onClick: props.onRetry }+ : undefined+ }+ />+ );}/** Renders entity content or the appropriate loading and access-error view. */export function EntityLoadGate<Data>(props: EntityLoadGateProps<Data>) {const error = props.result.error;+ const hasData = () => props.result.data() !== undefined;return (<Suspense fallback={<LoadingBlock />}>@@ -70,15 +149,26 @@ export function EntityLoadGate<Data>(props: EntityLoadGateProps<Data>) {<Match when={error() === 'GONE'}><Gone /></Match>- <Match when={error() === 'UNEXPECTED'}>- <div class="flex flex-col items-center justify-center h-full text-lg">- Sorry, an unexpected error has occurred.- </div>+ {/* LOAD_FAILED is retryable, so loaded content outranks it — with+ data available it falls through to the content match below. An+ offline device with nothing to show also lands here: its query+ may be paused rather than errored and would otherwise pend+ forever. */}+ <Match+ when={+ !hasData() &&+ (error() === 'LOAD_FAILED' || nativeNetworkStatus() === 'offline')+ }+ >+ <LoadErrorPanel+ title={props.loadErrorTitle}+ onRetry={props.onRetry}+ /></Match><Match when={props.result.isPending()}><LoadingBlock /></Match>- <Match when={props.result.data() !== undefined}>{props.children}</Match>+ <Match when={hasData()}>{props.children}</Match></Switch></Suspense>);diff --git a/apps/web/src/lib/core/internal/BlockLoader.tsx b/apps/web/src/lib/core/internal/BlockLoader.tsxindex 40b72c4163..5fe2a4502d 100644--- a/apps/web/src/lib/core/internal/BlockLoader.tsx+++ b/apps/web/src/lib/core/internal/BlockLoader.tsx@@ -19,6 +19,7 @@ import {blockErrorSignal,blockFileSignal,blockHandleSignal,+ blockLoadRetrySignal,blockLoroManagerSignal,blockMetadataSignal,blockSourceSignal,@@ -72,7 +73,11 @@ export function BlockLoader<setLiveTrackingEnabled(props.definition.liveTrackingEnabled ?? false);setEditPermissionEnabled(props.definition.editPermissionEnabled ?? false);+ const retryToken = blockLoadRetrySignal.get;+const getResult = createAsync(async () => {+ // Tracked before the first await so a failure view can re-run the load.+ retryToken();const result = await loadBlockDataAfterComponentPreload(() => props.definition.load(props.source, 'initial'),props.definition.component.preloaddiff --git a/apps/web/src/lib/core/mobile/native-network-status.ts b/apps/web/src/lib/core/mobile/native-network-status.tsnew file mode 100644index 0000000000..d52f152aa2--- /dev/null+++ b/apps/web/src/lib/core/mobile/native-network-status.ts@@ -0,0 +1,98 @@+import { isPlatform } from '@core/util/platform';+import { Channel, invoke } from '@tauri-apps/api/core';+import { createSignal } from 'solid-js';++/** Reachability reported by the native platform monitor. */+export type NativeNetworkStatus = 'unknown' | 'online' | 'offline';++type NetworkStatusPayload = {+ status: NativeNetworkStatus;+};++/** Message carried by aborts and load errors caused by a missing network path. */+export const NATIVE_OFFLINE_ERROR_MESSAGE = 'Native network path unavailable';++const WATCH_START_ATTEMPTS = 3;+const WATCH_START_RETRY_DELAY_MS = 1_000;++const [nativeNetworkStatus, setNativeNetworkStatus] =+ createSignal<NativeNetworkStatus>('unknown');++let networkAbortController = new AbortController();+let statusChannel: Channel<NetworkStatusPayload> | undefined;+let initialization: Promise<void> | undefined;+const listeners = new Set<(status: NativeNetworkStatus) => void>();++function isNetworkStatus(value: unknown): value is NativeNetworkStatus {+ return value === 'unknown' || value === 'online' || value === 'offline';+}++function applyStatus(payload: NetworkStatusPayload): void {+ if (!isNetworkStatus(payload.status)) {+ console.error(+ '[network-status] ignored invalid native status',+ payload.status+ );+ return;+ }++ const status = payload.status;+ if (status === nativeNetworkStatus()) return;++ if (status === 'offline') {+ networkAbortController.abort(new Error(NATIVE_OFFLINE_ERROR_MESSAGE));+ } else if (status === 'online' && networkAbortController.signal.aborted) {+ networkAbortController = new AbortController();+ }++ setNativeNetworkStatus(status);+ for (const listener of listeners) listener(status);+}++/** Current native reachability state. Remains `unknown` off iOS. */+export { nativeNetworkStatus };++/** Signal aborted whenever iOS reports that no network path is available. */+export function getNativeNetworkAbortSignal(): AbortSignal {+ return networkAbortController.signal;+}++/** Subscribes to native reachability changes for imperative consumers. */+export function subscribeNativeNetworkStatus(+ listener: (status: NativeNetworkStatus) => void+): () => void {+ listeners.add(listener);+ listener(nativeNetworkStatus());+ return () => listeners.delete(listener);+}++/** Starts the singleton iOS `NWPathMonitor` channel. */+export function initializeNativeNetworkStatus(): Promise<void> {+ if (!isPlatform('ios')) return Promise.resolve();+ if (!initialization) initialization = startNativeMonitor();+ return initialization;+}++async function startNativeMonitor(): Promise<void> {+ for (let attempt = 1; attempt <= WATCH_START_ATTEMPTS; attempt += 1) {+ statusChannel = new Channel<NetworkStatusPayload>(applyStatus);+ try {+ await invoke<void>('plugin:network-status|watch_status', {+ channel: statusChannel,+ });+ return;+ } catch (error) {+ statusChannel = undefined;+ if (attempt === WATCH_START_ATTEMPTS) {+ // Fail open: status stays 'unknown' and offline aborts never engage+ // this session, matching the browser-connectivity behavior off iOS.+ initialization = undefined;+ console.error('[network-status] failed to start native monitor', error);+ return;+ }+ await new Promise((resolve) =>+ setTimeout(resolve, WATCH_START_RETRY_DELAY_MS * attempt)+ );+ }+ }+}diff --git a/apps/web/src/lib/core/signal/load.ts b/apps/web/src/lib/core/signal/load.tsindex b335b7e029..236a643121 100644--- a/apps/web/src/lib/core/signal/load.ts+++ b/apps/web/src/lib/core/signal/load.ts@@ -11,6 +11,8 @@ import type { DocumentMetadata } from '@service-storage/generated/schemas/documeexport const blockErrorSignal = createBlockSignal<keyof typeof LoadErrors | 'UNKNOWN' | null>();+/** Bumped by load-failure views to re-run the block's load. */+export const blockLoadRetrySignal = createBlockSignal<number>();export const blockFileSignal = createBlockSignal<IDocumentStorageServiceFile>();export const blockTextSignal = createBlockSignal<string>();export const blockUserAccessSignal = createBlockSignal<UserAccessLevel>();diff --git a/apps/web/src/lib/queries/client.ts b/apps/web/src/lib/queries/client.tsindex 991a2184ee..0826ba19b4 100644--- a/apps/web/src/lib/queries/client.ts+++ b/apps/web/src/lib/queries/client.ts@@ -1,4 +1,10 @@+import {+ initializeNativeNetworkStatus,+ subscribeNativeNetworkStatus,+} from '@core/mobile/native-network-status';+import { isPlatform } from '@core/util/platform';import { thrownResultErrorHasCode } from '@core/util/result';+import { onlineManager } from '@tanstack/query-core';import { QueryClient } from '@tanstack/solid-query';import { setupQueryPersistence } from './persistence';import { createQueryPersistenceScopes } from './persistence-scopes';@@ -26,6 +32,16 @@ export const queryClient = new QueryClient({},});+if (isPlatform('ios')) {+ // Replace WKWebView's navigator.onLine integration with NWPathMonitor.+ onlineManager.setEventListener((setOnline) =>+ subscribeNativeNetworkStatus((status) => {+ if (status !== 'unknown') setOnline(status === 'online');+ })+ );+ void initializeNativeNetworkStatus();+}+const buster = import.meta.env.__APP_VERSION__ ?? 'dev';setupQueryPersistence({diff --git a/apps/web/src/lib/queries/email/graphql/thread.test.ts b/apps/web/src/lib/queries/email/graphql/thread.test.tsnew file mode 100644index 0000000000..5bf09cf72b--- /dev/null+++ b/apps/web/src/lib/queries/email/graphql/thread.test.ts@@ -0,0 +1,117 @@+import type { EmailThreadPageQuery } from '@service-storage/graphql/generated/graphql';+import { CombinedError } from '@urql/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const queryMock = vi.hoisted(() => vi.fn());+const cacheEnabledMock = vi.hoisted(() => vi.fn(() => true));++vi.mock('@service-storage/graphql-soup', () => ({+ getGraphqlSoupClient: () => ({ query: queryMock }),+ graphqlCacheEnabled: cacheEnabledMock,+}));++import { EmailThreadPageDocument } from '@service-storage/graphql/generated/graphql';+import { fetchGraphqlEmailThread } from './thread';++const cachedPage: EmailThreadPageQuery = {+ user: {+ id: 'user-1',+ emailThread: {+ __typename: 'GraphqlSoupEmailThread',+ id: 'thread-1',+ providerId: 'provider-thread-1',+ linkId: 'link-1',+ inboxVisible: true,+ isRead: false,+ projectId: null,+ latestInboundMessageTs: '2026-08-06T12:00:00Z',+ createdAt: '2026-08-01T00:00:00Z',+ updatedAt: '2026-08-06T12:02:00Z',+ viewerPermission: {+ __typename: 'GraphqlAccessLevelPermission',+ accessLevel: 'OWNER',+ },+ labels: [],+ messages: [],+ },+ },+};++describe('fetchGraphqlEmailThread', () => {+ beforeEach(() => {+ queryMock.mockReset();+ cacheEnabledMock.mockReset();+ cacheEnabledMock.mockReturnValue(true);+ });++ it('falls back to the persisted operation after a network failure', async () => {+ queryMock+ .mockReturnValueOnce({+ toPromise: async () => ({+ error: new CombinedError({ networkError: new Error('offline') }),+ }),+ })+ .mockReturnValueOnce({+ toPromise: async () => ({ data: cachedPage }),+ });++ await expect(fetchGraphqlEmailThread('thread-1')).resolves.toMatchObject({+ db_id: 'thread-1',+ provider_id: 'provider-thread-1',+ access_level: 'owner',+ });++ expect(queryMock).toHaveBeenNthCalledWith(+ 1,+ EmailThreadPageDocument,+ { threadId: 'thread-1', offset: 0, limit: 20 },+ { requestPolicy: 'cache-and-network' }+ );+ expect(queryMock).toHaveBeenNthCalledWith(+ 2,+ EmailThreadPageDocument,+ { threadId: 'thread-1', offset: 0, limit: 20 },+ { requestPolicy: 'cache-only' }+ );+ });++ it('skips the persisted fallback while the cache is inactive', async () => {+ cacheEnabledMock.mockReturnValue(false);+ queryMock.mockReturnValueOnce({+ toPromise: async () => ({+ error: new CombinedError({ networkError: new Error('offline') }),+ }),+ });++ await expect(fetchGraphqlEmailThread('thread-1')).rejects.toMatchObject({+ errors: [{ code: 'UNKNOWN', message: 'offline' }],+ });+ expect(queryMock).toHaveBeenCalledOnce();+ });++ it('surfaces a typed error when the thread was not persisted', async () => {+ const networkError = new CombinedError({+ networkError: new Error('offline'),+ });+ queryMock+ .mockReturnValueOnce({+ toPromise: async () => ({ error: networkError }),+ })+ .mockReturnValueOnce({+ toPromise: async () => ({}),+ });++ await expect(fetchGraphqlEmailThread('thread-1')).rejects.toMatchObject({+ errors: [{ code: 'UNKNOWN', message: 'offline' }],+ });++ // The persisted fallback was attempted before giving up.+ expect(queryMock).toHaveBeenCalledTimes(2);+ expect(queryMock).toHaveBeenNthCalledWith(+ 2,+ EmailThreadPageDocument,+ { threadId: 'thread-1', offset: 0, limit: 20 },+ { requestPolicy: 'cache-only' }+ );+ });+});diff --git a/apps/web/src/lib/queries/email/graphql/thread.ts b/apps/web/src/lib/queries/email/graphql/thread.tsindex 681637eadb..2e2c22abc6 100644--- a/apps/web/src/lib/queries/email/graphql/thread.ts+++ b/apps/web/src/lib/queries/email/graphql/thread.ts@@ -10,7 +10,11 @@ import {type EmailThreadPageQuery,type EmailThreadPageQueryVariables,} from '@service-storage/graphql/generated/graphql';-import { getGraphqlSoupClient } from '@service-storage/graphql-soup';+import {+ getGraphqlSoupClient,+ graphqlCacheEnabled,+} from '@service-storage/graphql-soup';+import type { CombinedError } from '@urql/core';import type { Accessor } from 'solid-js';import { mapGraphqlEmailThreadPage } from './mapper';@@ -46,6 +50,92 @@ function threadFromPage(page: EmailThreadPageQuery) {]);}+/**+ * Maps a GraphQL transport error onto the typed result codes the email query+ * facade exposes.+ */+export function mapGraphqlThreadError(error: CombinedError): ThrownResultError {+ // Selector failures are normalized into CombinedError.networkError; a+ // ThrownResultError thrown there (e.g. NOT_FOUND from threadFromPage)+ // carries typed codes — surface it rather than flattening to UNKNOWN.+ if (error.networkError instanceof ThrownResultError) {+ return error.networkError;+ }++ const resultErrors = error.graphQLErrors.map((graphqlError) => ({+ ...graphqlError.extensions,+ code:+ typeof graphqlError.extensions?.code === 'string'+ ? graphqlError.extensions.code+ : 'UNKNOWN',+ message: graphqlError.message,+ }));+ return new ThrownResultError(+ resultErrors.length > 0+ ? resultErrors+ : [+ {+ code: 'UNKNOWN',+ message: error.networkError?.message ?? error.message,+ },+ ]+ );+}++/**+ * Fetches the first page of an email thread through the persistent GraphQL+ * cache. A normal read still waits for the network, but while the persistent+ * cache is active a transport failure falls back to the previously persisted+ * operation so a visited thread can be opened offline. Every failure is+ * thrown as a ThrownResultError with typed result codes.+ */+export async function fetchGraphqlEmailThread(+ threadId: string+): Promise<ApiThread> {+ const client = getGraphqlSoupClient();+ const variables: EmailThreadPageQueryVariables = {+ threadId,+ offset: 0,+ limit: DEFAULT_THREAD_MESSAGES_LIMIT,+ };+ const result = await client+ .query<EmailThreadPageQuery, EmailThreadPageQueryVariables>(+ EmailThreadPageDocument,+ variables,+ { requestPolicy: 'cache-and-network' }+ )+ .toPromise();++ if (result.error) {+ // Without an active cache exchange a `cache-only` request is never+ // answered, so only fall back when the persistent cache is live.+ if (result.error.networkError && graphqlCacheEnabled()) {+ const cached = await client+ .query<EmailThreadPageQuery, EmailThreadPageQueryVariables>(+ EmailThreadPageDocument,+ variables,+ { requestPolicy: 'cache-only' }+ )+ .toPromise();+ if (cached.data) {+ return mapGraphqlEmailThreadPage(threadFromPage(cached.data));+ }+ }+ throw mapGraphqlThreadError(result.error);+ }++ if (!result.data) {+ throw new ThrownResultError([+ {+ code: 'UNKNOWN',+ message: 'GraphQL email thread query returned no data',+ },+ ]);+ }++ return mapGraphqlEmailThreadPage(threadFromPage(result.data));+}+/** Creates the native urql-solid query for one thread's message pages. */export function createGraphqlEmailThreadQuery<TData = GraphqlEmailThreadPages>(threadId: Accessor<string>,diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.tsindex ab7626287c..7cb1245fa7 100644--- a/apps/web/src/lib/queries/email/thread.ts+++ b/apps/web/src/lib/queries/email/thread.ts@@ -7,11 +7,7 @@ import {ENABLE_GRAPHQL_SOUP_OVERRIDE,} from '@core/constant/featureFlags';import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';-import {- catchToResult,- ThrownResultError,- throwOnErr,-} from '@core/util/result';+import { catchToResult, throwOnErr } from '@core/util/result';import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';import { emailClient } from '@service-email/client';import type {@@ -20,21 +16,11 @@ import type {ApiThread as Thread,UpsertScheduledResponse,} from '@service-email/generated/schemas';-import {- EmailThreadPageDocument,- type EmailThreadPageQuery,- type EmailThreadPageQueryVariables,-} from '@service-storage/graphql/generated/graphql';-import {- getGraphqlSoupClient,- graphqlCacheEnabled,-} from '@service-storage/graphql-soup';import {type InfiniteData,useInfiniteQuery,useMutation,} from '@tanstack/solid-query';-import type { CombinedError } from '@urql/core';import { err, ok } from 'neverthrow';import type { Accessor } from 'solid-js';import { queryClient } from '../client';@@ -42,8 +28,11 @@ import { optimisticUpdateSoupEntity, refetchSoupEntity } from '../soup/cache';import { invalidateAllSoup } from '../soup/normalized-cache';import { type UndoHandle, useUndoableMutation } from '../undo';import { type MutationCallbacks, withCallbacks } from '../utils';-import { mapGraphqlEmailThreadPage } from './graphql/mapper';-import { createGraphqlEmailThreadQuery } from './graphql/thread';+import {+ createGraphqlEmailThreadQuery,+ fetchGraphqlEmailThread,+ mapGraphqlThreadError,+} from './graphql/thread';import { emailKeys } from './keys';const THREAD_STALE_TIME = 5 * 60 * 1000;@@ -109,45 +98,7 @@ export async function fetchAndCacheThread(return ok({ thread });}- const result = await catchToResult(async () => {- const client = getGraphqlSoupClient();- const variables: EmailThreadPageQueryVariables = {- threadId,- offset: 0,- limit: DEFAULT_THREAD_MESSAGES_LIMIT,- };- let queryResult = await client- .query<EmailThreadPageQuery, EmailThreadPageQueryVariables>(- EmailThreadPageDocument,- variables,- { requestPolicy: 'cache-and-network' }- )- .toPromise();-- if (queryResult.error?.networkError && graphqlCacheEnabled()) {- const cached = await client- .query<EmailThreadPageQuery, EmailThreadPageQueryVariables>(- EmailThreadPageDocument,- variables,- { requestPolicy: 'cache-only' }- )- .toPromise();- if (cached.data) queryResult = cached;- }-- if (queryResult.error) {- throw mapGraphqlThreadError(queryResult.error);- }-- const thread = queryResult.data?.user.emailThread;- if (!thread) {- throw new ThrownResultError([- { code: 'NOT_FOUND', message: 'Email thread not found' },- ]);- }-- return mapGraphqlEmailThreadPage(thread);- });+ const result = await catchToResult(() => fetchGraphqlEmailThread(threadId));if (result.isErr()) return err(result.error as any);return ok({ thread: result.value });@@ -214,31 +165,6 @@ function selectThreadQueryData(};}-function mapGraphqlThreadError(- error: CombinedError | null-): ThrownResultError | null {- if (!error) return null;-- const resultErrors = error.graphQLErrors.map((graphqlError) => ({- ...graphqlError.extensions,- code:- typeof graphqlError.extensions?.code === 'string'- ? graphqlError.extensions.code- : 'UNKNOWN',- message: graphqlError.message,- }));- return new ThrownResultError(- resultErrors.length > 0- ? resultErrors- : [- {- code: 'UNKNOWN',- message: error.networkError?.message ?? error.message,- },- ]- );-}-/*** Transport-neutral live query for a thread and its paginated messages.* GraphQL uses urql-solid while the rollout flag is enabled; REST remains the@@ -284,9 +210,10 @@ export function useThreadQuery<TData = ThreadQueryData>(: (restQuery.data as TData | undefined);},get error() {- return usesGraphql()+ if (!usesGraphql()) return (restQuery.error as Error | null) ?? null;+ return graphqlQuery.error? mapGraphqlThreadError(graphqlQuery.error)- : ((restQuery.error as Error | null) ?? null);+ : null;},get isLoading() {return usesGraphql() ? graphqlQuery.isLoading : restQuery.isLoading;diff --git a/apps/web/src/lib/queries/soup/items.ts b/apps/web/src/lib/queries/soup/items.tsindex 04638683cc..cba3a1ab87 100644--- a/apps/web/src/lib/queries/soup/items.ts+++ b/apps/web/src/lib/queries/soup/items.ts@@ -37,6 +37,10 @@ import type { Accessor } from 'solid-js';import { queryClient } from '../client';import { createGraphqlGroupedSoupAstItemsQuery } from './graphql/grouped-items';import { createGraphqlSoupAstItemsQuery } from './graphql/items';+import {+ createSoupRequestSignal,+ SOUP_NETWORK_QUERY_OPTIONS,+} from './request-timeout';export type SoupParams = Params;@@ -163,6 +167,8 @@ const useRestSoupAstItemsQuery = (queryKey: soupKeys.astItems({ params, body, groupBy, transport }).queryKey,queryFn: async (ctx): Promise<SoupAstItemsPage> => {+ const signal = createSoupRequestSignal(ctx.signal);+if (groupBy) {const sort_method = groupedSortMethod(params.sort_method);@@ -176,6 +182,7 @@ const useRestSoupAstItemsQuery = (sort_method,},body,+ signal,}));@@ -206,6 +213,7 @@ const useRestSoupAstItemsQuery = (...body,...params,},+ signal,}));@@ -273,6 +281,12 @@ const useRestSoupAstItemsQuery = (return { entities, groups: undefined };},enabled: options?.().enabled,+ // Do not spin through background retries while the explicit load-error+ // state is visible. NWPathMonitor lets TanStack pause an offline query+ // and resume it automatically when the path becomes available again.+ ...SOUP_NETWORK_QUERY_OPTIONS,+ // A timed-out native request should reach the view's load-error state.+ // Retry remains available explicitly from that state.staleTime: options?.().staleTime,placeholderData: (prev, prevQuery) => {// Keep the previous rows on screen while params/filters change, butdiff --git a/apps/web/src/lib/queries/soup/request-timeout.test.ts b/apps/web/src/lib/queries/soup/request-timeout.test.tsnew file mode 100644index 0000000000..9150e71c48--- /dev/null+++ b/apps/web/src/lib/queries/soup/request-timeout.test.ts@@ -0,0 +1,52 @@+import { onlineManager, QueryClient } from '@tanstack/query-core';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ createSoupRequestSignal,+ SOUP_NETWORK_QUERY_OPTIONS,+ SOUP_REQUEST_TIMEOUT_MS,+} from './request-timeout';++describe('createSoupRequestSignal', () => {+ afterEach(() => onlineManager.setOnline(true));++ it('aborts when TanStack cancels the query', () => {+ const query = new AbortController();+ const signal = createSoupRequestSignal(query.signal);++ query.abort();++ expect(signal.aborted).toBe(true);+ });++ it('uses the bounded Soup request deadline', () => {+ const timeout = vi+ .spyOn(AbortSignal, 'timeout')+ .mockReturnValue(new AbortController().signal);++ createSoupRequestSignal(new AbortController().signal);++ expect(timeout).toHaveBeenCalledWith(SOUP_REQUEST_TIMEOUT_MS);+ timeout.mockRestore();+ });++ it('pauses while offline and resumes when connectivity returns', async () => {+ onlineManager.setOnline(false);+ const queryFn = vi.fn(async () => 'loaded');+ const queryClient = new QueryClient();+ queryClient.mount();+ const result = queryClient.fetchQuery({+ queryKey: ['soup', 'offline-transition'],+ queryFn,+ ...SOUP_NETWORK_QUERY_OPTIONS,+ });++ await Promise.resolve();+ expect(queryFn).not.toHaveBeenCalled();++ onlineManager.setOnline(true);++ await expect(result).resolves.toBe('loaded');+ expect(queryFn).toHaveBeenCalledOnce();+ queryClient.unmount();+ });+});diff --git a/apps/web/src/lib/queries/soup/request-timeout.ts b/apps/web/src/lib/queries/soup/request-timeout.tsnew file mode 100644index 0000000000..05dfc5b451--- /dev/null+++ b/apps/web/src/lib/queries/soup/request-timeout.ts@@ -0,0 +1,25 @@+import { getNativeNetworkAbortSignal } from '@core/mobile/native-network-status';++/** Maximum time an active Soup view may wait for its network response. */+export const SOUP_REQUEST_TIMEOUT_MS = 12_000;++/** Soup failures remain user-retryable instead of retrying in the background. */+export const SOUP_NETWORK_QUERY_OPTIONS = {+ retry: false,+} as const;++/**+ * Combines TanStack's query-cancellation signal with a hard request deadline.+ * Native HTTP requests can otherwise remain pending indefinitely when+ * connectivity disappears after the app has started.+ */+export function createSoupRequestSignal(+ querySignal: AbortSignal,+ timeoutMs = SOUP_REQUEST_TIMEOUT_MS+): AbortSignal {+ return AbortSignal.any([+ querySignal,+ getNativeNetworkAbortSignal(),+ AbortSignal.timeout(timeoutMs),+ ]);+}diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex 38ea903276..b8b7f090d7 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -478,6 +478,7 @@ export const storageServiceClient = {async getSoupAstItems(args: {params: { cursor?: string | null };body: PostSoupAstRequest;+ signal?: AbortSignal;}) {const searchParams = args.params.cursor? `?cursor=${args.params.cursor}`@@ -486,6 +487,7 @@ export const storageServiceClient = {return await dssFetch<SoupPage>(`/items/soup/ast${searchParams}`, {method: 'POST',body: JSON.stringify(args.body),+ signal: args.signal,});},@@ -496,6 +498,7 @@ export const storageServiceClient = {sort_method?: GroupedSoupSort;};body: PostSoupAstRequest;+ signal?: AbortSignal;}) {const { limit: _limit, ...filters } = args.body;const body = {@@ -511,6 +514,7 @@ export const storageServiceClient = {return await dssFetch<GroupedSoupInitialPage>(`/items/soup/ast/grouped`, {method: 'POST',body: JSON.stringify(body),+ signal: args.signal,});},diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.tsindex 752ad4ea03..a547d4822b 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts@@ -202,7 +202,7 @@ describe('GraphQL Soup subscription lifecycle', () => {expect(toastFailure).toHaveBeenCalledOnce();expect(toastFailure).toHaveBeenCalledWith('Live updates disconnected', {- subtext: 'Refresh the app to reconnect.',+ subtext: 'Refresh to reconnect.',});lifecycle.dispose();});diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.tsindex b21a6e94a8..0c9da30021 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts@@ -153,7 +153,7 @@ export function createGraphqlSoupSubscriptionsLifecycle(): {if (!signaledFailure) {signaledFailure = true;toast.failure('Live updates disconnected', {- subtext: 'Refresh the app to reconnect.',+ subtext: 'Refresh to reconnect.',});}}diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex d835b79503..f7dda666b5 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -220,6 +220,7 @@ dependencies = ["tauri-plugin-http","tauri-plugin-input-accessory","tauri-plugin-log",+ "tauri-plugin-network-status","tauri-plugin-notification","tauri-plugin-notifications","tauri-plugin-opener",@@ -6460,6 +6461,14 @@ dependencies = ["tracing",]+[[package]]+name = "tauri-plugin-network-status"+version = "0.1.0"+dependencies = [+ "tauri",+ "tauri-plugin",+]+[[package]]name = "tauri-plugin-notification"version = "2.3.3"diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.tomlindex 3441531052..6b33852299 100644--- a/apps/web/tauri/Cargo.toml+++ b/apps/web/tauri/Cargo.toml@@ -6,6 +6,7 @@ members = ["logger","macro_bundle_updater_plugin","navigation_plugin",+ "network_status_plugin","pasteboard_plugin","photo_library_plugin","staged_upload_constants",diff --git a/apps/web/tauri/network_status_plugin/.gitignore b/apps/web/tauri/network_status_plugin/.gitignorenew file mode 100644index 0000000000..a2ba4dd574--- /dev/null+++ b/apps/web/tauri/network_status_plugin/.gitignore@@ -0,0 +1,6 @@+# Swift Package Manager build artifacts+ios/.build/+ios/Package.resolved++# Tauri-generated Swift API (placed here by `cargo tauri ios build`)+.tauri/diff --git a/apps/web/tauri/network_status_plugin/Cargo.toml b/apps/web/tauri/network_status_plugin/Cargo.tomlnew file mode 100644index 0000000000..00da9dbada--- /dev/null+++ b/apps/web/tauri/network_status_plugin/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "tauri-plugin-network-status"+version = "0.1.0"+edition = "2024"+links = "tauri-plugin-network-status"++[build-dependencies]+tauri-plugin = { version = "2.4", features = ["build"] }++[dependencies]+tauri = { workspace = true }++[target.'cfg(target_os = "ios")'.dependencies]+tauri = { workspace = true, features = ["wry"] }diff --git a/apps/web/tauri/network_status_plugin/build.rs b/apps/web/tauri/network_status_plugin/build.rsnew file mode 100644index 0000000000..66c7d07027--- /dev/null+++ b/apps/web/tauri/network_status_plugin/build.rs@@ -0,0 +1,6 @@+fn main() {+ tauri_plugin::Builder::new(&["watch_status"])+ .ios_path("ios")+ .try_build()+ .unwrap();+}diff --git a/apps/web/tauri/network_status_plugin/ios/Package.swift b/apps/web/tauri/network_status_plugin/ios/Package.swiftnew file mode 100644index 0000000000..327b48a521--- /dev/null+++ b/apps/web/tauri/network_status_plugin/ios/Package.swift@@ -0,0 +1,29 @@+// swift-tools-version:5.3+import PackageDescription++let package = Package(+ name: "tauri-plugin-network-status",+ platforms: [+ .macOS(.v10_13),+ .iOS(.v14),+ ],+ products: [+ .library(+ name: "tauri-plugin-network-status",+ type: .static,+ targets: ["tauri-plugin-network-status"]+ )+ ],+ dependencies: [+ .package(name: "Tauri", path: "../.tauri/tauri-api")+ ],+ targets: [+ .target(+ name: "tauri-plugin-network-status",+ dependencies: [+ .byName(name: "Tauri")+ ],+ path: "Sources"+ )+ ]+)diff --git a/apps/web/tauri/network_status_plugin/ios/Sources/NetworkStatusPlugin.swift b/apps/web/tauri/network_status_plugin/ios/Sources/NetworkStatusPlugin.swiftnew file mode 100644index 0000000000..73012fe9a0--- /dev/null+++ b/apps/web/tauri/network_status_plugin/ios/Sources/NetworkStatusPlugin.swift@@ -0,0 +1,72 @@+import Network+import Tauri+import WebKit++private struct WatchStatusArgs: Decodable {+ let channel: Channel+}++private enum NetworkStatus: String {+ case unknown+ case online+ case offline+}++final class NetworkStatusPlugin: Plugin, @unchecked Sendable {+ private let monitor = NWPathMonitor()+ private let monitorQueue = DispatchQueue(+ label: "com.macro.network-status",+ qos: .utility+ )+ private let stateLock = NSLock()+ private var status = NetworkStatus.unknown+ private var statusChannel: Channel?++ override public func load(webview: WKWebView) {+ monitor.pathUpdateHandler = { [weak self] path in+ self?.updateStatus(path.status == .satisfied ? .online : .offline)+ }+ monitor.start(queue: monitorQueue)+ }++ deinit {+ monitor.cancel()+ }++ @objc public func watchStatus(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(WatchStatusArgs.self)+ let currentStatus: NetworkStatus++ stateLock.lock()+ statusChannel = args.channel+ currentStatus = status+ stateLock.unlock()++ args.channel.send(statusPayload(currentStatus))+ invoke.resolve()+ }++ private func updateStatus(_ nextStatus: NetworkStatus) {+ let channel: Channel?++ stateLock.lock()+ guard status != nextStatus else {+ stateLock.unlock()+ return+ }+ status = nextStatus+ channel = statusChannel+ stateLock.unlock()++ channel?.send(statusPayload(nextStatus))+ }++ private func statusPayload(_ value: NetworkStatus) -> JsonObject {+ return ["status": value.rawValue]+ }+}++@_cdecl("init_plugin_network_status")+public func initPlugin() -> Plugin {+ return NetworkStatusPlugin()+}diff --git a/apps/web/tauri/network_status_plugin/permissions/autogenerated/commands/watch_status.toml b/apps/web/tauri/network_status_plugin/permissions/autogenerated/commands/watch_status.tomlnew file mode 100644index 0000000000..f84bea48e7--- /dev/null+++ b/apps/web/tauri/network_status_plugin/permissions/autogenerated/commands/watch_status.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-watch-status"+description = "Enables the watch_status command without any pre-configured scope."+commands.allow = ["watch_status"]++[[permission]]+identifier = "deny-watch-status"+description = "Denies the watch_status command without any pre-configured scope."+commands.deny = ["watch_status"]diff --git a/apps/web/tauri/network_status_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/network_status_plugin/permissions/autogenerated/reference.mdnew file mode 100644index 0000000000..3b2ad73215--- /dev/null+++ b/apps/web/tauri/network_status_plugin/permissions/autogenerated/reference.md@@ -0,0 +1,35 @@+## Permission Table++<table>+<tr>+<th>Identifier</th>+<th>Description</th>+</tr>+++<tr>+<td>++`network-status:allow-watch-status`++</td>+<td>++Enables the watch_status command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`network-status:deny-watch-status`++</td>+<td>++Denies the watch_status command without any pre-configured scope.++</td>+</tr>+</table>diff --git a/apps/web/tauri/network_status_plugin/permissions/schemas/schema.json b/apps/web/tauri/network_status_plugin/permissions/schemas/schema.jsonnew file mode 100644index 0000000000..300ff57f4e--- /dev/null+++ b/apps/web/tauri/network_status_plugin/permissions/schemas/schema.json@@ -0,0 +1,312 @@+{+ "$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 watch_status command without any pre-configured scope.",+ "type": "string",+ "const": "allow-watch-status",+ "markdownDescription": "Enables the watch_status command without any pre-configured scope."+ },+ {+ "description": "Denies the watch_status command without any pre-configured scope.",+ "type": "string",+ "const": "deny-watch-status",+ "markdownDescription": "Denies the watch_status command without any pre-configured scope."+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/apps/web/tauri/network_status_plugin/src/lib.rs b/apps/web/tauri/network_status_plugin/src/lib.rsnew file mode 100644index 0000000000..040201b320--- /dev/null+++ b/apps/web/tauri/network_status_plugin/src/lib.rs@@ -0,0 +1,20 @@+//! Tauri plugin exposing native iOS network-path status.+#![deny(missing_docs)]++#[cfg(target_os = "ios")]+tauri::ios_plugin_binding!(init_plugin_network_status);++/// Builds the `network-status` Tauri plugin.+///+/// On iOS this registers a Swift `NWPathMonitor` adapter. Other targets keep+/// the plugin inert and continue using their existing browser connectivity+/// integration.+pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {+ tauri::plugin::Builder::new("network-status")+ .setup(|_app, _api| {+ #[cfg(target_os = "ios")]+ _api.register_ios_plugin(init_plugin_network_status)?;+ Ok(())+ })+ .build()+}diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex 677c240908..6aea7caa6e 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -80,6 +80,7 @@ tauri-plugin-haptics = "2"[target.'cfg(target_os = "ios")'.dependencies]tauri-plugin-call-kit = { path = "../callkit_plugin" }tauri-plugin-input-accessory = { path = "../input_accessory_plugin" }+tauri-plugin-network-status = { path = "../network_status_plugin" }tauri-plugin-pasteboard = { path = "../pasteboard_plugin" }tauri-plugin-photo-library = { path = "../photo_library_plugin" }# Used to call NSFileManager from Rust to get the App Group container path.diff --git a/apps/web/tauri/src-tauri/capabilities/mobile.json b/apps/web/tauri/src-tauri/capabilities/mobile.jsonindex 0f2d363491..03b7fb135c 100644--- a/apps/web/tauri/src-tauri/capabilities/mobile.json+++ b/apps/web/tauri/src-tauri/capabilities/mobile.json@@ -15,6 +15,7 @@"log:default","auth:allow-authenticate","device-info:default",+ "network-status:allow-watch-status","pasteboard:allow-stage-pasteboard-image","photo-library:allow-pick-photo-library-images","call-kit:allow-register-listener",diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex c5d0327261..6b35135a24 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -162,6 +162,7 @@ pub fn run() {builder = builder.plugin(tauri_plugin_haptics::init()).plugin(tauri_plugin_input_accessory::init())+ .plugin(tauri_plugin_network_status::init()).plugin(tauri_plugin_pasteboard::init()).plugin(tauri_plugin_photo_library::init()).plugin(tauri_plugin_call_kit::init());