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(tauri): reconnect websockets after read errors and handle dropped IPC promises (#8207)

teo7d0b1af3be63
diff --git a/.agents/rules/web/architecture.md b/.agents/rules/web/architecture.md
index d28dc244b6..54e7379a77 100644
--- a/.agents/rules/web/architecture.md
+++ b/.agents/rules/web/architecture.md
@@ -78,6 +78,16 @@ Module layout, layering, and TypeScript conventions.
a `<Block>` wrapper merely to satisfy a missing dependency. If shared code
needs an owner or other host capability, expose it through the owning surface
context instead of borrowing `BlockContext`.
+- **FE-56** Tauri IPC promises (`invoke`, `listen`, `addPluginListener`,
+ `unregister`, and plugin wrappers) follow FE-13 in teardown too: native
+ resources are often already gone then, so the call rejects. `UnlistenFn` is
+ typed `() => void` but returns the unlisten IPC promise, which the floating
+ promise lint can't see, so start it with `fireAndForget(unlisten(), surface)`
+ or `fireAndForget(unlistenPromise.then((fn) => fn()), surface)`, never a bare
+ call. Channel `onmessage` handlers must never throw, because Tauri then
+ stalls every later message on that channel. Enforced by ast-grep
+ `ts-/tsx-tauri-ipc-promise-handled`, CI error, which also catches IPC chains
+ returned from an `onCleanup` arrow; unlisten calls still need review.
## TypeScript
diff --git a/apps/web/src/features/settings/Account.tsx b/apps/web/src/features/settings/Account.tsx
index f36c89f6a7..05127b71e1 100644
--- a/apps/web/src/features/settings/Account.tsx
+++ b/apps/web/src/features/settings/Account.tsx
@@ -824,23 +824,22 @@ function bundleUpdateAction(
): { label: string; action: () => void } | null {
const grantBundleUpdate = () =>
invoke('grant_bundle_update', { approved: true }).catch(console.error);
+ const checkForUpdate = () => invoke('check_for_update').catch(console.error);
+ const performUpdate = () => invoke('perform_update').catch(console.error);
switch (status.status) {
case 'Idle':
- return {
- label: 'Check for Update',
- action: () => invoke('check_for_update'),
- };
+ return { label: 'Check for Update', action: checkForUpdate };
case 'Error':
- return { label: 'Retry', action: () => invoke('check_for_update') };
+ return { label: 'Retry', action: checkForUpdate };
case 'UpdateFound':
return { label: 'Download', action: grantBundleUpdate };
case 'WaitingForWifi':
return { label: 'Download anyway', action: grantBundleUpdate };
case 'ClearRequired':
- return { label: 'Reload', action: () => invoke('perform_update') };
+ return { label: 'Reload', action: performUpdate };
case 'Completed':
- return { label: 'Update', action: () => invoke('perform_update') };
+ return { label: 'Update', action: performUpdate };
default:
return null;
}
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index 00bb695f64..b43ee988af 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -1036,6 +1036,30 @@ describe('createTauriCacheHost', () => {
expect(unlisten).toHaveBeenCalled();
});
+ it('absorbs unlisten rejections on dispose', async () => {
+ const unhandled: unknown[] = [];
+ const record = (reason: unknown) => unhandled.push(reason);
+ process.on('unhandledRejection', record);
+ try {
+ const rejectingUnlisten = vi.fn(() =>
+ Promise.reject(new Error('listener already gone'))
+ );
+ listenMock.mockResolvedValue(rejectingUnlisten);
+ const host = createTauriCacheHost({ scope: 'scope-1' });
+ host.dispose();
+
+ await vi.waitFor(() =>
+ expect(rejectingUnlisten).toHaveBeenCalledTimes(
+ listenMock.mock.calls.length
+ )
+ );
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(unhandled).toEqual([]);
+ } finally {
+ process.off('unhandledRejection', record);
+ }
+ });
+
describe('calendar ranges', () => {
const rangeArgs = { startMs: 0, endMs: 10, startDay: 0, endDay: 1 };
const range = {
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
index 98f5da3e37..297e6d3c0a 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -251,10 +251,6 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
}
}
const unlistenHydration = listenForHydration();
- async function removeHydrationListener(): Promise<void> {
- const unlisten = await unlistenHydration;
- unlisten?.();
- }
async function initialize(): Promise<void> {
const { default: schemaSdl } = await import(
@@ -682,19 +678,18 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
hydrationSubscribers.clear();
generationChangeSubscribers.clear();
settlementSubscribers.clear();
- fireAndForget(
- unlistenOps.then((fn) => fn?.()),
- 'graphql-cache-host'
- );
- fireAndForget(
- unlistenCacheChanges.then((fn) => fn?.()),
- 'graphql-cache-host'
- );
- fireAndForget(removeHydrationListener(), 'graphql-cache-host');
- fireAndForget(
- unlistenSettlements.then((fn) => fn?.()),
- 'graphql-cache-host'
- );
+ for (const unlisten of [
+ unlistenOps,
+ unlistenCacheChanges,
+ unlistenHydration,
+ unlistenSettlements,
+ ]) {
+ // UnlistenFn returns the unlisten IPC promise despite its void type.
+ fireAndForget(
+ unlisten.then((fn) => fn?.()),
+ 'graphql-cache-host'
+ );
+ }
},
};
}
diff --git a/apps/web/src/lib/tauri/http-plugin.test.ts b/apps/web/src/lib/tauri/http-plugin.test.ts
index 5dcf9b72ef..6115c30ee1 100644
--- a/apps/web/src/lib/tauri/http-plugin.test.ts
+++ b/apps/web/src/lib/tauri/http-plugin.test.ts
@@ -85,4 +85,20 @@ describe('tauri http plugin fetch', () => {
expect(unhandled).toEqual([]);
});
+
+ it('ignores an abort that arrives while the body is streaming', async () => {
+ const controller = new AbortController();
+ const response = await fetch('https://example.com/', {
+ signal: controller.signal,
+ });
+ const reader = response.body!.getReader();
+ await reader.read();
+
+ controller.abort();
+ await expect(reader.read()).rejects.toBeDefined();
+ await reader.cancel().catch(() => {});
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(unhandled).toEqual([]);
+ });
});
diff --git a/apps/web/src/lib/tauri/native-updates.ts b/apps/web/src/lib/tauri/native-updates.ts
index d90a14cdf0..e6316bf534 100644
--- a/apps/web/src/lib/tauri/native-updates.ts
+++ b/apps/web/src/lib/tauri/native-updates.ts
@@ -95,10 +95,11 @@ export function createNativeUpdates(flush: () => Promise<void>) {
}
);
if (disposed) {
- stop();
+ // UnlistenFn returns the unlisten IPC promise despite its void type.
+ fireAndForget(stop(), 'native-updates');
return;
}
- unsubscribe = stop;
+ unsubscribe = () => fireAndForget(stop(), 'native-updates');
const current = await invoke<NativeUpdateStatus>(
'get_native_update_status'
);
diff --git a/apps/web/src/lib/tauri/navigation.ts b/apps/web/src/lib/tauri/navigation.ts
index 458024f88c..c42d6202b1 100644
--- a/apps/web/src/lib/tauri/navigation.ts
+++ b/apps/web/src/lib/tauri/navigation.ts
@@ -1,4 +1,5 @@
import { handlePipedreamCallback } from '@core/pipedream/connect-callback';
+import { fireAndForget } from '@core/util/fireAndForget';
import { getNativeMobilePlatform } from '@core/util/platform';
import { setPostLoginRedirect } from '@core/util/postLoginRedirect';
import { Telemetry } from '@macro-inc/observability';
@@ -23,61 +24,65 @@ export function useTauriNavigationEffect() {
// Macro `/app` links opened via `openExternalUrl` in-app instead of the
// system browser.
const unregisterInterceptor = registerMacroLinkInterceptor();
- let unsubscribe: () => void | undefined;
- async function inner() {
- unsubscribe = await listen<NavigateEvent>('navigate', (ev) => {
- if (handlePipedreamCallback(ev.payload.path, ev.payload.query)) return;
- if (ev.payload.path === '/notification') {
- const notificationId = new URLSearchParams(ev.payload.query).get(
- 'notificationId'
- );
- if (notificationId) {
- const span = Telemetry.span('notification.activate');
- try {
- span.setAttr('notification.id', notificationId);
- span.run(() => triggerNotificationNavigation(notificationId));
- } finally {
- span.end();
- }
+ const unlisten = listen<NavigateEvent>('navigate', (ev) => {
+ if (handlePipedreamCallback(ev.payload.path, ev.payload.query)) return;
+ if (ev.payload.path === '/notification') {
+ const notificationId = new URLSearchParams(ev.payload.query).get(
+ 'notificationId'
+ );
+ if (notificationId) {
+ const span = Telemetry.span('notification.activate');
+ try {
+ span.setAttr('notification.id', notificationId);
+ span.run(() => triggerNotificationNavigation(notificationId));
+ } finally {
+ span.end();
}
- return;
}
- const path = ev.payload.query
- ? `${ev.payload.path}?${ev.payload.query}`
- : ev.payload.path;
- if (
- getNativeMobilePlatform() === 'android' &&
- ev.payload.path !== '/login'
- ) {
- // Route through the session gate. During cold start the login marker
- // can precede the user-info query and is not proof of authentication.
- if (ev.payload.path === '/') {
- navigate(path);
- } else {
- setPostLoginRedirect(path);
- navigate('/');
- }
- } else {
+ return;
+ }
+ const path = ev.payload.query
+ ? `${ev.payload.path}?${ev.payload.query}`
+ : ev.payload.path;
+ if (
+ getNativeMobilePlatform() === 'android' &&
+ ev.payload.path !== '/login'
+ ) {
+ // Route through the session gate. During cold start the login marker
+ // can precede the user-info query and is not proof of authentication.
+ if (ev.payload.path === '/') {
navigate(path);
+ } else {
+ setPostLoginRedirect(path);
+ navigate('/');
}
- });
- // On a cold open, the deep-link handler emits `navigate` during
- // startup, before this listener exists, and the event is lost — pull
- // the launch deep link now that we can receive it.
- invoke('flush_launch_deep_link').catch((e) => {
- console.error('failed to flush launch deep link', e);
- });
- }
- inner().catch((error) =>
- Telemetry.error(error, { surface: 'tauri-navigation' })
+ } else {
+ navigate(path);
+ }
+ });
+ unlisten.then(
+ () => {
+ // On a cold open, the deep-link handler emits `navigate` during
+ // startup, before this listener exists, and the event is lost — pull
+ // the launch deep link now that we can receive it.
+ invoke('flush_launch_deep_link').catch((e) => {
+ console.error('failed to flush launch deep link', e);
+ });
+ },
+ (error) => Telemetry.error(error, { surface: 'tauri-navigation' })
);
return onCleanup(() => {
unregisterInterceptor();
- if (unsubscribe) {
- unsubscribe();
- }
+ // A failed listen() was already reported above.
+ fireAndForget(
+ unlisten.then(
+ (fn) => fn(),
+ () => {}
+ ),
+ 'tauri-navigation'
+ );
});
});
}
diff --git a/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts b/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts
index 43b2a92956..f6ec870e7b 100644
--- a/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts
+++ b/packages/collaboration/src/websocket/platform/tauri-websocket.test.ts
@@ -338,3 +338,143 @@ describe('TauriWebSocketWrapper', () => {
expect(plugin.sent).toEqual([]);
});
});
+
+describe('TauriWebSocketWrapper incoming messages', () => {
+ async function openSocket() {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const socket = new TauriWebSocketWrapper('wss://dss.test/ws');
+ const events = track(socket);
+ const received: unknown[] = [];
+ socket.onmessage = (event) => received.push(event.data);
+ plugin.connects[0]?.resolve(7);
+ await settle();
+ let seq = 0;
+ const channel = plugin.connects[0]!.args.onMessage;
+ const push = (message: unknown) =>
+ channel.onmessage?.({ seq: ++seq, message });
+ const pushRaw = (payload: unknown) =>
+ (channel.onmessage as (payload: unknown) => void)(payload);
+ return { socket, events, received, push, pushRaw };
+ }
+
+ it('delivers text messages', async () => {
+ const { received, push } = await openSocket();
+ push({ type: 'Text', data: 'hello' });
+ expect(received).toEqual(['hello']);
+ });
+
+ it('delivers binary messages as an ArrayBuffer', async () => {
+ const { socket, received, push } = await openSocket();
+ socket.binaryType = 'arraybuffer';
+ push({ type: 'Binary', data: [1, 2, 3] });
+ expect(received).toHaveLength(1);
+ expect(received[0]).toBeInstanceOf(ArrayBuffer);
+ expect([...new Uint8Array(received[0] as ArrayBuffer)]).toEqual([1, 2, 3]);
+ });
+
+ it('delivers binary messages as a Blob by default', async () => {
+ const { received, push } = await openSocket();
+ push({ type: 'Binary', data: [1, 2, 3] });
+ expect(received[0]).toBeInstanceOf(Blob);
+ expect((received[0] as Blob).size).toBe(3);
+ });
+
+ it.each([
+ ['a null payload', { type: 'Close', data: null }],
+ ['no payload', { type: 'Close' }],
+ ['a malformed payload', { type: 'Close', data: { code: 'x' } }],
+ ])('closes normally on a close frame with %s', async (_label, frame) => {
+ const { socket, events, push } = await openSocket();
+ push(frame);
+ expect(events).toEqual(['open', 'close:1000']);
+ expect(socket.readyState).toBe(socket.CLOSED);
+ });
+
+ it('ignores ping and pong frames', async () => {
+ const { socket, events, received, push } = await openSocket();
+ push({ type: 'Ping', data: [] });
+ push({ type: 'Pong', data: [1] });
+ expect(events).toEqual(['open']);
+ expect(received).toEqual([]);
+ expect(socket.readyState).toBe(socket.OPEN);
+ });
+
+ it.each([
+ 'IO error: Socket is not connected (os error 57)',
+ 'Connection reset without closing handshake',
+ 'IO error: Connection reset by peer (os error 54)',
+ 'IO error: timed out',
+ ])('fails the connection on the read error %j', async (error) => {
+ const { socket, events, received, push } = await openSocket();
+ let closeEvent: CloseEvent | undefined;
+ socket.addEventListener('close', (event) => {
+ closeEvent = event;
+ });
+
+ expect(() => push(error)).not.toThrow();
+ push({ type: 'Text', data: 'after the stream ended' });
+
+ expect(events).toEqual(['open', 'error', 'close:1006']);
+ expect(closeEvent?.wasClean).toBe(false);
+ expect(socket.readyState).toBe(socket.CLOSED);
+ expect(received).toEqual([]);
+ expect(plugin.sent).toEqual([
+ {
+ id: 7,
+ message: {
+ type: 'Close',
+ data: { code: 1000, reason: 'Disconnected by client' },
+ },
+ },
+ ]);
+ });
+
+ it('reports only the local closure when a read error races close()', async () => {
+ const { events, push, socket } = await openSocket();
+ socket.close(4000, 'bye');
+ push('IO error: Broken pipe (os error 32)');
+ await settle();
+ expect(events).toEqual(['open', 'close:4000']);
+ });
+
+ it.each([
+ ['a raw frame', null],
+ ['an unknown message type', { type: 'Fragment', data: [] }],
+ ['a known type with a malformed payload', { type: 'Text', data: 42 }],
+ ['a number', 5],
+ ])('ignores %s and keeps delivering', async (_label, message) => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const { socket, events, received, push } = await openSocket();
+
+ expect(() => push(message)).not.toThrow();
+ push({ type: 'Text', data: 'still alive' });
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(events).toEqual(['open']);
+ expect(received).toEqual(['still alive']);
+ expect(socket.readyState).toBe(socket.OPEN);
+ });
+
+ it('accepts messages from native builds without the replay envelope', async () => {
+ const { events, received, pushRaw } = await openSocket();
+ pushRaw({ type: 'Text', data: 'bare' });
+ pushRaw('IO error: Socket is not connected (os error 57)');
+ expect(received).toEqual(['bare']);
+ expect(events).toEqual(['open', 'error', 'close:1006']);
+ });
+
+ it('keeps delivering after a message handler throws', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { socket, push } = await openSocket();
+ const received: unknown[] = [];
+ socket.onmessage = (event) => {
+ received.push(event.data);
+ if (event.data === 'first') throw new Error('consumer bug');
+ };
+
+ expect(() => push({ type: 'Text', data: 'first' })).not.toThrow();
+ push({ type: 'Text', data: 'second' });
+
+ expect(received).toEqual(['first', 'second']);
+ });
+});
diff --git a/packages/collaboration/src/websocket/platform/tauri-websocket.ts b/packages/collaboration/src/websocket/platform/tauri-websocket.ts
index e4267d778c..01d48c35ba 100644
--- a/packages/collaboration/src/websocket/platform/tauri-websocket.ts
+++ b/packages/collaboration/src/websocket/platform/tauri-websocket.ts
@@ -36,13 +36,26 @@ type TauriMessage =
* (seanaye/feat/ws-replay-buffer). Every incoming message carries a
* per-connection sequence number so missed messages can be recovered after
* the webview was suspended.
+ *
+ * `message` is a `TauriMessage`, a bare string when the read failed (the
+ * plugin's display of the tungstenite error; the stream ends after it), or
+ * `null` for a raw frame. It stays `unknown` because native builds ship
+ * separately from this code and may send shapes this version does not know.
*/
interface ReplayEnvelope {
seq: number;
- // The native plugin serializes read errors as strings in the same stream.
- message: TauriMessage | string;
+ message: unknown;
}
+/** Native builds that predate the replay fork send bare messages. */
+const toEnvelope = (payload: unknown): ReplayEnvelope =>
+ match(payload)
+ .with({ seq: P.number }, (envelope) => ({
+ seq: envelope.seq,
+ message: 'message' in envelope ? envelope.message : undefined,
+ }))
+ .otherwise((message) => ({ seq: 0, message }));
+
interface RecoverResponse {
messages: ReplayEnvelope[];
/**
@@ -110,15 +123,15 @@ 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: ReplayEnvelope['message']) => void>();
+ const listeners = new Set<(message: unknown) => void>();
- const handleMessage = (message: ReplayEnvelope['message']) => {
+ const handleMessage = (message: unknown) => {
match(message)
.with(P.string, () => this.handleFailure('receive'))
- .with({ type: 'Text' }, ({ data }) => {
+ .with({ type: 'Text', data: P.string }, ({ data }) => {
this.handleMessage(data);
})
- .with({ type: 'Binary' }, ({ data }) => {
+ .with({ type: 'Binary', data: P.array(P.number) }, ({ data }) => {
// Convert number array back to Uint8Array/Blob based on binaryType
const messageData =
this._binaryType === 'arraybuffer'
@@ -126,21 +139,32 @@ export class TauriWebSocketWrapper implements MinimalWebSocket {
: new Blob([new Uint8Array(data)]);
this.handleMessage(messageData);
})
- .with({ type: 'Close' }, ({ data }) => {
- const closeEvent = new CloseEvent('close', {
- code: data?.code || 1000,
- reason: data?.reason || '',
- wasClean: true,
- });
- this.handleClose(closeEvent);
- })
- .with({ type: 'Ping' }, () => {
- // Handle ping (usually automatic)
+ .with(
+ { type: 'Close', data: { code: P.number, reason: P.string } },
+ ({ data }) => {
+ this.handleClose(
+ new CloseEvent('close', {
+ code: data.code || 1000,
+ reason: data.reason,
+ wasClean: true,
+ })
+ );
+ }
+ )
+ .with({ type: 'Close' }, () => {
+ this.handleClose(
+ new CloseEvent('close', { code: 1000, wasClean: true })
+ );
})
- .with({ type: 'Pong' }, () => {
- // Handle pong (usually automatic)
+ .with({ type: P.union('Ping', 'Pong') }, () => {
+ // The plugin answers pings itself.
})
- .exhaustive();
+ .otherwise((unknown) => {
+ console.warn(
+ `Tauri WebSocket ${url}: ignoring unrecognized message`,
+ unknown
+ );
+ });
};
// Register BEFORE invoke so any message that arrives during the handshake
@@ -166,14 +190,24 @@ export class TauriWebSocketWrapper implements MinimalWebSocket {
}
this.lastSeq = envelope.seq;
}
+ // A throw here would escape into Tauri's Channel, which then never
+ // advances past this message and stalls every later one.
listeners.forEach((l) => {
- l(envelope.message);
+ try {
+ l(envelope.message);
+ } catch (error) {
+ console.error(
+ `Tauri WebSocket ${url}: message handler threw`,
+ error
+ );
+ }
});
};
this.deliver = deliver;
- const onMessage = new Channel<ReplayEnvelope>();
- onMessage.onmessage = (envelope: ReplayEnvelope) => {
+ const onMessage = new Channel<unknown>();
+ onMessage.onmessage = (payload: unknown) => {
+ const envelope = toEnvelope(payload);
if (this.recovering) {
this.queued.push(envelope);
} else {
@@ -206,7 +240,9 @@ export class TauriWebSocketWrapper implements MinimalWebSocket {
// suspended (e.g. iOS backgrounding) whenever we become visible again.
this.visibilityHandler = () => {
if (document.visibilityState === 'visible') {
- void this.recover();
+ this.recover().catch((error: unknown) => {
+ console.error(`Tauri WebSocket recover failed for ${url}:`, error);
+ });
}
};
document.addEventListener('visibilitychange', this.visibilityHandler);
@@ -317,17 +353,7 @@ export class TauriWebSocketWrapper implements MinimalWebSocket {
console.warn(
`Tauri WebSocket ${this._url}: unrecoverable missed messages, forcing reconnect`
);
- this.disconnectSocket().catch(() => {});
- this._readyState = this.CLOSED;
- this.removeListener?.();
- this.handleError(new Event('error'));
- this.handleClose(
- new CloseEvent('close', {
- code: 1006,
- reason: 'Replay gap detected',
- wasClean: false,
- })
- );
+ this.failConnection('Replay gap detected');
}
}
@@ -463,16 +489,17 @@ export class TauriWebSocketWrapper implements MinimalWebSocket {
// Native errors may contain URLs or payloads. Record only the operation.
span.error(reason);
span.end();
+ this.failConnection(reason);
+ }
+
+ /** Reports an abnormal closure, like a browser socket's error then close. */
+ private failConnection(reason: string) {
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,
- wasClean: false,
- })
+ new CloseEvent('close', { code: 1006, reason, wasClean: false })
);
}
diff --git a/rules/ast-grep/ts-tauri-ipc-promise-handled.yml b/rules/ast-grep/ts-tauri-ipc-promise-handled.yml
new file mode 100644
index 0000000000..0ea1d3e6ac
--- /dev/null
+++ b/rules/ast-grep/ts-tauri-ipc-promise-handled.yml
@@ -0,0 +1,68 @@
+id: ts-tauri-ipc-promise-handled
+language: typescript
+# Twin of tsx-tauri-ipc-promise-handled — ast-grep rules are single-language,
+# and `tsx` only scans .tsx files.
+severity: error
+message: Await, return, `.catch`, or fireAndForget this Tauri IPC promise; a dropped one becomes an unhandled rejection when the plugin rejects.
+note: |-
+ Rule FE-56 in docs/development/style-guide.md. Native plugins reject when
+ their resource is already gone (a cancelled request, a closed socket, a
+ listener removed during teardown), and nothing awaits a promise started with
+ `void` or a bare `.then(cb)`, so each rejection reaches the global
+ unhandledrejection handler. Start un-awaited teardown work with
+ fireAndForget from @core/util/fireAndForget (FE-13).
+files:
+ - apps/web/src/**
+ - packages/**
+ignores:
+ - '**/*.test.ts'
+rule:
+ matches: unhandled-ipc-chain
+ any:
+ - inside:
+ kind: expression_statement
+ - inside:
+ kind: unary_expression
+ regex: ^void
+ - inside:
+ kind: arrow_function
+ inside:
+ kind: arguments
+ inside:
+ pattern: onCleanup($$$)
+ inside:
+ kind: program
+ stopBy: end
+ has:
+ kind: import_statement
+ regex: "@tauri-apps/"
+utils:
+ ipc-call:
+ any:
+ - pattern: invoke($$$)
+ - pattern: invoke<$$$T>($$$)
+ - pattern: listen($$$)
+ - pattern: listen<$$$T>($$$)
+ - pattern: once($$$)
+ - pattern: once<$$$T>($$$)
+ - pattern: addPluginListener($$$)
+ - pattern: addPluginListener<$$$T>($$$)
+ - pattern: $LISTENER.unregister()
+ ipc-chain:
+ any:
+ - matches: ipc-call
+ # A stored IPC promise (e.g. an unlisten promise) chained in teardown.
+ - pattern: $PROMISE.then($ON_FULFILLED)
+ - kind: call_expression
+ has:
+ field: function
+ kind: member_expression
+ has:
+ field: object
+ matches: ipc-chain
+ unhandled-ipc-chain:
+ matches: ipc-chain
+ not:
+ any:
+ - pattern: $PROMISE.catch($$$)
+ - pattern: $PROMISE.then($ON_FULFILLED, $ON_REJECTED)
diff --git a/rules/ast-grep/tsx-tauri-ipc-promise-handled.yml b/rules/ast-grep/tsx-tauri-ipc-promise-handled.yml
new file mode 100644
index 0000000000..b64d2a6616
--- /dev/null
+++ b/rules/ast-grep/tsx-tauri-ipc-promise-handled.yml
@@ -0,0 +1,68 @@
+id: tsx-tauri-ipc-promise-handled
+language: tsx
+# Twin of ts-tauri-ipc-promise-handled — ast-grep rules are single-language,
+# and `typescript` only scans .ts files.
+severity: error
+message: Await, return, `.catch`, or fireAndForget this Tauri IPC promise; a dropped one becomes an unhandled rejection when the plugin rejects.
+note: |-
+ Rule FE-56 in docs/development/style-guide.md. Native plugins reject when
+ their resource is already gone (a cancelled request, a closed socket, a
+ listener removed during teardown), and nothing awaits a promise started with
+ `void` or a bare `.then(cb)`, so each rejection reaches the global
+ unhandledrejection handler. Start un-awaited teardown work with
+ fireAndForget from @core/util/fireAndForget (FE-13).
+files:
+ - apps/web/src/**
+ - packages/**
+ignores:
+ - '**/*.test.tsx'
+rule:
+ matches: unhandled-ipc-chain
+ any:
+ - inside:
+ kind: expression_statement
+ - inside:
+ kind: unary_expression
+ regex: ^void
+ - inside:
+ kind: arrow_function
+ inside:
+ kind: arguments
+ inside:
+ pattern: onCleanup($$$)
+ inside:
+ kind: program
+ stopBy: end
+ has:
+ kind: import_statement
+ regex: "@tauri-apps/"
+utils:
+ ipc-call:
+ any:
+ - pattern: invoke($$$)
+ - pattern: invoke<$$$T>($$$)
+ - pattern: listen($$$)
+ - pattern: listen<$$$T>($$$)
+ - pattern: once($$$)
+ - pattern: once<$$$T>($$$)
+ - pattern: addPluginListener($$$)
+ - pattern: addPluginListener<$$$T>($$$)
+ - pattern: $LISTENER.unregister()
+ ipc-chain:
+ any:
+ - matches: ipc-call
+ # A stored IPC promise (e.g. an unlisten promise) chained in teardown.
+ - pattern: $PROMISE.then($ON_FULFILLED)
+ - kind: call_expression
+ has:
+ field: function
+ kind: member_expression
+ has:
+ field: object
+ matches: ipc-chain
+ unhandled-ipc-chain:
+ matches: ipc-chain
+ not:
+ any:
+ - pattern: $PROMISE.catch($$$)
+ - pattern: $PROMISE.then($ON_FULFILLED, $ON_REJECTED)