diff --git a/integrations/deepseek-harness/gallery-host.mjs b/integrations/deepseek-harness/gallery-host.mjs index ff986c6..4fb1673 100644 --- a/integrations/deepseek-harness/gallery-host.mjs +++ b/integrations/deepseek-harness/gallery-host.mjs @@ -8,6 +8,7 @@ import { pipeline } from "node:stream/promises"; import { fileURLToPath } from "node:url"; import { SKIN_CENTER_ORIGIN, + createGalleryOperations, downloadApprovedAsset, getApprovedSkin, listApprovedSkins, @@ -173,7 +174,61 @@ export function createGalleryHandlers({ dataRoot, actions }) { throw new Error("当前引擎不支持导入皮肤。"); } + const operations=createGalleryOperations(); + async function performInstall(id,operation) { + const tmpDir=path.join(dataRoot,"tmp","gallery",crypto.randomUUID()); + try { + const skin = await getApprovedSkin(id, { signal: operation.signal }); + await fsp.mkdir(tmpDir, { recursive: true }); + const imageDownload = await downloadApprovedAsset(skin, "image", { + directory: tmpDir, + signal: operation.signal, + onProgress: (done, total) => operation.progress("download"), + }); + const imagePath = imageDownload.filePath; + let videoPath; + if (skin.type === "video") { + const videoDownload = await downloadApprovedAsset(skin, "video", { + directory: tmpDir, + signal: operation.signal, + onProgress: (done, total) => operation.progress("download"), + }); + videoPath = videoDownload.filePath; + } + // Skin-center media is downloaded into the store, so it is a managed + // import. importTheme applies-and-saves atomically; the media is copied + // before it returns, so tmpDir is safe to remove in finally. + operation.beginApply(); + // The apply/save step is atomic and cannot be interrupted; refuse to + // start it when the client already went away so a disconnected UI does + // not still commit and apply a background after the controls recovered. + if (operation.signal.aborted) throw new Error("客户端已断开。"); + const imported = await importTheme({ + name: normalizeThemeName(skin.name || id), + imagePath, + ...(videoPath ? { videoPath } : {}), + ...(skin.effects ? { effects: skin.effects } : {}), + source: "managed", + provenance: { + source: skin.source, + sourceSkinId: skin.sourceSkinId, + sourceVersion: skin.sourceVersion, + }, + }); + + if(imported?.ok===false)return imported; + return {ok:true,theme:imported.theme||imported,message:imported.message||"已安装并应用。"}; + } finally {await fsp.rm(tmpDir,{recursive:true,force:true}).catch(()=>{});} + } + return { + async operation(req,res,sendJson,isSameOrigin,readJson) { + if(req.method!=="POST"){res.writeHead(405).end();return;} + if(!isSameOrigin(req)){res.writeHead(403).end();return;} + const body=await readJson(req); + if(body.action==="start") {const id=String(body.id||"");if(!isSafeSkinId(id)){sendJson(res,400,{ok:false,error:"皮肤 ID 无效。"});return;}sendJson(res,200,operations.start(id,ctx=>performInstall(id,ctx),body.operationId));return;} + sendJson(res,200,body.action==="cancel"?operations.cancel(String(body.operationId)):operations.status(String(body.operationId))); + }, async config(req, res, sendJson, isSameOrigin) { if (req.method !== "GET") { res.writeHead(405).end(); @@ -199,12 +254,16 @@ export function createGalleryHandlers({ dataRoot, actions }) { try { const incoming = new URL(req.url || "/", "http://127.0.0.1"); const type = incoming.searchParams.get("type"); - const skins = await listApprovedSkins({ + const cancel=new AbortController();const onClose=()=>cancel.abort();res.once('close',onClose); + let skins; + try { skins = await listApprovedSkins({ + signal:cancel.signal, query: { ...(incoming.searchParams.get("q") ? { q: incoming.searchParams.get("q") } : {}), ...(type === "image" || type === "video" ? { type } : {}), }, }); + } finally {res.off('close',onClose);} sendJson(res, 200, { ok: true, skins, diff --git a/integrations/deepseek-harness/gallery.js b/integrations/deepseek-harness/gallery.js index 0be6af1..fc87a05 100644 --- a/integrations/deepseek-harness/gallery.js +++ b/integrations/deepseek-harness/gallery.js @@ -50,6 +50,33 @@ const typeSelect = host.querySelector(".bcg-type"); let centerUrl = ""; let busy = false; + + let queryAbort=null, openAbort=null, polling=null; + const operationKey="beauticode-gallery-operation"; + let operationId=""; + try { operationId=sessionStorage.getItem(operationKey)||""; } catch {} + const cancelButton=document.createElement("button");cancelButton.type="button";cancelButton.className="bcg-btn";cancelButton.textContent="取消下载";cancelButton.hidden=true; + host.querySelector(".bcg-head").append(cancelButton); + function rememberOperation(id){operationId=id;try{id?sessionStorage.setItem(operationKey,id):sessionStorage.removeItem(operationKey);}catch{}} + const operation=(action,body={})=>request("/__beauticode/ui/gallery/operation",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action,...body})}); + async function watchOperation(){ + polling?.abort();const controller=new AbortController();polling=controller;busy=true;cancelButton.hidden=false; + const deadline=Date.now()+120000; + try{ + while(!controller.signal.aborted&&!host.hidden){ + const state=await operation("status",{operationId}); + if(controller.signal.aborted||host.hidden)return; + if(state.result){msg.textContent=state.result.message||state.result.error||(state.result.ok?"已安装。":"安装失败。");if(state.result.ok)document.dispatchEvent(new CustomEvent("beauticode-gallery-installed"));rememberOperation("");return;} + cancelButton.disabled=state.phase==="apply"; + msg.textContent=state.phase==="apply"?"正在提交背景,可稍后重新打开查询结果。":"正在下载,可取消。"; + if(Date.now()>deadline){msg.textContent="操作仍在进行,关闭后重新打开可查询结果。";return;} + await new Promise(resolve=>{const finish=()=>{clearTimeout(timer);controller.signal.removeEventListener("abort",finish);resolve()};const timer=setTimeout(finish,400);controller.signal.addEventListener("abort",finish,{once:true})}); + } + }catch(error){if(!controller.signal.aborted){msg.textContent=error.message;if(error.code==="operation_unknown")rememberOperation("");}} + finally{if(polling===controller){polling=null;busy=false;cancelButton.hidden=!operationId;}} + } + cancelButton.onclick=()=>{if(operationId)void operation("cancel",{operationId}).then(state=>{if(state.message)msg.textContent=state.message;else msg.textContent="正在取消下载…";if(!host.hidden&&!busy)void watchOperation()}).catch(error=>{msg.textContent=error.message})}; + let loadGeneration = 0; let returnFocus = null; @@ -95,6 +122,7 @@ async function request(path, init) { const response = await fetch(path, { ...init, + signal:init?.signal ? AbortSignal.any([init.signal,AbortSignal.timeout(45000)]) : AbortSignal.timeout(45000), headers: { ...(init?.headers || {}), ...(globalThis.__beauticodeTransport?.headers() ?? {}) }, }); if ((response.headers.get("content-type") || "").includes("ndjson")) { @@ -102,7 +130,7 @@ } const body = await response.json().catch(() => null); if (!response.ok || body?.ok === false) { - throw new Error(body?.error || `请求失败(${response.status})`); + throw Object.assign(new Error(body?.error || `请求失败(${response.status})`),{code:body?.code}); } return body; } @@ -138,12 +166,13 @@ async function load() { const generation = ++loadGeneration; + queryAbort?.abort();queryAbort=new AbortController();const signal=queryAbort.signal; msg.textContent = "正在读取目录…"; try { const params = new URLSearchParams(); if (queryInput.value.trim()) params.set("q", queryInput.value.trim()); if (typeSelect.value) params.set("type", typeSelect.value); - const data = await request(`/__beauticode/ui/gallery/catalog?${params}`); + const data = await request(`/__beauticode/ui/gallery/catalog?${params}`,{signal}); if (generation !== loadGeneration || host.hidden) return; centerUrl = data.url || centerUrl; grid.innerHTML = (data.skins || []) @@ -170,9 +199,12 @@ if (host.hidden) returnFocus = document.activeElement; host.hidden = false; focusInside(); + openAbort?.abort();openAbort=new AbortController();const opening=openAbort; + if(operationId){void watchOperation();return;} try { - const config = await request("/__beauticode/ui/gallery/config"); - centerUrl = config.url || ""; + let config;try{config=await request("/__beauticode/ui/gallery/config",{signal:opening.signal});}catch(error){if(!opening.signal.aborted)msg.textContent=error.message;return;} + if(opening.signal.aborted||host.hidden)return; + centerUrl = config.url || ""; if (!config.enabled) { grid.innerHTML = ""; msg.textContent = "尚未配置皮肤中心地址。"; @@ -190,6 +222,8 @@ function close() { host.hidden = true; loadGeneration += 1; + queryAbort?.abort();openAbort?.abort();polling?.abort(); + if(operationId)void operation('cancel',{operationId}).catch(()=>{}); if (returnFocus?.isConnected) returnFocus.focus(); returnFocus = null; } @@ -211,21 +245,10 @@ const id = card.getAttribute("data-id"); busy = true; msg.textContent = "开始安装…"; - request("/__beauticode/ui/gallery/install", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ id }), - }) - .then((result) => { - msg.textContent = result.message || "已安装。"; - document.dispatchEvent(new CustomEvent("beauticode-gallery-installed")); - }) - .catch((error) => { - msg.textContent = error instanceof Error ? error.message : String(error); - }) - .finally(() => { - busy = false; - }); + rememberOperation(crypto.randomUUID()); + operation("start",{id,operationId}).then(state=>{rememberOperation(state.id);if(host.hidden)return operation("cancel",{operationId});return watchOperation()}) + .catch(error=>{msg.textContent=error.message;}) + .finally(()=>{if(!polling)busy=false;}); }); document.addEventListener("keydown", (event) => { if (event.key === "Escape" && !host.hidden) { diff --git a/integrations/deepseek-harness/index.mjs b/integrations/deepseek-harness/index.mjs index 3dbd2fb..f5428af 100644 --- a/integrations/deepseek-harness/index.mjs +++ b/integrations/deepseek-harness/index.mjs @@ -443,6 +443,11 @@ export function apply(ctx, config = {}) { path: "/__beauticode/ui/gallery/catalog", handler: (req, res) => ui.galleryCatalog(req, res), }), + ctx.webServer.register({ + kind: "exact", + path: "/__beauticode/ui/gallery/operation", + handler: (req,res) => ui.galleryOperation(req,res), + }), ctx.webServer.register({ kind: "exact", path: "/__beauticode/ui/gallery/install", diff --git a/integrations/deepseek-harness/test/gallery-operation.test.mjs b/integrations/deepseek-harness/test/gallery-operation.test.mjs new file mode 100644 index 0000000..08a30b6 --- /dev/null +++ b/integrations/deepseek-harness/test/gallery-operation.test.mjs @@ -0,0 +1,23 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import os from 'node:os'; +import {createGalleryHandlers} from '../gallery-host.mjs'; + +test('DSH operation metadata download is cancellable before any atomic import',{ timeout: 10000 },async t=>{ + const root=await fs.mkdtemp(path.join(os.tmpdir(),'bc-gallery-op-'));t.after(()=>fs.rm(root,{recursive:true,force:true})); + const original=globalThis.fetch;t.after(()=>{globalThis.fetch=original});let aborted=false,imports=0; + const fetchStarted = Promise.withResolvers(); + globalThis.fetch=(_url,{signal})=>new Promise((resolve,reject)=>{fetchStarted.resolve();signal.addEventListener('abort',()=>{aborted=true;reject(signal.reason)},{once:true})}); + const handlers=createGalleryHandlers({dataRoot:root,actions:{importTheme(){imports++;return{ok:true}}}}); + async function call(body){let payload;await handlers.operation({method:'POST'},{writeHead(){return this},end(){}},(_res,_status,value)=>{payload=value},()=>true,async()=>body);return payload;} + const started=await call({action:'start',id:'skin-abcdefgh'});assert.equal(started.ok,true); + await fetchStarted.promise; + await call({action:'cancel',operationId:started.id}); + const deadline = Date.now() + 5000; + while (!(await call({action:'status',operationId:started.id})).result && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 10)); + } + assert.equal(aborted,true);assert.equal(imports,0);assert.equal((await call({action:'status',operationId:started.id})).phase,'cancelled'); +}); diff --git a/integrations/deepseek-harness/ui-host.mjs b/integrations/deepseek-harness/ui-host.mjs index 6c1b055..5b57f8c 100644 --- a/integrations/deepseek-harness/ui-host.mjs +++ b/integrations/deepseek-harness/ui-host.mjs @@ -805,6 +805,7 @@ export function createBeauticodeUi({ return gallery.catalog(req, res, sendJson, isSameOrigin); }, + async galleryOperation(req,res) { return gallery.operation(req,res,sendJson,isSameOrigin,readJson); }, async galleryInstall(req, res) { return gallery.install(req, res, sendJson, isSameOrigin, readJson); }, diff --git a/packages/adapter-codex/src/console-host.ts b/packages/adapter-codex/src/console-host.ts index 89e38d4..15494d9 100644 --- a/packages/adapter-codex/src/console-host.ts +++ b/packages/adapter-codex/src/console-host.ts @@ -1,7 +1,7 @@ import crypto from "node:crypto"; import path from "node:path"; import type { BeautiSession } from "./session.js"; -import { toChineseErrorMessage } from "@beauticode/core"; +import { createGalleryOperations, isSafeSkinId, toChineseErrorMessage } from "@beauticode/core"; import { pickLocalMedia } from "./native-picker.js"; import { installSkinFromCenter, @@ -31,6 +31,8 @@ function applyFailure(result: { error: string; rolledBack?: boolean }) { export function createConsoleHost(session: BeautiSession) { const selections = new Map(); let pickerBusy = false; + const galleryOperations = createGalleryOperations(); + const queries = new Map(); function publicThemes() { return session.listSavedThemes().then((list) => @@ -69,6 +71,12 @@ export function createConsoleHost(session: BeautiSession) { request.body && typeof request.body === "object" && !Array.isArray(request.body) ? (request.body as Record) : {}; + if (route === "/__beauticode/ui/gallery/cancel-request") { queries.get(String(body.requestId))?.abort(); return {ok:true}; } + if (route === "/__beauticode/ui/gallery/operation") { + const action=String(body.action||"status"); + if(action==="start") { const id=String(body.id||"");if(!isSafeSkinId(id))return fail("皮肤 ID 无效。");return galleryOperations.start(id, context=>installSkinFromCenter(session,id,context), typeof body.operationId==='string'?body.operationId:undefined); } + return action==="cancel"?galleryOperations.cancel(String(body.operationId)):galleryOperations.status(String(body.operationId)); + } if (route === "/__beauticode/ui/status") return status(); if (route === "/__beauticode/ui/gallery/config") return skinCenterConfig(); if (route.startsWith("/__beauticode/ui/gallery/catalog")) { @@ -78,7 +86,10 @@ export function createConsoleHost(session: BeautiSession) { const type = url.searchParams.get("type"); if (q) query.q = q; if (type) query.type = type; - return skinCenterCatalog(query); + const id=String(request.id||crypto.randomUUID()), controller=new AbortController(); + queries.set(id,controller); + try { return await skinCenterCatalog(query,controller.signal); } + finally { queries.delete(id); } } if (route === "/__beauticode/ui/gallery/install") { const id = typeof body.id === "string" ? body.id.trim() : ""; diff --git a/packages/adapter-codex/src/renderer/gallery.js b/packages/adapter-codex/src/renderer/gallery.js index 32e9b52..dd34f64 100644 --- a/packages/adapter-codex/src/renderer/gallery.js +++ b/packages/adapter-codex/src/renderer/gallery.js @@ -53,6 +53,33 @@ const SKIN_ID = /^skin-[a-z0-9]{8,40}$/; let centerUrl = ""; let busy = false; + + let queryAbort=null, openAbort=null, polling=null; + const operationKey="beauticode-gallery-operation"; + let operationId=""; + try { operationId=sessionStorage.getItem(operationKey)||""; } catch {} + const cancelButton=document.createElement("button");cancelButton.type="button";cancelButton.className="bcg-btn";cancelButton.textContent="取消下载";cancelButton.hidden=true; + host.querySelector(".bcg-head").append(cancelButton); + function rememberOperation(id){operationId=id;try{id?sessionStorage.setItem(operationKey,id):sessionStorage.removeItem(operationKey);}catch{}} + const operation=(action,body={})=>request("/__beauticode/ui/gallery/operation",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action,...body})}); + async function watchOperation(){ + polling?.abort();const controller=new AbortController();polling=controller;busy=true;cancelButton.hidden=false; + const deadline=Date.now()+120000; + try{ + while(!controller.signal.aborted&&!host.hidden){ + const state=await operation("status",{operationId}); + if(controller.signal.aborted||host.hidden)return; + if(state.result){msg.textContent=state.result.message||state.result.error||(state.result.ok?"已安装。":"安装失败。");if(state.result.ok)document.dispatchEvent(new CustomEvent("beauticode-gallery-installed"));rememberOperation("");return;} + cancelButton.disabled=state.phase==="apply"; + msg.textContent=state.phase==="apply"?"正在提交背景,可稍后重新打开查询结果。":"正在下载,可取消。"; + if(Date.now()>deadline){msg.textContent="操作仍在进行,关闭后重新打开可查询结果。";return;} + await new Promise(resolve=>{const finish=()=>{clearTimeout(timer);controller.signal.removeEventListener("abort",finish);resolve()};const timer=setTimeout(finish,400);controller.signal.addEventListener("abort",finish,{once:true})}); + } + }catch(error){if(!controller.signal.aborted){msg.textContent=error.message;if(error.code==="operation_unknown")rememberOperation("");}} + finally{if(polling===controller){polling=null;busy=false;cancelButton.hidden=!operationId;}} + } + cancelButton.onclick=()=>{if(operationId)void operation("cancel",{operationId}).then(state=>{if(state.message)msg.textContent=state.message;else msg.textContent="正在取消下载…";if(!host.hidden&&!busy)void watchOperation()}).catch(error=>{msg.textContent=error.message})}; + let loadGeneration = 0; let returnFocus = null; @@ -103,53 +130,33 @@ body = null; } } - const payload = await new Promise((resolve, reject) => { - const timer = - timeoutMs === 0 - ? null - : setTimeout(() => { - pending.delete(id); - reject(new Error("皮肤中心请求超时。")); - }, timeoutMs || 45_000); - pending.set(id, { - resolve: (value) => { - if (timer) clearTimeout(timer); - resolve(value); - }, - reject: (error) => { - if (timer) clearTimeout(timer); - reject(error); - }, - }); - try { - window.beauticodeConsole( - JSON.stringify({ - id, - path, - method: init?.method || "GET", - body, - }), - ); - } catch (error) { - if (timer) clearTimeout(timer); - pending.delete(id); - reject(error instanceof Error ? error : new Error(String(error))); - } + const payload = await new Promise((resolve,reject)=>{ + const signal=init?.signal;let timer; + const cleanup=()=>{clearTimeout(timer);signal?.removeEventListener("abort",abort);pending.delete(id)}; + const cancelRemote=()=>{try{window.beauticodeConsole(JSON.stringify({id:crypto.randomUUID(),path:"/__beauticode/ui/gallery/cancel-request",body:{requestId:id}}))}catch{}}; + const abort=()=>{cleanup();cancelRemote();reject(new DOMException("已取消","AbortError"))}; + timer=setTimeout(()=>{cleanup();cancelRemote();reject(new Error("皮肤中心请求超时,请重新打开查询结果。"))},timeoutMs||45000); + if(signal?.aborted){abort();return;} + signal?.addEventListener("abort",abort,{once:true}); + pending.set(id,{resolve(value){cleanup();resolve(value)},reject(error){cleanup();reject(error)}}); + try{window.beauticodeConsole(JSON.stringify({id,path,method:init?.method||"GET",body}));} + catch(error){cleanup();reject(error);} }); if (payload?.ok === false) { - throw new Error(payload.error || "请求失败"); + throw Object.assign(new Error(payload.error || "请求失败"),{code:payload.code}); } return payload; } async function load() { const generation = ++loadGeneration; + queryAbort?.abort();queryAbort=new AbortController();const signal=queryAbort.signal; msg.textContent = "正在读取目录…"; try { const params = new URLSearchParams(); if (queryInput.value.trim()) params.set("q", queryInput.value.trim()); if (typeSelect.value) params.set("type", typeSelect.value); - const data = await request(`/__beauticode/ui/gallery/catalog?${params}`); + const data = await request(`/__beauticode/ui/gallery/catalog?${params}`,{signal}); if (generation !== loadGeneration || host.hidden) return; centerUrl = data.url || centerUrl; grid.innerHTML = (data.skins || []) @@ -175,7 +182,10 @@ if (host.hidden) returnFocus = document.activeElement; host.hidden = false; focusInside(); - const config = await request("/__beauticode/ui/gallery/config"); + openAbort?.abort();openAbort=new AbortController();const opening=openAbort; + if(operationId){void watchOperation();return;} + let config;try{config=await request("/__beauticode/ui/gallery/config",{signal:opening.signal});}catch(error){if(!opening.signal.aborted)msg.textContent=error.message;return;} + if(opening.signal.aborted||host.hidden)return; centerUrl = config.url || ""; if (!config.enabled) { grid.innerHTML = ""; @@ -189,6 +199,8 @@ function close() { host.hidden = true; loadGeneration += 1; + queryAbort?.abort();openAbort?.abort();polling?.abort(); + if(operationId)void operation('cancel',{operationId}).catch(()=>{}); if (returnFocus?.isConnected) returnFocus.focus(); returnFocus = null; } @@ -210,24 +222,10 @@ const id = card.getAttribute("data-id"); busy = true; msg.textContent = "开始安装…"; - request( - "/__beauticode/ui/gallery/install", - { - method: "POST", - body: JSON.stringify({ id }), - }, - 0, - ) - .then((result) => { - msg.textContent = result.message || "已安装。"; - document.dispatchEvent(new CustomEvent("beauticode-gallery-installed")); - }) - .catch((error) => { - msg.textContent = error instanceof Error ? error.message : String(error); - }) - .finally(() => { - busy = false; - }); + rememberOperation(crypto.randomUUID()); + operation("start",{id,operationId}).then(state=>{rememberOperation(state.id);if(host.hidden)return operation("cancel",{operationId});return watchOperation()}) + .catch(error=>{msg.textContent=error.message;}) + .finally(()=>{if(!polling)busy=false;}); }); // Registered once per page: a console revision change re-runs this file, and // every extra keydown listener would close the same adopted overlay. diff --git a/packages/adapter-codex/src/skin-center.ts b/packages/adapter-codex/src/skin-center.ts index a5e9559..496e185 100644 --- a/packages/adapter-codex/src/skin-center.ts +++ b/packages/adapter-codex/src/skin-center.ts @@ -45,7 +45,7 @@ export async function skinCenterConfig(): Promise<{ export async function skinCenterCatalog(query: { q?: string; type?: string; -}): Promise<{ +}, signal?: AbortSignal): Promise<{ ok: boolean; skins: unknown[]; nextCursor?: unknown; @@ -55,6 +55,7 @@ export async function skinCenterCatalog(query: { try { const type = query.type === "image" || query.type === "video" ? query.type : undefined; const skins = await listApprovedSkins({ + ...(signal ? { signal } : {}), ...(query.q ? { query: { q: query.q, ...(type ? { type } : {}) } } : type ? { query: { type } } : {}), }); return { ok: true, skins, nextCursor: null, url: SKIN_CENTER_ORIGIN }; @@ -81,17 +82,18 @@ function normalizeThemeName(value: unknown, fallback = "主题"): string { export async function installSkinFromCenter( session: BeautiSession, id: string, + operation?: { signal: AbortSignal; beginApply(): void; progress(phase:string): void }, ): Promise<{ ok: boolean; error?: string; theme?: unknown; message?: string }> { if (!isSafeSkinId(id)) return { ok: false, error: "皮肤 ID 无效。" }; const tempDirs: string[] = []; try { - const skin = await getApprovedSkin(id); + const skin = await getApprovedSkin(id, operation ? {signal:operation.signal} : {}); const directory = path.join(session.dataRoot, "tmp", "gallery"); - const image = await downloadApprovedAsset(skin, "image", { directory }); + const image = await downloadApprovedAsset(skin, "image", { directory, ...(operation ? {signal:operation.signal} : {}) }); tempDirs.push(image.tempDir); let video: Awaited> | undefined; if (skin.type === "video") { - video = await downloadApprovedAsset(skin, "video", { directory }); + video = await downloadApprovedAsset(skin, "video", { directory, ...(operation ? {signal:operation.signal} : {}) }); tempDirs.push(video.tempDir); } const provenance = { @@ -116,6 +118,7 @@ export async function installSkinFromCenter( provenance, }; const name = normalizeThemeName(skin.name || id); + operation?.beginApply(); const result = await session.applyAndSaveTheme(input, name); if (!result.ok) return { ok: false, error: result.error || "安装失败。" }; return { diff --git a/packages/adapter-codex/test/gallery-operations.browser.test.js b/packages/adapter-codex/test/gallery-operations.browser.test.js new file mode 100644 index 0000000..e49bc51 --- /dev/null +++ b/packages/adapter-codex/test/gallery-operations.browser.test.js @@ -0,0 +1,28 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +const run=process.env.BEAUTICODE_PLAYWRIGHT_MODULE?test:test.skip; +for(const host of ['codex','dsh'])run(`${host} cancels queries and reconnects to an installation receipt`,async t=>{ + const {chromium}=await import(process.env.BEAUTICODE_PLAYWRIGHT_MODULE),browser=await chromium.launch({channel:'msedge',headless:true});t.after(()=>browser.close());const page=await browser.newPage(); + await page.route('http://127.0.0.1:19409/**',route=>route.fulfill({body:'',contentType:'text/html'}));await page.goto('http://127.0.0.1:19409/'); + await page.evaluate(()=>{ + window.cancelled=0;window.complete=false;window.phase='download';window.calls=[];const controllers=new Map(); + function response(req){ + if(req.path.includes('/config'))return{ok:true,enabled:true,url:''}; + if(req.path.includes('/operation')){const b=req.body;window.calls.push(b.action);if(b.action==='start')return{ok:true,id:'op-fixture'};if(b.action==='cancel'){window.cancelled++;return{ok:true,cancellable:false,message:'正在提交'}};return{ok:true,phase:window.phase,...(window.complete?{result:{ok:true,message:'恢复结果成功'}}:{})};} + return{ok:true,skins:[{id:'skin-abcdefgh',name:'fixture',type:'image'}]}; + } + window.fetch=(url,init={})=>new Promise((resolve,reject)=>{ + const req={path:url,body:JSON.parse(init.body||'null')};const timer=setTimeout(()=>resolve({ok:true,headers:{get:()=> 'application/json'},json:async()=>response(req)}),url.includes('type=image')?250:5); + init.signal?.addEventListener('abort',()=>{clearTimeout(timer);window.cancelled++;reject(new DOMException('aborted','AbortError'))},{once:true}); + }); + window.beauticodeConsole=raw=>{const req=JSON.parse(raw);if(req.path.endsWith('/cancel-request')){const timer=controllers.get(req.body.requestId);if(timer){clearTimeout(timer);controllers.delete(req.body.requestId);window.cancelled++;}return;} + const timer=setTimeout(()=>{controllers.delete(req.id);const p=window.__beauticodeBridgePending.get(req.id);if(p)p.resolve(response(req));},req.path.includes('type=image')?250:5);controllers.set(req.id,timer); + }; + }); + const file=host==='codex'?new URL('../src/renderer/gallery.js',import.meta.url):new URL('../../../integrations/deepseek-harness/gallery.js',import.meta.url);await page.addScriptTag({content:await fs.readFile(file,'utf8')}); + await page.evaluate(()=>window.BeauticodeGallery.open());await page.locator('.bcg-type').selectOption('image');await page.locator('.bcg-type').selectOption('video');await page.waitForFunction(()=>window.cancelled>0); + await page.locator('[data-id="skin-abcdefgh"]').click();await page.waitForFunction(()=>sessionStorage.getItem('beauticode-gallery-operation')==='op-fixture'); + await page.evaluate(()=>{window.phase='apply';window.BeauticodeGallery.close();window.complete=true});await page.evaluate(()=>window.BeauticodeGallery.open()); + await page.waitForFunction(()=>document.querySelector('.bcg-msg').textContent==='恢复结果成功');assert.equal(await page.evaluate(()=>sessionStorage.getItem('beauticode-gallery-operation')),null); +}); diff --git a/packages/core/src/gallery-operations.ts b/packages/core/src/gallery-operations.ts new file mode 100644 index 0000000..61a3c8c --- /dev/null +++ b/packages/core/src/gallery-operations.ts @@ -0,0 +1,32 @@ +import { randomUUID } from 'node:crypto'; + +type Result = { ok: boolean; error?: string; [key: string]: unknown }; +type Entry = { id: string; skinId: string; phase: string; result?: Result; updatedAt: number; controller: AbortController }; + +/** Session-local operation receipts survive renderer disconnects, but never claim durability across a host restart. */ +export function createGalleryOperations({timeoutMs=30*60*1000,ttlMs=15*60*1000,maxEntries=32}={}) { + const entries=new Map(); + function prune(){for(const [id,entry]of entries)if(entry.result&&Date.now()-entry.updatedAt>ttlMs)entries.delete(id);} + function status(id:string){prune();const entry=entries.get(id);return entry?{ok:true,id,skinId:entry.skinId,phase:entry.phase,...(entry.result?{result:entry.result}:{})}:{ok:false,error:'操作记录不存在或已过期,请检查当前背景后重试。',code:'operation_unknown'};} + return { + status, + start(skinId:string,task:(context:{signal:AbortSignal;progress(phase:string):void;beginApply():void})=>Promise, requestedId?: string) { + prune(); + if(requestedId && !/^[a-zA-Z0-9-]{16,80}$/.test(requestedId))return {ok:false,error:'无效的操作编号。'}; + if(requestedId && entries.has(requestedId)){const existing=entries.get(requestedId)!;return existing.skinId===skinId?status(requestedId):{ok:false,error:'操作编号已用于其他皮肤。'};} + const active=[...entries.values()].find(e=>!e.result); + if(active)return !requestedId && active.skinId===skinId?status(active.id):{ok:false,error:'已有皮肤操作正在进行,请等待或取消。'}; + while(entries.size>=maxEntries)entries.delete(entries.keys().next().value!); + const entry:Entry={id:requestedId||randomUUID(),skinId,phase:'download',updatedAt:Date.now(),controller:new AbortController()}; + entries.set(entry.id,entry); + const timer=setTimeout(()=>{if(entry.phase!=='apply')entry.controller.abort();},timeoutMs); + timer.unref?.(); + const update=(phase:string)=>{entry.phase=phase;entry.updatedAt=Date.now();}; + void Promise.resolve().then(()=>{entry.controller.signal.throwIfAborted();return task({signal:entry.controller.signal,progress:update,beginApply(){entry.controller.signal.throwIfAborted();update('apply');}})}).then(result=>{ + entry.result=result;update(result.ok?'done':entry.controller.signal.aborted?'cancelled':'failed'); + },error=>{entry.result={ok:false,error:entry.controller.signal.aborted?'下载已取消或超时。':error instanceof Error?error.message:String(error)};update(entry.controller.signal.aborted?'cancelled':'failed');}).finally(()=>clearTimeout(timer)); + return status(entry.id); + }, + cancel(id:string){const entry=entries.get(id);if(!entry)return status(id);if(entry.result)return status(id);if(entry.phase==='apply')return {...status(id),cancellable:false,message:'正在提交背景,无法中断;可关闭后重新打开查询结果。'};entry.controller.abort();return {...status(id),cancellable:true};}, + }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 231380a..5cdcdfe 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -16,6 +16,7 @@ export { export * from "./file-lock.js"; export * from "./error-message.js"; export * from "./media-health.js"; +export * from "./gallery-operations.js"; export * from "./background-store.js"; export * from "./bundled-gallery.js"; export * from "./apply-transaction.js"; diff --git a/packages/core/src/skin-catalog.ts b/packages/core/src/skin-catalog.ts index d5a1c13..1294771 100644 --- a/packages/core/src/skin-catalog.ts +++ b/packages/core/src/skin-catalog.ts @@ -231,13 +231,14 @@ async function fetchJson( target: URL, maxBytes: number, fetchImpl: FetchImpl, + signal?: AbortSignal, ): Promise { let response: Response; try { response = await fetchImpl(target, { redirect: "error", headers: { accept: "application/json" }, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]) : AbortSignal.timeout(REQUEST_TIMEOUT_MS), }); } catch (error) { if (error instanceof SkinCatalogError) throw error; @@ -262,21 +263,23 @@ async function fetchJson( export async function listApprovedSkins(options: { query?: { q?: string; type?: "image" | "video" }; fetchImpl?: FetchImpl; + signal?: AbortSignal; } = {}): Promise { const target = requestUrl("/api/catalog", options.query); - const body = await fetchJson(target, CATALOG_MAX_BYTES, options.fetchImpl ?? fetch); + const body = await fetchJson(target, CATALOG_MAX_BYTES, options.fetchImpl ?? fetch, options.signal); return parseApprovedSkinCatalog(body); } export async function getApprovedSkin( id: string, - options: { fetchImpl?: FetchImpl } = {}, + options: { fetchImpl?: FetchImpl; signal?: AbortSignal } = {}, ): Promise { assertSafeSkinId(id); const body = await fetchJson( requestUrl(`/api/skins/${id}`), METADATA_MAX_BYTES, options.fetchImpl ?? fetch, + options.signal, ); const object = assertObject(body, "Skin metadata is malformed."); return parseApprovedSkin(object.skin ?? object); diff --git a/packages/core/test/gallery-operations.test.js b/packages/core/test/gallery-operations.test.js new file mode 100644 index 0000000..a9e82ca --- /dev/null +++ b/packages/core/test/gallery-operations.test.js @@ -0,0 +1,36 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createGalleryOperations} from '../dist/index.js'; +const wait=()=>new Promise(r=>setTimeout(r,5)); + +test('operation receipt survives disconnect, cancel stops downloads, atomic apply is queryable',async()=>{ + const ops=createGalleryOperations();let applied=false; + const first=ops.start('a',async({signal,beginApply})=>{await new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}));beginApply();applied=true;return{ok:true}}); + await wait();assert.equal(ops.cancel(first.id).cancellable,true);await wait();assert.equal(ops.status(first.id).phase,'cancelled');assert.equal(applied,false); + let finish;const gate=new Promise(r=>{finish=r}); + const second=ops.start('b',async({beginApply})=>{beginApply();await gate;return{ok:true,message:'done'}}); + await wait();assert.equal(ops.start('b', async () => ({ok:true}), 'second-client-operation').ok, false); + assert.equal(ops.cancel(second.id).cancellable,false);assert.equal(ops.status(second.id).phase,'apply'); + assert.equal(ops.start('other',async()=>({ok:true})).ok,false); + finish();await wait();assert.equal(ops.status(second.id).result.ok,true);assert.equal(ops.status('not-there').code,'operation_unknown'); +}); +test('download deadline and receipt capacity are bounded',async()=>{ + const ops=createGalleryOperations({timeoutMs:10,maxEntries:2}); + const first=ops.start('a',async({signal})=>{await new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}));return{ok:true}}); + await new Promise(r=>setTimeout(r,25));assert.equal(ops.status(first.id).phase,'cancelled'); + const second=ops.start('b',async()=>({ok:true}));await wait();ops.start('c',async()=>({ok:true}));await wait(); + assert.equal(ops.status(first.id).ok,false);assert.equal(ops.status(second.id).result.ok,true); +}); + +test('client operation ID recovers a lost start response and prevents duplicate apply',async()=>{ + const ops=createGalleryOperations();let calls=0;const id='client-operation-12345'; + ops.start('a',async()=>{calls++;return{ok:true}},id);await wait(); + assert.equal(ops.status(id).result.ok,true); + assert.equal(ops.start('a',async()=>{calls++;return{ok:true}},id).result.ok,true); + assert.equal(calls,1);assert.equal(ops.start('other',async()=>({ok:true}),id).ok,false); +}); +test('cancel before task dispatch cannot start a download',async()=>{ + const ops=createGalleryOperations();let calls=0; + const entry=ops.start('a',async()=>{calls++;return{ok:true}});ops.cancel(entry.id);await wait(); + assert.equal(calls,0);assert.equal(ops.status(entry.id).phase,'cancelled'); +});