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
Make freeskillz download wait abortable by Stop
Emre Sokullu02a6f9005134
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex b87808d20..cdb29e56a 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -41597,11 +41597,12 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai}if (skillTool.skillId === 'wikipedia') {return await executeWikipediaSkillTool(skillTool, args, {- executeOnline: (onlineTool, onlineArgs) => executeHttpSkillTool(onlineTool, onlineArgs, { tabId }),+ executeOnline: (onlineTool, onlineArgs) => executeHttpSkillTool(onlineTool, onlineArgs, { tabId, signal: typeof executionContext !== 'undefined' ? executionContext?._contentActionAbortSignal : undefined }),});}return await executeHttpSkillTool(skillTool, args, {tabId,+ signal: typeof executionContext !== 'undefined' ? executionContext?._contentActionAbortSignal : undefined,onProgress: message => onUpdate?.('tool_progress', { name, message }),});}diff --git a/src/chrome/src/network/network-tools.js b/src/chrome/src/network/network-tools.jsindex 5ec61f68f..65c8b5de1 100644--- a/src/chrome/src/network/network-tools.js+++ b/src/chrome/src/network/network-tools.js@@ -644,7 +644,32 @@ function defaultSkillDownloadFilename(contentType) {return extension ? `public-media.${extension}` : undefined;}-async function fetchSkillJson(url, init, endpoint, tool) {+function throwIfSkillAborted(signal) {+ if (signal?.aborted) throw responseAbortError(signal);+}++function sleepAbortable(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(responseAbortError(signal));+ if (!signal?.addEventListener) {+ setTimeout(resolve, ms);+ return;+ }+ const timer = setTimeout(() => {+ try { signal.removeEventListener('abort', onAbort); } catch {}+ resolve();+ }, ms);+ const onAbort = () => {+ clearTimeout(timer);+ reject(responseAbortError(signal));+ };+ try { signal.addEventListener('abort', onAbort, { once: true }); } catch {+ // If the signal cannot be observed, fall back to an uninterruptible sleep.+ }+ });+}++async function fetchSkillJson(url, init, endpoint, tool, signal = null) {const urlCheck = validateFetchUrl(url, { allowLocalNetwork: getAllowLocalNetwork() });if (!urlCheck.ok) {return {@@ -657,10 +682,12 @@ async function fetchSkillJson(url, init, endpoint, tool) {};}try {+ throwIfSkillAborted(signal);const res = await fetch(url, {credentials: 'omit',redirect: 'manual',...init,+ ...(signal ? { signal } : {}),});if (res?.type === 'opaqueredirect' || isHttpRedirectStatus(res?.status)) {return {@@ -701,6 +728,7 @@ async function fetchSkillJson(url, init, endpoint, tool) {}return { success: true, status: res.status, data: data && typeof data === 'object' ? data : { text: rawText } };} catch (e) {+ if (signal?.aborted || e?.name === 'AbortError') throw responseAbortError(signal);return { success: false, provider: endpoint.hostname, skillTool: tool.name || '', skillName: tool.skillName || '', error: `Skill tool request failed: ${e.message}` };}}@@ -855,17 +883,19 @@ async function readSkillDownloadBuffer(res) {return { success: true, buffer, bytesReceived: buffer.byteLength };}-async function fetchSkillDownloadData(url, expectedUrl) {+async function fetchSkillDownloadData(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 res = await fetch(url, {method: 'GET',credentials: 'omit',redirect: 'manual',cache: 'no-store',+ ...(signal ? { signal } : {}),});if (res?.type === 'opaqueredirect' || isHttpRedirectStatus(res?.status)) {return {@@ -925,6 +955,7 @@ async function fetchSkillDownloadData(url, expectedUrl) {bytesReceived: file.bytesReceived,};} catch (e) {+ if (signal?.aborted || e?.name === 'AbortError') throw responseAbortError(signal);return { success: false, finalUrl: url, error: `Skill download file request failed: ${e.message}` };}}@@ -1042,8 +1073,9 @@ function scheduleSkillDownloadCleanup(downloadId, cleanupUrl, endpoint, tool, opreturn true;}-async function downloadSkillFile(url, filename, waitMs = 60000) {- const file = await fetchSkillDownloadData(url, url);+async function downloadSkillFile(url, filename, waitMs = 60000, signal = null) {+ throwIfSkillAborted(signal);+ const file = await fetchSkillDownloadData(url, url, signal);let staged = null;if (file.tooLarge === true) {staged = await prepareStagedSkillDownload(url, url);@@ -1090,7 +1122,8 @@ async function downloadSkillFile(url, filename, waitMs = 60000) {await releaseStagedSkillDownload(staged?.releaseToken);throw error;}- const info = await resolveDownloadInfo(downloadId, waitMs);+ const info = await resolveDownloadInfo(downloadId, waitMs, { signal });+ throwIfSkillAborted(signal);const result = {downloadId,success: false,@@ -1137,11 +1170,13 @@ async function downloadSkillFile(url, filename, waitMs = 60000) {}async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}) {+ const signal = ctx?.signal || null;+ throwIfSkillAborted(signal);const create = await fetchSkillJson(endpoint.href, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(payload),- }, endpoint, tool);+ }, endpoint, tool, signal);if (!create.success) return create;const idField = tool.job?.idField || 'job_id';@@ -1165,12 +1200,14 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}let waitNoticeSent = false;const notifyLongWait = data => {if (waitNoticeSent) return;+ // Elapsed-based: only notify after 30s of waiting, regardless of metadata.+ // Metadata only customizes the message, so fast jobs never over-promise.+ if (Date.now() - startedAt < 30000) return;const metadata = data?.metadata || {};const duration = Number(metadata.duration);const bytes = Number(metadata.filesize || metadata.filesize_approx);const longVideo = Number.isFinite(duration) && duration >= 120;const largeFile = Number.isFinite(bytes) && bytes >= 50 * 1024 * 1024;- if (!longVideo && !largeFile && Date.now() - startedAt < 30000) return;waitNoticeSent = true;// Only numeric metadata enters chat; provider titles and text stay untrusted.const size = largeFile ? `about ${Math.ceil(bytes / (1024 * 1024))} MB`@@ -1180,11 +1217,11 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}: 'The media is still downloading or being prepared. Larger files and longer videos can take several minutes. I’ll keep waiting.';try { ctx.onProgress?.(message); } catch { /* Chat updates must not interrupt delivery. */ }};- notifyLongWait(create.data);const pollIntervalMs = tool.job?.pollIntervalMs || 1000;let lastStatus = create.data;while (Date.now() < deadline) {- const poll = await fetchSkillJson(statusEndpoint.url, { method: 'GET' }, endpoint, tool);+ throwIfSkillAborted(signal);+ const poll = await fetchSkillJson(statusEndpoint.url, { method: 'GET' }, endpoint, tool, signal);if (!poll.success) return await withSkillDownloadJobCleanup({ ...poll, jobId }, cleanupEndpoint, endpoint, tool);lastStatus = poll.data;const status = String(poll.data?.status || '').toLowerCase();@@ -1202,12 +1239,15 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}}, cleanupEndpoint, endpoint, tool);}notifyLongWait(lastStatus);- await new Promise(r => setTimeout(r, pollIntervalMs));+ await sleepAbortable(pollIntervalMs, signal);}+ throwIfSkillAborted(signal);const finalStatus = String(lastStatus?.status || '').toLowerCase();if (!(finalStatus === 'complete' || finalStatus === 'completed' || finalStatus === 'done' || finalStatus === 'success')) {- // A polling deadline does not cancel the remote job. Keep its identity for recovery.+ // A polling deadline does not cancel the remote job. FreeSkillz rejects+ // DELETE while queued/running (409) and expires completed files via+ // MEDIA_TTL_SECONDS, so keep the identity for recovery instead of deleting.return {success: false,provider: endpoint.hostname,@@ -1217,13 +1257,16 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}jobStatus: finalStatus || 'unknown',statusUrl: statusEndpoint.url,fileUrl: fileEndpoint.url,+ ...REMOTE_MEDIA_FAILURE_CONTEXT,error: 'The wait limit was reached, but the remote job may still finish. Check statusUrl before starting another download.',};}let cleanup = null;try {- const download = await downloadSkillFile(fileEndpoint.url, payload.filename, Math.min(tool.job?.timeoutMs || 90000, 120000));+ 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;@@ -1266,6 +1309,7 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}...download,};} catch (e) {+ 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}` };}@@ -2544,6 +2588,7 @@ async function resolveDownloadInfo(downloadId, timeoutMs = 15000, opts = {}) {const deadline = Date.now() + timeoutMs;let last = null;while (Date.now() < deadline) {+ if (opts.signal?.aborted) throw responseAbortError(opts.signal);let items;try {items = await new Promise((resolve, reject) => {@@ -2562,7 +2607,7 @@ async function resolveDownloadInfo(downloadId, timeoutMs = 15000, opts = {}) {if (last.finalUrlBlocked) return last;if (it.state === 'complete' || it.state === 'interrupted') return last;}- await new Promise(r => setTimeout(r, 200));+ await sleepAbortable(200, opts.signal || null);}return last; // timed out — return best-known (may still be in_progress)}diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 4bde9f72d..b44d23f5a 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -37721,11 +37721,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}if (skillTool.skillId === 'wikipedia') {return await executeWikipediaSkillTool(skillTool, args, {- executeOnline: (onlineTool, onlineArgs) => executeHttpSkillTool(onlineTool, onlineArgs, { tabId }),+ executeOnline: (onlineTool, onlineArgs) => executeHttpSkillTool(onlineTool, onlineArgs, { tabId, signal: typeof executionContext !== 'undefined' ? executionContext?._contentActionAbortSignal : undefined }),});}return await executeHttpSkillTool(skillTool, args, {tabId,+ signal: typeof executionContext !== 'undefined' ? executionContext?._contentActionAbortSignal : undefined,onProgress: message => onUpdate?.('tool_progress', { name, message }),});}diff --git a/src/firefox/src/network/network-tools.js b/src/firefox/src/network/network-tools.jsindex ff8ca593a..fee7235ef 100644--- a/src/firefox/src/network/network-tools.js+++ b/src/firefox/src/network/network-tools.js@@ -613,7 +613,32 @@ function defaultSkillDownloadFilename(contentType) {return extension ? `public-media.${extension}` : undefined;}-async function fetchSkillJson(url, init, endpoint, tool) {+function throwIfSkillAborted(signal) {+ if (signal?.aborted) throw responseAbortError(signal);+}++function sleepAbortable(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(responseAbortError(signal));+ if (!signal?.addEventListener) {+ setTimeout(resolve, ms);+ return;+ }+ const timer = setTimeout(() => {+ try { signal.removeEventListener('abort', onAbort); } catch {}+ resolve();+ }, ms);+ const onAbort = () => {+ clearTimeout(timer);+ reject(responseAbortError(signal));+ };+ try { signal.addEventListener('abort', onAbort, { once: true }); } catch {+ // If the signal cannot be observed, fall back to an uninterruptible sleep.+ }+ });+}++async function fetchSkillJson(url, init, endpoint, tool, signal = null) {const urlCheck = validateFetchUrl(url, { allowLocalNetwork: getAllowLocalNetwork() });if (!urlCheck.ok) {return {@@ -626,10 +651,12 @@ async function fetchSkillJson(url, init, endpoint, tool) {};}try {+ throwIfSkillAborted(signal);const res = await fetch(url, {credentials: 'omit',redirect: 'manual',...init,+ ...(signal ? { signal } : {}),});if (res?.type === 'opaqueredirect' || isHttpRedirectStatus(res?.status)) {return {@@ -670,6 +697,7 @@ async function fetchSkillJson(url, init, endpoint, tool) {}return { success: true, status: res.status, data: data && typeof data === 'object' ? data : { text: rawText } };} catch (e) {+ if (signal?.aborted || e?.name === 'AbortError') throw responseAbortError(signal);return { success: false, provider: endpoint.hostname, skillTool: tool.name || '', skillName: tool.skillName || '', error: `Skill tool request failed: ${e.message}` };}}@@ -819,17 +847,19 @@ async function readSkillDownloadBuffer(res) {return { success: true, buffer, bytesReceived: buffer.byteLength };}-async function fetchSkillDownloadData(url, expectedUrl) {+async function fetchSkillDownloadData(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 res = await fetch(url, {method: 'GET',credentials: 'omit',redirect: 'manual',cache: 'no-store',+ ...(signal ? { signal } : {}),});if (res?.type === 'opaqueredirect' || isHttpRedirectStatus(res?.status)) {return {@@ -889,6 +919,7 @@ async function fetchSkillDownloadData(url, expectedUrl) {bytesReceived: file.bytesReceived,};} catch (e) {+ if (signal?.aborted || e?.name === 'AbortError') throw responseAbortError(signal);return { success: false, finalUrl: url, error: `Skill download file request failed: ${e.message}` };}}@@ -1050,8 +1081,9 @@ function scheduleSkillDownloadCleanup(downloadId, cleanupUrl, endpoint, tool, opreturn true;}-async function downloadSkillFile(url, filename, waitMs = 60000) {- const file = await fetchSkillDownloadData(url, url);+async function downloadSkillFile(url, filename, waitMs = 60000, signal = null) {+ throwIfSkillAborted(signal);+ const file = await fetchSkillDownloadData(url, url, signal);let staged = null;if (file.tooLarge === true) {staged = await prepareStagedSkillDownload(url, url);@@ -1098,7 +1130,8 @@ async function downloadSkillFile(url, filename, waitMs = 60000) {await releaseStagedSkillDownload(staged?.releaseToken);throw error;}- const info = await resolveDownloadInfo(downloadId, waitMs);+ const info = await resolveDownloadInfo(downloadId, waitMs, { signal });+ throwIfSkillAborted(signal);const result = {downloadId,success: false,@@ -1145,11 +1178,13 @@ async function downloadSkillFile(url, filename, waitMs = 60000) {}async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}) {+ const signal = ctx?.signal || null;+ throwIfSkillAborted(signal);const create = await fetchSkillJson(endpoint.href, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(payload),- }, endpoint, tool);+ }, endpoint, tool, signal);if (!create.success) return create;const idField = tool.job?.idField || 'job_id';@@ -1173,12 +1208,14 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}let waitNoticeSent = false;const notifyLongWait = data => {if (waitNoticeSent) return;+ // Elapsed-based: only notify after 30s of waiting, regardless of metadata.+ // Metadata only customizes the message, so fast jobs never over-promise.+ if (Date.now() - startedAt < 30000) return;const metadata = data?.metadata || {};const duration = Number(metadata.duration);const bytes = Number(metadata.filesize || metadata.filesize_approx);const longVideo = Number.isFinite(duration) && duration >= 120;const largeFile = Number.isFinite(bytes) && bytes >= 50 * 1024 * 1024;- if (!longVideo && !largeFile && Date.now() - startedAt < 30000) return;waitNoticeSent = true;// Only numeric metadata enters chat; provider titles and text stay untrusted.const size = largeFile ? `about ${Math.ceil(bytes / (1024 * 1024))} MB`@@ -1188,11 +1225,11 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}: 'The media is still downloading or being prepared. Larger files and longer videos can take several minutes. I’ll keep waiting.';try { ctx.onProgress?.(message); } catch { /* Chat updates must not interrupt delivery. */ }};- notifyLongWait(create.data);const pollIntervalMs = tool.job?.pollIntervalMs || 1000;let lastStatus = create.data;while (Date.now() < deadline) {- const poll = await fetchSkillJson(statusEndpoint.url, { method: 'GET' }, endpoint, tool);+ throwIfSkillAborted(signal);+ const poll = await fetchSkillJson(statusEndpoint.url, { method: 'GET' }, endpoint, tool, signal);if (!poll.success) return await withSkillDownloadJobCleanup({ ...poll, jobId }, cleanupEndpoint, endpoint, tool);lastStatus = poll.data;const status = String(poll.data?.status || '').toLowerCase();@@ -1210,12 +1247,15 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}}, cleanupEndpoint, endpoint, tool);}notifyLongWait(lastStatus);- await new Promise(r => setTimeout(r, pollIntervalMs));+ await sleepAbortable(pollIntervalMs, signal);}+ throwIfSkillAborted(signal);const finalStatus = String(lastStatus?.status || '').toLowerCase();if (!(finalStatus === 'complete' || finalStatus === 'completed' || finalStatus === 'done' || finalStatus === 'success')) {- // A polling deadline does not cancel the remote job. Keep its identity for recovery.+ // A polling deadline does not cancel the remote job. FreeSkillz rejects+ // DELETE while queued/running (409) and expires completed files via+ // MEDIA_TTL_SECONDS, so keep the identity for recovery instead of deleting.return {success: false,provider: endpoint.hostname,@@ -1225,13 +1265,16 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}jobStatus: finalStatus || 'unknown',statusUrl: statusEndpoint.url,fileUrl: fileEndpoint.url,+ ...REMOTE_MEDIA_FAILURE_CONTEXT,error: 'The wait limit was reached, but the remote job may still finish. Check statusUrl before starting another download.',};}let cleanup = null;try {- const download = await downloadSkillFile(fileEndpoint.url, payload.filename, Math.min(tool.job?.timeoutMs || 90000, 120000));+ 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;@@ -1274,6 +1317,7 @@ async function executeHttpDownloadJobSkillTool(tool, payload, endpoint, ctx = {}...download,};} catch (e) {+ 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}` };}@@ -2509,6 +2553,7 @@ async function resolveDownloadInfo(downloadId, timeoutMs = 15000, opts = {}) {const deadline = Date.now() + timeoutMs;let last = null;while (Date.now() < deadline) {+ if (opts.signal?.aborted) throw responseAbortError(opts.signal);let items;try {items = await browser.downloads.search({ id: downloadId });@@ -2522,7 +2567,7 @@ async function resolveDownloadInfo(downloadId, timeoutMs = 15000, opts = {}) {if (last.finalUrlBlocked) return last;if (it.state === 'complete' || it.state === 'interrupted') return last;}- await new Promise(r => setTimeout(r, 200));+ await sleepAbortable(200, opts.signal || null);}return last; // timed out — return best-known (may still be in_progress)}diff --git a/test/run.js b/test/run.jsindex fb17cf520..6d58d98cb 100644--- a/test/run.js+++ b/test/run.js@@ -32142,6 +32142,8 @@ test('executeHttpSkillTool cleans up failures and preserves timed-out provider jassertResult(result, label) {assert.match(result.error, /wait limit/i, `${label}: timeout error missing`);assert.equal(result.statusUrl, 'https://freeskillz.xyz/v1/media/jobs/job_timeout');+ assert.equal(result.executionContext, 'remote_service', `${label}: timeout should identify the remote execution context`);+ assert.equal(result.browserLoginAffectsRequest, false, `${label}: browser login must not be presented as affecting the provider request`);},},];diff --git a/test/skill-download-wait.mjs b/test/skill-download-wait.mjsindex 040131e4c..a47696fe3 100644--- a/test/skill-download-wait.mjs+++ b/test/skill-download-wait.mjs@@ -50,6 +50,8 @@ for (const build of ['chrome', 'firefox']) {assert.equal(result.jobId, 'slow');assert.equal(result.statusUrl, 'https://freeskillz.xyz/v1/media/jobs/slow');assert.equal(result.jobStatus, 'running');+ assert.equal(result.executionContext, 'remote_service');+ assert.equal(result.browserLoginAffectsRequest, false);assert.ok(!methods.includes('DELETE'), 'timeout must preserve a running job');}}@@ -61,6 +63,104 @@ for (const build of ['chrome', 'firefox']) {});}+for (const build of ['chrome', 'firefox']) {+ test(`${build}: long metadata does not notify when the job finishes fast`, async () => {+ const { executeHttpSkillTool } = await import(`../src/${build}/src/network/network-tools.js`);+ const { normalizeCustomSkills, buildSkillToolRegistry } = await import(`../src/${build}/src/agent/skills.js`);+ const skills = normalizeCustomSkills([{+ id: 'freeskillz-xyz', name: 'FreeSkillz.xyz', enabled: true,+ content: fs.readFileSync(new URL(`../src/${build}/skills/freeskillz-xyz.md`, import.meta.url), 'utf8'),+ }]);+ const tool = buildSkillToolRegistry(skills).get('download_public_media');+ const originalFetch = globalThis.fetch;+ const originalNow = Date.now;+ const originalTimeout = globalThis.setTimeout;+ try {+ let clock = 0;+ const notices = [];+ Date.now = () => clock;+ globalThis.setTimeout = callback => { clock += 1000; callback(); return 0; };+ // Long video metadata, but completes on first poll well before 30s elapsed.+ globalThis.fetch = async (_url, opts) => {+ if (opts.method === 'POST') return { ok: true, status: 200, text: async () => JSON.stringify({ job_id: 'fast', metadata: { duration: 300 } }) };+ clock += 2000;+ return { ok: true, status: 200, text: async () => JSON.stringify({ status: 'complete', metadata: { duration: 300 } }) };+ };+ // Stub the final file download to avoid browser APIs in this unit test.+ const originalChrome = globalThis.chrome;+ const originalBrowser = globalThis.browser;+ try {+ if (build === 'chrome') {+ delete globalThis.browser;+ globalThis.chrome = { runtime: { lastError: null }, downloads: { download(_o, cb) { cb(1); }, search(_q, cb) { cb([{ id: 1, state: 'complete', filename: 'f.mp4' }]); } } };+ } else {+ delete globalThis.chrome;+ globalThis.browser = { downloads: { async download() { return 1; }, async search() { return [{ id: 1, state: 'complete' }]; } } };+ }+ // fetchSkillDownloadData path uses data: URLs in this stubbed fetch; force it+ // to return a tiny file so downloadSkillFile can proceed without network.+ globalThis.fetch = async (_url, opts) => {+ if (opts.method === 'POST') return { ok: true, status: 200, text: async () => JSON.stringify({ job_id: 'fast', metadata: { duration: 300 } }) };+ if (String(_url).endsWith('/file')) {+ return { ok: true, status: 200, url: _url, headers: { get: () => 'video/mp4' }, text: async () => '', arrayBuffer: async () => new ArrayBuffer(4), body: null };+ }+ clock += 2000;+ return { ok: true, status: 200, text: async () => JSON.stringify({ status: 'complete', metadata: { duration: 300 } }) };+ };+ await executeHttpSkillTool(tool, { url: 'https://x.com/user/status/123', kind: 'video' }, {+ onProgress: message => notices.push(message),+ });+ assert.deepEqual(notices, []);+ } finally {+ if (originalChrome === undefined) delete globalThis.chrome;+ else globalThis.chrome = originalChrome;+ if (originalBrowser === undefined) delete globalThis.browser;+ else globalThis.browser = originalBrowser;+ }+ } finally {+ globalThis.fetch = originalFetch;+ Date.now = originalNow;+ globalThis.setTimeout = originalTimeout;+ }+ });+}++for (const build of ['chrome', 'firefox']) {+ test(`${build}: skill download wait aborts promptly on Stop`, async () => {+ const { executeHttpSkillTool } = await import(`../src/${build}/src/network/network-tools.js`);+ const { normalizeCustomSkills, buildSkillToolRegistry } = await import(`../src/${build}/src/agent/skills.js`);+ const skills = normalizeCustomSkills([{+ id: 'freeskillz-xyz', name: 'FreeSkillz.xyz', enabled: true,+ content: fs.readFileSync(new URL(`../src/${build}/skills/freeskillz-xyz.md`, import.meta.url), 'utf8'),+ }]);+ const tool = buildSkillToolRegistry(skills).get('download_public_media');+ const originalFetch = globalThis.fetch;+ try {+ const methods = [];+ globalThis.fetch = async (_url, opts = {}) => {+ methods.push(opts.method);+ if (opts.signal?.aborted) throw new DOMException('The operation was aborted', 'AbortError');+ if (opts.method === 'POST') return { ok: true, status: 200, text: async () => JSON.stringify({ job_id: 'slow' }) };+ // 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 });+ });+ throw new Error('unreachable');+ };+ const controller = new AbortController();+ const pending = executeHttpSkillTool(tool, { url: 'https://x.com/user/status/123', kind: 'video' }, {+ signal: controller.signal,+ onProgress: () => {},+ });+ controller.abort();+ await assert.rejects(pending, err => err?.name === 'AbortError');+ assert.ok(!methods.includes('DELETE'), 'abort must not delete the running provider job');+ } finally {+ globalThis.fetch = originalFetch;+ }+ });+}+for (const build of ['chrome', 'firefox']) {test(`${build}: skill progress reaches the chat tool-progress channel`, async () => {const source = fs.readFileSync(new URL(`../src/${build}/src/agent/agent.js`, import.meta.url), 'utf8');