Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Fix staged skill download cancellation and cleanup
Emre Sokullu287baa494a41
diff --git a/src/chrome/src/network/network-tools.js b/src/chrome/src/network/network-tools.jsindex 65c8b5de1..db686cdea 100644--- a/src/chrome/src/network/network-tools.js+++ b/src/chrome/src/network/network-tools.js@@ -974,25 +974,48 @@ async function callChromeDownloadAction(name, ...args) {}}-async function sendOffscreenSkillDownloadMessage(message) {+async function sendOffscreenSkillDownloadMessage(message, signal = null) {await ensureOffscreen();+ throwIfSkillAborted(signal);return await new Promise((resolve, reject) => {- chrome.runtime.sendMessage(message, (response) => {- if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));- else resolve(response || { success: false, error: 'Offscreen skill download returned no response.' });- });+ const onAbort = () => {+ try {+ chrome.runtime.sendMessage({ type: 'skill-download-cancel', requestId: message.requestId }, () => {+ void chrome.runtime.lastError;+ });+ } catch (_) {}+ reject(responseAbortError(signal));+ };+ signal?.addEventListener('abort', onAbort, { once: true });+ try {+ chrome.runtime.sendMessage(message, (response) => {+ signal?.removeEventListener('abort', onAbort);+ const error = chrome.runtime.lastError;+ if (signal?.aborted) {+ // Cancellation can race a successful reply from the offscreen host.+ if (response?.releaseToken) void releaseStagedSkillDownload(response.releaseToken);+ reject(responseAbortError(signal));+ } else if (error) reject(new Error(error.message));+ else resolve(response || { success: false, error: 'Offscreen skill download returned no response.' });+ });+ } catch (error) {+ signal?.removeEventListener('abort', onAbort);+ reject(error);+ }});}-async function prepareStagedSkillDownload(url, expectedUrl) {+async function prepareStagedSkillDownload(url, expectedUrl, signal = null) {try {return await sendOffscreenSkillDownloadMessage({type: 'skill-download-prepare',+ requestId: crypto.randomUUID(),url,expectedUrl,maxBytes: SKILL_DOWNLOAD_STAGED_MAX_BYTES,- });+ }, signal);} catch (error) {+ if (signal?.aborted || error?.name === 'AbortError') throw responseAbortError(signal);return { success: false, finalUrl: url, error: `Skill download staging failed: ${error.message}` };}}@@ -1078,7 +1101,7 @@ async function downloadSkillFile(url, filename, waitMs = 60000, signal = null) {const file = await fetchSkillDownloadData(url, url, signal);let staged = null;if (file.tooLarge === true) {- staged = await prepareStagedSkillDownload(url, url);+ staged = await prepareStagedSkillDownload(url, url, signal);if (!staged?.success) {return {success: false,@@ -1109,21 +1132,24 @@ async function downloadSkillFile(url, filename, waitMs = 60000, signal = null) {|| filenameFromContentDisposition(file.contentDisposition);const opts = { url: staged ? staged.localUrl : file.dataUrl, conflictAction: 'uniquify' };const safeName = safeDownloadFilename(filename) || responseFilename || defaultSkillDownloadFilename(contentType);- if (safeName) opts.filename = await filenameInConfiguredDownloadDirectory(chrome, safeName);let downloadId;+ let info;try {+ if (safeName) opts.filename = await filenameInConfiguredDownloadDirectory(chrome, safeName);+ throwIfSkillAborted(signal);downloadId = await new Promise((resolve, reject) => {chrome.downloads.download(opts, (id) => {if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));else resolve(id);});});+ info = await resolveDownloadInfo(downloadId, waitMs, { signal });+ throwIfSkillAborted(signal);} catch (error) {+ if (downloadId != null) await callChromeDownloadAction('cancel', downloadId);await releaseStagedSkillDownload(staged?.releaseToken);throw error;}- const info = await resolveDownloadInfo(downloadId, waitMs, { signal });- throwIfSkillAborted(signal);const result = {downloadId,success: false,@@ -1263,14 +1289,14 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}}let cleanup = null;+ let cleanupScheduled = false;try {throwIfSkillAborted(signal);const download = await downloadSkillFile(fileEndpoint.url, payload.filename, Math.min(tool.job?.timeoutMs || 90000, 120000), signal);- throwIfSkillAborted(signal);const releaseToken = download.releaseToken || '';if (Object.prototype.hasOwnProperty.call(download, 'releaseToken')) delete download.releaseToken;const cleanupDeferred = cleanupEndpoint.ok && download.pending === true;- const cleanupScheduled = cleanupDeferred+ cleanupScheduled = cleanupDeferred? scheduleSkillDownloadCleanup(download.downloadId,cleanupEndpoint.url,@@ -1279,6 +1305,7 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}{ releaseToken },): false;+ throwIfSkillAborted(signal);if (cleanupEndpoint.ok && !cleanupDeferred) cleanup = await cleanupSkillDownloadJob(cleanupEndpoint.url, endpoint, tool);if (!download.success) {return {@@ -1309,8 +1336,8 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}...download,};} catch (e) {+ if (cleanupEndpoint.ok && !cleanupScheduled) cleanup = await cleanupSkillDownloadJob(cleanupEndpoint.url, endpoint, tool);if (signal?.aborted || e?.name === 'AbortError') throw responseAbortError(signal);- if (cleanupEndpoint.ok) cleanup = await cleanupSkillDownloadJob(cleanupEndpoint.url, endpoint, tool);return { success: false, provider: endpoint.hostname, skillTool: tool.name || '', skillName: tool.skillName || '', jobId, fileUrl: fileEndpoint.url, cleanup, error: `Skill download failed: ${e.message}` };}}diff --git a/src/chrome/src/offscreen/skill-download.js b/src/chrome/src/offscreen/skill-download.jsindex 75a52a7e4..174c68ef0 100644--- a/src/chrome/src/offscreen/skill-download.js+++ b/src/chrome/src/offscreen/skill-download.js@@ -11,6 +11,11 @@const DEFAULT_MAX_BYTES = 1024 * 1024 * 1024;const staged = new Map();+ const preparing = new Map();++ function throwIfAborted(signal) {+ if (signal?.aborted) throw new DOMException('Skill download stopped.', 'AbortError');+ }async function cleanupStaleStages() {try {@@ -70,8 +75,9 @@return true;}- async function stageResponse(response, maxBytes) {+ async function stageResponse(response, maxBytes, signal) {await startupCleanup;+ throwIfAborted(signal);const token = crypto.randomUUID();const filename = `${token}.media`;const expectedSize = parseLength(response.headers.get('content-length'));@@ -84,14 +90,22 @@const storageRoot = await navigator.storage.getDirectory();const dir = await storageRoot.getDirectoryHandle('skill-downloads', { create: true });- const handle = await dir.getFileHandle(filename, { create: true });- const writable = await handle.createWritable();+ let writable;+ let reader;let bytesReceived = 0;+ const onAbort = () => { void reader?.cancel().catch(() => {}); };+ signal.addEventListener('abort', onAbort, { once: true });try {- const reader = response.body?.getReader?.();+ throwIfAborted(signal);+ const handle = await dir.getFileHandle(filename, { create: true });+ throwIfAborted(signal);+ writable = await handle.createWritable();+ throwIfAborted(signal);+ reader = response.body?.getReader?.();if (reader) {while (true) {const { done, value } = await reader.read();+ throwIfAborted(signal);if (done) break;const chunk = value instanceof Uint8Array ? value : new Uint8Array(value);bytesReceived += chunk.byteLength;@@ -100,27 +114,35 @@throw new Error(`Skill download exceeds the staged-file limit (${bytesReceived} bytes > ${maxBytes} bytes).`);}await writable.write(chunk);+ throwIfAborted(signal);}} else {const blob = await response.blob();+ throwIfAborted(signal);bytesReceived = blob.size;if (bytesReceived > maxBytes) {throw new Error(`Skill download exceeds the staged-file limit (${bytesReceived} bytes > ${maxBytes} bytes).`);}await writable.write(blob);}+ throwIfAborted(signal);await writable.close();+ throwIfAborted(signal);+ const file = await handle.getFile();+ throwIfAborted(signal);+ const typedBlob = file.type === contentType ? file : new Blob([file], { type: contentType });+ const localUrl = URL.createObjectURL(typedBlob);+ staged.set(token, { localUrl, dir, filename, typedBlob });+ return { token, localUrl, bytesReceived, contentType, contentDisposition };} catch (error) {- try { await writable.abort(); } catch {}+ try { await reader?.cancel(); } catch {}+ try { await writable?.abort(); } catch {}try { await dir.removeEntry(filename); } catch {}throw error;+ } finally {+ signal.removeEventListener('abort', onAbort);+ try { reader?.releaseLock(); } catch {}}-- const file = await handle.getFile();- const typedBlob = file.type === contentType ? file : new Blob([file], { type: contentType });- const localUrl = URL.createObjectURL(typedBlob);- staged.set(token, { localUrl, dir, filename, typedBlob });- return { token, localUrl, bytesReceived, contentType, contentDisposition };}async function prepare(message) {@@ -131,12 +153,17 @@return { success: false, blocked: true, finalUrl: url, error: 'Skill download URL is outside its expected HTTPS origin.' };}+ const requestId = message.requestId || crypto.randomUUID();+ const controller = new AbortController();+ preparing.set(requestId, controller);+ const signal = controller.signal;try {const response = await fetch(url, {method: 'GET',credentials: 'omit',redirect: 'manual',cache: 'no-store',+ signal,});if (response.type === 'opaqueredirect' || isRedirectStatus(response.status)) {return {@@ -154,7 +181,11 @@if (!response.ok) {return { success: false, status: response.status, finalUrl, error: `Skill download file request failed with HTTP ${response.status}.` };}- const prepared = await stageResponse(response, maxBytes);+ const prepared = await stageResponse(response, maxBytes, signal);+ if (signal.aborted) {+ await release(prepared.token);+ throwIfAborted(signal);+ }return {success: true,status: response.status,@@ -167,6 +198,8 @@};} catch (error) {return { success: false, finalUrl: url, error: `Skill download staging failed: ${error.message}` };+ } finally {+ preparing.delete(requestId);}}@@ -199,6 +232,11 @@prepare(message).then(sendResponse);return true;}+ if (message?.type === 'skill-download-cancel') {+ preparing.get(message.requestId)?.abort();+ sendResponse({ success: true });+ return false;+ }if (message?.type === 'skill-download-release') {release(message.releaseToken).then((released) => sendResponse({ success: true, released }));return true;diff --git a/src/firefox/src/network/network-tools.js b/src/firefox/src/network/network-tools.jsindex fee7235ef..4566a27b5 100644--- a/src/firefox/src/network/network-tools.js+++ b/src/firefox/src/network/network-tools.js@@ -935,17 +935,19 @@ async function callBrowserDownloadAction(name, ...args) {}}-async function prepareStagedSkillDownload(url, expectedUrl) {+async function prepareStagedSkillDownload(url, expectedUrl, signal = null) {const initialUrlCheck = validateSkillDownloadFinalUrl(url, expectedUrl);if (!initialUrlCheck.ok) {return { success: false, blocked: true, finalUrl: url, error: initialUrlCheck.error };}try {+ throwIfSkillAborted(signal);const response = await fetch(url, {method: 'GET',credentials: 'omit',redirect: 'manual',cache: 'no-store',+ ...(signal ? { signal } : {}),});if (response?.type === 'opaqueredirect' || isHttpRedirectStatus(response?.status)) {return {@@ -980,6 +982,7 @@ async function prepareStagedSkillDownload(url, expectedUrl) {const responseBlob = typeof response.blob === 'function'? await response.blob(): new Blob([await response.arrayBuffer()], { type: responseContentType || 'application/octet-stream' });+ throwIfSkillAborted(signal);const contentType = safeDataUrlMimeType(responseContentType || responseBlob.type);const blob = responseBlob.type === contentType? responseBlob@@ -1005,6 +1008,7 @@ async function prepareStagedSkillDownload(url, expectedUrl) {...(contentDisposition ? { contentDisposition } : {}),};} catch (error) {+ if (signal?.aborted || error?.name === 'AbortError') throw responseAbortError(signal);return { success: false, finalUrl: url, error: `Skill download staging failed: ${error.message}` };}}@@ -1086,7 +1090,7 @@ async function downloadSkillFile(url, filename, waitMs = 60000, signal = null) {const file = await fetchSkillDownloadData(url, url, signal);let staged = null;if (file.tooLarge === true) {- staged = await prepareStagedSkillDownload(url, url);+ staged = await prepareStagedSkillDownload(url, url, signal);if (!staged?.success) {return {success: false,@@ -1121,17 +1125,20 @@ async function downloadSkillFile(url, filename, waitMs = 60000, signal = null) {|| filenameFromContentDisposition(file.contentDisposition);const opts = { url: staged ? staged.localUrl : file.dataUrl, conflictAction: 'uniquify' };const safeName = safeDownloadFilename(filename) || responseFilename || defaultSkillDownloadFilename(contentType);- const configuredName = await filenameInConfiguredDownloadDirectory(browser, safeName);- if (configuredName) opts.filename = configuredName;let downloadId;+ let info;try {+ const configuredName = await filenameInConfiguredDownloadDirectory(browser, safeName);+ if (configuredName) opts.filename = configuredName;+ throwIfSkillAborted(signal);downloadId = await browser.downloads.download(opts);+ info = await resolveDownloadInfo(downloadId, waitMs, { signal });+ throwIfSkillAborted(signal);} catch (error) {+ if (downloadId != null) await callBrowserDownloadAction('cancel', downloadId);await releaseStagedSkillDownload(staged?.releaseToken);throw error;}- const info = await resolveDownloadInfo(downloadId, waitMs, { signal });- throwIfSkillAborted(signal);const result = {downloadId,success: false,@@ -1271,14 +1278,14 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}}let cleanup = null;+ let cleanupScheduled = false;try {throwIfSkillAborted(signal);const download = await downloadSkillFile(fileEndpoint.url, payload.filename, Math.min(tool.job?.timeoutMs || 90000, 120000), signal);- throwIfSkillAborted(signal);const releaseToken = download.releaseToken || '';if (Object.prototype.hasOwnProperty.call(download, 'releaseToken')) delete download.releaseToken;const cleanupDeferred = cleanupEndpoint.ok && download.pending === true;- const cleanupScheduled = cleanupDeferred+ cleanupScheduled = cleanupDeferred? scheduleSkillDownloadCleanup(download.downloadId,cleanupEndpoint.url,@@ -1287,6 +1294,7 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}{ releaseToken },): false;+ throwIfSkillAborted(signal);if (cleanupEndpoint.ok && !cleanupDeferred) cleanup = await cleanupSkillDownloadJob(cleanupEndpoint.url, endpoint, tool);if (!download.success) {return {@@ -1317,8 +1325,8 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}...download,};} catch (e) {+ if (cleanupEndpoint.ok && !cleanupScheduled) cleanup = await cleanupSkillDownloadJob(cleanupEndpoint.url, endpoint, tool);if (signal?.aborted || e?.name === 'AbortError') throw responseAbortError(signal);- if (cleanupEndpoint.ok) cleanup = await cleanupSkillDownloadJob(cleanupEndpoint.url, endpoint, tool);return { success: false, provider: endpoint.hostname, skillTool: tool.name || '', skillName: tool.skillName || '', jobId, fileUrl: fileEndpoint.url, cleanup, error: `Skill download failed: ${e.message}` };}}diff --git a/test/skill-download-wait.mjs b/test/skill-download-wait.mjsindex a47696fe3..97a83b864 100644--- a/test/skill-download-wait.mjs+++ b/test/skill-download-wait.mjs@@ -1,6 +1,7 @@import assert from 'node:assert/strict';import fs from 'node:fs';import { test } from 'node:test';+import vm from 'node:vm';for (const build of ['chrome', 'firefox']) {test(`${build}: long media waits beyond three minutes, reports once, and retains timed-out job`, async () => {@@ -137,6 +138,7 @@ for (const build of ['chrome', 'firefox']) {const originalFetch = globalThis.fetch;try {const methods = [];+ const polling = Promise.withResolvers();globalThis.fetch = async (_url, opts = {}) => {methods.push(opts.method);if (opts.signal?.aborted) throw new DOMException('The operation was aborted', 'AbortError');@@ -144,6 +146,7 @@ for (const build of ['chrome', 'firefox']) {// Never resolve until aborted: the abortable sleep/fetch must win.await new Promise((_resolve, reject) => {opts.signal?.addEventListener('abort', () => reject(new DOMException('The operation was aborted', 'AbortError')), { once: true });+ polling.resolve();});throw new Error('unreachable');};@@ -152,8 +155,10 @@ for (const build of ['chrome', 'firefox']) {signal: controller.signal,onProgress: () => {},});+ await polling.promise;controller.abort();await assert.rejects(pending, err => err?.name === 'AbortError');+ assert.deepEqual(methods, ['POST', 'GET'], 'test must stop a running provider job');assert.ok(!methods.includes('DELETE'), 'abort must not delete the running provider job');} finally {globalThis.fetch = originalFetch;@@ -177,3 +182,165 @@ for (const build of ['chrome', 'firefox']) {assert.deepEqual(updates, [['tool_progress', { name: 'download_public_media', message: 'Preparing a large file' }]]);});}++// Exercise the real Chrome offscreen handler and Firefox Blob path, including+// response bodies that stay open until Stop. Only browser APIs and OPFS are fake.+async function stagedDownloadHarness(t, build, stopAt) {+ const { executeHttpSkillTool } = await import(`../src/${build}/src/network/network-tools.js`);+ const { normalizeCustomSkills, buildSkillToolRegistry } = await import(`../src/${build}/src/agent/skills.js`);+ const tool = buildSkillToolRegistry(normalizeCustomSkills([{+ id: 'freeskillz-xyz', name: 'FreeSkillz.xyz', enabled: true,+ content: fs.readFileSync(new URL(`../src/${build}/skills/freeskillz-xyz.md`, import.meta.url), 'utf8'),+ }])).get('download_public_media');+ const original = { fetch: globalThis.fetch, chrome: globalThis.chrome, browser: globalThis.browser,+ create: URL.createObjectURL, revoke: URL.revokeObjectURL };+ t.after(() => {+ globalThis.fetch = original.fetch;+ for (const key of ['chrome', 'browser']) {+ if (original[key] === undefined) delete globalThis[key];+ else globalThis[key] = original[key];+ }+ URL.createObjectURL = original.create;+ URL.revokeObjectURL = original.revoke;+ });+ const ready = Promise.withResolvers();+ const proceed = Promise.withResolvers();+ const stageSettled = Promise.withResolvers();+ const released = Promise.withResolvers();+ const controller = new AbortController();+ const events = [], messages = [], files = new Map(), created = [], revoked = [], downloads = [];+ let stageSignal, fileRequests = 0;+ URL.createObjectURL = blob => {+ const url = original.create(blob);+ created.push(url);+ return url;+ };+ URL.revokeObjectURL = url => { events.push('release'); revoked.push(url); original.revoke(url); };+ const headers = { 'content-type': 'video/mp4', 'content-length': String(26 * 1024 * 1024) };+ globalThis.fetch = async (url, opts) => {+ if (opts.method === 'POST') return new Response(JSON.stringify({ job_id: 'staged' }));+ if (opts.method === 'DELETE') { events.push('delete'); return new Response(null, { status: 204 }); }+ if (!url.endsWith('/file')) return new Response(JSON.stringify({ status: 'complete' }));+ if (++fileRequests === 1) return new Response(null, { headers });+ stageSignal = opts.signal;+ assert.ok(stageSignal, 'staging fetch must receive an abort signal');+ assert.equal(opts.credentials, 'omit');+ assert.equal(opts.redirect, 'manual');+ if (stopAt === 'headers') {+ ready.resolve();+ return await new Promise((_resolve, reject) => {+ stageSignal.addEventListener('abort', () => reject(stageSignal.reason), { once: true });+ });+ }+ if (stopAt === 'body') {+ const body = new ReadableStream({+ start(stream) {+ stream.enqueue(new Uint8Array([1, 2, 3]));+ stageSignal.addEventListener('abort', () => stream.error(stageSignal.reason), { once: true });+ },+ });+ const response = new Response(body, { headers });+ if (build === 'firefox') {+ const blob = response.blob.bind(response);+ response.blob = () => { ready.resolve(); return blob(); };+ }+ return response;+ }+ return new Response(new Uint8Array([1, 2, 3]), { headers });+ };+ const api = {+ storage: { local: { async get() {+ if (stopAt === 'directory') { ready.resolve(); await proceed.promise; }+ return {};+ } } },+ downloads: build === 'chrome' ? {+ download(opts, cb) { downloads.push(opts); cb(99); },+ search(_query, cb) { cb([{ id: 99, state: 'in_progress' }]); ready.resolve(); },+ cancel(id, cb) { assert.equal(id, 99); events.push('cancel'); cb(); },+ } : {+ async download(opts) { downloads.push(opts); return 99; },+ async search() { ready.resolve(); return [{ id: 99, state: 'in_progress' }]; },+ async cancel(id) { assert.equal(id, 99); events.push('cancel'); },+ },+ };+ if (build === 'chrome') {+ const listeners = [];+ api.runtime = { lastError: null, onMessage: { addListener(fn) { listeners.push(fn); } },+ sendMessage(message, cb) {+ messages.push(message);+ for (const listener of listeners) listener(message, {}, response => {+ const respond = () => {+ cb(response);+ if (message.type === 'skill-download-prepare') stageSettled.resolve();+ if (message.type === 'skill-download-release') released.resolve();+ };+ if (stopAt === 'reply' && message.type === 'skill-download-prepare') {+ ready.resolve();+ void proceed.promise.then(respond);+ } else respond();+ });+ } };+ api.offscreen = { async hasDocument() { return true; } };+ const dir = {+ async *keys() { yield* files.keys(); },+ async removeEntry(name) { files.delete(name); },+ async getFileHandle(name) {+ const chunks = [];+ files.set(name, chunks);+ return {+ async createWritable() { return {+ async write(chunk) { chunks.push(chunk); if (stopAt === 'body') ready.resolve(); },+ async close() {}, async abort() { events.push('abort-write'); },+ }; },+ async getFile() { return new Blob(chunks); },+ };+ },+ };+ vm.runInNewContext(fs.readFileSync(new URL('../src/chrome/src/offscreen/skill-download.js', import.meta.url), 'utf8'), {+ chrome: api, navigator: { storage: { async getDirectory() { return { async getDirectoryHandle() { return dir; } }; } } },+ fetch: (...args) => globalThis.fetch(...args), URL, Blob, Uint8Array, crypto, AbortController, DOMException,+ });+ globalThis.chrome = api;+ delete globalThis.browser;+ } else {+ globalThis.browser = api;+ delete globalThis.chrome;+ }+ const pending = executeHttpSkillTool(tool, { url: 'https://x.com/user/status/123', kind: 'video' }, { signal: controller.signal });+ return { controller, pending, ready: ready.promise, proceed, stageSettled: stageSettled.promise,+ released: released.promise, events, messages, files, created, revoked, downloads,+ get stageSignal() { return stageSignal; } };+}++for (const build of ['chrome', 'firefox']) {+ for (const phase of ['headers', 'body', 'directory', 'save', ...(build === 'chrome' ? ['reply'] : [])]) {+ test(`${build}: Stop during staged download ${phase} cancels transfer and releases ownership`, { timeout: 3000 }, async t => {+ const h = await stagedDownloadHarness(t, build, phase);+ const rejected = assert.rejects(h.pending, error => error?.name === 'AbortError');+ await h.ready;+ h.controller.abort();+ h.proceed.resolve();+ await rejected;+ if (build === 'chrome') await h.stageSettled;+ if (phase === 'reply') await h.released;+ assert.equal(h.events.filter(event => event === 'delete').length, 1, 'completed provider job must be cleaned up');+ assert.equal(h.files.size, 0, 'no partial OPFS file may remain after Stop');+ assert.deepEqual(h.revoked, h.created, 'every completed stage must release its Blob URL');+ if (phase === 'headers' || phase === 'body') {+ assert.equal(h.stageSignal.aborted, true, 'Stop must reach the actual staging request');+ assert.equal(h.downloads.length, 0);+ if (build === 'chrome') {+ const prepare = h.messages.find(message => message.type === 'skill-download-prepare');+ assert.equal(h.messages.find(message => message.type === 'skill-download-cancel')?.requestId, prepare.requestId);+ if (phase === 'body') assert.ok(h.events.includes('abort-write'), 'partial OPFS write must be aborted');+ }+ } else {+ assert.equal(h.created.length, 1, 'test must reach a fully staged file');+ assert.equal(h.downloads.length, phase === 'save' ? 1 : 0);+ if (phase === 'save') {+ assert.deepEqual(h.events, ['cancel', 'release', 'delete'], 'cancel local download before releasing the stage and remote job');+ }+ }+ });+ }+}