Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 60 additions & 1 deletion integrations/deepseek-harness/gallery-host.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { pipeline } from "node:stream/promises";
import { fileURLToPath } from "node:url";
import {
SKIN_CENTER_ORIGIN,
createGalleryOperations,
downloadApprovedAsset,
getApprovedSkin,
listApprovedSkins,
Expand Down Expand Up @@ -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();
Expand All @@ -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,
Expand Down
61 changes: 42 additions & 19 deletions integrations/deepseek-harness/gallery.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -95,14 +122,15 @@
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")) {
return readNdjson(response);
}
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;
}
Expand Down Expand Up @@ -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 || [])
Expand All @@ -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 = "尚未配置皮肤中心地址。";
Expand All @@ -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;
}
Expand All @@ -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) {
Expand Down
5 changes: 5 additions & 0 deletions integrations/deepseek-harness/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
23 changes: 23 additions & 0 deletions integrations/deepseek-harness/test/gallery-operation.test.mjs
Original file line number Diff line number Diff line change
@@ -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');
});
1 change: 1 addition & 0 deletions integrations/deepseek-harness/ui-host.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
},
Expand Down
15 changes: 13 additions & 2 deletions packages/adapter-codex/src/console-host.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -31,6 +31,8 @@ function applyFailure(result: { error: string; rolledBack?: boolean }) {
export function createConsoleHost(session: BeautiSession) {
const selections = new Map<string, PendingSelection>();
let pickerBusy = false;
const galleryOperations = createGalleryOperations();
const queries = new Map<string,AbortController>();

function publicThemes() {
return session.listSavedThemes().then((list) =>
Expand Down Expand Up @@ -69,6 +71,12 @@ export function createConsoleHost(session: BeautiSession) {
request.body && typeof request.body === "object" && !Array.isArray(request.body)
? (request.body as Record<string, unknown>)
: {};
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")) {
Expand All @@ -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() : "";
Expand Down
Loading
Loading