diff --git a/apps/extension/e2e/progress.spec.ts b/apps/extension/e2e/progress.spec.ts index 8133fad..1db573b 100644 --- a/apps/extension/e2e/progress.spec.ts +++ b/apps/extension/e2e/progress.spec.ts @@ -57,3 +57,97 @@ test("a long capture reports which slice it is on, rather than sitting on one me await popup.close(); await page.close(); }); + +test("a popup reopened while a capture runs shows the capture's progress, then its result", async ({ + context, + serviceWorker, + extensionId, +}) => { + const page = await context.newPage(); + await page.setViewportSize({ width: 900, height: 600 }); + // Long enough that the capture is still running long after the popup + // below reloads: 10000px in a 600px viewport is ~17 slices at ~two a + // second, and the reload lands one second in — nowhere near the tail. + await page.goto(`${BASE_URL}/very-long.html?h=10000`); + + // The popup opens as a tab, which makes it the active tab — and a capture + // stops if the active tab is not the one it is photographing (see the + // test above). Put the page back in front before starting anything; the + // popup keeps receiving messages either way. + const popup = await context.newPage(); + await popup.goto(`chrome-extension://${extensionId}/popup.html`); + await page.bringToFront(); + + // Through handleRequest, not the orchestrator hook: the captureFinished + // broadcast an attached popup waits on is emitted by the handler's + // completion path, and setLastCaptureUi — which the popup restores from — + // is written there too. + const finished = serviceWorker.evaluate(() => { + // @ts-expect-error test-only global, see background/index.ts + return globalThis.__test.captureFullPageViaHandleRequest(); + }); + + // A real reopen is the popup being destroyed on blur and rebuilt from + // scratch on the next toolbar click. A reload is the same thing for this + // purpose — a fresh popup instance that never heard the capture begin — + // without making the popup tab the active tab mid-capture, which would + // stop the capture for real. + await popup.waitForTimeout(1000); + await popup.reload(); + await popup.waitForSelector("#captureProgress:not([hidden])"); + await expect(popup.locator("#captureFullPage")).toBeDisabled(); + await expect(popup.locator("#status")).toContainText(/\d+ of \d+/); + await finished; + + // The broadcast is what hands the attached popup over: the bar goes, the + // buttons come back, and the restored UI is this capture's, not "No + // capture yet". + await expect(popup.locator("#captureProgress")).toBeHidden(); + await expect(popup.locator("#captureFullPage")).toBeEnabled(); + await expect(popup.locator("#report")).toBeVisible(); + + await popup.close(); + await page.close(); +}); + +test("a popup attached to a capture that fails shows why instead of hanging on the bar", async ({ + context, + serviceWorker, + extensionId, +}) => { + const page = await context.newPage(); + await page.setViewportSize({ width: 900, height: 600 }); + await page.goto(`${BASE_URL}/very-long.html?h=10000`); + + // Same construction as the test above: popup open and parked, page in + // front. The capture is sent as a real runtime message from the popup + // rather than through the handleRequest hook: the failure broadcast an + // attached popup waits on lives in the message listener's catch, which a + // direct handleRequest call never reaches. + const popup = await context.newPage(); + await popup.goto(`chrome-extension://${extensionId}/popup.html`); + await page.bringToFront(); + const finished = popup + .evaluate(() => chrome.runtime.sendMessage({ action: "captureFullPage" })) + .catch(() => null); + await popup.waitForTimeout(1000); + await popup.reload(); + await popup.waitForSelector("#captureProgress:not([hidden])"); + + // Steal the active tab mid-capture — the one way a running capture stops + // on its own. The attached popup must be told, not left on a bar that + // never fills. + await popup.bringToFront(); + // The abort rejects the request that started the capture — here reaching + // nobody, exactly like the popup a real user blurred. The assertions below + // are what check the failure arrived where it matters. + await finished; + + await expect(popup.locator("#captureProgress")).toBeHidden(); + await expect(popup.locator("#captureFullPage")).toBeEnabled(); + await expect(popup.locator("#status")).toContainText("stopped"); + await expect(popup.locator("#status")).toHaveClass(/is-error/); + + await popup.close(); + await page.close(); +}); diff --git a/apps/extension/src/background/index.ts b/apps/extension/src/background/index.ts index 69398df..1864765 100644 --- a/apps/extension/src/background/index.ts +++ b/apps/extension/src/background/index.ts @@ -18,12 +18,13 @@ import { getSavePrefs, resolveFilename } from "../chrome/save-prefs"; import { registerCallbackScript } from "../chrome/auth-permission"; import { PDF_EDIT_HANDOFF_URL, registerHandoffScript } from "../chrome/pdf-handoff"; import { ext } from "../platform/webext"; -import type { PopupRequest, PopupResponse } from "../types"; +import type { CaptureFailure, PopupRequest, PopupResponse } from "../types"; import { captureFullPage, captureSelectedArea, captureVisibleOnly, exportLastCaptureAsPdf, + getCaptureProgress, getLastCaptureDpr, getLastCaptureFirstImage, getLastCaptureImageCount, @@ -329,6 +330,22 @@ function watchPdfHandoff(): void { }, PDF_HANDOFF_GRACE_MS); } +/** + * Tell popups that a capture they may be attached to is over. + * + * A popup reopened mid-capture (popup.ts's adoptRunningCapture) has no reply + * of its own to wait for — the request that started the capture belonged to + * a popup instance that no longer exists. This is how it learns the outcome + * instead. On success it is fired only after setLastCaptureUi, so the + * popup's restore reads the capture that just finished rather than the one + * before it; the failure form carries the classified reason, so "the active + * tab changed" reaches the user instead of a progress bar that silently + * never fills. + */ +function broadcastCaptureFinished(failure?: CaptureFailure): void { + void ext.runtime.sendMessage({ type: "captureFinished", failure }).catch(() => {}); +} + async function handleRequest(request: PopupRequest): Promise { switch (request.action) { case "ping": { @@ -336,6 +353,9 @@ async function handleRequest(request: PopupRequest): Promise { // listener is registered. return { ok: true }; } + case "captureState": { + return { ok: true, capture: getCaptureProgress() }; + } case "captureFullPage": { const tab = await getActiveTab(); const { report, images } = await captureFullPage(tab.id!, tab.windowId); @@ -366,6 +386,9 @@ async function handleRequest(request: PopupRequest): Promise { await setLastCaptureUi({ report, openedEditor }); await rememberInHistory(tab, report, images[0]!); await bumpUsageCount(); + // Here, not earlier: an attached popup restores the last-capture record + // when this lands, and it must read this capture, not the one before it. + broadcastCaptureFinished(); return { ok: true, report, pngDataUrls: images.map((img) => bytesToDataUrl(img, "image/png")), openedEditor }; } case "captureVisible": { @@ -451,7 +474,13 @@ ext.runtime.onMessage.addListener((message: unknown, _sender, sendResponse) => { // in the reader's own language instead of forwarding the browser's // developer-facing sentence. const reason = err instanceof CaptureFailureError ? err.reason : "raw"; - sendResponse({ ok: false, error: err instanceof Error ? err.message : String(err), reason }); + const failure: CaptureFailure = { + ok: false, + error: err instanceof Error ? err.message : String(err), + reason, + }; + broadcastCaptureFinished(failure); + sendResponse(failure); }); return true; // keep the message channel open for the async response diff --git a/apps/extension/src/background/orchestrator.ts b/apps/extension/src/background/orchestrator.ts index 9cab557..97834d8 100644 --- a/apps/extension/src/background/orchestrator.ts +++ b/apps/extension/src/background/orchestrator.ts @@ -3,7 +3,15 @@ import { CaptureFailureError } from "./injection-error"; import { captureVisibleTabPaced } from "../chrome/capture"; import { LAST_CAPTURE_BLOB_KEY, extraLastCaptureBlobKey, getBlob, putBlob } from "../chrome/blob-store"; import { ext } from "../platform/webext"; -import type { CaptureReport, ContentRequest, PageMetrics, PrepResponse, ScrollToResponse, SelectAreaResponse } from "../types"; +import type { + CaptureProgress, + CaptureReport, + ContentRequest, + PageMetrics, + PrepResponse, + ScrollToResponse, + SelectAreaResponse, +} from "../types"; import { loadShotCore } from "./wasm-loader"; export interface CaptureOutcome { @@ -193,6 +201,18 @@ async function assertStillActive(tabId: number, windowId: number): Promise ); } +/** How far the running full-page capture is, for popup.ts's + * adoptRunningCapture. Module state on purpose, not storage: the capture in + * flight is exactly what keeps this service worker alive, so the record + * cannot outlive the capture it describes — a worker evicted mid-capture + * wakes blank and truthfully answers "nothing running", where a storage copy + * would survive as a progress bar nothing would ever advance. */ +let captureProgress: CaptureProgress | null = null; + +export function getCaptureProgress(): CaptureProgress | null { + return captureProgress; +} + /** * Tell the popup how far along a capture is. * @@ -207,10 +227,22 @@ async function assertStillActive(tabId: number, windowId: number): Promise * the capture carries on either way. */ function reportProgress(done: number, total: number): void { + captureProgress = { done, total }; void ext.runtime.sendMessage({ type: "captureProgress", done, total }).catch(() => {}); } export async function captureFullPage(tabId: number, windowId: number): Promise { + // Cleared on every exit, success or not — a capture that died halfway must + // not answer captureState as if it were still going. + captureProgress = { done: 0, total: 0 }; + try { + return await runFullPageCapture(tabId, windowId); + } finally { + captureProgress = null; + } +} + +async function runFullPageCapture(tabId: number, windowId: number): Promise { await injectContentScript(tabId); const shotCore = await loadShotCore(); diff --git a/apps/extension/src/popup/popup.ts b/apps/extension/src/popup/popup.ts index cde6362..e92595b 100644 --- a/apps/extension/src/popup/popup.ts +++ b/apps/extension/src/popup/popup.ts @@ -434,8 +434,6 @@ async function restoreLastCaptureUi(): Promise { } } -restoreLastCaptureUi(); - // Nudges toward a store rating after real, repeated use — see // chrome/rating-prompt.ts for the show-again/never-again rules. Checked // on every popup open (not synchronously after a capture) because a @@ -619,6 +617,66 @@ ext.runtime.onMessage.addListener((message: unknown) => { setStatusText(`${captureBusyMessage} ${m.done + 1} of ${m.total}`); }); +// A capture runs on in the service worker after the popup that started it is +// torn down (MV3 destroys a popup the moment it loses focus). The popup a +// user reopens mid-capture is a new instance that never heard the progress +// messages above and has no busy state of its own — so it attaches to the +// running capture instead of sitting on "No capture yet" while the page +// visibly scrolls. + +/** True when this popup attached to a capture it did not start. Only such a + * popup listens for captureFinished: the one that started the capture learns + * the outcome from its own awaited reply. */ +let adoptedCapture = false; + +/** Attach this popup to a capture already running in the service worker. + * + * Returns true when it did, so the caller can skip restoreLastCaptureUi — + * that would render the *previous* capture underneath (and read tens of + * megabytes of preview out of blob-store doing it) until this one finished + * and replaced it. + * + * Asking the worker is the whole liveness test: a capture in flight is what + * keeps the worker alive, so an answer means a live capture, and a fresh + * worker woken by this very message truthfully has nothing to offer. There + * is no stored flag to go stale. + */ +async function adoptRunningCapture(): Promise { + let response: PopupResponse; + try { + response = await send({ action: "captureState" }); + } catch { + return false; // worker unreachable — nothing running to attach to + } + if (!response.ok || !("capture" in response) || !response.capture) return false; + + const { done, total } = response.capture; + adoptedCapture = true; + const busyMessage = t("Capturing full page…"); + captureBusyMessage = busyMessage.replace(/…$/, ""); + showCaptureProgress(total > 0 ? done / total : 0); + setBusy(true); + setStatusText(done < total ? `${captureBusyMessage} ${done + 1} of ${total}` : busyMessage); + return true; +} + +ext.runtime.onMessage.addListener((message: unknown) => { + const m = message as { type?: string; failure?: CaptureFailure }; + if (m?.type !== "captureFinished") return; + if (!adoptedCapture) return; + adoptedCapture = false; + captureBusyMessage = ""; + showCaptureProgress(null); + setBusy(false); + void (async () => { + // Written before the broadcast fired (background/index.ts), so this reads + // the capture that just finished — or, when it failed, the record it + // never displaced. + await restoreLastCaptureUi(); + if (m.failure) setStatusText(captureErrorText(m.failure), true); + })(); +}); + /** Resolves true when the request came back without an error. */ async function runCapture(request: PopupRequest, busyMessage: string): Promise { captureBusyMessage = busyMessage.replace(/…$/, ""); @@ -801,3 +859,12 @@ declare const __OPENCAPTURE_BUILD__: string; const el = document.getElementById("buildLabel"); if (el) el.textContent = __OPENCAPTURE_BUILD__; } + +// Open onto whichever state the world is in: a capture still running (its +// progress), or the last capture's result. Asked in this order because the +// restore is the expensive path — its preview read alone can take visible +// time — and is skipped entirely when a capture is mid-flight. +(async () => { + if (await adoptRunningCapture()) return; + await restoreLastCaptureUi(); +})(); diff --git a/apps/extension/src/types.ts b/apps/extension/src/types.ts index 2ba2bbe..bdb35b0 100644 --- a/apps/extension/src/types.ts +++ b/apps/extension/src/types.ts @@ -97,7 +97,12 @@ export type PopupRequest = | { action: "exportPdf"; handoff?: boolean } | { action: "savePngs" } | { action: "openPdfEdit" } - | { action: "openEditor" }; + | { action: "openEditor" } + // Asked by a popup reopened while a capture is still running (MV3 tore the + // one that started it down the moment it lost focus) — the answer is what + // it shows instead of a reset "No capture yet" while the page visibly + // scrolls. See popup.ts's adoptRunningCapture. + | { action: "captureState" }; export interface CaptureResult { ok: true; @@ -132,4 +137,17 @@ export interface CaptureFailure { reason?: "restricted-page" | "needs-refresh" | "file-access" | "raw"; } -export type PopupResponse = CaptureResult | AckResult | CancelledResult | CaptureFailure; +/** How far a running full-page capture is, in slices. */ +export interface CaptureProgress { + done: number; + total: number; +} + +/** Answer to captureState: how far the running full-page capture is, or null + * when none is. */ +export interface CaptureStateResult { + ok: true; + capture: CaptureProgress | null; +} + +export type PopupResponse = CaptureResult | AckResult | CancelledResult | CaptureStateResult | CaptureFailure;