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(pdf): stop unhandled "timed out" rejections (#8208)

teo955094832381
diff --git a/apps/web/src/features/block-pdf/signal/location.test.ts b/apps/web/src/features/block-pdf/signal/location.test.ts
new file mode 100644
index 0000000000..680a9ae225
--- /dev/null
+++ b/apps/web/src/features/block-pdf/signal/location.test.ts
@@ -0,0 +1,64 @@
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useGoToLinkLocation } from './location';
+
+const state = vi.hoisted(() => ({
+ persistedViewLocation: (): string | undefined => undefined,
+ ready: (): boolean => false,
+ goToLocationHash: vi.fn(),
+}));
+
+vi.mock('../context/pdf-document-context', () => ({
+ usePdfDocument: () => ({
+ persistedViewLocation: () => state.persistedViewLocation(),
+ }),
+}));
+vi.mock('../context/pdf-viewer-context', () => ({
+ usePdfViewer: () => ({
+ root: {
+ isReady: () => state.ready(),
+ hasVisiblePages: () => state.ready(),
+ instance: () => ({ goToLocationHash: state.goToLocationHash }),
+ findControlState: () => undefined,
+ },
+ }),
+}));
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+});
+afterEach(() => vi.useRealTimers());
+
+function setup(persistedViewLocation?: string) {
+ const [ready, setReady] = createSignal(false);
+ state.persistedViewLocation = () => persistedViewLocation;
+ state.ready = ready;
+ const goToLinkLocation = createRoot(() => useGoToLinkLocation());
+ return { goToLinkLocation, setReady };
+}
+
+it('settles without restoring when the PDF has no saved location', async () => {
+ const { goToLinkLocation } = setup();
+ const navigation = goToLinkLocation({});
+ await vi.advanceTimersByTimeAsync(5000);
+ await expect(navigation).resolves.toBeUndefined();
+ expect(state.goToLocationHash).not.toHaveBeenCalled();
+});
+
+it('restores the saved location once the viewer shows pages', async () => {
+ const { goToLinkLocation, setReady } = setup('#page=4');
+ const navigation = goToLinkLocation({});
+ await vi.advanceTimersByTimeAsync(1000);
+ setReady(true);
+ await expect(navigation).resolves.toBeUndefined();
+ expect(state.goToLocationHash).toHaveBeenCalledExactlyOnceWith('#page=4');
+});
+
+it('settles without restoring when the viewer never shows pages', async () => {
+ const { goToLinkLocation } = setup('#page=4');
+ const navigation = goToLinkLocation({});
+ await vi.advanceTimersByTimeAsync(5000);
+ await expect(navigation).resolves.toBeUndefined();
+ expect(state.goToLocationHash).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/features/block-pdf/signal/location.ts b/apps/web/src/features/block-pdf/signal/location.ts
index 4b54e97587..26956e6d2a 100644
--- a/apps/web/src/features/block-pdf/signal/location.ts
+++ b/apps/web/src/features/block-pdf/signal/location.ts
@@ -380,13 +380,13 @@ async function applyCustomHighlights(
viewer.container().scrollTop = currentScrollTop;
viewer.container().scrollLeft = currentScrollLeft;
- if (searchResult?.state === FindState.NOT_FOUND) {
- console.warn('Terms not found:', terms);
+ if (searchResult.isErr()) {
+ console.warn('Highlight search timed out:', terms);
return;
}
- if (!searchResult) {
- console.warn('Search result is undefined');
+ if (searchResult.value?.state === FindState.NOT_FOUND) {
+ console.warn('Terms not found:', terms);
return;
}
@@ -501,16 +501,14 @@ function useGoToPdfLocation() {
findControllerStateEventSignal,
(val) =>
val?.state === FindState.FOUND || val?.state === FindState.NOT_FOUND
- ).catch((_e) => {
- console.error('search timed out');
- return undefined;
- });
+ );
- if (!findControllerStateEvent) {
+ if (findControllerStateEvent.isErr()) {
+ console.warn('search timed out', { location });
return;
}
- if (findControllerStateEvent.state === FindState.NOT_FOUND) {
+ if (findControllerStateEvent.value?.state === FindState.NOT_FOUND) {
console.warn('unable to find match', { location });
// TODO: fallback to raw query
return;
@@ -582,7 +580,7 @@ function useGoToPdfLocation() {
return;
}
- go(location);
+ await go(location);
};
}
@@ -592,19 +590,11 @@ const useGoToPreviousLocation = () => {
const isViewerReady = useIsViewerReadyForScroll();
return async () => {
- const rootViewer = viewer();
-
- await waitForSignal(
- pdf.persistedViewLocation,
- (location) => !!location,
- 300
- ).then((prevLocationHash) => {
- waitForSignal(isViewerReady).then(() => {
- if (rootViewer && prevLocationHash) {
- rootViewer.goToLocationHash(prevLocationHash);
- }
- });
- });
+ const prevLocationHash = pdf.persistedViewLocation();
+ if (!prevLocationHash) return;
+ const ready = await waitForSignal(isViewerReady);
+ if (ready.isErr()) return;
+ viewer()?.goToLocationHash(prevLocationHash);
};
};
diff --git a/apps/web/src/lib/core/util/waitForSignal.test.ts b/apps/web/src/lib/core/util/waitForSignal.test.ts
new file mode 100644
index 0000000000..465765367a
--- /dev/null
+++ b/apps/web/src/lib/core/util/waitForSignal.test.ts
@@ -0,0 +1,32 @@
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { waitForSignal } from './waitForSignal';
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+it('resolves with the first value that satisfies the condition', async () => {
+ const [count, setCount] = createSignal(0);
+ const result = waitForSignal(count, (value) => value >= 2);
+ setCount(1);
+ setCount(2);
+ expect((await result)._unsafeUnwrap()).toBe(2);
+});
+
+it('settles with a timeout error instead of rejecting', async () => {
+ const [ready] = createSignal(false);
+ const result = waitForSignal(ready, Boolean, 300);
+ await vi.advanceTimersByTimeAsync(300);
+ expect((await result)._unsafeUnwrapErr()).toEqual({ kind: 'timeout' });
+});
+
+it('stops tracking the signal once settled', async () => {
+ const [count, setCount] = createSignal(0);
+ const condition = vi.fn((value: number) => value === 1);
+ const result = waitForSignal(count, condition);
+ setCount(1);
+ await result;
+ setCount(2);
+ expect(condition).toHaveBeenCalledTimes(2);
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/apps/web/src/lib/core/util/waitForSignal.ts b/apps/web/src/lib/core/util/waitForSignal.ts
index 58cb15c00f..bffdda6b07 100644
--- a/apps/web/src/lib/core/util/waitForSignal.ts
+++ b/apps/web/src/lib/core/util/waitForSignal.ts
@@ -1,29 +1,35 @@
-import { type Accessor, createEffect } from 'solid-js';
+import { err, ok, type Result } from 'neverthrow';
+import { type Accessor, createEffect, createRoot } from 'solid-js';
+
+export type WaitForSignalTimeout = { kind: 'timeout' };
/**
- * Waits until the given signal satisfies a condition, then resolves the Promise.
- * By default, it waits until the signal value is "truthy."
- * Times out after specified time (ms) or default of 3 seconds.
+ * Waits until the given signal satisfies a condition (truthy by default).
+ * Settles with a timeout error after `timeout` ms instead of rejecting, so a
+ * wait that is started and abandoned never surfaces as an unhandled rejection.
*
* Usage:
- * const ready = createSignal(false);
- * // somewhere else: await waitForSignal(ready);
+ * const ready = await waitForSignal(isReady);
+ * if (ready.isErr()) return;
*/
export function waitForSignal<T>(
signal: Accessor<T>,
condition: (val: T) => boolean = Boolean,
timeout: number = 3000
-): Promise<T> {
- return new Promise((resolve, reject) => {
- createEffect(() => {
- setTimeout(() => {
- reject(new Error('timed out'));
+): Promise<Result<T, WaitForSignalTimeout>> {
+ return new Promise((resolve) => {
+ createRoot((dispose) => {
+ const timer = setTimeout(() => {
+ dispose();
+ resolve(err({ kind: 'timeout' }));
}, timeout);
-
- const value = signal();
- if (condition(value)) {
- resolve(value);
- }
+ createEffect(() => {
+ const value = signal();
+ if (!condition(value)) return;
+ clearTimeout(timer);
+ dispose();
+ resolve(ok(value));
+ });
});
});
}