Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(ios): recover socket failures and diagnose webview reloads (#8354)

Peter Chinman1c03899297ff
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 5e5bd448db..31b3da4330 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -102,6 +102,7 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.
- Mount the floating mobile AI composer only on the Agents view; other views keep their New action or their own reply/comment composer.
- Passive PR mentions must not retry initial GitHub status failures on remount; preserve confirmed status through refetch errors and keep pending data reads out of their parent Suspense boundary.
- Keep native booking exit navigation in the route shell, outside page loading boundaries, and use the router so the native hash route stays intact.
+- Diagnose native full reloads with `native_webview_started` and native launch/termination/update counters; termination coverage is iOS/macOS only, and a pageview alone also includes SPA navigation. See `tauri/src-tauri/README.md`.
- All API/network calls live in service-clients.
- Route explicit call exits using the server's `callEnded` result: ended calls
open their record; ongoing channel and scheduled calls return to the channel
diff --git a/apps/web/src/lib/queries/email/local-draft-store.test.ts b/apps/web/src/lib/queries/email/local-draft-store.test.ts
index 1ebde171cb..e7e813c8ab 100644
--- a/apps/web/src/lib/queries/email/local-draft-store.test.ts
+++ b/apps/web/src/lib/queries/email/local-draft-store.test.ts
@@ -49,6 +49,41 @@ describe('draft connection recovery', () => {
});
});
+ it('waits for rollback and preserves the underlying request error', async () => {
+ const report = vi.fn();
+ const store = createLocalDraftStore(crypto.randomUUID(), report);
+ stores.push(store);
+ const session = await store.activate('owner');
+ await store.save(session, snapshot());
+ let aborted = false;
+ vi.spyOn(IDBObjectStore.prototype, 'get').mockImplementationOnce(function (
+ this: IDBObjectStore
+ ) {
+ this.transaction.addEventListener('abort', () => {
+ aborted = true;
+ });
+ // The session key already exists. The request's ConstraintError bubbles
+ // before IDBTransaction.error is populated.
+ return this.add('duplicate', 'session');
+ });
+ await expect(
+ store.save(session, snapshot('Rejected edit', 1))
+ ).rejects.toMatchObject({
+ name: 'ConstraintError',
+ });
+ expect(aborted).toBe(true);
+ expect(report).toHaveBeenCalledWith({
+ type: 'failed',
+ error: expect.objectContaining({ name: 'ConstraintError' }),
+ });
+ expect(await store.read(session, 'local')).toMatchObject({
+ revision: 1,
+ content: { subject: 'Keep this draft' },
+ });
+ await store.save(session, snapshot('Later edit', 1));
+ expect(await store.read(session, 'local')).toMatchObject({ revision: 2 });
+ });
+
it.each(['closed', 'terminated'])(
'saves the latest edit and continues server autosave after a connection is %s',
async (reason) => {
diff --git a/apps/web/src/lib/queries/email/local-draft-store.ts b/apps/web/src/lib/queries/email/local-draft-store.ts
index 9c1345a0bd..bb2561c049 100644
--- a/apps/web/src/lib/queries/email/local-draft-store.ts
+++ b/apps/web/src/lib/queries/email/local-draft-store.ts
@@ -116,21 +116,30 @@ export function createLocalDraftStore(
const tx = await beginTransaction(mode);
const result = await new Promise<T>((resolve, reject) => {
let value: T;
+ let executionError: unknown;
tx.oncomplete = () => {
resolve(value);
if (mode === 'readwrite' && publish) changed();
};
+ // Request errors bubble before tx.error is set and before rollback
+ // finishes. Settle only on abort so callers see the real cause and
+ // cannot start recovery against a transaction that is still running.
tx.onabort = () =>
- reject(tx.error ?? new Error('Draft storage transaction aborted'));
- tx.onerror = () =>
- reject(tx.error ?? new Error('Unable to save draft on this device'));
+ reject(
+ executionError ??
+ tx.error ??
+ new DOMException(
+ 'Draft storage transaction aborted',
+ 'AbortError'
+ )
+ );
try {
run(tx, (next) => {
value = next;
});
} catch (error) {
+ executionError = error;
tx.abort();
- reject(error);
}
});
if (recovering || failed) report({ type: 'recovered' });
diff --git a/apps/web/src/observability/browser.test.ts b/apps/web/src/observability/browser.test.ts
index 7980cef3f3..c6e33dc028 100644
--- a/apps/web/src/observability/browser.test.ts
+++ b/apps/web/src/observability/browser.test.ts
@@ -4,6 +4,11 @@ import { initializeBrowserObservability } from './browser';
import { readDesktopDiagnostics } from './desktop';
import { initializeUiOperationTelemetry } from './ui-operation';
+const startupSpan = vi.hoisted(() => ({
+ setAttr: vi.fn(),
+ end: vi.fn(),
+}));
+
vi.mock('@core/util/platform', () => ({
getPlatform: () => 'desktop',
isTauri: () => true,
@@ -12,7 +17,13 @@ vi.mock('@graphql-cache/rollout-observability', () => ({
recordBrowserTursoCacheNavigation: vi.fn(),
}));
vi.mock('@macro-inc/observability', () => ({
- Telemetry: { init: vi.fn(), info: vi.fn(), flush: vi.fn(), error: vi.fn() },
+ Telemetry: {
+ init: vi.fn(),
+ info: vi.fn(),
+ flush: vi.fn(),
+ error: vi.fn(),
+ span: vi.fn(() => startupSpan),
+ },
}));
vi.mock('@macro-inc/observability/web', () => ({
createWebTracingProvider: vi.fn(),
@@ -70,6 +81,12 @@ it('explicit native recording overrides the normal enablement gate and exporter
'service.instance.id': 'launch-1',
'macro.recording.id': 'recording-1',
});
+ expect(Telemetry.span).toHaveBeenCalledWith('native.webview.start');
+ expect(startupSpan.setAttr).toHaveBeenCalledWith(
+ 'native_instance_id',
+ 'launch-1'
+ );
+ expect(startupSpan.end).toHaveBeenCalledOnce();
});
it('drops browser and extension noise from window errors but reports app errors', async () => {
diff --git a/apps/web/src/observability/browser.ts b/apps/web/src/observability/browser.ts
index 4144986788..4ad0ff4fef 100644
--- a/apps/web/src/observability/browser.ts
+++ b/apps/web/src/observability/browser.ts
@@ -11,6 +11,7 @@ import {
desktopResourceAttributes,
readDesktopDiagnostics,
} from './desktop';
+import { recordNativeWebviewStart } from './native-lifecycle';
import { initializeUiOperationTelemetry } from './ui-operation';
async function browserTelemetryEnabled(hasExporter: boolean): Promise<boolean> {
@@ -95,6 +96,7 @@ export async function initializeBrowserObservability(): Promise<void> {
tracingProvider: (resource, getUserId) =>
createWebTracingProvider(telemetryConfig, resource, getUserId),
});
+ if (isTauri()) recordNativeWebviewStart(desktop);
if (recording && desktop) {
recording.accept(desktop);
Telemetry.info('Desktop memory recording enabled', {
diff --git a/apps/web/src/observability/desktop.ts b/apps/web/src/observability/desktop.ts
index 11dcae345a..fdfef859b7 100644
--- a/apps/web/src/observability/desktop.ts
+++ b/apps/web/src/observability/desktop.ts
@@ -29,6 +29,15 @@ export type DesktopSnapshot = {
};
samples: MemorySample[];
droppedSamples: number;
+ /** Absent on binaries shipped before WebContent termination reporting. */
+ webContent?: {
+ terminations: number;
+ lastTerminationMs: number | null;
+ };
+ bundleReloads?: {
+ dispatches: number;
+ lastSource: string | null;
+ } | null;
};
type SampleSink = {
diff --git a/apps/web/src/observability/native-lifecycle.test.ts b/apps/web/src/observability/native-lifecycle.test.ts
new file mode 100644
index 0000000000..d3ef592162
--- /dev/null
+++ b/apps/web/src/observability/native-lifecycle.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { recordNativeWebviewStart } from './native-lifecycle';
+
+const telemetry = vi.hoisted(() => ({
+ track: vi.fn(),
+ register: vi.fn(),
+ span: { setAttr: vi.fn(), end: vi.fn() },
+}));
+vi.mock('@app/lib/analytics', () => ({
+ analytics: {
+ track: telemetry.track,
+ posthog: { register: telemetry.register },
+ },
+}));
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: { span: () => telemetry.span },
+}));
+
+afterEach(() => {
+ document.head.querySelector('meta[name="macro-bundle-build"]')?.remove();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+});
+
+describe('native WebView startup diagnostics', () => {
+ it.each(['android', 'windows', 'linux'])(
+ 'does not claim termination coverage for %s',
+ (os) => {
+ recordNativeWebviewStart({
+ identity: {
+ instanceId: 'native-launch',
+ nativeVersion: '2.0',
+ recordingId: null,
+ tracesUrl: null,
+ os,
+ hostPid: 123,
+ },
+ samples: [],
+ droppedSamples: 0,
+ webContent: { terminations: 0, lastTerminationMs: null },
+ });
+ expect(telemetry.track).toHaveBeenCalledWith(
+ 'native_webview_started',
+ expect.objectContaining({
+ native_diagnostics_available: true,
+ native_termination_reporting_available: false,
+ native_web_content_terminations: undefined,
+ native_last_termination_ms: undefined,
+ })
+ );
+ }
+ );
+
+ it('correlates replacement documents with their native launch and termination history', () => {
+ const meta = document.createElement('meta');
+ meta.name = 'macro-bundle-build';
+ meta.content = '42';
+ document.head.append(meta);
+ vi.spyOn(performance, 'getEntriesByType').mockReturnValue([]);
+ recordNativeWebviewStart({
+ identity: {
+ instanceId: 'native-launch',
+ nativeVersion: '2.0',
+ recordingId: null,
+ tracesUrl: null,
+ os: 'ios',
+ hostPid: 123,
+ },
+ samples: [],
+ droppedSamples: 0,
+ webContent: { terminations: 2, lastTerminationMs: 1234 },
+ bundleReloads: { dispatches: 1, lastSource: 'run_event_resumed' },
+ });
+ const expected = expect.objectContaining({
+ native_instance_id: 'native-launch',
+ native_web_content_terminations: 2,
+ native_last_termination_ms: 1234,
+ native_termination_reporting_available: true,
+ loaded_bundle_build: '42',
+ native_bundle_reload_dispatches: 1,
+ native_bundle_reload_last_source: 'run_event_resumed',
+ });
+ expect(telemetry.register).toHaveBeenCalledWith(expected);
+ expect(telemetry.track).toHaveBeenCalledWith(
+ 'native_webview_started',
+ expected
+ );
+ expect(telemetry.span.end).toHaveBeenCalledOnce();
+ });
+
+ it('reports missing native support as unknown, rather than zero terminations', () => {
+ vi.spyOn(performance, 'getEntriesByType').mockReturnValue([]);
+ recordNativeWebviewStart(undefined);
+ expect(telemetry.track).toHaveBeenCalledWith(
+ 'native_webview_started',
+ expect.objectContaining({
+ native_diagnostics_available: false,
+ native_termination_reporting_available: false,
+ native_web_content_terminations: undefined,
+ })
+ );
+ });
+});
diff --git a/apps/web/src/observability/native-lifecycle.ts b/apps/web/src/observability/native-lifecycle.ts
new file mode 100644
index 0000000000..f69ae81154
--- /dev/null
+++ b/apps/web/src/observability/native-lifecycle.ts
@@ -0,0 +1,45 @@
+import { analytics } from '@app/lib/analytics';
+import { Telemetry } from '@macro-inc/observability';
+import type { DesktopSnapshot } from './desktop';
+
+/** Called once per document, including recovery after a WebContent termination. */
+export function recordNativeWebviewStart(
+ snapshot: DesktopSnapshot | undefined
+) {
+ const bundleBuild = document
+ .querySelector('meta[name="macro-bundle-build"]')
+ ?.getAttribute('content');
+ const navigation = performance.getEntriesByType('navigation')[0];
+ // Native snapshots include this field on every platform, but only Apple's
+ // WebKit termination callback records it. Other platforms remain unknown.
+ const webContent =
+ snapshot?.identity.os === 'ios' || snapshot?.identity.os === 'macos'
+ ? snapshot.webContent
+ : undefined;
+ const attributes = {
+ native_instance_id: snapshot?.identity.instanceId,
+ native_version: snapshot?.identity.nativeVersion,
+ native_diagnostics_available: snapshot !== undefined,
+ native_termination_reporting_available: webContent !== undefined,
+ native_web_content_terminations: webContent?.terminations,
+ native_last_termination_ms: webContent?.lastTerminationMs ?? undefined,
+ native_bundle_reload_dispatches: snapshot?.bundleReloads?.dispatches,
+ native_bundle_reload_last_source:
+ snapshot?.bundleReloads?.lastSource ?? undefined,
+ loaded_bundle_build: bundleBuild ?? undefined,
+ web_version: import.meta.env.__APP_VERSION__,
+ navigation_type:
+ navigation && 'type' in navigation && typeof navigation.type === 'string'
+ ? navigation.type
+ : 'unknown',
+ };
+ // Include the native launch and termination count on subsequent exceptions.
+ // These are runtime identifiers, not account data.
+ analytics.posthog.register(attributes);
+ analytics.track('native_webview_started', attributes);
+ const span = Telemetry.span('native.webview.start');
+ for (const [key, value] of Object.entries(attributes)) {
+ if (value !== undefined) span.setAttr(key, value);
+ }
+ span.end();
+}
diff --git a/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs b/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs
index 0191b9c9e9..a41d906664 100644
--- a/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs
+++ b/apps/web/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs
@@ -27,6 +27,33 @@ pub type PluginService = Service<FileSystem>;
const EVENT_NAME: &str = "bundle-update-status";
const WIFI_RETRY_INTERVAL: Duration = Duration::from_secs(30);
+/// Launch-scoped reload dispatches, retained across replacement documents.
+#[derive(Clone, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BundleReloadDiagnostics {
+ dispatches: u64,
+ last_source: Option<&'static str>,
+}
+
+/// Read reload evidence without waiting for the updater's async service lock.
+pub fn bundle_reload_diagnostics<R: Runtime>(
+ app: &tauri::AppHandle<R>,
+) -> Option<BundleReloadDiagnostics> {
+ let state = app.try_state::<std::sync::Mutex<BundleReloadDiagnostics>>()?;
+ let diagnostics = state.lock().ok()?;
+ Some(diagnostics.clone())
+}
+
+fn record_reload_dispatch<R: Runtime>(app: &tauri::AppHandle<R>, source: &'static str) {
+ if let Some(state) = app.try_state::<std::sync::Mutex<BundleReloadDiagnostics>>()
+ && let Ok(mut diagnostics) = state.lock()
+ {
+ diagnostics.dispatches += 1;
+ diagnostics.last_source = Some(source);
+ }
+ tracing::info!(source, "Dispatching bundle update WebView reload");
+}
+
/// Serializable event emitted to the frontend via Tauri's event system.
#[derive(Clone, Serialize)]
#[serde(tag = "status", content = "data")]
@@ -257,6 +284,7 @@ pub async fn apply_completed_update_from<R: Runtime>(
// Reload to pick up the new bundle. Using location.reload() instead of
// navigating to a new URL preserves WKWebView's cookie store.
if let Some(webview) = app_handle.webview_windows().values().next() {
+ record_reload_dispatch(app_handle, source);
if let Err(e) = webview.eval("window.location.reload();") {
tracing::warn!(
source,
@@ -368,6 +396,7 @@ pub async fn clear_bundle<R: Runtime>(
if apply_result == ApplyUpdateResult::ReloadNeeded {
if let Some(webview) = app_handle.webview_windows().values().next() {
+ record_reload_dispatch(&app_handle, "clear_bundle");
if let Err(error) = webview.eval("window.location.reload();") {
tracing::warn!(error=?error, "[bundle-update] failed to reload after clearing bundle");
service.unmark_update_reload_dispatched();
@@ -390,6 +419,7 @@ impl<R: Runtime> Plugin<R> for MacroBundleUpdaterPlugin {
app: &tauri::AppHandle<R>,
config: serde_json::Value,
) -> Result<(), Box<dyn std::error::Error>> {
+ app.manage(std::sync::Mutex::new(BundleReloadDiagnostics::default()));
let client = BundleClient::new(self.base_url.clone());
let fs = FileSystem;
// Desktop release builds embed their compatibility number in Tauri config.
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index 7aa0239c79..a8149d5788 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -33,6 +33,28 @@ Commit the source and generated files together. They are checked in so desktop
release builds do not need Icon Composer. Verify Finder and Dock rendering at
both 1× and 2× display scale on Tahoe, and on a pre-Tahoe Mac.
+## Diagnosing unexpected WebView reloads
+
+Each frontend startup emits `native_webview_started` to PostHog and a
+`native.webview.start` OTel span. The event records the loaded HTML bundle build,
+native version and launch ID, and navigation type. Native diagnostics retain
+WebContent termination counts/timestamps and bundle-update reload dispatch
+counts/last source across WebView replacements. Compare counters within the same
+native launch: an increased termination count identifies WebKit process recovery;
+an increased updater count identifies an app-requested update reload attempt.
+Dispatch does not prove the JavaScript reload completed. A new native launch ID
+means the host process restarted. Missing counters on an older binary mean
+unknown, not zero. The properties are also attached to subsequent PostHog events.
+Termination reporting is available only on iOS and macOS. On other platforms,
+startup events mark it unavailable and omit termination counts/timestamps even
+when the native snapshot includes an unused zero-valued counter.
+
+The Apple termination callback preserves Tauri's default reload behavior and adds
+the native evidence before reloading. It does not establish why WebKit terminated
+(for example, memory pressure versus a crash); device crash/termination reports
+are needed for that distinction. Native counters require a full app release,
+while the frontend remains compatible with older binaries.
+
## Running in development
```sh
diff --git a/apps/web/tauri/src-tauri/src/diagnostics.rs b/apps/web/tauri/src-tauri/src/diagnostics.rs
index 296b832513..2b53eb70c7 100644
--- a/apps/web/tauri/src-tauri/src/diagnostics.rs
+++ b/apps/web/tauri/src-tauri/src/diagnostics.rs
@@ -99,9 +99,24 @@ impl SampleBuffer {
}
}
+#[derive(Clone, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WebContentDiagnostics {
+ terminations: u64,
+ last_termination_ms: Option<u64>,
+}
+
+impl WebContentDiagnostics {
+ fn record_termination(&mut self, timestamp_ms: u64) {
+ self.terminations += 1;
+ self.last_termination_ms = Some(timestamp_ms);
+ }
+}
+
pub struct Diagnostics {
identity: Identity,
buffer: Mutex<SampleBuffer>,
+ web_content: Mutex<WebContentDiagnostics>,
}
impl Diagnostics {
@@ -120,12 +135,25 @@ impl Diagnostics {
host_pid: std::process::id(),
},
buffer: Mutex::new(SampleBuffer::default()),
+ web_content: Mutex::new(WebContentDiagnostics::default()),
}
}
pub fn is_recording(&self) -> bool {
self.identity.recording_id.is_some()
}
+
+ /// Retain process termination evidence outside the WebView being reloaded.
+ pub fn record_web_content_termination(&self) -> Result<(), String> {
+ let mut web_content = self.web_content.lock().map_err(|e| e.to_string())?;
+ web_content.record_termination(
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis() as u64,
+ );
+ Ok(())
+ }
}
#[derive(Serialize)]
@@ -134,10 +162,13 @@ pub struct Snapshot {
identity: Identity,
samples: Vec<MemorySample>,
dropped_samples: u64,
+ web_content: WebContentDiagnostics,
+ bundle_reloads: Option<macro_bundle_updater_plugin::inbound::plugin::BundleReloadDiagnostics>,
}
#[tauri::command]
-pub fn read_desktop_diagnostics(
+pub fn read_desktop_diagnostics<R: tauri::Runtime>(
+ app_handle: tauri::AppHandle<R>,
state: tauri::State<'_, Diagnostics>,
after_sequence: Option<u64>,
) -> Result<Snapshot, String> {
@@ -147,6 +178,10 @@ pub fn read_desktop_diagnostics(
identity: state.identity.clone(),
samples,
dropped_samples,
+ web_content: state.web_content.lock().map_err(|e| e.to_string())?.clone(),
+ bundle_reloads: macro_bundle_updater_plugin::inbound::plugin::bundle_reload_diagnostics(
+ &app_handle,
+ ),
})
}
diff --git a/apps/web/tauri/src-tauri/src/diagnostics/test.rs b/apps/web/tauri/src-tauri/src/diagnostics/test.rs
index 96655f68e2..9af93f7245 100644
--- a/apps/web/tauri/src-tauri/src/diagnostics/test.rs
+++ b/apps/web/tauri/src-tauri/src/diagnostics/test.rs
@@ -1,5 +1,20 @@
use super::*;
+#[test]
+fn termination_evidence_survives_multiple_frontend_reads() {
+ let mut state = WebContentDiagnostics::default();
+ assert_eq!(state.terminations, 0);
+ assert_eq!(state.last_termination_ms, None);
+ state.record_termination(123);
+ let first = serde_json::to_value(&state).unwrap();
+ assert_eq!(first["terminations"], 1);
+ assert_eq!(first["lastTerminationMs"], 123);
+ assert_eq!(serde_json::to_value(&state).unwrap(), first);
+ state.record_termination(456);
+ assert_eq!(state.terminations, 2);
+ assert_eq!(state.last_termination_ms, Some(456));
+}
+
fn sample() -> MemorySample {
MemorySample {
sequence: 0,
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index cf7614f044..8b1a3ee3aa 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -183,6 +183,23 @@ pub fn run() {
.expect("Embedded documents must be valid urls");
let mut builder = tauri::Builder::default();
+ #[cfg(any(target_os = "ios", target_os = "macos"))]
+ {
+ builder = builder.on_web_content_process_terminate(|webview| {
+ tracing::warn!(webview = %webview.label(), "WebContent process terminated; reloading");
+ if let Some(state) = webview.try_state::<diagnostics::Diagnostics>() {
+ let _ = state.record_web_content_termination().inspect_err(|error| {
+ tracing::warn!(%error, "Failed to record WebContent termination");
+ });
+ }
+ // Preserve Tauri's default recovery, but retain the cause in the
+ // native process so the replacement document can report it.
+ let _ = webview.reload().inspect_err(|error| {
+ tracing::error!(%error, "Failed to reload terminated WebContent process");
+ });
+ });
+ }
+
#[cfg(desktop)]
{
// single instance plugin should always be the first registered
diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission/activation.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission/activation.rs
index ddb6c720da..395b38cb2c 100644
--- a/apps/web/tauri/src-tauri/src/macos_notification_permission/activation.rs
+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission/activation.rs
@@ -53,9 +53,7 @@ define_class!(
) {
// SAFETY: this immutable framework constant is available on every
// supported macOS version. Dismissal is never a navigation action.
- if response.actionIdentifier().as_ref()
- == unsafe { UNNotificationDefaultActionIdentifier }
- {
+ if &*response.actionIdentifier() == unsafe { UNNotificationDefaultActionIdentifier } {
let identifier = response.notification().request().identifier().to_string();
activate(self.ivars(), notification_url(&identifier));
}
diff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.json
index 7d32c90a78..33050018d9 100644
--- a/apps/web/tauri/src-tauri/tauri.android.conf.json
+++ b/apps/web/tauri/src-tauri/tauri.android.conf.json
@@ -1,20 +1,50 @@
{
- "$schema": "https://schema.tauri.app/config/2",
- "productName": "Macro Alpha",
- "identifier": "com.macro.workspace.mobile",
"version": "2.5.0",
"bundle": {
"android": {
- "versionCode": 6
+ "versionCode": 7
}
},
+ "$schema": "https://schema.tauri.app/config/2",
+ "productName": "Macro Alpha",
+ "identifier": "com.macro.workspace.mobile",
"plugins": {
"deep-link": {
"mobile": [
- { "scheme": ["macro"], "host": "app", "appLink": false },
- { "host": "macro.com", "path": ["/app"], "pathPrefix": ["/app/"] },
- { "host": "dev.macro.com", "path": ["/app"], "pathPrefix": ["/app/"] },
- { "host": "staging.macro.com", "path": ["/app"], "pathPrefix": ["/app/"] }
+ {
+ "scheme": [
+ "macro"
+ ],
+ "host": "app",
+ "appLink": false
+ },
+ {
+ "host": "macro.com",
+ "path": [
+ "/app"
+ ],
+ "pathPrefix": [
+ "/app/"
+ ]
+ },
+ {
+ "host": "dev.macro.com",
+ "path": [
+ "/app"
+ ],
+ "pathPrefix": [
+ "/app/"
+ ]
+ },
+ {
+ "host": "staging.macro.com",
+ "path": [
+ "/app"
+ ],
+ "pathPrefix": [
+ "/app/"
+ ]
+ }
]
}
},
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index a8c377e516..a9f5776462 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -448,6 +448,10 @@ reloading. Repeat across background/resume on an iPhone. A transaction that has
already started is never automatically replayed. Persistent failures still block
server autosave; copy unsaved content before restarting. Storage failures and
recovery report current page visibility and network state without draft content.
+Request errors settle only after the transaction's abort event, preserving the
+underlying IndexedDB error and waiting for rollback before recovery. To verify,
+force a request constraint failure: the prior draft must remain intact, the error
+must be `ConstraintError`, and a subsequent valid save must succeed.
Repeated local-save failures show one persistent warning per composer; recovery
or closing that composer dismisses it. A later failure shows a new warning.
diff --git a/packages/collaboration/src/websocket/README.md b/packages/collaboration/src/websocket/README.md
index b6d5dd4076..cb8e1eddf9 100644
--- a/packages/collaboration/src/websocket/README.md
+++ b/packages/collaboration/src/websocket/README.md
@@ -41,6 +41,15 @@ const ws = new WebsocketBuilder('ws://localhost:5000')
Configure retries with the builder:
+The Tauri transport converts native read errors (string payloads, including
+connection resets after iOS suspension) into one `error` followed by an abnormal
+`close` (1006). The same handling applies to recovered replay messages. Consumers
+can reconnect normally; a transport error must never escape as a pattern-match
+exception or leave the wrapper reporting `OPEN`.
+Read/send failures emit one `websocket.transport.failure` span with the native
+socket ID when assigned, operation, and closed outcome. URLs, message payloads,
+and raw provider errors are excluded.
+
```typescript
const ws = new WebsocketBuilder(url)
.withMaxRetries(10)
diff --git a/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts b/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts
index de87fa4ba9..43b2a92956 100644
--- a/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts
+++ b/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
+import { invoke } from '@tauri-apps/api/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
type ReplayEnvelope = { seq: number; message: unknown };
@@ -17,6 +18,21 @@ const plugin = vi.hoisted(() => ({
sent: [] as Array<{ id: number; message: unknown }>,
}));
+const telemetry = vi.hoisted(() => ({
+ start: vi.fn(),
+ setAttr: vi.fn(),
+ error: vi.fn(),
+ end: vi.fn(),
+}));
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: {
+ span: (name: string) => {
+ telemetry.start(name);
+ return telemetry;
+ },
+ },
+}));
+
vi.mock('@tauri-apps/api/core', () => ({
Channel: class {
onmessage?: (envelope: ReplayEnvelope) => void;
@@ -47,6 +63,7 @@ function track(socket: TauriWebSocketWrapper) {
}
beforeEach(() => {
+ vi.clearAllMocks();
plugin.connects.length = 0;
plugin.sent.length = 0;
});
@@ -56,6 +73,136 @@ afterEach(() => {
});
describe('TauriWebSocketWrapper', () => {
+ it.each(['receive', 'send'] as const)(
+ 'records one %s failure without recording URLs, payloads, or provider errors',
+ async (operation) => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const socket = new TauriWebSocketWrapper(
+ 'wss://dss.test/ws?token=private-token'
+ );
+ const events = track(socket);
+ plugin.connects[0].resolve(7);
+ await Promise.resolve();
+ const closed = new Promise<void>((resolve) =>
+ socket.addEventListener('close', () => resolve())
+ );
+ if (operation === 'receive') {
+ plugin.connects[0].args.onMessage.onmessage?.({
+ seq: 1,
+ message: 'private provider error',
+ });
+ } else {
+ vi.mocked(invoke).mockRejectedValueOnce(
+ new Error('private provider error')
+ );
+ socket.send('private payload');
+ }
+ await closed;
+ plugin.connects[0].args.onMessage.onmessage?.({
+ seq: 2,
+ message: 'duplicate error',
+ });
+
+ expect(events).toEqual(['open', 'error', 'close:1006']);
+ expect(telemetry.start.mock.calls).toEqual([
+ ['websocket.transport.failure'],
+ ]);
+ expect(telemetry.setAttr.mock.calls).toEqual([
+ ['websocket.transport', 'tauri'],
+ ['websocket.socket_id', 7],
+ ['websocket.operation', operation],
+ ['websocket.outcome', 'closed'],
+ ]);
+ expect(telemetry.error.mock.calls).toEqual([
+ [operation === 'send' ? 'Send failed' : 'Receive failed'],
+ ]);
+ expect(telemetry.end).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('handles a disconnect replayed after the WebView resumes', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
+ const listen = vi.spyOn(document, 'addEventListener');
+ const socket = new TauriWebSocketWrapper('wss://dss.test/ws');
+ const events = track(socket);
+ plugin.connects[0].resolve(7);
+ await Promise.resolve();
+ const resume = listen.mock.calls.find(
+ ([event]) => event === 'visibilitychange'
+ )?.[1];
+ if (typeof resume !== 'function')
+ throw new Error('Missing resume listener');
+ vi.mocked(invoke).mockResolvedValueOnce({
+ messages: [
+ { seq: 1, message: 'IO error: Socket is not connected (os error 57)' },
+ { seq: 2, message: { type: 'Text', data: 'stale message' } },
+ ],
+ gap: false,
+ });
+ const onMessage = vi.fn();
+ socket.onmessage = onMessage;
+ resume.call(document, new Event('visibilitychange'));
+ await Promise.resolve();
+
+ expect(events).toEqual(['open', 'error', 'close:1006']);
+ expect(onMessage).not.toHaveBeenCalled();
+ expect(socket.readyState).toBe(socket.CLOSED);
+ });
+
+ it('reports native read errors as an abnormal closure so callers can reconnect', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const socket = new TauriWebSocketWrapper('wss://dss.test/ws');
+ const events = track(socket);
+ const onMessage = plugin.connects[0].args.onMessage;
+ plugin.connects[0].resolve(7);
+ await Promise.resolve();
+
+ expect(() =>
+ onMessage.onmessage?.({
+ seq: 1,
+ message: 'IO error: Socket is not connected (os error 57)',
+ })
+ ).not.toThrow();
+ expect(socket.readyState).toBe(socket.CLOSED);
+ expect(events).toEqual(['open', 'error', 'close:1006']);
+ onMessage.onmessage?.({
+ seq: 2,
+ message:
+ 'WebSocket protocol error: Connection reset without closing handshake',
+ });
+ expect(events).toEqual(['open', 'error', 'close:1006']);
+ });
+
+ it('does not open a socket when a native read error arrives before connect resolves', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const socket = new TauriWebSocketWrapper('wss://dss.test/ws');
+ const events = track(socket);
+ expect(() =>
+ plugin.connects[0].args.onMessage.onmessage?.({
+ seq: 1,
+ message: 'IO error: Socket is not connected (os error 57)',
+ })
+ ).not.toThrow();
+ plugin.connects[0].resolve(7);
+ await Promise.resolve();
+
+ expect(events).toEqual(['error', 'close:1006']);
+ expect(socket.readyState).toBe(socket.CLOSED);
+ expect(plugin.sent).toEqual([
+ {
+ id: 7,
+ message: {
+ type: 'Close',
+ data: { code: 1000, reason: 'Disconnected by client' },
+ },
+ },
+ ]);
+ });
+
it('can stand in for the WebSocket constructor', () => {
expect(TauriWebSocketWrapper.CONNECTING).toBe(0);
expect(TauriWebSocketWrapper.OPEN).toBe(1);
diff --git a/packages/collaboration/src/websocket/platform/tauri-websocket.ts b/packages/collaboration/src/websocket/platform/tauri-websocket.ts
index 123c930c3b..e4267d778c 100644
--- a/packages/collaboration/src/websocket/platform/tauri-websocket.ts
+++ b/packages/collaboration/src/websocket/platform/tauri-websocket.ts
@@ -1,5 +1,6 @@
+import { Telemetry } from '@macro-inc/observability';
import { Channel, invoke } from '@tauri-apps/api/core';
-import { match } from 'ts-pattern';
+import { match, P } from 'ts-pattern';
import { isTauri } from '../../internal/platform';
import type { MinimalWebSocket, WebSocketFactory } from './minimal-websocket';
@@ -38,7 +39,8 @@ type TauriMessage =
*/
interface ReplayEnvelope {
seq: number;
- message: TauriMessage;
+ // The native plugin serializes read errors as strings in the same stream.
+ message: TauriMessage | string;
}
interface RecoverResponse {
@@ -108,10 +110,11 @@ export class TauriWebSocketWrapper implements MinimalWebSocket {
// We call invoke() directly and pre-register our handler BEFORE the
// connection is made, so messages sent by the server immediately after
// the handshake cannot be dropped (see module comment above).
- const listeners = new Set<(message: TauriMessage) => void>();
+ const listeners = new Set<(message: ReplayEnvelope['message']) => void>();
- const handleMessage = (message: TauriMessage) => {
+ const handleMessage = (message: ReplayEnvelope['message']) => {
match(message)
+ .with(P.string, () => this.handleFailure('receive'))
.with({ type: 'Text' }, ({ data }) => {
this.handleMessage(data);
})
@@ -447,17 +450,27 @@ export class TauriWebSocketWrapper implements MinimalWebSocket {
});
}
- private handleSendRejection(error: unknown) {
+ private handleFailure(operation: 'receive' | 'send') {
if (this._readyState === this.CLOSING || this._readyState === this.CLOSED)
return;
- console.error(`Tauri WebSocket send error for ${this._url}:`, error);
+ const reason = operation === 'send' ? 'Send failed' : 'Receive failed';
+ const span = Telemetry.span('websocket.transport.failure');
+ span.setAttr('websocket.transport', 'tauri');
+ if (this.socketId !== null)
+ span.setAttr('websocket.socket_id', this.socketId);
+ span.setAttr('websocket.operation', operation);
+ span.setAttr('websocket.outcome', 'closed');
+ // Native errors may contain URLs or payloads. Record only the operation.
+ span.error(reason);
+ span.end();
this._readyState = this.CLOSED;
this.removeListener?.();
+ if (this.socketId !== null) this.disconnectSocket().catch(() => {});
this.handleError(new Event('error'));
this.handleClose(
new CloseEvent('close', {
code: 1006,
- reason: 'Send failed',
+ reason,
wasClean: false,
})
);
@@ -472,8 +485,8 @@ export class TauriWebSocketWrapper implements MinimalWebSocket {
if (typeof data === 'string') {
// Send as text message
- this.sendMessage({ type: 'Text', data }).catch((e: unknown) =>
- this.handleSendRejection(e)
+ this.sendMessage({ type: 'Text', data }).catch(() =>
+ this.handleFailure('send')
);
} else {
// Convert binary data to number array for Tauri
@@ -506,7 +519,7 @@ export class TauriWebSocketWrapper implements MinimalWebSocket {
// Send as binary message with number array
this.sendMessage({ type: 'Binary', data: Array.from(uint8Array) }).catch(
- (e: unknown) => this.handleSendRejection(e)
+ () => this.handleFailure('send')
);
}
}