Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

发布 1.18.16,完成 Skill 分享与创作流程闭环

MigenAI9d9e253cb842
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1ee15da..477f1b1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,22 @@
# Changelog
+## 1.18.16
+
+- 统一创作 Skill、精选 Skill 与创作台参考区的分段导航和卡片密度,去除多余空白、整卡高亮与页面间的尺寸漂移。
+- 精选 Skill 列表只突出名称、用途和保存操作;版本与许可移入详情折叠区,重复的正文标题不再重复显示。
+- 精选 Skill 支持从列表直接安全保存,并明确区分首次保存、同版已保存、新版本另存与校验过程。
+
+## 1.18.15
+
+- 精选 Skill 目录与投稿保留用户可读调用名,稳定公开 ID 继续独立用于版本识别;保存到本地后不再显示内部 `creative-skill-*` 编号。
+
+## 1.18.14
+
+- 精选 Skill 新增独立目录、手动投稿与本地保存流程;投稿只需公开署名、自动摘要和开放确认,维护字段移到人工审核阶段。
+- 精选案例与精选 Skill 统一深浅色、导航、按钮和空态;公共目录先行上线,空目录不再误报 404。
+- 图片分析支持把动态发现的模型手动分配给 DeepSeek;修复 JSON 视觉 Schema 断链、空响应原因不明以及 `OCR` 根字段大小写漂移。
+- 跨设备备份改为严格手动执行,未变化时零写入,重复启动合并为同一任务,取消后停止并回滚未完成写入。
+
## 1.18.13
- 项目排序时不再误选文字,案例选择期间排序入口保持原位并以禁用状态表达互斥关系。
diff --git a/ai-provider-module.js b/ai-provider-module.js
index c904d2e..0a1c3f3 100644
--- a/ai-provider-module.js
+++ b/ai-provider-module.js
@@ -55,7 +55,7 @@ export function createAiProviderModule(options = {}) {
discoveredAt: new Date().toISOString(),
models: mergeModels(discovery.models, configuredModels(profile).map((model) => ({
...model,
- status: discovery.models?.length && !discovery.models.some((item) => item.id === model.id) && !profile.id.startsWith("custom")
+ status: Array.isArray(discovery.models) && !discovery.models.some((item) => item.id === model.id) && !profile.id.startsWith("custom")
? "unavailable"
: model.status
}))),
@@ -111,12 +111,20 @@ async function discoverIdentityModels(fetchImpl, profile, cache) {
const response = await modelRequest(fetchImpl, url, profile, cache);
if (response.notModified) return response;
const list = requiredArrayFrom(response.payload, `${profile.id} 返回了当前版本尚未适配的模型列表结构`, "data", "models");
- const preset = getAiProviderPreset(profile.id);
- const protocolDeclared = preset?.discovery?.adapter === "identity" && preset.category !== "custom";
- const confidence = protocolDeclared ? "protocol_inferred" : "manual_unverified";
- const tasks = protocolDeclared ? TEXT_TASKS : [];
return {
- models: list.map((item) => modelDescriptor(item, { confidence, tasks, source: "provider_models" })),
+ models: list.map((item) => {
+ const architecture = item?.architecture && typeof item.architecture === "object" ? item.architecture : item;
+ const inputModalities = normalizeModalities(architecture.input_modalities ?? architecture.inputModalities);
+ const outputModalities = normalizeModalities(architecture.output_modalities ?? architecture.outputModalities);
+ const hasDeclaredModalities = inputModalities.length > 0 && outputModalities.length > 0;
+ return modelDescriptor(item, {
+ confidence: hasDeclaredModalities ? "declared" : "manual_unverified",
+ tasks: hasDeclaredModalities ? tasksFromModalities(inputModalities, outputModalities) : [],
+ inputModalities,
+ outputModalities,
+ source: "provider_models"
+ });
+ }),
cache: response.cache,
source: "provider_models"
};
diff --git a/ai-provider-presets.js b/ai-provider-presets.js
index 0a2b7cc..7713e49 100644
--- a/ai-provider-presets.js
+++ b/ai-provider-presets.js
@@ -17,7 +17,8 @@ export const AI_PROVIDER_PRESETS = Object.freeze([
endpoint: "https://api.deepseek.com/chat/completions",
protocol: "chat_completions",
discovery: { adapter: "identity" },
- capabilities: TEXT_CAPABILITIES
+ capabilities: [...TEXT_CAPABILITIES, "imageAnalysis"],
+ structuredOutput: "json_object"
}),
preset({
id: "openai",
diff --git a/ai-provider-registry.js b/ai-provider-registry.js
index af16ca9..7f94d3c 100644
--- a/ai-provider-registry.js
+++ b/ai-provider-registry.js
@@ -15,6 +15,11 @@ const CUSTOM_PROVIDER_LABELS = Object.freeze({
"custom-media": "自定义兼容服务(图片与生成)"
});
+const ASSIGNMENT_EVIDENCE = new Set(["declared", "protocol_inferred", "manual_unverified"]);
+const MANUAL_ASSIGNMENT_TASKS = new Set([
+ "textTags", "skillExtraction", "creativePlanning", "imageAnalysis", "videoAnalysis"
+]);
+
export function normalizeAiProviderRegistry(value = {}) {
const source = value?.providers && typeof value.providers === "object" ? value.providers : {};
const providers = {};
@@ -31,11 +36,19 @@ export function normalizeAiProviderRegistry(value = {}) {
return { version: 4, providers };
}
-export function normalizeAiTaskAssignments(value = {}) {
+export function normalizeAiTaskAssignments(value = {}, registryValue = {}) {
return Object.fromEntries(AI_ASSIGNMENT_TASKS.map((task) => {
const candidate = value?.[task.id];
const source = candidate && typeof candidate === "object" ? candidate : {};
- return [task.id, { providerId: clean(source.providerId), model: clean(source.model) }];
+ const assignment = { providerId: clean(source.providerId), model: clean(source.model) };
+ const profile = registryValue?.providers?.[assignment.providerId];
+ const discovered = profile?.discoveredModels?.find((model) => model.id === assignment.model);
+ const inferredEvidence = discovered ? modelAssignmentEvidence(task.id, discovered, profile) : "";
+ const evidence = ASSIGNMENT_EVIDENCE.has(source.evidence)
+ ? source.evidence
+ : inferredEvidence === "manual_unverified" ? inferredEvidence : "";
+ if (evidence) assignment.evidence = evidence;
+ return [task.id, assignment];
}));
}
@@ -49,6 +62,7 @@ export function publicAiProviderRegistry(value = {}) {
category: profile.category,
endpoint: profile.endpoint,
protocol: profile.protocol,
+ structuredOutput: profile.structuredOutput,
models: structuredClone(profile.models),
capabilities: [...profile.capabilities],
catalogRequiredTasks: [...profile.catalogRequiredTasks],
@@ -70,19 +84,75 @@ export function availableAiProvidersForTask(taskId, value = {}) {
).map((profile) => ({ id: profile.id, label: profile.label, model: profile.models[taskId] }));
}
+export function availableAiModelsForTask(taskId, profileValue = {}) {
+ requireTask(taskId);
+ const profile = provider(clean(profileValue?.id), profileValue);
+ if (!profile.capabilities.includes(taskId)) return [];
+ const available = profile.discoveredModels.flatMap((model) => {
+ if (model.status === "unavailable") return [];
+ const assignmentEvidence = modelAssignmentEvidence(taskId, model, profile);
+ return assignmentEvidence ? [{ ...structuredClone(model), assignmentEvidence }] : [];
+ });
+ const configuredModel = taskId === "imageGeneration"
+ ? clean(profile.models.imageGeneration) || clean(profile.imageGeneration?.model)
+ : taskId === "videoGeneration"
+ ? clean(profile.models.videoGeneration) || clean(profile.videoGeneration?.model)
+ : clean(profile.models[taskId]);
+ if (!available.length && !profile.discovery.discoveredAt && configuredModel) {
+ return [{
+ id: configuredModel,
+ name: configuredModel,
+ status: "available",
+ confidence: "manual_unverified",
+ tasks: [],
+ inputModalities: [],
+ outputModalities: [],
+ assignmentEvidence: "manual_unverified"
+ }];
+ }
+ return available;
+}
+
+export function createAiTaskAssignment(taskId, providerIdValue, modelValue, registryValue = {}) {
+ requireTask(taskId);
+ const registry = normalizeAiProviderRegistry(registryValue);
+ const providerId = clean(providerIdValue);
+ const model = clean(modelValue);
+ const profile = registry.providers[providerId];
+ if (!profile) throw new Error("所选 AI 服务不存在");
+ const taskLabel = taskName(taskId);
+ if (!profile.capabilities.includes(taskId)) throw new Error(`${profile.label} 的协议不支持${taskLabel}`);
+ if (!model) throw new Error(`${taskLabel}尚未选择模型`);
+ const discovered = profile.discoveredModels.find((item) => item.id === model);
+ if (!discovered) {
+ const configured = availableAiModelsForTask(taskId, profile).some((item) => item.id === model);
+ if (configured) return { providerId, model, evidence: "manual_unverified" };
+ throw new Error(`${profile.label} 的当前模型目录中没有该模型`);
+ }
+ if (discovered.status === "unavailable") throw new Error(`${profile.label} 中已选模型已下架或当前账号不可用,请重新选择`);
+ const evidence = modelAssignmentEvidence(taskId, discovered, profile);
+ if (!evidence) throw new Error(`${profile.label} 模型目录声明该模型不支持${taskLabel}`);
+ return { providerId, model, evidence };
+}
+
export function resolveAiProviderAssignment(taskId, registryValue = {}, assignmentsValue = {}) {
- if (!AI_ASSIGNMENT_TASKS.some((task) => task.id === taskId)) throw new Error("未知 AI 任务");
+ requireTask(taskId);
const registry = normalizeAiProviderRegistry(registryValue);
const raw = assignmentsValue?.[taskId] ?? {};
const providerId = clean(raw.providerId);
if (!providerId) throw new Error(`${AI_ASSIGNMENT_TASKS.find((task) => task.id === taskId)?.label || taskId}尚未分配 AI 服务`);
const profile = registry.providers[providerId];
if (!profile) throw new Error("所选 AI 服务不存在");
- const taskLabel = AI_ASSIGNMENT_TASKS.find((task) => task.id === taskId)?.label || taskId;
- if (!profile.capabilities.includes(taskId)) throw new Error(`${profile.label} 不支持${taskLabel}`);
+ const taskLabel = taskName(taskId);
+ if (!profile.capabilities.includes(taskId)) throw new Error(`${profile.label} 的协议不支持${taskLabel}`);
const model = clean(raw.model);
const discovered = profile.discoveredModels.find((item) => item.id === model);
+ if (!discovered && profile.discovery.discoveredAt) {
+ throw new Error(`${profile.label} 的当前模型目录中没有该模型,请重新选择`);
+ }
if (discovered?.status === "unavailable") throw new Error(`${profile.label} 中已选模型已下架或当前账号不可用,请重新选择`);
+ const evidence = discovered ? modelAssignmentEvidence(taskId, discovered, profile) : "manual_unverified";
+ if (discovered && !evidence) throw new Error(`${profile.label} 模型目录声明该模型不支持${taskLabel}`);
if (!providerConfiguredForTask(profile, taskId, model) || !model) throw new Error(`${profile.label} 尚未完成${taskLabel}配置`);
return { taskId, providerId, provider: profile.label, model };
}
@@ -134,6 +204,7 @@ function provider(id, value = {}) {
category: preset?.category ?? "custom",
endpoint: clean(value?.endpoint) || preset?.endpoint || "",
protocol: clean(value?.protocol) || preset?.protocol || "native",
+ structuredOutput: normalizeStructuredOutput(preset?.structuredOutput ?? value?.structuredOutput),
apiKey: clean(value?.apiKey),
credentialConfigured: Object.hasOwn(value ?? {}, "apiKey")
? Boolean(clean(value?.apiKey) || isLoopback(value?.endpoint))
@@ -207,7 +278,7 @@ function providerConfiguredForTask(profile, taskId, selectedModel = "") {
: profile.apiKey;
const configuredModel = clean(selectedModel) || profile.models[taskId];
const discoveredCandidate = profile.discoveredModels.some((item) =>
- item.status !== "unavailable" && item.tasks.includes(taskId)
+ item.status !== "unavailable" && Boolean(modelAssignmentEvidence(taskId, item, profile))
);
const discovered = profile.discoveredModels.find((item) => item.id === configuredModel);
const catalogRequired = profile.catalogRequiredTasks.includes(taskId);
@@ -217,14 +288,43 @@ function providerConfiguredForTask(profile, taskId, selectedModel = "") {
return Boolean(
(catalogRequired
? clean(selectedModel)
- ? discovered?.status !== "unavailable" && discovered?.tasks.includes(taskId)
+ ? discovered?.status !== "unavailable" && Boolean(modelAssignmentEvidence(taskId, discovered, profile))
: discoveredCandidate
- : configuredModel || discoveredCandidate)
+ : (configuredModel && (!discovered || Boolean(modelAssignmentEvidence(taskId, discovered, profile)))) || discoveredCandidate)
&& discovered?.status !== "unavailable"
&& (key || savedCredential || isLoopback(endpoint))
);
}
+function modelAssignmentEvidence(taskId, model = {}, profile = null) {
+ if ((model.tasks ?? []).includes(taskId)) {
+ return ASSIGNMENT_EVIDENCE.has(model.confidence) ? model.confidence : "declared";
+ }
+ if (model.confidence === "manual_unverified"
+ && (model.inputModalities ?? []).length === 0 && (model.outputModalities ?? []).length === 0) {
+ if (MANUAL_ASSIGNMENT_TASKS.has(taskId)) return "manual_unverified";
+ const configuredGenerationModel = taskId === "imageGeneration"
+ ? clean(profile?.models?.imageGeneration) || clean(profile?.imageGeneration?.model)
+ : taskId === "videoGeneration" ? clean(profile?.models?.videoGeneration) || clean(profile?.videoGeneration?.model) : "";
+ if (!profile?.discovery?.discoveredAt && configuredGenerationModel === clean(model.id)) {
+ return "manual_unverified";
+ }
+ }
+ return "";
+}
+
+function normalizeStructuredOutput(value) {
+ return value === "json_object" ? "json_object" : "json_schema";
+}
+
+function taskName(taskId) {
+ return AI_ASSIGNMENT_TASKS.find((task) => task.id === taskId)?.label || taskId;
+}
+
+function requireTask(taskId) {
+ if (!AI_ASSIGNMENT_TASKS.some((task) => task.id === taskId)) throw new Error("未知 AI 任务");
+}
+
function requiresDedicatedImageCredential(profile = {}) {
if (profile.imageGeneration?.protocol !== "images_generations") return false;
try {
diff --git a/ai-runtime.js b/ai-runtime.js
index f7e557f..9496137 100644
--- a/ai-runtime.js
+++ b/ai-runtime.js
@@ -8,7 +8,7 @@ import {
const TEXT_TASKS = new Set(["textTags", "skillExtraction", "creativePlanning"]);
-export const AI_RUNTIME_PROTOCOL_VERSION = 1;
+export const AI_RUNTIME_PROTOCOL_VERSION = 2;
export function requireAiRuntimeProtocolVersion(value) {
if (Number(value) !== AI_RUNTIME_PROTOCOL_VERSION) {
@@ -51,33 +51,46 @@ export function projectAiRuntime(configurationValue = {}) {
const { registry, assignments, preferences } = configuration;
const providers = registry.providers;
const planning = settingsForTextAssignment(assignments.creativePlanning, providers, preferences, false);
- const openai = providers.openai;
- const compatible = providers["custom-media"];
const imageAnalysis = assignments.imageAnalysis;
+ const imageAnalysisProfile = providers[imageAnalysis.providerId] ?? providers["custom-media"];
+ const imageAnalysisUsesOpenAi = imageAnalysis.providerId === "openai";
+ const openai = providers.openai;
+ const customMedia = providers["custom-media"];
const vision = normalizeVisionSettings({
- activeProvider: imageAnalysis.providerId === "custom-media" ? "compatible" : "openai",
+ activeProvider: imageAnalysisUsesOpenAi ? "openai" : "compatible",
consent: true,
autoAnalyzeImports: preferences.autoAnalyzeImports,
instructionsByLocale: preferences.visionInstructionsByLocale,
openai: {
- model: assignments.imageAnalysis.providerId === "openai" ? assignments.imageAnalysis.model : "",
+ model: imageAnalysisUsesOpenAi
+ ? assignments.imageAnalysis.model
+ : openai?.models?.imageAnalysis || openai?.models?.imageGeneration || "",
apiKey: usableKey(openai),
videoGeneration: {
- ...(openai?.videoGeneration ?? {}),
+ ...(providers.openai?.videoGeneration ?? {}),
model: assignments.videoGeneration.providerId === "openai" ? assignments.videoGeneration.model : ""
}
},
compatible: {
- protocol: compatible?.protocol,
- endpoint: compatible?.endpoint,
- model: assignments.imageAnalysis.providerId === "custom-media" ? assignments.imageAnalysis.model : "",
- apiKey: usableKey(compatible),
+ protocol: imageAnalysisProfile?.protocol === "responses" ? "responses" : "chat_completions",
+ structuredOutput: imageAnalysisProfile?.structuredOutput,
+ endpoint: clean(imageAnalysis?.providerId) ? chatEndpoint(imageAnalysisProfile) : "",
+ model: !imageAnalysisUsesOpenAi ? assignments.imageAnalysis.model : "",
+ apiKey: !imageAnalysisUsesOpenAi ? usableKey(imageAnalysisProfile) : "",
imageGeneration: {
- ...(compatible?.imageGeneration ?? {}),
- model: assignments.imageGeneration.providerId === "custom-media" ? assignments.imageGeneration.model : "",
- apiKey: usableKey(compatible, true, "imageGeneration")
+ ...(customMedia?.imageGeneration ?? {}),
+ model: assignments.imageGeneration.providerId === "custom-media"
+ ? assignments.imageGeneration.model
+ : customMedia?.models?.imageGeneration || customMedia?.imageGeneration?.model || "",
+ apiKey: usableKey(customMedia, true, "imageGeneration")
}
- }
+ },
+ nativeProvider: imageAnalysis.providerId === "gemini" ? {
+ id: "gemini",
+ endpoint: imageAnalysisProfile.endpoint,
+ apiKey: imageAnalysisProfile.apiKey,
+ model: imageAnalysis.model
+ } : null
});
if (!clean(imageAnalysis?.providerId)) {
vision.activeProvider = "compatible";
@@ -86,20 +99,21 @@ export function projectAiRuntime(configurationValue = {}) {
vision.compatible.model = "";
}
const xai = providers.xai;
+ const xaiRuntime = {
+ apiKey: usableKey(xai),
+ textModel: assignments.creativePlanning.providerId === "xai" ? assignments.creativePlanning.model : "",
+ imageModel: assignments.imageGeneration.providerId === "xai"
+ ? assignments.imageGeneration.model
+ : assignments.imageAnalysis.providerId === "xai" ? assignments.imageAnalysis.model : "",
+ videoModel: assignments.videoGeneration.providerId === "xai" ? assignments.videoGeneration.model : "",
+ mediaConsent: xai?.consent === true
+ };
return {
aiSettings: planning,
visionSettings: {
...vision,
providerProfiles: providers,
- xai: {
- apiKey: usableKey(xai),
- textModel: assignments.creativePlanning.providerId === "xai" ? assignments.creativePlanning.model : "",
- imageModel: assignments.imageGeneration.providerId === "xai"
- ? assignments.imageGeneration.model
- : assignments.imageAnalysis.providerId === "xai" ? assignments.imageAnalysis.model : "",
- videoModel: assignments.videoGeneration.providerId === "xai" ? assignments.videoGeneration.model : "",
- mediaConsent: xai?.consent === true
- }
+ xai: xaiRuntime
},
aiServiceProfiles: {
gemini: {
@@ -168,6 +182,7 @@ export function resolveVisionTaskSettings(taskId, configurationValue = {}, optio
},
compatible: {
protocol: profile.protocol === "responses" ? "responses" : "chat_completions",
+ structuredOutput: profile.structuredOutput,
endpoint,
model: resolved.model,
apiKey: openai ? "" : profile.apiKey,
diff --git a/background.js b/background.js
index 22c991d..d210aac 100644
--- a/background.js
+++ b/background.js
@@ -166,8 +166,7 @@ import {
retryLibraryMaintenanceFailures
} from "./library-maintenance.js";
import {
- commitMetadataThenDeleteImages,
- replaceImagesWithRollback
+ commitMetadataThenDeleteImages
} from "./image-transaction.js";
import { createEntrySaveUndo, normalizeLastSaveUndo, restoreScreenshotSaveEntry } from "./save-history.js";
import {
@@ -262,6 +261,7 @@ import {
import { PAGE_CAPTURE_LIMITS, PAGE_CAPTURE_QUALITY_LIMITS, PORTABLE_LIBRARY_LIMITS } from "./resource-limits.js";
import { publicAiServiceProfiles } from "./ai-service-profiles.js";
import {
+ availableAiModelsForTask,
availableAiProvidersForTask,
mergeAiProviderRegistry,
normalizeAiTaskAssignments,
@@ -319,24 +319,16 @@ import {
} from "./creative-runs.js";
import { mergeCreativeExperimentPackage } from "./creative-experiment-package.js";
import {
- attachSyncImageReferences,
- collectSyncImageReferences,
- createRevisionSnapshot,
- mergeRevisionSnapshots,
+ markSyncMetaDirty,
+ normalizeSyncMeta,
normalizeSyncSettings,
- syncErrorDetails,
- syncStateHasContent,
- SYNC_SNAPSHOT_FORMAT,
- SYNC_SNAPSHOT_VERSION
+ syncErrorDetails
} from "./sync-model.js";
import {
createOrUnlockSyncVault,
- listSyncSnapshots,
- openSyncVaultWithKey,
- readSyncObject,
- writeSyncObject,
- writeSyncSnapshot
+ openSyncVaultWithKey
} from "./sync-vault.js";
+import { createManualSyncController } from "./manual-sync.js";
import {
clearSyncPrivateState,
getSyncCryptoKey,
@@ -406,7 +398,6 @@ const OFFSCREEN_DOCUMENT_PATH = "offscreen.html";
const DOWNLOAD_TIMEOUT_MS = 30_000;
let writeQueue = Promise.resolve();
let captureWriteQueue = Promise.resolve();
-let automaticSyncScheduled = false;
let creatingOffscreenDocument = null;
let visionAnalysisInFlight = false;
const aiProviderModule = createAiProviderModule();
@@ -425,9 +416,20 @@ const VIDEO_ANALYSIS_ADAPTERS = Object.freeze({
openrouter: analyzeVideoWithOpenRouter
});
let activePageCapture = null;
-let syncInFlight = null;
let syncApplyInProgress = false;
-let syncIdleTimer = null;
+const manualSyncController = createManualSyncController({
+ readState,
+ readMeta: async () => {
+ const stored = await chrome.storage.local.get(STORAGE_KEYS.syncMeta);
+ return stored[STORAGE_KEYS.syncMeta];
+ },
+ readMedia: getMediaBlob,
+ writeMedia: saveMediaBlob,
+ deleteMedia: deleteMediaBlob,
+ commit: commitManualSyncResult,
+ onProgress: notifySyncProgress,
+ onStatus: notifySyncProgress
+});
let maintenanceRunnerActive = false;
let maintenanceRunnerTimer = 0;
let automaticVisionRunnerActive = false;
@@ -454,7 +456,7 @@ chrome.runtime.onInstalled.addListener(async (details) => {
await chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: false });
const state = await readState();
- await commitLocalChanges({ [STORAGE_KEYS.settings]: state.settings });
+ await commitLocalChanges({ [STORAGE_KEYS.settings]: state.settings }, { markSyncDirty: false });
await migrateLegacyScreenshots(state.entries);
});
@@ -538,17 +540,24 @@ function openCreativeResultSidePanel(message, sender) {
async function handleMessage(message, interaction = {}) {
switch (message?.type) {
case "GET_STATE": {
- const stateRead = enqueue(async () => ({ ok: true, ...publicLibraryState(await readState()) }));
- scheduleAutomaticSync();
- return stateRead;
+ return enqueue(async () => ({ ok: true, ...publicLibraryState(await readState()) }));
}
case "GET_FOLDER_BACKUP_STATE":
return enqueue(async () => ({ ok: true, ...folderBackupState(await readState()) }));
case "GET_CAPTURE_WORKSPACE":
- scheduleAutomaticSync();
return enqueueCapture(async () => captureWorkspace());
case "GET_DATA_SAFETY_STATUS":
return enqueue(async () => dataSafetyStatus(await readState()));
+ case "GET_SYNC_RUN_STATUS":
+ return Promise.resolve({ ok: true, syncStatus: manualSyncController.status() });
+ case "CANCEL_SYNC": {
+ const cancelRequested = manualSyncController.cancel();
+ return Promise.resolve({
+ ok: true,
+ cancelRequested,
+ message: cancelRequested ? "正在停止本次同步" : "当前没有正在运行的同步"
+ });
+ }
case "GET_EXTENSION_UPDATE_STATUS":
return extensionUpdateLifecycle.getStatus()
.then((status) => ({ ok: true, status }));
@@ -566,7 +575,7 @@ async function handleMessage(message, interaction = {}) {
case "UNLOCK_SYNC_VAULT":
return enqueue(async () => unlockSyncVault(message.password));
case "SYNC_NOW":
- return enqueue(async () => synchronizeNow("manual"));
+ return enqueue(async () => performManualSynchronization((input) => manualSyncController.start(input)));
case "DISCONNECT_SYNC_FOLDER":
return enqueue(async () => disconnectSyncFolder());
case "UPDATE_CAPTURE_DRAFT":
@@ -2506,7 +2515,10 @@ async function undoLastSave() {
}
const entries = state.entries.map((item) => item.id === updated.id ? updated : item);
try {
- await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
+ await commitLocalChanges(
+ { [STORAGE_KEYS.entries]: entries },
+ { dirtyAssetIds: [current.id] }
+ );
} catch (error) {
if (replacedScreenshot) await saveScreenshotBlob(current.id, replacedScreenshot).catch(() => undefined);
if (restoredScreenshot) {
@@ -2798,7 +2810,7 @@ async function readState() {
const locale = resolveLocale(uiPreferences, chrome.i18n.getUILanguage());
const composerSessions = normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions]);
if (JSON.stringify(stored[STORAGE_KEYS.composerSessions] ?? []) !== JSON.stringify(composerSessions)) {
- await commitLocalChanges({ [STORAGE_KEYS.composerSessions]: composerSessions });
+ await commitLocalChanges({ [STORAGE_KEYS.composerSessions]: composerSessions }, { markSyncDirty: false });
}
const creativeRuns = normalizeCreativeRuns(stored[STORAGE_KEYS.creativeRuns]);
const creativeJobs = normalizeCreativeJobsState(stored[STORAGE_KEYS.creativeJobs]);
@@ -2825,7 +2837,7 @@ async function readState() {
[STORAGE_KEYS.creativeJobs]: creativeJobs,
[STORAGE_KEYS.creativeExperimentSettings]: creativeExperimentSettings,
[STORAGE_KEYS.activeCreativeResult]: activeCreativeResult
- });
+ }, { markSyncDirty: false });
}
const storedBatchJob = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
const textBatchSummary = storedBatchJob?.kind === "text_tags"
@@ -4419,7 +4431,13 @@ async function discoverAiProviderModels(providerIdValue, force = false) {
if (!profile.endpoint || !profile.apiKey) throw new Error(`${profile.label} 需要先保存接口地址和 API Key`);
let result;
try {
- result = await aiProviderModule.discoverModels(profile, {
+ result = await aiProviderModule.discoverModels({
+ ...profile,
+ models: {
+ ...profile.models,
+ ...assignedModelsForProvider(configuration.assignments, providerId)
+ }
+ }, {
etag: force ? "" : profile.discovery?.etag
});
} catch (error) {
@@ -4461,6 +4479,12 @@ async function discoverAiProviderModels(providerIdValue, force = false) {
});
}
+function assignedModelsForProvider(assignments = {}, providerId = "") {
+ return Object.fromEntries(Object.entries(assignments).flatMap(([taskId, assignment]) =>
+ assignment?.providerId === providerId && assignment.model ? [[taskId, assignment.model]] : []
+ ));
+}
+
function sameProviderConnection(current, requested) {
return Boolean(current
&& current.endpoint === requested.endpoint
@@ -4549,9 +4573,7 @@ function aiTaskProviderOptions(taskId, configuration) {
const profile = configuration.registry.providers[provider.id];
const models = [...new Set([
profile?.models?.[taskId],
- ...(profile?.discoveredModels ?? [])
- .filter((model) => model.status !== "unavailable" && model.tasks.includes(taskId))
- .map((model) => model.id)
+ ...availableAiModelsForTask(taskId, profile).map((model) => model.id)
].filter(Boolean))];
return { id: provider.id, label: provider.label, models };
});
@@ -4582,7 +4604,12 @@ function aiTaskRuntimeDescriptor(taskId, configuration) {
async function getComposerAiRuntime() {
const configuration = await loadAiConfiguration();
- return { ok: true, aiRuntimeProtocolVersion: AI_RUNTIME_PROTOCOL_VERSION, ...projectAiRuntime(configuration) };
+ const runtime = projectAiRuntime(configuration);
+ return {
+ ok: true,
+ aiRuntimeProtocolVersion: AI_RUNTIME_PROTOCOL_VERSION,
+ ...runtime
+ };
}
function canonicalAiTaskId(value) {
@@ -6102,11 +6129,17 @@ function storagePayload(state) {
};
}
-async function commitLocalChanges(update) {
- await chrome.storage.local.set(update);
- if (!syncApplyInProgress && Object.keys(update).some((key) => SYNCED_STORAGE_KEYS.has(key))) {
- scheduleIdleSync();
+async function commitLocalChanges(update, options = {}) {
+ const payload = { ...update };
+ const changesSyncedContent = Object.keys(payload).some((key) => SYNCED_STORAGE_KEYS.has(key));
+ if (!syncApplyInProgress && options.markSyncDirty !== false && changesSyncedContent) {
+ const stored = await chrome.storage.local.get(STORAGE_KEYS.syncMeta);
+ payload[STORAGE_KEYS.syncMeta] = markSyncMetaDirty(
+ stored[STORAGE_KEYS.syncMeta],
+ options.dirtyAssetIds
+ );
}
+ await chrome.storage.local.set(payload);
}
async function persistDomainState(state, undo, historyOptions) {
@@ -6458,22 +6491,6 @@ async function createArchiveUrl(state, sharing = false) {
return result;
}
-function scheduleIdleSync() {
- clearTimeout(syncIdleTimer);
- syncIdleTimer = setTimeout(() => {
- syncIdleTimer = null;
- enqueue(() => synchronizeNow("idle")).catch(() => undefined);
- }, 1_500);
-}
-
-function scheduleAutomaticSync() {
- if (automaticSyncScheduled) return;
- automaticSyncScheduled = true;
- enqueue(() => synchronizeNow("open"))
- .catch(() => undefined)
- .finally(() => { automaticSyncScheduled = false; });
-}
-
async function connectSyncFolder(password) {
const directory = await getSyncDirectoryHandle();
if (!directory) throw new Error("请先选择同步文件夹");
@@ -6489,12 +6506,10 @@ async function connectSyncFolder(password) {
});
await saveSyncCryptoKey(vault.key);
await commitLocalChanges({ [STORAGE_KEYS.syncSettings]: settings });
- const result = await synchronizeWithVault(vault, settings, "connect");
return {
- ...result,
- message: result.restored
- ? `同步库已连接,并恢复 ${result.entryCount} 个案例`
- : `同步库已连接,${result.entryCount} 个案例已安全同步`
+ ok: true,
+ connected: true,
+ message: "同步文件夹已连接,尚未读取或合并资料;需要时请点击“立即同步”"
};
}
@@ -6517,24 +6532,18 @@ async function unlockSyncVault(password) {
});
await saveSyncCryptoKey(vault.key);
await commitLocalChanges({ [STORAGE_KEYS.syncSettings]: settings });
- const result = await synchronizeWithVault(vault, settings, "unlock");
- return { ...result, message: "同步库已解锁并完成同步" };
-}
-
-async function synchronizeNow(reason = "manual") {
- if (syncInFlight) return syncInFlight;
- syncInFlight = performSynchronization(reason).finally(() => {
- syncInFlight = null;
- });
- return syncInFlight;
+ return {
+ ok: true,
+ unlocked: true,
+ message: "同步库已解锁,尚未读取或合并资料;需要时请点击“立即同步”"
+ };
}
-async function performSynchronization(reason) {
+async function performManualSynchronization(start) {
const stored = await chrome.storage.local.get(STORAGE_KEYS.syncSettings);
const settings = normalizeSyncSettings(stored[STORAGE_KEYS.syncSettings]);
if (!settings.enabled) {
- if (reason === "manual") throw new Error("请先在“数据与同步”中选择同步文件夹");
- return { ok: false, skipped: true };
+ throw new Error("请先在“数据与同步”中选择同步文件夹");
}
const directory = await getSyncDirectoryHandle();
if (!directory) throw await recordSyncError(settings, "同步文件夹需要重新选择");
@@ -6544,156 +6553,59 @@ async function performSynchronization(reason) {
if (!key) throw await recordSyncError(settings, "同步库已锁定,请输入密码解锁");
try {
const vault = await openSyncVaultWithKey(directory, key, settings.vaultId);
- return await synchronizeWithVault(vault, settings, reason);
+ const result = await start({ vault, settings });
+ if (result.canceled) {
+ return {
+ ...result,
+ ok: true,
+ libraryChanged: false,
+ message: "本次同步已停止,本机未提交的资料没有改变"
+ };
+ }
+ if (result.upToDate) {
+ return {
+ ...result,
+ ok: true,
+ libraryChanged: false,
+ message: "两端没有变化,没有写入同步文件夹"
+ };
+ }
+ return {
+ ...result,
+ ok: true,
+ libraryChanged: result.effects?.localBusinessChanged === true,
+ message: syncResultMessage(result)
+ };
} catch (error) {
throw await recordSyncError(settings, error);
}
}
-async function synchronizeWithVault(vault, settingsValue, reason) {
- const settings = normalizeSyncSettings(settingsValue);
- const current = await readState();
- const metaStored = await chrome.storage.local.get(STORAGE_KEYS.syncMeta);
- const meta = normalizeSyncMeta(metaStored[STORAGE_KEYS.syncMeta]);
- const remoteSnapshots = await listSyncSnapshots(vault);
- const localPrepared = await prepareStateForSync(current, vault, (progress) => notifySyncProgress(progress));
- const localImageRefs = collectSyncImageReferences(localPrepared);
- const localClock = Math.max(
- meta.logicalClock,
- ...remoteSnapshots.map((snapshot) => Number(snapshot.logicalClock) || 0)
- ) + 1;
- const baseSnapshot = {
- format: SYNC_SNAPSHOT_FORMAT,
- version: SYNC_SNAPSHOT_VERSION,
- records: meta.records
- };
- const localSnapshot = await createRevisionSnapshot(localPrepared, {
- deviceId: settings.deviceId,
- logicalClock: localClock,
- baseSnapshot
- });
- const merged = mergeRevisionSnapshots([...remoteSnapshots, localSnapshot]);
- if (syncStateHasContent(current) && !syncStateHasContent(merged.state)) {
- throw new Error("同步结果异常为空,本地资料未被修改");
- }
-
- notifySyncProgress({ phase: "merging" });
- const finalPrepared = attachSyncImageReferences(merged.state, merged.imageRefs);
- const finalSnapshot = await createRevisionSnapshot(finalPrepared, {
- deviceId: settings.deviceId,
- logicalClock: localClock + 1,
- baseSnapshot: {
- format: SYNC_SNAPSHOT_FORMAT,
- version: SYNC_SNAPSHOT_VERSION,
- records: merged.records
- }
- });
- const lastSyncAt = new Date().toISOString();
- const nextSettings = normalizeSyncSettings({
- ...settings,
- enabled: true,
- vaultId: vault.header.vaultId,
- lastSyncAt,
- lastError: "",
- lastErrorCode: ""
- });
- await replaceImagesWithRollback({
- replacements: syncedImageReplacements(
- vault,
- merged.imageRefs,
- localImageRefs,
- (progress) => notifySyncProgress(progress)
- ),
- readImage: getMediaBlob,
- writeImage: saveMediaBlob,
- deleteImage: deleteMediaBlob,
- commitMetadata: async () => {
- notifySyncProgress({ phase: "saving" });
- await writeSyncSnapshot(vault, finalSnapshot, { retentionCount: settings.retentionCount });
- syncApplyInProgress = true;
- try {
- await commitLocalChanges({
- ...synchronizedStatePayload(current, merged.state),
- [STORAGE_KEYS.syncSettings]: nextSettings,
- [STORAGE_KEYS.syncMeta]: {
- logicalClock: localClock + 1,
- records: finalSnapshot.records
- }
- });
- } finally {
- syncApplyInProgress = false;
- }
+async function commitManualSyncResult({ state, settings, meta, trackingOnly }) {
+ syncApplyInProgress = true;
+ try {
+ const update = {
+ [STORAGE_KEYS.syncSettings]: normalizeSyncSettings(settings),
+ [STORAGE_KEYS.syncMeta]: normalizeSyncMeta(meta)
+ };
+ if (!trackingOnly) {
+ Object.assign(update, synchronizedStatePayload(await readState(), state));
}
- });
- return {
- ok: true,
- reason,
- restored: !current.entries.length && Boolean(merged.state.entries?.length),
- entryCount: merged.state.entries?.length ?? 0,
- imageCount: Object.keys(merged.imageRefs).length,
- mediaCount: Object.keys(merged.imageRefs).length,
- conflictCount: merged.conflicts.length,
- lastSyncAt
- };
-}
-
-async function prepareStateForSync(state, vault, onProgress = () => undefined) {
- const prepared = structuredClone({
- entries: state.entries,
- trashState: normalizeTrashState(state.trashState),
- compoundCases: state.compoundCases,
- organizerState: state.organizerState,
- taxonomy: state.taxonomy,
- facetCatalog: state.facetCatalog,
- classificationRules: state.classificationRules,
- settings: { libraryTitle: state.settings?.libraryTitle },
- composerSettings: state.composerSettings,
- composerSessions: state.composerSessions,
- creativeExperimentSettings: state.creativeExperimentSettings,
- creativeRuns: state.creativeRuns,
- creativeSkills: state.creativeSkills
- });
- const seenVisualIds = new Set();
- const visuals = [
- ...prepared.entries.flatMap((entry) => entry.mediaAssets ?? entry.visuals ?? []),
- ...prepared.trashState.items.flatMap((item) => {
- if (item.kind === "entry") return item.snapshot?.mediaAssets ?? item.snapshot?.visuals ?? [];
- if (item.kind === "media") return item.snapshot?.mediaAssets ?? item.snapshot?.visuals ?? [];
- return [];
- }),
- ...prepared.creativeRuns.flatMap((run) => run.outputs.map((output) => output.visual)),
- ...(prepared.creativeSkills?.items ?? []).flatMap((skill) => skill.packageFiles ?? []),
- ...prepared.composerSessions.flatMap((session) => (session.referenceSnapshots ?? [])
- .filter((reference) => reference.sourceType === "temporary")
- .flatMap((reference) => reference.assetRefs ?? []))
- ].filter((visual) => {
- const assetId = visual?.id ?? visual?.assetId;
- if (!assetId || seenVisualIds.has(assetId)) return false;
- seenVisualIds.add(assetId);
- return true;
- });
- for (const [index, visual] of visuals.entries()) {
- if (index % 5 === 0) onProgress({ phase: "encrypting", current: index, total: visuals.length });
- if (visual.storageMode === "reference") continue;
- const blob = await getMediaBlob(visual.id ?? visual.assetId);
- if (!blob) continue;
- visual.syncObjectId = await writeSyncObject(vault, blob);
- visual.syncContentType = blob.type;
+ await commitLocalChanges(update);
+ } finally {
+ syncApplyInProgress = false;
}
- onProgress({ phase: "encrypting", current: visuals.length, total: visuals.length });
- return prepared;
}
-async function* syncedImageReplacements(vault, imageRefs, localImageRefs = {}, onProgress = () => undefined) {
- const pending = Object.entries(imageRefs).filter(([visualId, reference]) =>
- localImageRefs?.[visualId]?.objectId !== reference?.objectId
- );
- for (const [index, [visualId, reference]] of pending.entries()) {
- if (index % 5 === 0) onProgress({ phase: "restoring", current: index, total: pending.length });
- const blob = await readSyncObject(vault, reference.objectId);
- yield { id: visualId, blob };
- }
- onProgress({ phase: "restoring", current: pending.length, total: pending.length });
+function syncResultMessage(result = {}) {
+ const summary = result.changeSummary ?? {};
+ const changes = [
+ summary.added ? `新增 ${summary.added} 项` : "",
+ summary.updated ? `更新 ${summary.updated} 项` : "",
+ summary.deleted ? `删除 ${summary.deleted} 项` : "",
+ summary.conflicts ? `保留 ${summary.conflicts} 个冲突副本` : ""
+ ].filter(Boolean).join(",");
+ return changes ? `手动同步完成:${changes}` : "手动同步完成";
}
function notifySyncProgress(progress = {}) {
@@ -6769,6 +6681,9 @@ async function dataSafetyStatus(state) {
async function publicSyncStatus(settingsValue) {
const settings = normalizeSyncSettings(settingsValue);
+ const metaStored = await chrome.storage.local.get(STORAGE_KEYS.syncMeta);
+ const meta = normalizeSyncMeta(metaStored[STORAGE_KEYS.syncMeta]);
+ const run = manualSyncController.status();
const directory = await getSyncDirectoryHandle().catch(() => null);
const permission = directory ? await directoryPermission(directory) : "missing";
const unlocked = Boolean(await getSyncCryptoKey().catch(() => null));
@@ -6780,7 +6695,10 @@ async function publicSyncStatus(settingsValue) {
needsAuthorization: settings.enabled && permission !== "granted",
lastSyncAt: settings.lastSyncAt,
lastError: settings.lastError,
- lastErrorCode: settings.lastErrorCode
+ lastErrorCode: settings.lastErrorCode,
+ localDirty: meta.localDirty,
+ dirtyAssetCount: meta.dirtyAssetIds.length,
+ ...run
};
}
@@ -6815,13 +6733,6 @@ async function recordSyncError(settings, failure) {
return error;
}
-function normalizeSyncMeta(value = {}) {
- return {
- logicalClock: Math.max(0, Math.floor(Number(value.logicalClock) || 0)),
- records: value.records && typeof value.records === "object" ? structuredClone(value.records) : {}
- };
-}
-
async function migrateLegacyScreenshots(entries) {
for (const entryValue of entries) {
const entry = normalizeEntryVisuals(entryValue);
diff --git a/compatible-provider-presets.js b/compatible-provider-presets.js
new file mode 100644
index 0000000..0c601dc
--- /dev/null
+++ b/compatible-provider-presets.js
@@ -0,0 +1,68 @@
+const MICU_1K_IMAGE_SIZES = Object.freeze([
+ "1024x1024",
+ "1280x720",
+ "720x1280",
+ "1024x1536",
+ "1536x1024"
+]);
+
+const MICU_2K_IMAGE_SIZES = Object.freeze([
+ "2048x2048",
+ "2048x1152",
+ "1152x2048"
+]);
+
+const MICU_4K_IMAGE_SIZES = Object.freeze([
+ "3840x2160",
+ "2160x3840"
+]);
+
+const micuImageModels = Object.freeze({
+ "gpt-image-2": Object.freeze({
+ sizes: Object.freeze([...MICU_1K_IMAGE_SIZES, ...MICU_2K_IMAGE_SIZES])
+ }),
+ "gpt-image-2-openai": Object.freeze({
+ sizes: Object.freeze([...MICU_1K_IMAGE_SIZES, ...MICU_2K_IMAGE_SIZES, ...MICU_4K_IMAGE_SIZES])
+ })
+});
+
+// Verified provider capability:
+// https://docs.micuapi.ai/tools#micu-image-mcp
+// https://github.com/Subaru486desuwa/micu-image-mcp
+export const MICU_COMPATIBLE_PROVIDER_PRESET = Object.freeze({
+ id: "micu-personal",
+ label: "米醋",
+ hostname: "micuapi.ai",
+ protocol: "responses",
+ endpoint: "https://www.micuapi.ai/v1/responses",
+ defaultChatModel: "gpt-5.4-mini",
+ imageGeneration: Object.freeze({
+ protocol: "images_generations",
+ endpoint: "https://www.micuapi.ai/v1/images/generations",
+ editsEndpoint: "https://www.micuapi.ai/v1/images/edits",
+ defaultModel: "gpt-image-2",
+ defaultSize: "1536x1024",
+ models: micuImageModels
+ })
+});
+
+export function compatibleProviderPresetForEndpoint(value) {
+ try {
+ const hostname = new URL(value).hostname.toLocaleLowerCase("en-US");
+ const suffix = MICU_COMPATIBLE_PROVIDER_PRESET.hostname;
+ return hostname === suffix || hostname.endsWith(`.${suffix}`)
+ ? MICU_COMPATIBLE_PROVIDER_PRESET
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+export function compatibleImageSizesFor(providerEndpoint, image = {}) {
+ const preset = compatibleProviderPresetForEndpoint(providerEndpoint);
+ if (preset && image.protocol === preset.imageGeneration.protocol) {
+ const model = preset.imageGeneration.models[String(image.model ?? "").trim()];
+ if (model) return [...model.sizes];
+ }
+ return Array.isArray(image.sizes) ? [...image.sizes] : [];
+}
diff --git a/composer-page.css b/composer-page.css
index 0dcf491..8f635fd 100644
--- a/composer-page.css
+++ b/composer-page.css
@@ -13,8 +13,11 @@
.composer-new span:first-child { color: var(--accent); font-size: 19px; font-weight: 400; line-height: 1; }
.composer-nav-section { min-height: 0; overflow: hidden; padding-top: 20px; }
.composer-nav-heading { padding: 0 9px 8px; color: var(--muted); font-size: 11px; }
-.composer-session-list { display: grid; align-content: start; gap: 3px; max-height: 100%; overflow: auto; }
-.composer-session-item { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; border-radius: 9px; }
+.composer-session-list { display: grid; align-content: start; gap: 14px; max-height: 100%; overflow: auto; }
+.composer-session-group { display: grid; gap: 3px; min-width: 0; }
+.composer-session-group-label { margin: 0; padding: 0 9px 4px; color: var(--muted); font-size: 10px; font-weight: 800; }
+.composer-session-group-list { display: grid; gap: 3px; min-width: 0; }
+.composer-session-item { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; min-width: 0; border-radius: 9px; }
.composer-session-item:hover, .composer-session-item:focus-within { background: var(--selection-hover); }
.composer-session-item[aria-current="true"] { background: var(--selection); box-shadow: inset 2px 0 var(--selection-indicator); }
.composer-session-item > button:first-child { min-width: 0; border: 0; padding: 9px; color: var(--ink); background: transparent; text-align: left; }
@@ -22,9 +25,18 @@
.composer-session-item strong, .composer-session-item small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.composer-session-item strong { font-size: 12px; }
.composer-session-item small { margin-top: 3px; color: var(--muted); font-size: 10px; }
-.composer-session-item .composer-session-remove { visibility: hidden; min-width: 30px; border: 0; padding: 6px; color: var(--muted); background: transparent; }
-.composer-session-item:hover .composer-session-remove, .composer-session-item:focus-within .composer-session-remove { visibility: visible; }
-.composer-session-item .composer-session-remove:hover:not(:disabled) { color: var(--danger); background: transparent; }
+.composer-session-menu { position: relative; margin-right: 4px; }
+.composer-session-menu > summary { display: grid; width: 28px; min-height: 28px; place-items: center; opacity: 0; border-radius: 6px; color: var(--muted); cursor: pointer; list-style: none; pointer-events: none; }
+.composer-session-menu > summary::-webkit-details-marker { display: none; }
+.composer-session-item:hover .composer-session-menu > summary,
+.composer-session-item:focus-within .composer-session-menu > summary,
+.composer-session-item[aria-current="true"] .composer-session-menu > summary,
+.composer-session-menu[open] > summary { opacity: 1; pointer-events: auto; }
+.composer-session-menu > summary:hover { color: var(--ink); background: var(--hover); }
+.composer-session-menu-panel { position: absolute; z-index: 18; top: calc(100% + 3px); right: 0; min-width: 112px; border: 1px solid var(--line); border-radius: 7px; padding: 4px; background: var(--card); box-shadow: 0 10px 30px color-mix(in srgb, var(--ink) 18%, transparent); }
+.composer-session-menu-panel button { width: 100%; min-height: 31px; border: 0; border-radius: 5px; padding: 5px 8px; color: var(--danger); background: transparent; text-align: left; font-size: 10px; }
+.composer-session-menu-panel button:hover:not(:disabled) { background: var(--hover); }
+.composer-session-menu-panel button:disabled { color: var(--muted); }
.composer-session-running { color: var(--accent-ink) !important; }
.composer-nav-footer { border-top: 1px solid var(--line); padding: 12px 7px 0; }
.composer-nav-footer p { margin: 0; color: var(--muted); font-size: 10px; line-height: 1.5; }
@@ -228,11 +240,9 @@
.composer-reference-workspace { position: fixed; z-index: 50; inset: 0; display: grid; grid-template-rows: auto minmax(0, 1fr) auto; width: 100%; height: 100dvh; background: var(--paper); }
.composer-reference-header { display: flex; min-height: 70px; align-items: center; justify-content: space-between; gap: 18px; border-bottom: 1px solid var(--line); padding: 12px clamp(18px, 3vw, 38px); background: var(--card); }
-.composer-reference-title { display: grid; grid-template-columns: auto auto; align-items: center; gap: 4px 16px; }
+.composer-reference-title { display: grid; width: max-content; max-width: 100%; grid-template-columns: max-content max-content; align-items: center; gap: 4px 16px; }
.composer-reference-title > p { grid-column: 1 / -1; }
-.composer-reference-tabs { display: flex; align-items: center; gap: 2px; border: 1px solid var(--line); border-radius: 6px; padding: 2px; }
-.composer-reference-tabs button { min-height: 28px; border: 0; border-radius: 4px; padding: 4px 10px; color: var(--muted); background: transparent; font-size: 11px; }
-.composer-reference-tabs button[aria-pressed="true"] { color: var(--ink); background: var(--selection); box-shadow: inset 0 0 0 1px var(--selection-edge); }
+.composer-reference-tabs { flex: none; }
.composer-reference-header strong { font-size: 17px; }
.composer-reference-header p { margin: 4px 0 0; color: var(--muted); font-size: 10px; }
.composer-reference-body { display: grid; grid-template-columns: minmax(260px, 320px) minmax(0, 1fr); min-height: 0; }
@@ -260,6 +270,11 @@
.composer-project-card > div { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
.composer-project-card button { min-height: 30px; padding: 5px 8px; font-size: 10px; }
.composer-project-card .composer-project-active { border-color: var(--selection-edge); color: var(--ink); background: var(--selection); box-shadow: inset 2px 0 var(--selection-indicator); }
+.composer-skill-card > header { display: flex; align-items: start; justify-content: space-between; gap: 12px; }
+.composer-skill-card > header > div { display: grid; gap: 2px; }
+.composer-skill-card code { color: var(--accent-ink); font-size: 12px; }
+.composer-skill-card small { color: var(--muted); font-size: 11px; }
+.composer-skill-card .composer-project-active { border-color: var(--selection-edge); color: var(--ink); background: var(--selection); box-shadow: inset 2px 0 var(--accent); }
.composer-case-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); align-content: start; gap: 14px; }
.composer-case-option { position: relative; display: grid; grid-template-rows: auto minmax(0, 1fr); min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 14px; background: var(--card); }
.composer-case-option:hover { border-color: color-mix(in srgb, var(--ink) 25%, var(--line)); box-shadow: 0 8px 24px color-mix(in srgb, var(--ink) 10%, transparent); }
diff --git a/composer-page.js b/composer-page.js
index 2f1dc89..1dfd805 100644
--- a/composer-page.js
+++ b/composer-page.js
@@ -83,7 +83,7 @@ import {
await initializeUi();
bindUiPreferenceReload();
-bindTransientMenus(document, ".composer-options");
+bindTransientMenus(document, ".composer-options, .composer-session-menu");
const elements = Object.fromEntries([
"composer-shell", "composer-nav", "composer-nav-open", "composer-nav-close", "composer-new", "composer-session-list",
@@ -705,26 +705,63 @@ function renderSessions() {
const current = sessionSummaryFromCurrent();
if (current) summaries.set(current.id, current);
const ordered = [...summaries.values()].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
- elements.composerSessionList.replaceChildren(...ordered.map((summary) => {
+ const groups = [
+ { id: "today", label: "今天", items: [] },
+ { id: "yesterday", label: "昨天", items: [] },
+ { id: "recent", label: "近 7 天", items: [] },
+ { id: "older", label: "更早", items: [] }
+ ];
+ const byId = new Map(groups.map((group) => [group.id, group]));
+ for (const summary of ordered) byId.get(sessionDateGroup(summary.updatedAt)).items.push(summary);
+ elements.composerSessionList.replaceChildren(...groups.filter((group) => group.items.length).map((group) => {
+ const section = el("section", "composer-session-group");
+ section.dataset.sessionGroup = group.id;
+ section.append(rawTextEl("h3", "composer-session-group-label", t(group.label)));
+ const list = el("div", "composer-session-group-list");
+ list.append(...group.items.map(renderSessionRow));
+ section.append(list);
+ return section;
+ }));
+}
+
+function renderSessionRow(summary) {
const row = el("div", "composer-session-item");
+ row.dataset.sessionId = summary.id;
row.setAttribute("aria-current", String(summary.id === composerSession?.id));
const load = document.createElement("button");
load.type = "button";
const running = activeOperation?.kind === "compose" && activeOperation.sessionId === summary.id;
- const meta = running ? operationLabel(activeOperation.phase) : relativeTime(summary.updatedAt);
- load.append(rawTextEl("strong", "", summary.title), rawTextEl("small", running ? "composer-session-running" : "", meta));
+ load.append(rawTextEl("strong", "", summary.title));
+ if (running) load.append(rawTextEl("small", "composer-session-running", operationLabel(activeOperation.phase)));
load.addEventListener("click", safely(() => loadComposerSession(summary.id)));
- const remove = rawTextEl("button", "composer-session-remove", "×");
+ const menu = el("details", "composer-session-menu");
+ const trigger = rawTextEl("summary", "", "…");
+ trigger.setAttribute("aria-label", t("更多操作:{title}", { title: summary.title }));
+ const panel = el("div", "composer-session-menu-panel");
+ panel.setAttribute("role", "menu");
+ const remove = rawTextEl("button", "composer-session-delete", t("删除"));
remove.type = "button";
remove.disabled = running;
- remove.setAttribute("aria-label", translateUiMessage(`删除对话:${summary.title}`));
+ remove.setAttribute("role", "menuitem");
remove.addEventListener("click", (event) => {
event.stopPropagation();
+ menu.open = false;
safely(() => deleteSession(summary.id))();
});
- row.append(load, remove);
+ panel.append(remove);
+ menu.append(trigger, panel);
+ row.append(load, menu);
return row;
- }));
+}
+
+function sessionDateGroup(value, now = new Date()) {
+ const updatedAt = new Date(value);
+ if (Number.isNaN(updatedAt.getTime())) return "older";
+ const localDay = (date) => Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86_400_000;
+ const elapsedDays = localDay(now) - localDay(updatedAt);
+ if (elapsedDays <= 0) return "today";
+ if (elapsedDays === 1) return "yesterday";
+ return elapsedDays <= 6 ? "recent" : "older";
}
function renderTimeline() {
@@ -978,16 +1015,36 @@ function showImageTempReferenceBlock() {
const service = selectedComposerService(composerSession.aiProfile, composerAiSettings, composerVisionSettings);
const block = imageTempReferenceBlock(composerSession.referenceSnapshots, service);
if (!block.blocked) return false;
- const provider = composerVisionSettings.activeProvider === "compatible"
- ? composerVisionSettings.compatible
- : composerVisionSettings.openai;
- const providerLabel = composerVisionSettings.activeProvider === "compatible" ? "兼容图片服务" : "OpenAI";
- const serviceLabel = provider.model ? `${providerLabel} · ${provider.model}` : `${providerLabel} · 未配置模型`;
+ const serviceLabel = currentImageAnalysisServiceLabel();
elements.composerImageBlockerDescription.textContent = `本轮有 ${block.imageCount} 张尚未分析的参考图片,但 ${service.shortLabel} 只能读取文字。可切换到视觉创作服务;也可调用当前图片分析服务(${serviceLabel}),预计发起 ${block.imageCount} 次额外请求,费用由服务商按你的账号计费。`;
elements.composerImageBlocker.showModal();
return true;
}
+function currentImageAnalysisServiceLabel() {
+ const assignment = composerAiTaskAssignments?.imageAnalysis ?? {};
+ const profiles = composerVisionSettings.providerProfiles ?? {};
+ const providerId = String(assignment.providerId ?? "").trim();
+ const profile = providerId ? profiles[providerId] ?? null : null;
+ const assignedModel = String(assignment.model ?? "").trim();
+ if (providerId) {
+ const providerLabel = profile?.label
+ || (providerId === "openai" ? "OpenAI" : providerId === "custom-media" ? "兼容图片服务" : providerId);
+ const model = assignedModel
+ || String(profile?.models?.imageAnalysis ?? "").trim()
+ || (providerId === "openai" ? String(composerVisionSettings.openai?.model ?? "").trim() : "")
+ || (providerId === "custom-media" ? String(composerVisionSettings.compatible?.model ?? "").trim() : "");
+ return model ? `${providerLabel} · ${model}` : `${providerLabel} · 未配置模型`;
+ }
+ const fallbackProvider = composerVisionSettings.activeProvider === "openai"
+ ? { label: "OpenAI", model: composerVisionSettings.openai?.model }
+ : { label: "兼容图片服务", model: composerVisionSettings.compatible?.model };
+ const fallbackModel = String(fallbackProvider.model ?? "").trim();
+ return fallbackModel
+ ? `${fallbackProvider.label} · ${fallbackModel}`
+ : `${fallbackProvider.label} · 未配置模型`;
+}
+
async function analyzeBlockedTempReferences() {
if (!composerSession || imageAnalysisPending) return;
const references = composerSession.referenceSnapshots.filter((reference) =>
@@ -1414,11 +1471,13 @@ function renderGenerationModelChoices(selectedProfile) {
}
function renderImageGenerationSettings() {
- const videoTask = composerSession?.outputMode === "create_video";
- const generationProfile = normalizeComposerAiProfile(composerSession?.generationAiProfile);
+ const videoTask = composerSession?.targetType === "video";
+ const generationProfile = generationRouteProfile(videoTask);
const capability = composerServiceCapabilities(generationProfile, composerVisionSettings)[videoTask ? "video" : "image"];
- const visible = ["create_image", "create_video"].includes(composerSession?.outputMode)
- && Boolean(capability?.generate);
+ const hasImageSize = capability?.parameters?.some((parameter) => ["size", "aspectRatio", "imageSize"].includes(parameter.key));
+ const visible = videoTask
+ ? composerSession?.outputMode === "create_video" && Boolean(capability?.generate)
+ : Boolean(capability?.generate && hasImageSize);
elements.composerGenerationSettings.hidden = !visible;
if (!visible) return;
elements.composerGenerationSettingsTitle.textContent = t(videoTask ? "本轮视频参数" : "本轮图片参数");
@@ -1447,7 +1506,8 @@ function renderImageGenerationSettings() {
fallbackLabel: "质量"
});
const referenceMode = imageReferenceModeAvailability(composerSession.referenceSnapshots);
- elements.composerImageReferenceModeField.hidden = !composerSession.referenceSnapshots.some((item) => item.imageRefs?.length);
+ elements.composerImageReferenceModeField.hidden = composerSession.outputMode !== "create_image"
+ || !composerSession.referenceSnapshots.some((item) => item.imageRefs?.length);
elements.composerImageReferenceMode.value = composerSession.imageReferenceMode;
elements.composerImageReferenceMode.disabled = Boolean(activeOperation) || !referenceMode.canDisableImages;
}
@@ -1456,6 +1516,9 @@ function renderImageGenerationSettings() {
...(!videoTask && !imageReferenceModeAvailability(composerSession.referenceSnapshots).canDisableImages
? [`还有 ${imageReferenceModeAvailability(composerSession.referenceSnapshots).missingAssetIds.length} 张参考图既没有案例提示词,也没有有效分析文字,暂时必须带原图`]
: []),
+ ...(!videoTask && composerSession.referenceSnapshots.some((item) => item.imageRefs?.length)
+ ? [t("参考图画幅无需与输出画幅一致。")]
+ : []),
...(state.ignored.length ? [`当前服务不会发送:${state.ignored.join("、")}`] : [])
];
elements.composerGenerationParameterNote.textContent = messages.map(translateUiMessage).join(currentLocale() === "en" ? "; " : ";");
@@ -1592,8 +1655,9 @@ function composerProfileForAssignment(assignment, fallback) {
}
async function updateImageGenerationParameters() {
- if (!composerSession || activeOperation || !["create_image", "create_video"].includes(composerSession.outputMode)) return;
- const videoTask = composerSession.outputMode === "create_video";
+ if (!composerSession || activeOperation) return;
+ const videoTask = composerSession.targetType === "video";
+ if (videoTask && composerSession.outputMode !== "create_video") return;
const generationParameters = videoTask
? {
...composerSession.generationParameters,
@@ -1822,11 +1886,13 @@ function renderSkills() {
}
const applied = new Set(composerSession.appliedSkills.map((item) => item.skillId));
const cards = skills.map((skill) => {
- const card = el("article", "composer-project-card");
+ const card = el("article", "ui-skill-card composer-skill-card");
const header = el("header", "");
- header.append(rawTextEl("strong", "", `/${skill.callName}`), rawTextEl("small", "", `v${skill.versions.findIndex((item) => item.id === skill.currentVersionId) + 1}`));
- card.append(header, rawTextEl("p", "composer-project-state", skill.description || "暂无说明"));
- const actions = el("div", "");
+ const title = el("div", "");
+ title.append(rawTextEl("h2", "ui-skill-card-title", skill.callName), rawTextEl("code", "", `/${skill.callName}`));
+ header.append(title, rawTextEl("small", "", `v${skill.versions.findIndex((item) => item.id === skill.currentVersionId) + 1}`));
+ card.append(header, rawTextEl("p", "ui-skill-card-summary composer-project-state", skill.description || "暂无说明"));
+ const actions = el("div", "ui-skill-card-actions");
const edit = textEl("button", "button-secondary", "查看与编辑");
edit.addEventListener("click", () => safely(() => openSkillCenter(skill.id))());
const apply = textEl("button", applied.has(skill.id) ? "composer-project-active" : "", applied.has(skill.id) ? "已应用" : "应用 Skill");
@@ -2815,10 +2881,10 @@ function operationLabel(phase) {
const profile = generationPhase ? session?.generationAiProfile : session?.aiProfile;
const service = selectedComposerService(profile, composerAiSettings, composerVisionSettings).shortLabel;
return ({
- planning: `${service} 正在规划`,
+ planning: t("{service} 正在规划", { service }),
streaming: routeOperationLabel(activeOperation?.executionRoute || activeOperation?.session?.currentRoute),
- stopping: `正在停止 ${service}`
- })[phase] || `${service} 正在处理`;
+ stopping: t("正在停止 {service}", { service })
+ })[phase] || t("{service} 正在处理", { service });
}
function routeOperationLabel(route) {
@@ -2827,10 +2893,12 @@ function routeOperationLabel(route) {
? session?.generationAiProfile
: session?.aiProfile;
const service = selectedComposerService(profile, composerAiSettings, composerVisionSettings).shortLabel;
- if (route === "analyze_materials") return `${service} 正在分析资料`;
- if (route === "chat") return `${service} 正在回答`;
- if (activeOperation?.session?.outputMode === "create_video") return `${service} 正在创建视频`;
- return activeOperation?.session?.outputMode === "create_image" ? `${service} 正在创建图片` : `${service} 正在生成`;
+ if (route === "analyze_materials") return t("{service} 正在分析资料", { service });
+ if (route === "chat") return t("{service} 正在回答", { service });
+ if (activeOperation?.session?.outputMode === "create_video") return t("{service} 正在创建视频", { service });
+ return activeOperation?.session?.outputMode === "create_image"
+ ? t("{service} 正在创建图片", { service })
+ : t("{service} 正在生成", { service });
}
function referenceAliasButton(reference) {
diff --git a/composer-service.js b/composer-service.js
index c23099e..d09ad7c 100644
--- a/composer-service.js
+++ b/composer-service.js
@@ -18,6 +18,10 @@ import { normalizeVisionSettings, OPENAI_RESPONSES_ENDPOINT, OPENAI_VIDEOS_ENDPO
import { PORTABLE_LIBRARY_LIMITS } from "./resource-limits.js";
import { boundedMediaBlobFromResponse, fetchBoundedMedia } from "./bounded-media.js";
import { createAiProviderModule } from "./ai-provider-module.js";
+import {
+ compatibleImageSizesFor,
+ compatibleProviderPresetForEndpoint
+} from "./compatible-provider-presets.js";
const REQUEST_TIMEOUT_MS = 120_000;
const IMAGE_REQUEST_TIMEOUT_MS = 240_000;
@@ -37,28 +41,6 @@ const RESPONSES_IMAGE_QUALITIES = Object.freeze([
{ value: "medium", label: "中" },
{ value: "high", label: "高" }
]);
-// Verified provider capability: https://docs.micuapi.ai/tools#micu-image-mcp
-const MICU_IMAGE_SIZES = Object.freeze({
- "gpt-image-2": Object.freeze([
- "1024x1024",
- "1280x720",
- "1536x1024",
- "2048x2048",
- "2048x1152",
- "1152x2048"
- ]),
- "gpt-image-2-pro": Object.freeze([
- "1024x1024",
- "1280x720",
- "1536x1024",
- "2048x2048",
- "2048x1152",
- "1152x2048",
- "3840x2160",
- "2160x3840"
- ])
-});
-
export class ComposerServiceError extends Error {
constructor(message, status = 0, options = {}) {
super(message, options);
@@ -254,15 +236,14 @@ export function composerServiceCapabilities(profileValue, visionSettingsValue =
}
const image = provider.imageGeneration;
const referenceCapability = compatibleImageReferenceCapability(visionSettingsValue, image.model);
- const providerLabel = serviceLabelForEndpoint(provider.endpoint);
- const supportedSizes = compatibleImageSizes(providerLabel, image);
+ const supportedSizes = compatibleImageSizesFor(provider.endpoint, image);
const sizeOptions = supportedSizes.map(imageSizeOption);
const qualityOptions = image.qualities.map((quality) => ({ value: quality, label: quality }));
return {
serviceId: "compatible",
model: image.model || profile.model || provider.model,
image: {
- generate: configured && !compatibleImageConfigurationIssue(image),
+ generate: configured && !compatibleImageConfigurationIssue(image, supportedSizes),
references: {
supported: referenceCapability.supported ?? Boolean(image.editsEndpoint),
maxItems: referenceCapability.maxItems,
@@ -390,7 +371,7 @@ export function composerImageAvailability(profileValue, visionSettingsValue = {}
? imageParameterAvailability(profileValue, visionSettingsValue, session, `由 ${service.shortLabel} 直接生成并保存到本轮结果`)
: { available: false, message: "创建图片还缺少兼容服务的接口、模型或 API Key" };
}
- const issue = compatibleImageConfigurationIssue(image);
+ const issue = compatibleImageConfigurationIssue(image, compatibleImageSizesFor(settings.compatible.endpoint, image));
if (issue) return { available: false, message: issue };
const count = referenceImageCount(session);
const micu = service.shortLabel === "米醋";
@@ -1472,7 +1453,7 @@ function requireVisualService(profileValue, visionSettingsValue, action) {
editsEndpoint: image.editsEndpoint,
apiKey: image.apiKey,
model: image.model,
- sizes: structuredClone(image.sizes),
+ sizes: compatibleImageSizesFor(provider.endpoint, image),
qualities: structuredClone(image.qualities),
referenceImages: compatibleImageReferenceCapability(visionSettingsValue, image.model)
}
@@ -1636,14 +1617,6 @@ function imageSizeOption(value) {
};
}
-function compatibleImageSizes(providerLabel, image = {}) {
- if (providerLabel === "米醋" && image.protocol === "images_generations") {
- const verified = MICU_IMAGE_SIZES[String(image.model ?? "").trim()];
- if (verified) return [...verified];
- }
- return Array.isArray(image.sizes) ? [...image.sizes] : [];
-}
-
function greatestCommonDivisor(left, right) {
let a = Math.max(1, Math.trunc(Math.abs(left)));
let b = Math.max(1, Math.trunc(Math.abs(right)));
@@ -1654,15 +1627,15 @@ function greatestCommonDivisor(left, right) {
function compatibleImageConfigured(provider) {
const image = provider.imageGeneration;
if (image.protocol === "responses_tool") return compatibleConfigured({ consent: true, compatible: provider });
- return !compatibleImageConfigurationIssue(image);
+ return !compatibleImageConfigurationIssue(image, compatibleImageSizesFor(provider.endpoint, image));
}
-function compatibleImageConfigurationIssue(image = {}) {
+function compatibleImageConfigurationIssue(image = {}, supportedSizes = image.sizes) {
if (image.protocol !== "images_generations") return "当前服务没有配置可用的生图协议";
if (!image.endpoint) return "创建图片还缺少生图接口";
if (!image.apiKey && !isLoopback(image.endpoint)) return "创建图片还缺少生图 API Key";
if (!image.model) return "创建图片还缺少生图模型";
- if (!image.parametersOptional && (!Array.isArray(image.sizes) || !image.sizes.length)) return "创建图片还缺少服务支持的尺寸选项";
+ if (!image.parametersOptional && (!Array.isArray(supportedSizes) || !supportedSizes.length)) return "创建图片还缺少服务支持的尺寸选项";
return "";
}
@@ -1678,8 +1651,7 @@ function normalizeXaiComposerSettings(value = {}) {
function compatibleReasoningSupported(provider = {}) {
if (provider.protocol !== "responses") return false;
- try { return new URL(provider.endpoint).hostname.toLocaleLowerCase("en-US").endsWith("micuapi.ai"); }
- catch { return false; }
+ return Boolean(compatibleProviderPresetForEndpoint(provider.endpoint));
}
function referenceImageCount(session) {
@@ -1799,8 +1771,7 @@ async function requestOpenAiFile(service, url, method, body, options) {
}
function serviceLabelForEndpoint(value) {
- try { return new URL(value).hostname.endsWith("micuapi.ai") ? "米醋" : "兼容服务"; }
- catch { return "兼容服务"; }
+ return compatibleProviderPresetForEndpoint(value)?.label || "兼容服务";
}
function isLoopback(value) {
diff --git a/composer.html b/composer.html
index fd6fd04..8b1c2a5 100644
--- a/composer.html
+++ b/composer.html
@@ -112,9 +112,9 @@
<header class="composer-reference-header">
<div class="composer-reference-title">
<strong id="composer-workspace-title" data-i18n="本次参考">本次参考</strong>
- <nav class="composer-reference-tabs" aria-label="参考类型">
- <button id="composer-reference-tab-cases" type="button" aria-pressed="true" data-i18n="案例">案例</button>
- <button id="composer-reference-tab-skills" type="button" aria-pressed="false">Skill</button>
+ <nav class="composer-reference-tabs ui-segmented" aria-label="参考类型">
+ <button id="composer-reference-tab-cases" class="ui-segmented-item" type="button" aria-pressed="true" data-i18n="案例">案例</button>
+ <button id="composer-reference-tab-skills" class="ui-segmented-item" type="button" aria-pressed="false">Skill</button>
</nav>
<p id="composer-workspace-description">只选择本次对话需要借鉴的案例,不会修改案例库或 Skill。</p>
</div>
diff --git a/creative-skill-package.js b/creative-skill-package.js
index a32e94d..0c2c0d7 100644
--- a/creative-skill-package.js
+++ b/creative-skill-package.js
@@ -78,6 +78,34 @@ export async function exportGeneratedSkillPackage(input = {}) {
return createZipBlob([...files].map(([name, data]) => ({ name, data })));
}
+export async function exportStoredSkillPackage(skillValue = {}, options = {}) {
+ const packageFiles = Array.isArray(skillValue.packageFiles) ? skillValue.packageFiles : [];
+ if (!packageFiles.length) {
+ const versions = Array.isArray(skillValue.versions) ? skillValue.versions : [];
+ const version = versions.find((item) => item.id === skillValue.currentVersionId) ?? versions.at(-1) ?? {};
+ return exportGeneratedSkillPackage({
+ portableId: skillValue.portableId,
+ description: skillValue.description,
+ skillMarkdown: version.skillMarkdown,
+ references: version.references,
+ provenanceMarkdown: version.provenanceMarkdown
+ });
+ }
+ if (typeof options.readFile !== "function") throw new Error("Skill 导出缺少文件读取器");
+ const files = [];
+ for (const file of packageFiles) {
+ const path = normalizePackagePath(file?.path);
+ if (!path || path !== file?.path) throw new Error("Skill 包含不安全的文件路径");
+ const blob = await options.readFile(file.assetId);
+ if (!(blob instanceof Blob)) throw new Error(`Skill 包文件缺失:${path}`);
+ if (Number(file.byteSize) > 0 && Number(file.byteSize) !== blob.size) {
+ throw new Error(`Skill 包文件大小不一致:${path}`);
+ }
+ files.push({ name: path, data: blob });
+ }
+ return createZipBlob(files);
+}
+
export async function parseSkillArchive(archive, limitsValue = {}) {
const files = await readZipBlob(archive, skillPackageLimits(limitsValue));
return parseSkillFiles(files, limitsValue);
diff --git a/creative-skills.js b/creative-skills.js
index f12725e..277f44e 100644
--- a/creative-skills.js
+++ b/creative-skills.js
@@ -43,6 +43,7 @@ export function createCreativeSkill(stateValue, input = {}, options = {}) {
currentVersionId: version.id,
versions: [version],
packageFiles: normalizePackageFiles(input.packageFiles),
+ ...(normalizeCuratedOrigin(input.curatedOrigin) ? { curatedOrigin: normalizeCuratedOrigin(input.curatedOrigin) } : {}),
textModeConfirmed: input.textModeConfirmed === true,
runtimeDependencies: normalizeStringList(input.runtimeDependencies),
createdAt: now,
@@ -240,6 +241,7 @@ function normalizeCreativeSkill(value) {
currentVersionId,
versions,
packageFiles: normalizePackageFiles(value?.packageFiles),
+ ...(normalizeCuratedOrigin(value?.curatedOrigin) ? { curatedOrigin: normalizeCuratedOrigin(value.curatedOrigin) } : {}),
textModeConfirmed: value?.textModeConfirmed === true,
runtimeDependencies: normalizeStringList(value?.runtimeDependencies),
createdAt: cleanText(value?.createdAt) || versions[0].createdAt,
@@ -301,6 +303,26 @@ function normalizePackageFiles(values) {
return result;
}
+function normalizeCuratedOrigin(value) {
+ const catalogId = cleanText(value?.catalogId);
+ const skillId = cleanPortableId(value?.skillId);
+ const version = cleanText(value?.version);
+ const sha256 = String(value?.sha256 ?? "").toLocaleLowerCase("en-US");
+ if (!catalogId || !skillId || !version || !/^[a-f0-9]{64}$/.test(sha256)) return null;
+ return {
+ catalogId,
+ skillId,
+ version,
+ sha256,
+ installedAt: validIso(value?.installedAt) || new Date(0).toISOString()
+ };
+}
+
+function validIso(value) {
+ const text = cleanText(value);
+ return text && !Number.isNaN(Date.parse(text)) ? new Date(text).toISOString() : "";
+}
+
function assertUniqueCallName(state, callName, exceptId = "") {
if (state.items.some((item) => item.id !== exceptId && canonicalCallName(item.callName) === canonicalCallName(callName))) {
throw new Error("这个 Skill 调用名已经存在");
diff --git a/curated-config.js b/curated-config.js
index 5f384b3..49b64d2 100644
--- a/curated-config.js
+++ b/curated-config.js
@@ -10,6 +10,12 @@ export const CURATED_PUBLIC_SITE_URL =
export const CURATED_SUBMISSION_URL =
"https://github.com/wchao6891/PromptDirector-Curated/issues/new?template=curated-submission.yml";
+export const CURATED_SKILL_CATALOG_URL =
+ "https://wchao6891.github.io/PromptDirector-Curated/skills-catalog.json";
+
+export const CURATED_SKILL_SUBMISSION_URL =
+ "https://github.com/wchao6891/PromptDirector-Curated/issues/new?template=curated-skill-submission.yml";
+
export const CURATED_PERMISSION_ORIGINS = Object.freeze([
"https://wchao6891.github.io/*",
"https://github.com/*",
diff --git a/curated-skill-catalog.js b/curated-skill-catalog.js
new file mode 100644
index 0000000..a5067d8
--- /dev/null
+++ b/curated-skill-catalog.js
@@ -0,0 +1,110 @@
+import { parseSkillArchive } from "./creative-skill-package.js";
+import { PORTABLE_LIBRARY_LIMITS } from "./resource-limits.js";
+import { sha256Hex } from "./sync-crypto.js";
+
+export const CURATED_SKILL_CATALOG_FORMAT = "prompt-director-curated-skills";
+export const CURATED_SKILL_CATALOG_VERSION = 1;
+
+const DOWNLOAD_HOSTS = new Set(["github.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com"]);
+const REVIEW_STATUSES = new Set(["approved"]);
+
+export function normalizeCuratedSkillCatalog(value) {
+ if (value?.format !== CURATED_SKILL_CATALOG_FORMAT || value.version !== CURATED_SKILL_CATALOG_VERSION || !Array.isArray(value.skills)) {
+ throw new Error("精选 Skill 目录格式无效");
+ }
+ const ids = new Set();
+ const versions = new Set();
+ const orders = new Set();
+ const skills = value.skills.map(normalizeItem).map((item) => {
+ const versionKey = `${item.skillId}@${item.version}`;
+ if (ids.has(item.id) || versions.has(versionKey) || orders.has(item.order)) throw new Error("精选 Skill 目录包含重复条目");
+ ids.add(item.id);
+ versions.add(versionKey);
+ orders.add(item.order);
+ return item;
+ }).toSorted((left, right) => left.order - right.order || left.id.localeCompare(right.id));
+ return {
+ format: CURATED_SKILL_CATALOG_FORMAT,
+ version: CURATED_SKILL_CATALOG_VERSION,
+ updatedAt: validIso(value.updatedAt),
+ skills
+ };
+}
+
+export async function verifyCuratedSkillPackageBlob(blob, expectedSha256, expectedBytes = 0) {
+ if (!(blob instanceof Blob) || blob.size < 22) throw new Error("精选 Skill 包为空或无效");
+ if (blob.size > PORTABLE_LIBRARY_LIMITS.maxArchiveBytes) throw new Error("精选 Skill 包超过安全大小上限");
+ if (Number(expectedBytes) > 0 && blob.size !== Number(expectedBytes)) throw new Error("精选 Skill 包大小与目录不一致");
+ const expected = String(expectedSha256 ?? "").toLocaleLowerCase("en-US");
+ if (!/^[a-f0-9]{64}$/.test(expected) || await sha256Hex(blob) !== expected) throw new Error("精选 Skill 包校验失败");
+ return true;
+}
+
+export async function validateCuratedSkillPackage(itemValue, archive) {
+ const item = normalizeItem(itemValue);
+ const parsed = await parseSkillArchive(archive);
+ if (parsed.name !== item.skillId) throw new Error("精选 Skill 包身份与目录不一致");
+ for (const path of parsed.files.keys()) {
+ const relative = parsed.root && path.startsWith(`${parsed.root}/`) ? path.slice(parsed.root.length + 1) : path;
+ if (relative !== "SKILL.md" && !/^references\/[A-Za-z0-9._/-]+\.md$/i.test(relative)) {
+ throw new Error(`精选 Skill 包包含不允许的文件:${relative}`);
+ }
+ }
+ if (parsed.dependencies.length) throw new Error("精选 Skill 包不能依赖脚本、程序或外部工具");
+ return parsed;
+}
+
+export function isTrustedCuratedSkillResponseUrl(value) {
+ const url = safeHttpsUrl(value);
+ return Boolean(url && DOWNLOAD_HOSTS.has(url.hostname));
+}
+
+function normalizeItem(value = {}) {
+ const id = clean(value.id);
+ const skillId = portableId(value.skillId);
+ const version = clean(value.version);
+ const title = clean(value.title);
+ const callName = localCallName(value.callName);
+ const authorId = portableId(value.authorId);
+ const author = clean(value.author);
+ const license = clean(value.license);
+ const reviewStatus = clean(value.reviewStatus);
+ const reviewedAt = validIso(value.reviewedAt);
+ const summary = clean(value.summary);
+ const downloadUrl = trustedUrl(value.downloadUrl);
+ const sha256 = String(value.sha256 ?? "").toLocaleLowerCase("en-US");
+ const archiveBytes = positiveInteger(value.archiveBytes);
+ const order = positiveInteger(value.order);
+ if (!id || !skillId || !/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/i.test(version) || !title || !callName || !authorId || !author || !license ||
+ !REVIEW_STATUSES.has(reviewStatus) || !reviewedAt || !summary || !downloadUrl || !/^[a-f0-9]{64}$/.test(sha256) || !archiveBytes || !order) {
+ throw new Error("精选 Skill 目录条目缺少必填字段或校验值");
+ }
+ return { id, skillId, version, title, callName, authorId, author, license, reviewStatus, reviewedAt, summary, downloadUrl, sha256, archiveBytes, order };
+}
+
+function trustedUrl(value) {
+ const url = safeHttpsUrl(value);
+ if (!url || !DOWNLOAD_HOSTS.has(url.hostname) || url.username || url.password || url.search || url.hash) return "";
+ return url.href;
+}
+
+function safeHttpsUrl(value) {
+ try { const url = new URL(String(value ?? "")); return url.protocol === "https:" ? url : null; }
+ catch { return null; }
+}
+
+function portableId(value) {
+ const text = String(value ?? "").trim().toLocaleLowerCase("en-US");
+ return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(text) && text.length <= 63 ? text : "";
+}
+
+function localCallName(value) {
+ const raw = String(value ?? "");
+ if (/[\u0000-\u001f\u007f/\\]/.test(raw)) return "";
+ const text = raw.replace(/\s+/g, " ").trim();
+ return text && text.length <= 80 ? text : "";
+}
+
+function clean(value) { return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim(); }
+function validIso(value) { const text = clean(value); return text && !Number.isNaN(Date.parse(text)) ? new Date(text).toISOString() : ""; }
+function positiveInteger(value) { const number = Math.floor(Number(value) || 0); return number > 0 ? number : 0; }
diff --git a/curated-skill-install.js b/curated-skill-install.js
new file mode 100644
index 0000000..2db23d3
--- /dev/null
+++ b/curated-skill-install.js
@@ -0,0 +1,78 @@
+import { normalizeCreativeSkillsState } from "./creative-skills.js";
+
+export function planCuratedSkillInstall(stateValue, itemValue) {
+ const items = Array.isArray(stateValue?.items) ? stateValue.items : [];
+ const skillId = clean(itemValue?.skillId);
+ const version = clean(itemValue?.version);
+ const matches = items.filter((skill) => clean(skill?.curatedOrigin?.skillId) === skillId);
+ const same = matches.find((skill) => skill.curatedOrigin?.version === version);
+ if (same) return { action: "already-installed", skill: same };
+ if (matches.length) return { action: "install-update-copy", previous: matches.at(-1) };
+ return { action: "install-new" };
+}
+
+export async function installCuratedSkillTransaction(options = {}) {
+ const plan = planCuratedSkillInstall(options.state, options.item);
+ if (plan.action === "already-installed") return { status: "already-installed", skill: plan.skill };
+ if (!(options.parsed?.files instanceof Map) || typeof options.saveBlob !== "function" || typeof options.deleteBlobs !== "function" || typeof options.createSkill !== "function") {
+ throw new Error("精选 Skill 保存事务缺少必要接口");
+ }
+ const existingNames = new Set(normalizeCreativeSkillsState(options.state).items.map((skill) => canonical(skill.callName)));
+ const baseCallName = clean(options.item?.callName || options.parsed.name || options.item?.skillId);
+ const callName = uniqueCallName(existingNames, baseCallName);
+ const savedIds = [];
+ const packageFiles = [];
+ try {
+ for (const [path, blob] of options.parsed.files) {
+ const assetId = typeof options.assetIdFactory === "function" ? options.assetIdFactory(path) : `skill-file:${crypto.randomUUID()}`;
+ await options.saveBlob(assetId, blob);
+ savedIds.push(assetId);
+ packageFiles.push({ path, assetId, byteSize: blob.size, mimeType: blob.type || "application/octet-stream" });
+ }
+ const result = await options.createSkill({
+ callName,
+ portableId: options.parsed.name,
+ description: options.parsed.description,
+ skillMarkdown: options.parsed.body,
+ references: options.parsed.references,
+ provenanceMarkdown: "",
+ source: "imported",
+ reason: "imported",
+ packageFiles,
+ runtimeDependencies: [],
+ textModeConfirmed: false,
+ curatedOrigin: {
+ catalogId: clean(options.item?.id),
+ skillId: clean(options.item?.skillId),
+ version: clean(options.item?.version),
+ sha256: String(options.item?.sha256 ?? "").toLocaleLowerCase("en-US"),
+ installedAt: new Date().toISOString()
+ }
+ });
+ return { status: plan.action, result, packageFiles };
+ } catch (error) {
+ if (savedIds.length) {
+ try { await options.deleteBlobs(savedIds); }
+ catch (cleanupError) {
+ throw new AggregateError([error, cleanupError], "精选 Skill 保存失败,且临时文件回滚未完成");
+ }
+ }
+ throw error;
+ }
+}
+
+function uniqueCallName(used, requested) {
+ const base = requested || "curated-skill";
+ if (!used.has(canonical(base))) return base;
+ let suffix = 2;
+ let candidate;
+ do {
+ const ending = ` ${suffix}`;
+ candidate = `${base.slice(0, 80 - ending.length).trimEnd()}${ending}`;
+ suffix += 1;
+ } while (used.has(canonical(candidate)));
+ return candidate;
+}
+
+function canonical(value) { return clean(value).toLocaleLowerCase().replace(/\s+/g, ""); }
+function clean(value) { return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim(); }
diff --git a/curated-skill-package.js b/curated-skill-package.js
new file mode 100644
index 0000000..4dfb7e4
--- /dev/null
+++ b/curated-skill-package.js
@@ -0,0 +1,107 @@
+import { currentCreativeSkillVersion } from "./creative-skills.js";
+import { generatedSkillFiles } from "./creative-skill-package.js";
+import { sha256Hex } from "./sync-crypto.js";
+import { createZipBlob } from "./zip.js";
+
+export const CURATED_SKILL_SUBMISSION_FORMAT = "prompt-director-curated-skill-submission";
+export const CURATED_SKILL_SUBMISSION_VERSION = 1;
+
+const PUBLIC_LICENSE = "CC BY 4.0";
+const encoder = new TextEncoder();
+
+export async function buildCuratedSkillSnapshot(skillValue, metadata = {}) {
+ const skill = structuredClone(skillValue ?? {});
+ const version = currentCreativeSkillVersion(skill);
+ if (!version) throw new Error("没有可投稿的 Skill 当前版本");
+ const manifest = normalizeSubmissionMetadata(metadata, skill);
+ const files = generatedSkillFiles({
+ portableId: manifest.skillId,
+ description: skill.description,
+ skillMarkdown: version.skillMarkdown,
+ references: version.references,
+ provenanceMarkdown: metadata.includeProvenance === true ? version.provenanceMarkdown : ""
+ });
+ const preview = [];
+ const findings = [];
+ for (const [path, blob] of files) {
+ const text = await blob.text();
+ preview.push({ path, text, byteSize: encoder.encode(text).byteLength });
+ findings.push(...findPrivacyRisks(text, path));
+ }
+ const digestInput = preview.map((item) => `${item.path}\0${item.text}\0`).join("");
+ const digest = await sha256Hex(digestInput);
+ return {
+ manifest: { ...manifest, digest, fileCount: files.size },
+ files,
+ preview,
+ findings,
+ digest
+ };
+}
+
+export async function buildCuratedSkillSubmissionArchive(snapshotValue = {}) {
+ const findings = Array.isArray(snapshotValue.findings) ? snapshotValue.findings : [];
+ if (findings.length) throw new Error("投稿快照包含隐私风险,请修改 Skill 后重新预览");
+ const files = snapshotValue.files instanceof Map ? snapshotValue.files : new Map();
+ if (!files.size || !snapshotValue.manifest) throw new Error("投稿快照无效");
+ const payload = await createZipBlob([...files].map(([name, data]) => ({ name, data })));
+ const payloadSha256 = await sha256Hex(payload);
+ const manifest = {
+ ...snapshotValue.manifest,
+ format: CURATED_SKILL_SUBMISSION_FORMAT,
+ version: CURATED_SKILL_SUBMISSION_VERSION,
+ payloadSha256,
+ payloadBytes: payload.size
+ };
+ return createZipBlob([
+ { name: "submission.json", data: new Blob([`${JSON.stringify(manifest, null, 2)}\n`], { type: "application/json" }) },
+ { name: "payload.zip", data: payload }
+ ]);
+}
+
+export function findPrivacyRisks(textValue, path = "") {
+ const text = String(textValue ?? "");
+ const rules = [
+ ["credential", /\b(?:api[_-]?key|access[_-]?token|secret|password)\s*[:=]\s*["']?[A-Za-z0-9_./+=-]{8,}["']?/giu, "可能包含密钥或口令"],
+ ["credential", /\b(?:sk|ghp|github_pat)_[A-Za-z0-9_-]{12,}\b/gu, "可能包含访问令牌"],
+ ["local-path", /(?:\/Users\/[^\s/]+|[A-Za-z]:\\Users\\[^\s\\]+)/gu, "包含本机用户路径"],
+ ["private-url", /https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+)(?=[:/\s]|$)/gu, "包含本机或内网地址"],
+ ["personal-identifier", /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/giu, "可能包含个人邮箱"]
+ ];
+ const findings = [];
+ for (const [kind, pattern, message] of rules) {
+ for (const match of text.matchAll(pattern)) findings.push({ kind, path, message, excerpt: match[0] });
+ }
+ return findings;
+}
+
+function normalizeSubmissionMetadata(value, skill) {
+ const skillId = portableId(skill.portableId);
+ const callName = clean(skill.callName);
+ const author = clean(value.author);
+ const summary = clean(value.summary);
+ if (!skillId) throw new Error("当前 Skill 缺少稳定公开 ID");
+ if (!callName) throw new Error("当前 Skill 缺少可读调用名");
+ if (!author) throw new Error("请填写公开署名");
+ if (!summary) throw new Error("请填写公开摘要");
+ if (value.rightsConfirmed !== true) throw new Error("请确认允许其他用户在保留署名的前提下保存、使用和修改");
+ return {
+ skillId,
+ callName,
+ title: callName,
+ author,
+ license: PUBLIC_LICENSE,
+ reviewStatus: "pending",
+ summary,
+ createdAt: new Date().toISOString()
+ };
+}
+
+function portableId(value) {
+ const text = String(value ?? "").trim().toLocaleLowerCase("en-US");
+ return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(text) && text.length <= 63 ? text : "";
+}
+
+function clean(value) {
+ return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim();
+}
diff --git a/curated-skill-page.css b/curated-skill-page.css
new file mode 100644
index 0000000..3aafdd5
--- /dev/null
+++ b/curated-skill-page.css
@@ -0,0 +1,30 @@
+.curated-skill-app { width: 100%; max-width: 1540px; margin: 0 auto 48px; padding: 28px 20px; }
+.curated-skill-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); align-content: start; gap: 8px; }
+.curated-skill-card h2, .curated-skill-card p { margin: 0; }
+.curated-skill-card-actions { justify-content: flex-start; }
+.curated-skill-card-actions button:last-child { margin-left: auto; }
+.curated-skill-dialog { width: min(920px, calc(100vw - 32px)); max-height: calc(100dvh - 32px); border: 1px solid var(--ui-border-strong); border-radius: var(--ui-container-radius); padding: 0; color: var(--ui-text); background: var(--ui-surface); }
+.curated-skill-detail { padding: 24px; }
+.curated-skill-detail header { display: flex; align-items: start; justify-content: space-between; gap: 18px; padding-right: 42px; }
+.curated-skill-detail-copy { display: grid; max-width: 650px; gap: 7px; }
+.curated-skill-detail h1 { margin: 0; font-size: 24px; line-height: 1.3; }
+.curated-skill-detail p { margin: 0; color: var(--ui-muted); }
+.curated-skill-maintenance { margin-top: 18px; border-top: 1px solid var(--ui-border); padding-top: 12px; color: var(--ui-muted); font-size: var(--ui-meta-size); }
+.curated-skill-maintenance summary { width: max-content; cursor: pointer; color: var(--ui-text); font-weight: 750; }
+.curated-skill-maintenance-copy { display: flex; flex-wrap: wrap; gap: 6px 14px; padding-top: 10px; }
+.curated-skill-markdown { margin-top: 18px; border-top: 1px solid var(--ui-border); padding-top: 18px; }
+.curated-skill-empty { display: grid; min-height: 55dvh; align-content: center; justify-items: center; gap: 10px; padding: 32px 20px; color: var(--ui-muted); text-align: center; }
+.curated-skill-state-copy { display: grid; justify-items: center; gap: 8px; }
+.curated-skill-empty strong { color: var(--ui-text); font-size: var(--ui-section-title-size); }
+.curated-skill-empty p { max-width: 520px; margin: 0; }
+.curated-skill-app .curated-loading { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 8px; }
+.curated-skill-app .curated-loading span { min-height: 152px; aspect-ratio: auto; }
+
+@media (max-width: 760px) {
+ .curated-skill-app { padding: 14px 10px 34px; }
+ .curated-skill-grid, .curated-skill-app .curated-loading { grid-template-columns: 1fr; }
+ .curated-skill-dialog { width: calc(100vw - 16px); max-height: calc(100dvh - 16px); }
+ .curated-skill-detail { padding: 18px 14px; }
+ .curated-skill-detail header { display: grid; padding-right: 38px; }
+ .curated-skill-detail header > button { justify-self: start; }
+}
diff --git a/curated-skill-page.js b/curated-skill-page.js
new file mode 100644
index 0000000..8bb3ca7
--- /dev/null
+++ b/curated-skill-page.js
@@ -0,0 +1,234 @@
+import {
+ isTrustedCuratedSkillResponseUrl,
+ normalizeCuratedSkillCatalog,
+ validateCuratedSkillPackage,
+ verifyCuratedSkillPackageBlob
+} from "./curated-skill-catalog.js";
+import { CURATED_SKILL_CATALOG_URL } from "./curated-config.js";
+import { fetchCuratedPackage, readResponseBlobWithProgress } from "./curated-download.js";
+import { installCuratedSkillTransaction, planCuratedSkillInstall } from "./curated-skill-install.js";
+import { initializeUi, t } from "./i18n.js";
+import { deleteMediaBlobs, saveSkillPackageBlob } from "./media-store.js";
+import { renderMarkdownDocument } from "./markdown-renderer.js";
+
+await initializeUi();
+
+const elements = Object.fromEntries([
+ "retry-catalog", "return-library", "skill-app", "skill-detail-close", "skill-detail-content", "skill-detail-dialog", "skill-search", "skill-status", "skill-status-bar", "skill-toast"
+].map((id) => [camel(id), document.querySelector(`#${id}`)]));
+const state = { catalog: null, creativeSkills: { version: 1, items: [] }, parsed: new Map(), archives: new Map(), query: "" };
+let toastTimer = 0;
+
+elements.returnLibrary.addEventListener("click", () => location.assign(chrome.runtime.getURL("library.html")));
+elements.retryCatalog.addEventListener("click", start);
+elements.skillSearch.addEventListener("input", () => { state.query = elements.skillSearch.value.trim().toLocaleLowerCase(); render(); });
+elements.skillDetailClose.addEventListener("click", () => elements.skillDetailDialog.close());
+elements.skillDetailDialog.addEventListener("click", (event) => { if (event.target === elements.skillDetailDialog) elements.skillDetailDialog.close(); });
+
+await start();
+
+async function start() {
+ hideStatus();
+ state.catalog = null;
+ elements.skillApp.replaceChildren(loading());
+ try {
+ const [response, local] = await Promise.all([
+ fetch(CURATED_SKILL_CATALOG_URL, { credentials: "omit", cache: "no-store" }),
+ chrome.runtime.sendMessage({ type: "GET_STATE" })
+ ]);
+ if (!response.ok) {
+ const error = new Error("catalog-request-failed");
+ error.status = response.status;
+ throw error;
+ }
+ state.catalog = normalizeCuratedSkillCatalog(await response.json());
+ if (local?.ok) state.creativeSkills = local.creativeSkills ?? state.creativeSkills;
+ render();
+ } catch (error) {
+ showStatus(catalogFailureReason(error), true);
+ elements.skillApp.replaceChildren(emptyState({
+ state: "error",
+ title: t("暂时无法读取精选 Skill"),
+ description: t("你的本地 Skill 不受影响,可以稍后重试。")
+ }));
+ }
+}
+
+function render() {
+ const query = state.query;
+ const items = (state.catalog?.skills ?? []).filter((item) => !query || [item.title, item.callName, item.author, item.summary].join(" ").toLocaleLowerCase().includes(query));
+ if (!items.length) {
+ return elements.skillApp.replaceChildren(emptyState(query ? {
+ state: "search-empty",
+ title: t("没有匹配的精选 Skill"),
+ description: t("换个关键词,或清空搜索查看全部内容。"),
+ actionLabel: t("清空搜索"),
+ action: clearSearch
+ } : {
+ state: "empty",
+ title: t("精选 Skill 目录暂时为空"),
+ description: t("首个 Skill 会在真实投稿并通过人工审核后出现。")
+ }));
+ }
+ const grid = element("section", "curated-skill-grid");
+ grid.append(...items.map(card));
+ elements.skillApp.replaceChildren(grid);
+}
+
+function card(item) {
+ const root = element("article", "ui-skill-card curated-skill-card");
+ root.append(
+ element("h2", "ui-skill-card-title", item.title),
+ element("p", "ui-skill-card-summary", item.summary)
+ );
+ const actions = element("div", "ui-skill-card-actions curated-skill-card-actions");
+ const view = element("button", "button-secondary", t("查看说明"));
+ view.type = "button";
+ view.addEventListener("click", () => openDetail(item));
+ actions.append(view, installButton(item));
+ root.append(actions);
+ return root;
+}
+
+async function openDetail(item) {
+ elements.skillDetailContent.replaceChildren(element("div", "curated-skill-detail", t("正在校验并读取 Skill…")));
+ elements.skillDetailDialog.showModal();
+ try {
+ const parsed = await loadParsed(item);
+ renderDetail(item, parsed);
+ } catch (error) {
+ elements.skillDetailContent.replaceChildren(element("div", "curated-skill-detail", error.message || t("Skill 读取失败")));
+ }
+}
+
+function renderDetail(item, parsed) {
+ const root = element("article", "curated-skill-detail");
+ const header = element("header");
+ const copy = element("div", "curated-skill-detail-copy");
+ copy.append(element("h1", "", item.title), element("p", "", item.summary));
+ const action = installButton(item, parsed);
+ action.classList.add("curated-skill-primary");
+ header.append(copy, action);
+ const maintenance = element("details", "curated-skill-maintenance");
+ maintenance.append(element("summary", "", t("版本与许可")));
+ const maintenanceCopy = element("div", "curated-skill-maintenance-copy");
+ maintenanceCopy.append(
+ element("span", "", t("作者:{author}", { author: item.author })),
+ element("span", "", t("版本:{version}", { version: item.version })),
+ element("span", "", t("许可:{license}", { license: item.license })),
+ element("span", "", t("人工审核通过"))
+ );
+ maintenance.append(maintenanceCopy);
+ const markdown = element("section", "curated-skill-markdown");
+ const document = renderMarkdownDocument(parsed.body);
+ removeDuplicateTitleHeading(document, item.title);
+ markdown.append(document);
+ root.append(header, maintenance, markdown);
+ elements.skillDetailContent.replaceChildren(root);
+}
+
+async function loadParsed(item) {
+ if (state.parsed.has(item.id)) return state.parsed.get(item.id);
+ const response = await fetchCuratedPackage(item.downloadUrl);
+ if (!isTrustedCuratedSkillResponseUrl(response.url || item.downloadUrl)) throw new Error(t("精选 Skill 下载跳转到不受信任的地址"));
+ const archive = await readResponseBlobWithProgress(response);
+ await verifyCuratedSkillPackageBlob(archive, item.sha256, item.archiveBytes);
+ const parsed = await validateCuratedSkillPackage(item, archive);
+ state.archives.set(item.id, archive);
+ state.parsed.set(item.id, parsed);
+ return parsed;
+}
+
+async function install(item, parsed, button) {
+ button.disabled = true;
+ button.setAttribute("aria-busy", "true");
+ button.textContent = t("正在校验…");
+ try {
+ const verified = parsed ?? await loadParsed(item);
+ const installed = await installCuratedSkillTransaction({
+ state: state.creativeSkills,
+ item,
+ parsed: verified,
+ saveBlob: saveSkillPackageBlob,
+ deleteBlobs: deleteMediaBlobs,
+ createSkill: async (skill) => {
+ const response = await chrome.runtime.sendMessage({ type: "CREATE_CREATIVE_SKILL", skill });
+ if (!response?.ok) throw new Error(response?.message || t("精选 Skill 保存失败"));
+ state.creativeSkills = response.creativeSkills;
+ return response;
+ }
+ });
+ showToast(t(installed.status === "already-installed" ? "这个版本已经在本地" : installed.status === "install-update-copy" ? "新版本已另存,不会覆盖本地修改" : "精选 Skill 已保存到本地"));
+ render();
+ if (elements.skillDetailDialog.open) renderDetail(item, verified);
+ } catch (error) {
+ button.disabled = planCuratedSkillInstall(state.creativeSkills, item).action === "already-installed";
+ button.removeAttribute("aria-busy");
+ button.textContent = installLabel(item);
+ showToast(error.message || t("精选 Skill 保存失败"));
+ }
+}
+
+function installLabel(item) {
+ const action = planCuratedSkillInstall(state.creativeSkills, item).action;
+ if (action === "already-installed") return t("已保存");
+ if (action === "install-update-copy") return t("另存新版本");
+ return t("保存到本地");
+}
+
+function installButton(item, parsed = null) {
+ const button = element("button", "button-primary", installLabel(item));
+ button.type = "button";
+ button.disabled = planCuratedSkillInstall(state.creativeSkills, item).action === "already-installed";
+ button.addEventListener("click", () => install(item, parsed, button));
+ return button;
+}
+
+function removeDuplicateTitleHeading(document, title) {
+ const heading = document.querySelector?.("h1");
+ if (heading && normalizedHeading(heading.textContent) === normalizedHeading(title)) heading.remove();
+}
+
+function normalizedHeading(value) {
+ return String(value ?? "").trim().replace(/\s+/g, " ").toLocaleLowerCase();
+}
+
+function loading() {
+ const node = element("section", "curated-loading");
+ node.setAttribute("aria-label", t("正在加载精选 Skill"));
+ node.append(...Array.from({ length: 4 }, () => element("span")));
+ return node;
+}
+function emptyState({ state, title, description = "", actionLabel = "", action = null }) {
+ const node = element("section", "curated-skill-empty curated-skill-state");
+ node.dataset.state = state;
+ const copy = element("div", "curated-skill-state-copy");
+ copy.append(element("strong", "", title));
+ if (description) copy.append(element("p", "", description));
+ node.append(copy);
+ if (actionLabel && typeof action === "function") {
+ const button = element("button", "button-secondary curated-skill-state-action", actionLabel);
+ button.type = "button";
+ button.addEventListener("click", action);
+ node.append(button);
+ }
+ return node;
+}
+function clearSearch() {
+ state.query = "";
+ elements.skillSearch.value = "";
+ elements.skillSearch.focus();
+ render();
+}
+function catalogFailureReason(error) {
+ const status = Number(error?.status);
+ if (status === 404) return t("精选 Skill 服务尚未上线或正在更新");
+ if (status >= 500) return t("精选 Skill 服务暂时不可用");
+ if (status >= 400) return t("精选 Skill 目录请求被拒绝");
+ return t("网络连接失败,未能读取精选 Skill 目录");
+}
+function showStatus(message, error = false) { elements.skillStatus.textContent = message; elements.skillStatusBar.hidden = false; elements.skillStatusBar.classList.toggle("error", error); }
+function hideStatus() { elements.skillStatusBar.hidden = true; elements.skillStatus.textContent = ""; }
+function showToast(message) { clearTimeout(toastTimer); elements.skillToast.textContent = message; elements.skillToast.hidden = false; toastTimer = setTimeout(() => { elements.skillToast.hidden = true; }, 2600); }
+function element(tag, className = "", text = "") { const node = document.createElement(tag); if (className) node.className = className; if (text) node.textContent = text; return node; }
+function camel(value) { return value.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase()); }
diff --git a/curated-skills.html b/curated-skills.html
new file mode 100644
index 0000000..563be53
--- /dev/null
+++ b/curated-skills.html
@@ -0,0 +1,31 @@
+<!doctype html>
+<html lang="zh-CN" data-i18n-title="精选 Skill">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>精选 Skill</title>
+ <script src="theme-bootstrap.js"></script>
+ <link rel="stylesheet" href="ui-foundation.css" />
+ <link rel="stylesheet" href="curated.css" />
+ <link rel="stylesheet" href="curated-skill-page.css" />
+ </head>
+ <body>
+ <header class="curated-header">
+ <div class="curated-title-group">
+ <img class="curated-brand-mark" src="assets/icons/icon-source.svg" alt="" />
+ <h1 data-i18n="精选 Skill">精选 Skill</h1>
+ <nav class="curated-sections ui-segmented" aria-label="精选内容" data-i18n-aria-label="精选内容">
+ <a class="ui-segmented-item" href="curated.html" data-i18n="精选案例">精选案例</a>
+ <a class="ui-segmented-item" href="curated-skills.html" aria-current="page" data-i18n="精选 Skill">精选 Skill</a>
+ </nav>
+ </div>
+ <label class="curated-search"><span class="visually-hidden" data-i18n="搜索精选 Skill">搜索精选 Skill</span><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-search"></use></svg><input id="skill-search" type="search" placeholder="搜索 Skill 或用途" data-i18n-placeholder="搜索 Skill 或用途" autocomplete="off" /></label>
+ <div class="curated-header-actions"><button id="return-library" class="button-secondary page-back-action" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-arrow-left"></use></svg><span data-i18n="返回案例库">返回案例库</span></button></div>
+ </header>
+ <div id="skill-status-bar" class="curated-status-bar" hidden><span id="skill-status" role="status" aria-live="polite"></span><button id="retry-catalog" class="button-secondary" type="button" data-i18n="重试">重试</button></div>
+ <main id="skill-app" class="curated-skill-app" aria-live="polite"><section class="curated-loading" aria-label="正在加载精选 Skill" data-i18n-aria-label="正在加载精选 Skill"><span></span><span></span><span></span><span></span></section></main>
+ <dialog id="skill-detail-dialog" class="curated-skill-dialog" aria-label="精选 Skill 详情" data-i18n-aria-label="精选 Skill 详情"><button id="skill-detail-close" class="icon-button detail-close" type="button" aria-label="关闭详情" data-i18n-aria-label="关闭详情"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-x"></use></svg></button><div id="skill-detail-content"></div></dialog>
+ <div id="skill-toast" class="curated-toast" role="status" hidden></div>
+ <script type="module" src="curated-skill-page.js"></script>
+ </body>
+</html>
diff --git a/curated.css b/curated.css
index 297fcc0..0d6f1eb 100644
--- a/curated.css
+++ b/curated.css
@@ -10,6 +10,9 @@ body { min-width: 320px; }
.curated-header { position: sticky; z-index: 20; top: 0; display: grid; min-height: 58px; grid-template-columns: auto minmax(260px, 720px) auto; align-items: center; justify-content: space-between; gap: 12px; border-bottom: 1px solid var(--ui-border); padding: 9px max(12px, calc((100vw - var(--curated-max-width)) / 2)); background: var(--bar); }
.curated-header h1 { margin: 0; font-size: 17px; line-height: 1.2; }
+.curated-title-group { display: flex; min-width: 0; align-items: center; gap: 14px; }
+.curated-brand-mark { width: 28px; height: 28px; flex: none; }
+.curated-sections { flex: none; }
.curated-search { display: grid; min-width: 0; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 8px; border: 1px solid var(--ui-border); border-radius: var(--curated-radius); padding: 0 10px; background: var(--ui-raised); }
.curated-search:focus-within { border-color: var(--ui-border-strong); }
.curated-search .ui-icon { width: 15px; height: 15px; color: var(--ui-muted); }
@@ -158,6 +161,10 @@ body { min-width: 320px; }
.case-detail-actions { padding: 10px 14px 14px; }
}
+@media (max-width: 580px) {
+ .curated-title-group { align-items: flex-start; flex-direction: column; gap: 8px; }
+}
+
@media (max-width: 460px) {
.tool-button > span:not(#filter-count) { display: none; }
.detail-info { gap: 12px; }
diff --git a/curated.html b/curated.html
index 0395a4c..01152c5 100644
--- a/curated.html
+++ b/curated.html
@@ -10,7 +10,14 @@
</head>
<body>
<header class="curated-header">
- <h1 data-i18n="精选案例">精选案例</h1>
+ <div class="curated-title-group">
+ <img class="curated-brand-mark" src="assets/icons/icon-source.svg" alt="" />
+ <h1 data-i18n="精选案例">精选案例</h1>
+ <nav class="curated-sections ui-segmented" aria-label="精选内容" data-i18n-aria-label="精选内容">
+ <a class="ui-segmented-item" href="curated.html" aria-current="page" data-i18n="精选案例">精选案例</a>
+ <a class="ui-segmented-item" href="curated-skills.html" data-i18n="精选 Skill">精选 Skill</a>
+ </nav>
+ </div>
<label class="curated-search">
<span class="visually-hidden" data-i18n="搜索创作包或包内案例">搜索创作包或包内案例</span>
<svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-search"></use></svg>
diff --git a/i18n.js b/i18n.js
index 6548ba6..be05beb 100644
--- a/i18n.js
+++ b/i18n.js
@@ -4,8 +4,39 @@ const EN = Object.freeze({
"创作 Skill 中心": "Creative Skill Center",
"创作 Skill": "Creative Skills",
"搜索 Skill": "Search Skills",
+ "精选 Skill": "Curated Skills",
+ "精选内容": "Curated content",
+ "搜索精选 Skill": "Search curated Skills",
+ "搜索 Skill、作者或摘要": "Search by Skill, author, or summary",
+ "搜索 Skill 或用途": "Search by Skill or purpose",
+ "正在加载精选 Skill": "Loading curated Skills",
+ "精选 Skill 详情": "Curated Skill details",
+ "关闭详情": "Close details",
+ "精选 Skill 目录返回 HTTP {status}": "The curated Skill catalog returned HTTP {status}",
+ "精选 Skill 加载失败": "Curated Skills failed to load",
+ "暂时无法读取精选 Skill": "Curated Skills are temporarily unavailable",
+ "没有匹配的精选 Skill": "No curated Skills match your search",
+ "精选 Skill 目录暂时为空": "The curated Skill catalog is currently empty",
+ "正在校验并读取 Skill…": "Verifying and reading the Skill…",
+ "正在校验…": "Verifying…",
+ "Skill 读取失败": "The Skill could not be read",
+ "查看说明": "View details",
+ "版本与许可": "Version and license",
+ "作者:{author}": "Author: {author}",
+ "版本:{version}": "Version: {version}",
+ "许可:{license}": "License: {license}",
+ "人工审核通过": "Human-reviewed",
+ "精选 Skill 下载跳转到不受信任的地址": "The curated Skill download redirected to an untrusted address",
+ "精选 Skill 保存失败": "The curated Skill could not be saved",
+ "这个版本已经在本地": "This version is already saved locally",
+ "新版本已另存,不会覆盖本地修改": "The new version was saved as a copy without overwriting local changes",
+ "精选 Skill 已保存到本地": "The curated Skill was saved locally",
+ "另存新版本": "Save new version as a copy",
+ "保存到本地": "Save locally",
+ "保存到本地 Skill": "Save to local Skills",
"搜索调用名或说明": "Search by call name or description",
"导入": "Import",
+ "投稿到精选 Skill": "Submit to Curated Skills",
"新建 Skill": "New Skill",
"还没有创作 Skill": "No creative Skills yet",
"从你真正喜欢的案例中,按明确目标提炼一份可重复调用的方法。": "Extract a reusable method from cases you genuinely like, guided by a clear goal.",
@@ -590,6 +621,12 @@ const EN = Object.freeze({
"关闭导航": "Close navigation",
"新对话": "New chat",
"最近对话": "Recent chats",
+ "今天": "Today",
+ "昨天": "Yesterday",
+ "近 7 天": "Previous 7 days",
+ "更早": "Older",
+ "更多操作:{title}": "More actions: {title}",
+ "删除这段对话?": "Delete this chat?",
"返回灵感库": "Back to archive",
"草稿与案例只保存在本机。": "Drafts and cases stay on this device.",
"打开导航": "Open navigation",
@@ -709,6 +746,7 @@ const EN = Object.freeze({
"本轮图片参数": "Image parameters for this run",
"本轮视频参数": "Video parameters for this run",
"画幅与分辨率": "Aspect ratio and resolution",
+ "参考图画幅无需与输出画幅一致。": "Reference images do not need to match the output aspect ratio.",
"画幅比例": "Aspect ratio",
"图片尺寸": "Image size",
"由服务决定": "Decided by the service",
@@ -838,6 +876,14 @@ const EN = Object.freeze({
"生成期间不能修改当前对话的参考资料": "References for the running chat cannot be changed during generation",
"生成期间不能修改当前对话设置": "Settings for the running chat cannot be changed during generation",
"请先停止这个对话的生成,再删除": "Stop generation in this chat before deleting it",
+ "{service} 正在规划": "{service} is planning",
+ "{service} 正在分析资料": "{service} is analyzing materials",
+ "{service} 正在回答": "{service} is responding",
+ "{service} 正在创建图片": "{service} is creating an image",
+ "{service} 正在创建视频": "{service} is creating a video",
+ "{service} 正在生成": "{service} is generating",
+ "正在停止 {service}": "Stopping {service}",
+ "{service} 正在处理": "{service} is working",
"另一对话正在生成": "Another chat is generating",
"DeepSeek 正在规划": "DeepSeek is planning",
"DeepSeek 正在生成": "DeepSeek is generating",
@@ -1347,6 +1393,7 @@ const EN = Object.freeze({
"(已下架或当前不可用)": " (retired or currently unavailable)",
"(当前目录不可用)": " (not available in the current catalog)",
"尚无已连接且模型目录明确支持“{task}”的服务,请先连接服务并刷新模型": "No connected service has a catalog model explicitly supporting {task}. Connect a service and refresh its models first.",
+ "尚无已连接且可用于“{task}”的模型,请先连接服务并刷新模型目录": "No connected model can be assigned to {task}. Connect a service and refresh its model catalog first.",
"这里设置全局默认;创作台中的本轮切换不会改动此处。": "Set the global default here. Switching a model for one Composer run does not change this setting.",
"模型": "Model",
"保存任务默认": "Save task default",
@@ -1393,10 +1440,8 @@ const EN = Object.freeze({
"{provider} 已发现 {count} 个模型": "{provider} discovered {count} models",
"模型目录暂时读取失败,可稍后手动刷新": "The model catalog could not be loaded. Refresh it manually later.",
"模型目录读取失败": "Model catalog load failed",
- "厂商声明": "Provider-declared",
- "协议确认": "Protocol-confirmed",
- "待验证": "Unverified",
- "{model}(手动声明,未验证)": "{model} (manually declared, unverified)",
+ "当前模型未声明这项能力;是否可用以真实执行结果为准": "This model does not declare this capability. Actual availability is determined by a real request.",
+ "{model}(模型目录尚未读取)": "{model} (model catalog not loaded)",
"请先保存该厂商的 API Key": "Save this provider's API key first",
"正在读取…": "Loading…",
"目录服务暂时不可用": "The catalog service is temporarily unavailable",
diff --git a/library.html b/library.html
index 768cac6..f159775 100644
--- a/library.html
+++ b/library.html
@@ -284,11 +284,13 @@
<summary data-i18n="跨设备同步">跨设备同步</summary>
<div class="sync-settings-body">
<p class="data-safety-note" data-i18n="同一台电脑可选择普通本地文件夹;跨设备请选择已登录的 iCloud Drive、Dropbox 或 OneDrive 文件夹。两端选择同一个父文件夹并使用相同密码。插件会在其中创建 PromptDirector-Sync,请勿手动修改。">同一台电脑可选择普通本地文件夹;跨设备请选择已登录的 iCloud Drive、Dropbox 或 OneDrive 文件夹。两端选择同一个父文件夹并使用相同密码。插件会在其中创建 PromptDirector-Sync,请勿手动修改。</p>
+ <p class="data-safety-note">连接和解锁只验证文件夹与密码,不会读取、合并或上传资料。只有你再次确认“立即同步”后,才会执行一次同步。</p>
<label id="data-safety-password" class="data-safety-password"><span data-i18n="同步密码">同步密码</span><input id="sync-password" type="password" minlength="8" autocomplete="off" placeholder="至少 8 个字符" data-i18n-placeholder="至少 8 个字符" /></label>
<div class="data-safety-secondary-actions">
<button id="connect-sync-folder" type="button" data-i18n="连接同步文件夹">连接同步文件夹</button>
<button id="unlock-sync-vault" type="button" data-i18n="解锁同步库">解锁同步库</button>
<button id="sync-now" type="button" data-i18n="立即同步">立即同步</button>
+ <button id="cancel-sync" class="button-secondary" type="button" hidden>停止同步</button>
<button id="disconnect-sync-folder" class="quiet-danger" type="button" data-i18n="断开同步">断开同步</button>
</div>
</div>
diff --git a/library.js b/library.js
index 68bd3be..e5ba1e7 100644
--- a/library.js
+++ b/library.js
@@ -70,13 +70,11 @@ import {
import { createStableMasonry } from "./stable-masonry.js";
import {
DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE,
- MICU_IMAGE_EDITS_ENDPOINT,
- MICU_IMAGE_GENERATIONS_ENDPOINT,
- MICU_RESPONSES_ENDPOINT,
normalizeVisionSettings,
blobToDataUrl,
visionProtocolDescription
} from "./vision.js";
+import { MICU_COMPATIBLE_PROVIDER_PRESET } from "./compatible-provider-presets.js";
import { contactSheetPlan, renderContactSheetBatch, selectedSkillContentImages } from "./skill-contact-sheet.js";
import {
entryHasVisual,
@@ -114,6 +112,7 @@ import { createUiIcon } from "./ui-icons.js";
import { confirmAppAction, promptAppText, showAppDialog } from "./ui-dialogs.js";
import {
AI_ASSIGNMENT_TASKS,
+ availableAiModelsForTask,
availableAiProvidersForTask
} from "./ai-provider-registry.js";
import { buildSearchIndex, searchIndexedEntries } from "./search-index.js";
@@ -185,7 +184,7 @@ const elements = Object.fromEntries([
"project-section", "manage-project-order", "selection-simple-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree",
"vision-instructions-en", "vision-instructions-zh", "vision-protocol", "vision-settings-form", "vision-settings-status", "restore-vision-default",
"open-curated", "open-skills", "open-trash", "trash-count", "trash-dialog", "trash-close", "trash-list", "trash-feedback", "trash-restore-all", "trash-empty", "data-safety-dialog", "data-safety-count", "data-safety-status", "data-safety-feedback",
- "sync-settings", "data-safety-password", "sync-password", "connect-sync-folder", "unlock-sync-vault", "sync-now", "create-folder-backup", "restore-folder-backup", "import-library-package", "library-package-file", "disconnect-sync-folder", "capture-web-permission-status", "capture-clipboard-permission-status", "revoke-capture-web-permission", "revoke-capture-clipboard-permission", "capture-permission-settings-feedback",
+ "sync-settings", "data-safety-password", "sync-password", "connect-sync-folder", "unlock-sync-vault", "sync-now", "cancel-sync", "create-folder-backup", "restore-folder-backup", "import-library-package", "library-package-file", "disconnect-sync-folder", "capture-web-permission-status", "capture-clipboard-permission-status", "revoke-capture-web-permission", "revoke-capture-clipboard-permission", "capture-permission-settings-feedback",
"vision-batch-dialog", "vision-batch-close", "vision-batch-summary", "vision-batch-service", "vision-batch-all-images", "vision-batch-reanalyze",
"vision-batch-start", "vision-batch-pause", "vision-batch-resume", "vision-batch-retry", "vision-batch-cancel", "vision-batch-feedback",
"library-drop-target", "import-dialog", "import-dialog-title", "import-close", "import-source", "import-choose-files", "import-last-job", "import-actions", "import-preparing", "import-confirmation", "import-supported-count", "import-skipped-count", "import-duplicate-count", "import-byte-size", "import-project", "import-project-hint", "import-auto-analyze", "import-label-editor", "import-file-list", "import-feedback", "import-job-panel", "import-job-title", "import-job-count", "import-job-progress", "import-job-feedback", "import-cancel", "import-retry", "import-undo", "import-view-project", "import-start"
@@ -314,6 +313,7 @@ const FEEDBACK_DURATION_MS = 3000;
const ERROR_FEEDBACK_DURATION_MS = 8000;
let syncStatus = {};
let dataSafetyOperationActive = false;
+let dataSafetyOperationType = "";
let visionBatchRunnerActive = false;
const activeDetailMediaIdByEntry = new Map();
let cancelVisionBatchAfterCurrent = false;
@@ -609,11 +609,10 @@ function bindEvents() {
chrome.runtime.onMessage.addListener(handleVideoAnalysisProgress);
elements.connectSyncFolder.addEventListener("click", chooseSyncFolder);
elements.unlockSyncVault.addEventListener("click", () =>
- runDataSafetyAction(elements.unlockSyncVault, { type: "UNLOCK_SYNC_VAULT", password: elements.syncPassword.value })
- );
- elements.syncNow.addEventListener("click", () =>
- runDataSafetyAction(elements.syncNow, { type: "SYNC_NOW" })
+ runDataSafetyAction(elements.unlockSyncVault, { type: "UNLOCK_SYNC_VAULT", password: elements.syncPassword.value }, false)
);
+ elements.syncNow.addEventListener("click", startManualSync);
+ elements.cancelSync.addEventListener("click", cancelManualSync);
elements.createFolderBackup.addEventListener("click", createCompleteFolderBackup);
elements.restoreFolderBackup.addEventListener("click", restoreCompleteFolderBackup);
elements.importLibraryPackage.addEventListener("click", () => elements.libraryPackageFile.click());
@@ -3528,8 +3527,7 @@ async function openDetail(entryId, { preserveQueue = false, returnFocus = null }
elements.detailDrawer.classList.add("open");
elements.detailDrawer.setAttribute("aria-hidden", "false");
elements.drawerBackdrop.hidden = false;
- await renderDetail();
- if (changedEntry) elements.detailContent.scrollTop = 0;
+ await renderDetail({ resetScroll: changedEntry });
elements.detailClose.focus();
return true;
}
@@ -3574,14 +3572,13 @@ async function confirmPromptEditDiscard() {
return true;
}
-async function renderDetail() {
+async function renderDetail({ resetScroll = false } = {}) {
const renderGeneration = ++detailRenderGeneration;
const renderEntryId = currentDetailId;
releaseDetailControllers();
releaseDetailMediaUrls();
const entry = logicalCases.find((item) => item.id === currentDetailId);
if (!entry) return closeDetail();
- elements.detailDrawer.dataset.entryId = entry.id;
const visibleIndex = visibleEntries.findIndex((item) => item.id === entry.id);
elements.detailPrev.disabled = visibleIndex <= 0;
elements.detailNext.disabled = visibleIndex < 0 || visibleIndex >= visibleEntries.length - 1;
@@ -3599,7 +3596,9 @@ async function renderDetail() {
await renderCompoundDetail(entry, content, body);
if (renderGeneration !== detailRenderGeneration || currentDetailId !== renderEntryId) return;
content.append(body);
+ elements.detailDrawer.dataset.entryId = entry.id;
elements.detailContent.replaceChildren(content);
+ if (resetScroll) elements.detailContent.scrollTop = 0;
return;
}
const primary = el("div", "detail-primary");
@@ -3635,7 +3634,9 @@ async function renderDetail() {
const discovery = createLocalDiscovery(entry);
if (discovery) content.append(discovery.section);
if (renderGeneration !== detailRenderGeneration || currentDetailId !== renderEntryId) return;
+ elements.detailDrawer.dataset.entryId = entry.id;
elements.detailContent.replaceChildren(content);
+ if (resetScroll) elements.detailContent.scrollTop = 0;
discovery?.mount();
}
@@ -3654,6 +3655,7 @@ function createLocalDiscovery(entry) {
let masonry = null;
let mediaObserver = null;
let loadObserver = null;
+ let paginationActivated = false;
function createDiscoveryCard(item) {
const button = el("button", "case-card local-discovery-item");
@@ -3688,11 +3690,11 @@ function createLocalDiscovery(entry) {
for (const image of grid.querySelectorAll("img[data-visual-id]:not([src])")) mediaObserver.observe(image);
renderedCount += next.length;
sentinel.hidden = renderedCount >= ranked.length;
- scheduleDiscoveryLoadCheck();
+ if (paginationActivated) scheduleDiscoveryLoadCheck();
}
function scheduleDiscoveryLoadCheck() {
- if (loadFrame || renderedCount >= ranked.length) return;
+ if (!paginationActivated || loadFrame || renderedCount >= ranked.length) return;
loadFrame = requestAnimationFrame(() => {
loadFrame = 0;
const bounds = elements.detailContent.getBoundingClientRect();
@@ -3700,11 +3702,18 @@ function createLocalDiscovery(entry) {
});
}
+ function activatePagination() {
+ if (elements.detailContent.scrollTop <= 1) return;
+ if (!paginationActivated) paginationActivated = true;
+ scheduleDiscoveryLoadCheck();
+ }
+
function cleanup() {
if (loadFrame) cancelAnimationFrame(loadFrame);
loadFrame = 0;
mediaObserver?.disconnect();
loadObserver?.disconnect();
+ elements.detailContent.removeEventListener("scroll", activatePagination);
masonry?.destroy();
detailControllerCleanups.delete(cleanup);
}
@@ -3722,18 +3731,18 @@ function createLocalDiscovery(entry) {
}
}, { root: elements.detailContent, rootMargin: "25% 0px" });
loadObserver = new IntersectionObserver((records) => {
- if (records.some((record) => record.isIntersecting)) renderNextDiscoveryBatch();
+ if (paginationActivated && records.some((record) => record.isIntersecting)) renderNextDiscoveryBatch();
}, { root: elements.detailContent, rootMargin: "700px" });
loadObserver.observe(sentinel);
detailControllerCleanups.add(cleanup);
renderNextDiscoveryBatch();
+ elements.detailContent.addEventListener("scroll", activatePagination, { passive: true });
}
return { mount, section };
}
async function renderCompoundDetail(entry, content, body) {
- elements.detailDrawer.dataset.entryId = entry.id;
if (entryHasMedia(entry)) content.append(await createDetailMediaGallery(entry, { immersive: true }));
else content.append(textEl("div", "detail-placeholder", "这个复合案例没有媒体"));
body.append(createDetailHeader(entry), createCompoundActions(entry), createCompoundOrganizer(entry));
@@ -7301,7 +7310,7 @@ async function openAiTaskAssignmentDialog(taskId) {
providerConnectionReady(profile) && taskModelOptions(profile, taskId).length
);
if (!capable.length) {
- showFeedback(t("尚无已连接且模型目录明确支持“{task}”的服务,请先连接服务并刷新模型", { task: t(task.label) }), true);
+ showFeedback(t("尚无已连接且可用于“{task}”的模型,请先连接服务并刷新模型目录", { task: t(task.label) }), true);
return openAiProviderDialog();
}
const selectedProviderId = capable.some((profile) => profile.id === current.providerId)
@@ -7325,6 +7334,14 @@ async function openAiTaskAssignmentDialog(taskId) {
localizeAiDialogClose(dialog);
const provider = controls.get("providerId");
const model = controls.get("model");
+ const modelField = model?.closest(".app-dialog-field");
+ const capabilityHelp = document.createElement("small");
+ capabilityHelp.className = "model-capability-help";
+ modelField?.append(capabilityHelp);
+ const syncCapabilityHelp = () => {
+ capabilityHelp.textContent = modelAssignmentHelp(aiProviderRegistry.providers?.[provider.value], taskId, model.value);
+ capabilityHelp.hidden = !capabilityHelp.textContent;
+ };
provider?.addEventListener("change", () => {
const options = modelOptions(provider.value);
if (model instanceof HTMLSelectElement) {
@@ -7336,7 +7353,10 @@ async function openAiTaskAssignmentDialog(taskId) {
}));
}
model.value = options[0]?.value || "";
+ syncCapabilityHelp();
});
+ model?.addEventListener("change", syncCapabilityHelp);
+ syncCapabilityHelp();
},
onSubmit: async (values) => {
if (!String(values.model ?? "").trim()) throw new Error(t("请选择或填写模型"));
@@ -7404,12 +7424,18 @@ async function openAiProviderDialog(initialProviderId = "") {
);
fields.push(...profile.capabilities.map((taskId) => {
const catalogRequired = profile.catalogRequiredTasks?.includes(taskId) === true;
- const options = discoveredModelOptions(profile, taskId, catalogRequired ? "" : profile.models?.[taskId]);
+ const assignedModel = aiTaskAssignments?.[taskId]?.providerId === profile.id
+ ? aiTaskAssignments[taskId].model
+ : "";
+ const configuredModel = profile.models?.[taskId]
+ || (profile.id === "custom-media" && taskId === "imageGeneration" ? profile.imageGeneration?.model : "")
+ || assignedModel;
+ const options = discoveredModelOptions(profile, taskId, catalogRequired ? "" : configuredModel);
return {
id: `provider_${key}_model_${taskId}`,
label: t("{task}模型(高级)", { task: taskDisplayLabel(taskId) }),
type: catalogRequired || options.length ? "select" : "text",
- value: options.some((option) => option.value === profile.models?.[taskId]) ? profile.models[taskId] : "",
+ value: options.some((option) => option.value === configuredModel) ? configuredModel : "",
options,
advanced: true
};
@@ -7470,11 +7496,19 @@ async function openAiProviderDialog(initialProviderId = "") {
const micuPreset = dialog.querySelector('[data-provider-preset="micu-personal"]');
micuPreset?.addEventListener("click", () => {
const prefix = "provider_custom_media_";
- controls.get(`${prefix}endpoint`).value = MICU_RESPONSES_ENDPOINT;
- controls.get(`${prefix}protocol`).value = "responses";
- controls.get(`${prefix}imageProtocol`).value = "images_generations";
- controls.get(`${prefix}imageEndpoint`).value = MICU_IMAGE_GENERATIONS_ENDPOINT;
- controls.get(`${prefix}imageEditsEndpoint`).value = MICU_IMAGE_EDITS_ENDPOINT;
+ const preset = MICU_COMPATIBLE_PROVIDER_PRESET;
+ const imagePreset = preset.imageGeneration;
+ controls.get(`${prefix}endpoint`).value = preset.endpoint;
+ controls.get(`${prefix}protocol`).value = preset.protocol;
+ controls.get(`${prefix}imageProtocol`).value = imagePreset.protocol;
+ controls.get(`${prefix}imageEndpoint`).value = imagePreset.endpoint;
+ controls.get(`${prefix}imageEditsEndpoint`).value = imagePreset.editsEndpoint;
+ const model = controls.get(`${prefix}model_imageGeneration`);
+ if (model instanceof HTMLSelectElement && ![...model.options].some((option) => option.value === imagePreset.defaultModel)) {
+ model.append(option(imagePreset.defaultModel, imagePreset.defaultModel));
+ }
+ if (model) model.value = imagePreset.defaultModel;
+ controls.get(`${prefix}imageSizes`).value = imagePreset.models[imagePreset.defaultModel].sizes.join(", ");
controls.get(`${prefix}apiKey`).focus();
});
const syncProviderFields = () => {
@@ -7487,8 +7521,28 @@ async function openAiProviderDialog(initialProviderId = "") {
if (micuPreset) micuPreset.hidden = editor.value !== "custom-media";
advanced.hidden = ![...advanced.querySelectorAll("[data-field-id]")].some((wrapper) => !wrapper.hidden);
};
+ const syncModelCapabilityHelp = () => {
+ for (const profile of profiles) {
+ const key = keyFor(profile.id);
+ for (const taskId of profile.capabilities) {
+ const input = controls.get(`provider_${key}_model_${taskId}`);
+ if (!input) continue;
+ const wrapper = input.closest(".app-dialog-field");
+ let help = wrapper.querySelector(":scope > .model-capability-help");
+ if (!help) {
+ help = document.createElement("small");
+ help.className = "model-capability-help";
+ wrapper.append(help);
+ input.addEventListener("change", syncModelCapabilityHelp);
+ }
+ help.textContent = modelAssignmentHelp(profile, taskId, input.value);
+ help.hidden = !help.textContent;
+ }
+ }
+ };
editor.addEventListener("change", syncProviderFields);
syncProviderFields();
+ syncModelCapabilityHelp();
},
onSubmit: async (values) => {
const registryUpdate = { providers: {} };
@@ -7619,19 +7673,27 @@ function applyAiConfigurationResponse(response) {
}
function discoveredModelOptions(profile, taskId, selectedValue = "") {
- const options = (profile?.discoveredModels ?? [])
- .filter((model) => model.status !== "unavailable" && model.tasks?.includes(taskId))
+ const options = availableAiModelsForTask(taskId, profile)
.map((model) => ({
value: model.id,
- label: `${model.name || model.id} · ${t(model.confidence === "declared" ? "厂商声明" : model.confidence === "protocol_inferred" ? "协议确认" : "待验证")}${modelPriceLabel(model.pricing)}`
+ label: `${model.name || model.id}${modelPriceLabel(model.pricing)}`
}));
const selected = String(selectedValue ?? "").trim();
- if (selected && !options.some((option) => option.value === selected)) {
- options.unshift({ value: selected, label: t("{model}(手动声明,未验证)", { model: selected }) });
+ if (selected && !options.some((option) => option.value === selected)
+ && (!profile?.discovery?.discoveredAt || profile?.category === "custom")) {
+ options.unshift({ value: selected, label: t("{model}(模型目录尚未读取)", { model: selected }) });
}
return options;
}
+function modelAssignmentHelp(profile, taskId, selectedValue) {
+ const selected = String(selectedValue ?? "").trim();
+ if (!selected) return "";
+ const model = availableAiModelsForTask(taskId, profile).find((item) => item.id === selected);
+ if (!model || ["declared", "protocol_inferred"].includes(model.assignmentEvidence)) return "";
+ return t("当前模型未声明这项能力;是否可用以真实执行结果为准");
+}
+
function taskModelOptions(profile, taskId) {
if (!profile?.capabilities?.includes(taskId)) return [];
const manualModel = profile.catalogRequiredTasks?.includes(taskId) ? "" : profile.models?.[taskId] || "";
@@ -8602,12 +8664,15 @@ async function renderDataSafetyStatus() {
const missingLocation = syncStatus.lastErrorCode === SYNC_ERROR_CODES.LOCATION_NOT_FOUND;
const needsFolder = missingLocation || !syncStatus.connected || syncStatus.permission !== "granted";
const needsUnlock = !missingLocation && syncStatus.connected && syncStatus.permission === "granted" && !syncStatus.unlocked;
- const canSync = !missingLocation && syncStatus.connected && syncStatus.permission === "granted" && syncStatus.unlocked;
+ const syncRunning = syncStatus.active === true || dataSafetyOperationType === "SYNC_NOW";
+ const canSync = !missingLocation && syncStatus.connected && syncStatus.permission === "granted" && syncStatus.unlocked && !syncRunning;
elements.connectSyncFolder.hidden = !needsFolder;
elements.connectSyncFolder.textContent = t(missingLocation ? "重新选择同步文件夹" : "连接同步文件夹");
elements.unlockSyncVault.hidden = !needsUnlock;
elements.syncNow.hidden = !canSync;
elements.syncNow.disabled = !canSync;
+ elements.cancelSync.hidden = !syncRunning;
+ elements.cancelSync.disabled = syncStatus.cancelRequested === true;
elements.dataSafetyPassword.hidden = !(needsFolder || needsUnlock);
elements.disconnectSyncFolder.hidden = !syncStatus.connected;
if (missingLocation) elements.syncSettings.open = true;
@@ -8687,7 +8752,7 @@ async function chooseSyncFolder() {
await runDataSafetyAction(
elements.connectSyncFolder,
{ type: "CONNECT_SYNC_FOLDER", password },
- true,
+ false,
{ keepDisabled: true }
);
} catch (error) {
@@ -8697,20 +8762,50 @@ async function chooseSyncFolder() {
}
}
+async function startManualSync() {
+ if (dataSafetyOperationActive) {
+ showDataSafetyFeedback(t("当前操作仍在进行,请等待完成"), true);
+ return;
+ }
+ const description = syncStatus.localDirty
+ ? "本机有尚未同步的变化。开始后会读取同步文件夹、合并两端变化并写回结果;完成前可以停止。"
+ : "开始后会检查同步文件夹并合并两端变化;如果没有变化,不会写入快照或刷新案例库。完成前可以停止。";
+ const confirmed = await confirmAppAction({
+ title: "开始一次手动同步?",
+ description,
+ confirmLabel: "开始同步"
+ });
+ if (!confirmed) return;
+ await runDataSafetyAction(elements.syncNow, { type: "SYNC_NOW" }, "changed");
+}
+
+async function cancelManualSync() {
+ if (dataSafetyOperationType !== "SYNC_NOW" && syncStatus.active !== true) return;
+ elements.cancelSync.disabled = true;
+ showDataSafetyFeedback("正在停止同步;已提交的数据不会被回滚,尚未提交的本机资料不会改变…");
+ try {
+ const response = await chrome.runtime.sendMessage({ type: "CANCEL_SYNC" });
+ if (!response?.ok) throw new Error(response?.message || "无法停止同步");
+ } catch (error) {
+ elements.cancelSync.disabled = false;
+ showDataSafetyFeedback(error.message || "无法停止同步", true);
+ }
+}
+
async function runDataSafetyAction(button, message, refresh = true, options = {}) {
if (dataSafetyOperationActive) {
showDataSafetyFeedback(t("当前操作仍在进行,请等待完成"), true);
return null;
}
const originalLabel = button.textContent;
- setDataSafetyBusy(true);
+ setDataSafetyBusy(true, message.type);
button.setAttribute("aria-busy", "true");
if (message.type === "CONNECT_SYNC_FOLDER") {
button.textContent = t("正在连接…");
- showDataSafetyFeedback(t("正在加密并写入同步文件夹,大资料库首次同步可能需要几分钟"));
+ showDataSafetyFeedback("正在验证文件夹与密码,不会读取或合并资料…");
} else if (message.type === "UNLOCK_SYNC_VAULT") {
button.textContent = t("正在解锁…");
- showDataSafetyFeedback(t("正在解锁并合并同步资料…"));
+ showDataSafetyFeedback("正在验证同步密码,不会读取或合并资料…");
} else if (message.type === "SYNC_NOW") {
button.textContent = t("正在同步…");
showDataSafetyFeedback(t("正在同步本地与文件夹资料…"));
@@ -8724,7 +8819,8 @@ async function runDataSafetyAction(button, message, refresh = true, options = {}
if (!response?.ok) throw new Error(response?.message || t("操作失败"));
elements.syncPassword.value = "";
showDataSafetyFeedback(response.message || t("操作完成"));
- if (refresh) await refreshLibrary();
+ const shouldRefresh = refresh === true || (refresh === "changed" && response.libraryChanged === true);
+ if (shouldRefresh) await refreshLibrary();
await renderDataSafetyStatus();
return response;
} catch (error) {
@@ -8739,8 +8835,9 @@ async function runDataSafetyAction(button, message, refresh = true, options = {}
}
}
-function setDataSafetyBusy(active) {
+function setDataSafetyBusy(active, operationType = "") {
dataSafetyOperationActive = active;
+ dataSafetyOperationType = active ? operationType : "";
elements.settingsClose.disabled = active;
for (const button of [
elements.importLibraryPackage,
@@ -8753,6 +8850,9 @@ function setDataSafetyBusy(active) {
]) {
button.disabled = active;
}
+ const syncRunning = active && operationType === "SYNC_NOW";
+ elements.cancelSync.hidden = !syncRunning;
+ elements.cancelSync.disabled = !syncRunning;
}
function handleDataSafetyProgress(message) {
@@ -8762,8 +8862,8 @@ function handleDataSafetyProgress(message) {
const count = total ? ` ${Math.min(current, total)}/${total}` : "";
const english = currentLocale() === "en";
const labels = english
- ? { encrypting: "Encrypting images", restoring: "Restoring new images", merging: "Merging library changes", saving: "Saving sync state" }
- : { encrypting: "正在加密图片", restoring: "正在恢复新增图片", merging: "正在合并资料变更", saving: "正在保存同步状态" };
+ ? { reading: "Checking changes", uploading: "Preparing changed media", downloading: "Restoring changed media", merging: "Merging library changes", committing: "Saving sync result", canceling: "Stopping sync" }
+ : { reading: "正在检查变化", uploading: "正在准备变化的媒体", downloading: "正在恢复变化的媒体", merging: "正在合并资料变更", committing: "正在保存同步结果", canceling: "正在停止同步" };
showDataSafetyFeedback(`${labels[message.phase] || (english ? "Syncing" : "正在同步")}${count}`);
}
@@ -8779,7 +8879,11 @@ function syncStatusMessage(status) {
if (status.lastErrorCode === SYNC_ERROR_CODES.LOCATION_NOT_FOUND) {
return t("同步文件夹中的文件或目录不存在,请重新选择同步文件夹后再同步");
}
+ if (status.active) return status.cancelRequested ? "正在停止本次同步…" : "正在执行一次手动同步…";
if (status.lastError) return status.lastError;
+ if (status.state === "canceled") return "上次手动同步已停止,本机未提交的资料没有改变";
+ if (status.state === "up-to-date") return "已检查:两端没有变化,没有写入同步文件夹";
+ if (status.localDirty) return "本机有尚未同步的变化;只有点击并确认后才会同步";
if (!status.lastSyncAt) return t("同步库已连接,尚未完成首次同步");
const date = new Date(status.lastSyncAt);
const formatted = Number.isNaN(date.getTime()) ? status.lastSyncAt : date.toLocaleString(currentLocale() === "en" ? "en" : "zh-CN");
diff --git a/manifest.json b/manifest.json
index d619a5a..b295de5 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.18.13",
+ "version": "1.18.16",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq2m8W9ACXJTkJqPAd36sPrtzonmHhOYU34uS7c+D7DXX6ggWNMwB4xZapGFJ4ScBQJv71PeG9KfsEnhcXFZ9RoX/X3wY+57evL19hf6woNX1xxhKOe1rtx5QmzWCEYIr99TzW50k/N9U6tS9Ri+2DHKYA85ssXTC8B2yRQ5zUXhsAWZe/HDU18UFuvUKXYt3ZdIUi31c2vIlgFFBfsyKbIUMny9LlxL/smb4vJzU/+A3LwJDjjvOtS/lmQ2vHoQGjHJItO18bYI6h67fIEvmWk+HJKtO08Ca+5RLS8TYhI+K7l7S0RyDVNujyVWtvhAULot1H0BvteYL87fKu3SNywIDAQAB",
"homepage_url": "https://github.com/wchao6891/PromptDirector",
"default_locale": "zh_CN",
diff --git a/manual-sync.js b/manual-sync.js
new file mode 100644
index 0000000..74e31e0
--- /dev/null
+++ b/manual-sync.js
@@ -0,0 +1,436 @@
+import { replaceImagesWithRollback } from "./image-transaction.js";
+import {
+ SYNC_SNAPSHOT_FORMAT,
+ SYNC_SNAPSHOT_VERSION,
+ attachSyncImageReferences,
+ collectSyncAssets,
+ collectSyncImageReferences,
+ createRevisionSnapshot,
+ mergeRevisionSnapshots,
+ normalizeSyncMeta,
+ normalizeSyncSettings,
+ sameRevisionRecords,
+ summarizeRevisionChanges,
+ syncObjectReferencesFromRecords,
+ syncStateHasContent
+} from "./sync-model.js";
+import {
+ listSyncSnapshots,
+ readSyncObject,
+ writeSyncObject,
+ writeSyncSnapshot
+} from "./sync-vault.js";
+
+const TERMINAL_STATES = new Set(["up-to-date", "success", "canceled", "error"]);
+
+export function createManualSyncController(dependencies = {}) {
+ const deps = validateDependencies(dependencies);
+ let activeRun = null;
+ let currentStatus = idleStatus();
+
+ function start(input = {}) {
+ if (activeRun) return activeRun.promise;
+ const abortController = new AbortController();
+ const effects = emptyEffects();
+ setStatus({
+ state: "running",
+ phase: "reading",
+ active: true,
+ pendingCount: 0,
+ runningCount: 1,
+ startedAt: deps.now(),
+ finishedAt: "",
+ cancelRequested: false,
+ effects,
+ changeSummary: emptyChangeSummary(),
+ error: ""
+ });
+ const promise = runManualSync({
+ ...input,
+ dependencies: deps,
+ signal: abortController.signal,
+ effects,
+ update: (patch) => setStatus({ ...patch, effects })
+ }).then((result) => {
+ const state = result.canceled ? "canceled" : result.upToDate ? "up-to-date" : "success";
+ setStatus({
+ state,
+ phase: state,
+ active: false,
+ pendingCount: 0,
+ runningCount: 0,
+ finishedAt: deps.now(),
+ effects,
+ changeSummary: result.changeSummary ?? emptyChangeSummary(),
+ error: ""
+ });
+ return result;
+ }).catch((error) => {
+ if (isAbortError(error)) {
+ const result = canceledResult(effects);
+ setStatus({
+ state: "canceled",
+ phase: "canceled",
+ active: false,
+ pendingCount: 0,
+ runningCount: 0,
+ finishedAt: deps.now(),
+ effects,
+ changeSummary: emptyChangeSummary(),
+ error: ""
+ });
+ return result;
+ }
+ setStatus({
+ state: "error",
+ phase: "error",
+ active: false,
+ pendingCount: 0,
+ runningCount: 0,
+ finishedAt: deps.now(),
+ effects,
+ changeSummary: emptyChangeSummary(),
+ error: cleanError(error)
+ });
+ throw error;
+ }).finally(() => {
+ activeRun = null;
+ });
+ activeRun = { abortController, promise };
+ return promise;
+ }
+
+ function cancel() {
+ if (!activeRun) return false;
+ if (currentStatus.phase === "committing") return false;
+ activeRun.abortController.abort();
+ setStatus({ phase: "canceling", cancelRequested: true });
+ return true;
+ }
+
+ function status() {
+ return structuredClone(currentStatus);
+ }
+
+ function setStatus(patch) {
+ currentStatus = normalizeStatus({ ...currentStatus, ...patch });
+ try { deps.onStatus(structuredClone(currentStatus)); } catch { }
+ }
+
+ return { start, cancel, status };
+}
+
+async function runManualSync({ vault, settings: settingsValue, dependencies: deps, signal, effects, update }) {
+ requireNotAborted(signal);
+ const settings = normalizeSyncSettings(settingsValue);
+ if (!settings.enabled || !settings.vaultId) throw new Error("请先连接同步文件夹");
+ if (!vault?.header?.vaultId || vault.header.vaultId !== settings.vaultId) {
+ throw new Error("所选文件夹不是此前连接的同步库,请重新连接");
+ }
+
+ const meta = normalizeSyncMeta(await deps.readMeta());
+ requireNotAborted(signal);
+ const remoteSnapshots = await deps.listSnapshots(vault, { signal });
+ requireNotAborted(signal);
+
+ const maximumClock = Math.max(
+ meta.logicalClock,
+ 0,
+ ...remoteSnapshots.map((snapshot) => Number(snapshot?.logicalClock) || 0)
+ );
+ const baseSnapshot = revisionBase(meta.records);
+ const dirtyAssetIds = new Set(meta.dirtyAssetIds);
+ const previousRefs = {
+ ...syncObjectReferencesFromRecords(meta.records),
+ ...meta.assetRefs
+ };
+ for (const assetId of dirtyAssetIds) delete previousRefs[assetId];
+ if (!meta.localDirty && !dirtyAssetIds.size && Object.keys(meta.records).length) {
+ const unchangedLocal = {
+ format: SYNC_SNAPSHOT_FORMAT,
+ version: SYNC_SNAPSHOT_VERSION,
+ snapshotId: `local-meta:${settings.deviceId}`,
+ deviceId: settings.deviceId,
+ logicalClock: meta.logicalClock,
+ createdAt: "",
+ records: meta.records
+ };
+ const remotePreview = mergeRevisionSnapshots([...remoteSnapshots, unchangedLocal]);
+ if (sameRevisionRecords(remotePreview.records, meta.records)) {
+ return upToDateResult(remotePreview.state, { ...meta, assetRefs: previousRefs }, effects);
+ }
+ }
+
+ const current = await deps.readState();
+ requireNotAborted(signal);
+ let localPrepared = attachSyncImageReferences(current, previousRefs);
+ let localSnapshot = await createRevisionSnapshot(localPrepared, {
+ deviceId: settings.deviceId,
+ logicalClock: maximumClock + 1,
+ baseSnapshot
+ });
+ const preview = mergeRevisionSnapshots([...remoteSnapshots, localSnapshot]);
+
+ if (!meta.localDirty && !dirtyAssetIds.size && sameRevisionRecords(preview.records, meta.records)) {
+ return upToDateResult(current, { ...meta, assetRefs: previousRefs }, effects);
+ }
+
+ const localRefs = collectSyncImageReferences(localPrepared);
+ const missingAssets = collectSyncAssets(localPrepared).filter((asset) =>
+ asset.storageMode !== "reference" && !asset.objectId
+ );
+ if (missingAssets.length) update({ phase: "uploading" });
+ for (const [index, asset] of missingAssets.entries()) {
+ requireNotAborted(signal);
+ deps.onProgress({ phase: "uploading", current: index, total: missingAssets.length });
+ const blob = await deps.readMedia(asset.id);
+ requireNotAborted(signal);
+ if (!(blob instanceof Blob) || !blob.size) {
+ throw new Error(`本机媒体 ${asset.id} 已缺失,同步已停止且资料未被修改`);
+ }
+ const objectId = await deps.writeObject(vault, blob, { signal });
+ requireNotAborted(signal);
+ localRefs[asset.id] = { objectId, contentType: blob.type || asset.contentType };
+ effects.preparedRemoteObjects += 1;
+ }
+ if (missingAssets.length) deps.onProgress({ phase: "uploading", current: missingAssets.length, total: missingAssets.length });
+
+ localPrepared = attachSyncImageReferences(current, localRefs);
+ localSnapshot = await createRevisionSnapshot(localPrepared, {
+ deviceId: settings.deviceId,
+ logicalClock: maximumClock + 1,
+ baseSnapshot
+ });
+ update({ phase: "merging" });
+ const merged = mergeRevisionSnapshots([...remoteSnapshots, localSnapshot]);
+ if (syncStateHasContent(current) && !syncStateHasContent(merged.state)) {
+ throw new Error("同步结果异常为空,本机资料未被修改");
+ }
+ const finalPrepared = attachSyncImageReferences(merged.state, merged.imageRefs);
+ const finalSnapshot = await createRevisionSnapshot(finalPrepared, {
+ deviceId: settings.deviceId,
+ logicalClock: maximumClock + 2,
+ baseSnapshot: revisionBase(merged.records)
+ });
+ const changeSummary = summarizeRevisionChanges(meta.records, finalSnapshot.records, merged.conflicts);
+ const appliedChangeSummary = summarizeRevisionChanges(localSnapshot.records, finalSnapshot.records, merged.conflicts);
+
+ if (sameRevisionRecords(finalSnapshot.records, meta.records)) {
+ if (meta.localDirty || dirtyAssetIds.size) {
+ requireNotAborted(signal);
+ await deps.commit({
+ state: current,
+ settings,
+ meta: { ...meta, assetRefs: localRefs, localDirty: false, dirtyAssetIds: [] },
+ trackingOnly: true,
+ changeSummary
+ });
+ effects.localMetadataCommitted = true;
+ }
+ return upToDateResult(current, { ...meta, assetRefs: localRefs }, effects);
+ }
+
+ const replacements = remoteMediaReplacements({
+ vault,
+ imageRefs: merged.imageRefs,
+ localRefs,
+ readObject: deps.readObject,
+ signal,
+ onProgress: deps.onProgress
+ });
+ update({ phase: "downloading", changeSummary });
+ const lastSyncAt = deps.now();
+ const restoredMediaCount = countDifferentReferences(merged.imageRefs, localRefs);
+ effects.localBusinessChanged = hasChanges(appliedChangeSummary) || restoredMediaCount > 0;
+ const nextSettings = normalizeSyncSettings({
+ ...settings,
+ lastSyncAt,
+ lastError: "",
+ lastErrorCode: ""
+ });
+
+ await deps.replaceMediaWithRollback({
+ replacements,
+ readImage: deps.readMedia,
+ writeImage: deps.writeMedia,
+ deleteImage: deps.deleteMedia,
+ commitMetadata: async () => {
+ requireNotAborted(signal);
+ update({ phase: "committing", changeSummary });
+ await deps.writeSnapshot(vault, finalSnapshot, { retentionCount: settings.retentionCount });
+ effects.snapshotWritten = true;
+ await deps.commit({
+ state: merged.state,
+ settings: nextSettings,
+ meta: {
+ logicalClock: maximumClock + 2,
+ records: finalSnapshot.records,
+ assetRefs: merged.imageRefs,
+ localDirty: false,
+ dirtyAssetIds: []
+ },
+ trackingOnly: false,
+ changeSummary
+ });
+ effects.localMetadataCommitted = true;
+ }
+ });
+ effects.localMediaCommitted = restoredMediaCount;
+
+ return {
+ ok: true,
+ upToDate: false,
+ canceled: false,
+ entryCount: merged.state.entries?.length ?? 0,
+ mediaCount: Object.keys(merged.imageRefs).length,
+ conflictCount: merged.conflicts.length,
+ addedCount: changeSummary.added,
+ updatedCount: changeSummary.updated,
+ deletedCount: changeSummary.deleted,
+ changeSummary,
+ appliedChangeSummary,
+ lastSyncAt,
+ effects: structuredClone(effects)
+ };
+}
+
+async function* remoteMediaReplacements({ vault, imageRefs, localRefs, readObject, signal, onProgress }) {
+ const pending = Object.entries(imageRefs).filter(([assetId, reference]) =>
+ localRefs?.[assetId]?.objectId !== reference?.objectId
+ );
+ for (const [index, [assetId, reference]] of pending.entries()) {
+ requireNotAborted(signal);
+ onProgress({ phase: "downloading", current: index, total: pending.length });
+ const blob = await readObject(vault, reference.objectId, { signal });
+ requireNotAborted(signal);
+ yield { id: assetId, blob };
+ }
+ onProgress({ phase: "downloading", current: pending.length, total: pending.length });
+}
+
+function validateDependencies(value) {
+ const required = ["readState", "readMeta", "readMedia", "writeMedia", "deleteMedia", "commit"];
+ for (const name of required) {
+ if (typeof value[name] !== "function") throw new Error(`手动同步缺少 ${name} 依赖`);
+ }
+ const onProgress = typeof value.onProgress === "function" ? value.onProgress : () => undefined;
+ return {
+ ...value,
+ listSnapshots: value.listSnapshots ?? listSyncSnapshots,
+ writeObject: value.writeObject ?? writeSyncObject,
+ readObject: value.readObject ?? readSyncObject,
+ writeSnapshot: value.writeSnapshot ?? writeSyncSnapshot,
+ replaceMediaWithRollback: value.replaceMediaWithRollback ?? replaceImagesWithRollback,
+ onProgress: (progress) => {
+ try { onProgress(progress); } catch { }
+ },
+ onStatus: typeof value.onStatus === "function" ? value.onStatus : () => undefined,
+ now: typeof value.now === "function" ? value.now : () => new Date().toISOString()
+ };
+}
+
+function revisionBase(records) {
+ return { format: SYNC_SNAPSHOT_FORMAT, version: SYNC_SNAPSHOT_VERSION, records };
+}
+
+function upToDateResult(state, meta, effects) {
+ return {
+ ok: true,
+ upToDate: true,
+ canceled: false,
+ entryCount: state.entries?.length ?? 0,
+ mediaCount: Object.keys(meta.assetRefs ?? {}).length,
+ conflictCount: 0,
+ addedCount: 0,
+ updatedCount: 0,
+ deletedCount: 0,
+ changeSummary: emptyChangeSummary(),
+ effects: structuredClone(effects)
+ };
+}
+
+function canceledResult(effects) {
+ return {
+ ok: false,
+ upToDate: false,
+ canceled: true,
+ conflictCount: 0,
+ addedCount: 0,
+ updatedCount: 0,
+ deletedCount: 0,
+ changeSummary: emptyChangeSummary(),
+ effects: structuredClone(effects)
+ };
+}
+
+function countDifferentReferences(next, before) {
+ return Object.entries(next).filter(([assetId, reference]) =>
+ before?.[assetId]?.objectId !== reference?.objectId
+ ).length;
+}
+
+function idleStatus() {
+ return normalizeStatus({
+ state: "idle",
+ phase: "idle",
+ active: false,
+ pendingCount: 0,
+ runningCount: 0,
+ startedAt: "",
+ finishedAt: "",
+ cancelRequested: false,
+ effects: emptyEffects(),
+ changeSummary: emptyChangeSummary(),
+ error: ""
+ });
+}
+
+function normalizeStatus(value) {
+ const state = String(value?.state ?? "idle");
+ return {
+ state,
+ phase: String(value?.phase ?? state),
+ active: value?.active === true,
+ terminal: TERMINAL_STATES.has(state),
+ pendingCount: Math.max(0, Number(value?.pendingCount) || 0),
+ runningCount: Math.max(0, Number(value?.runningCount) || 0),
+ startedAt: String(value?.startedAt ?? ""),
+ finishedAt: String(value?.finishedAt ?? ""),
+ cancelRequested: value?.cancelRequested === true,
+ effects: structuredClone(value?.effects ?? emptyEffects()),
+ changeSummary: structuredClone(value?.changeSummary ?? emptyChangeSummary()),
+ error: String(value?.error ?? "")
+ };
+}
+
+function emptyEffects() {
+ return {
+ preparedRemoteObjects: 0,
+ snapshotWritten: false,
+ localMediaCommitted: 0,
+ localBusinessChanged: false,
+ localMetadataCommitted: false
+ };
+}
+
+function emptyChangeSummary() {
+ return { added: 0, updated: 0, deleted: 0, conflicts: 0, byEntity: {} };
+}
+
+function hasChanges(summary = {}) {
+ return Boolean(summary.added || summary.updated || summary.deleted || summary.conflicts);
+}
+
+function requireNotAborted(signal) {
+ if (!signal?.aborted) return;
+ if (typeof signal.throwIfAborted === "function") signal.throwIfAborted();
+ throw new DOMException("同步已取消", "AbortError");
+}
+
+function isAbortError(error) {
+ return error?.name === "AbortError";
+}
+
+function cleanError(error) {
+ return String(error?.message ?? error ?? "同步失败").trim() || "同步失败";
+}
diff --git a/package-lock.json b/package-lock.json
index 91f3500..75746f2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "prompt-case-collector",
- "version": "1.18.13",
+ "version": "1.18.16",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.18.13",
+ "version": "1.18.16",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
diff --git a/package.json b/package.json
index 74eddb9..4de90e9 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.18.13",
+ "version": "1.18.16",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
diff --git a/skills-page.css b/skills-page.css
index ce77cdb..94ea30d 100644
--- a/skills-page.css
+++ b/skills-page.css
@@ -27,7 +27,7 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skills-heading-actions { display: flex; gap: 8px; }
.skill-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); align-content: start; align-items: start; gap: 8px; }
.skill-card { min-height: 152px; display: flex; flex-direction: column; align-items: stretch; padding: 16px; text-align: left; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); background: var(--skill-panel); color: var(--ink); box-shadow: none; }
-.skill-card:hover { border-color: var(--selection-edge); background: var(--raised); }
+.skill-card:hover:not(:disabled) { border-color: var(--selection-edge); background: var(--raised); }
.skill-card header { display: flex; justify-content: space-between; gap: 12px; }
.skill-card h2 { margin: 0; font-size: 17px; letter-spacing: 0; overflow-wrap: anywhere; }
.skill-card code { color: var(--accent, #39784d); font-size: 12px; }
@@ -139,6 +139,26 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skill-import-dialog header { display: flex; justify-content: space-between; gap: 16px; }
.skill-import-dialog h2 { margin: 3px 0 0; }
.skill-import-dialog p { color: var(--muted, #697069); line-height: 1.6; }
+.skill-submission-dialog { width: min(900px, calc(100vw - 32px)); max-height: calc(100dvh - 32px); border: 1px solid var(--ui-border-strong); border-radius: var(--ui-container-radius); padding: 24px; color: var(--ui-text); background: var(--ui-surface); }
+.skill-submission-dialog::backdrop { background: rgba(0,0,0,.72); }
+.skill-submission-dialog header { display: flex; justify-content: space-between; align-items: start; }
+.skill-submission-dialog header small { color: var(--ui-accent); }
+.skill-submission-dialog h2 { margin: 4px 0 0; }
+.skill-submission-dialog > p { color: var(--ui-muted); }
+.skill-submission-fields { display: grid; gap: 14px; }
+.skill-submission-fields label:not(.skill-submission-rights) { display: grid; gap: 6px; }
+.skill-submission-summary textarea { min-height: 90px; resize: vertical; }
+.skill-submission-rights { display: flex; align-items: flex-start; gap: 9px; border: 1px solid var(--ui-border); border-radius: var(--ui-container-radius); padding: 12px; background: var(--ui-raised); }
+.skill-submission-rights input { width: 16px; min-height: 16px; margin: 2px 0 0; accent-color: var(--ui-accent); }
+.skill-submission-field-error { color: var(--ui-danger); font-size: var(--ui-meta-size); }
+.skill-submission-rights-error { margin-top: -9px; }
+.skill-submission-license-details { color: var(--ui-muted); font-size: var(--ui-meta-size); }
+.skill-submission-license-details summary { width: max-content; cursor: pointer; color: var(--ui-text); }
+.skill-submission-license-details p { max-width: 660px; margin: 8px 0 0; }
+.skill-submission-actions { display: flex; justify-content: flex-end; gap: 10px; margin: 18px 0; }
+.skill-submission-findings { border: 1px solid var(--ui-danger); border-radius: var(--ui-container-radius); padding: 14px; }
+.skill-submission-preview details { margin-top: 10px; border: 1px solid var(--ui-border); border-radius: var(--ui-container-radius); padding: 10px; background: var(--ui-raised); }
+.skill-submission-preview pre { overflow: auto; white-space: pre-wrap; }
.skill-detail-header { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 18px; }
.skill-detail-header h1 { margin: 3px 0 0; font-size: clamp(24px, 3vw, 38px); letter-spacing: 0; }
@@ -216,6 +236,10 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skill-step-actions button { flex: 1 1 140px; }
}
+@media (max-width: 480px) {
+ .skill-submission-actions { align-items: stretch; flex-direction: column; }
+}
+
@media (max-width: 480px) {
.skills-topbar { gap: 8px; padding-inline: 12px; }
.skills-brand { min-width: 0; gap: 8px; }
diff --git a/skills-page.js b/skills-page.js
index 2d1e2e4..4afb41e 100644
--- a/skills-page.js
+++ b/skills-page.js
@@ -7,10 +7,15 @@ import {
} from "./creative-skills.js";
import {
buildProvenanceMarkdown,
- exportGeneratedSkillPackage,
+ exportStoredSkillPackage,
parseSkillArchive,
parseSkillFiles
} from "./creative-skill-package.js";
+import {
+ buildCuratedSkillSnapshot,
+ buildCuratedSkillSubmissionArchive
+} from "./curated-skill-package.js";
+import { CURATED_SKILL_SUBMISSION_URL } from "./curated-config.js";
import {
analyzeCreativeSkillVisualBatch,
anonymousSkillSources,
@@ -55,14 +60,17 @@ import { bindTransientMenus } from "./transient-menu.js";
await initializeUi();
bindTransientMenus(document, ".skill-detail-more, .skill-project-picker");
+const CURATED_SKILL_PUBLISHER_STORAGE_KEY = "curatedSkillPublisher";
+
const elements = Object.fromEntries([
"skill-search", "skill-import", "skill-create", "skill-context-back", "skill-zip-file", "skill-folder-files", "skill-library", "skill-summary", "skill-feedback", "skill-list", "skill-empty", "skill-empty-create",
- "skill-detail", "skill-detail-title", "skill-detail-call-name", "skill-detail-feedback", "skill-detail-description", "skill-detail-version", "skill-detail-source", "skill-detail-updated", "skill-detail-markdown", "skill-detail-edit", "skill-detail-more", "skill-detail-refine", "skill-export",
+ "skill-detail", "skill-detail-title", "skill-detail-call-name", "skill-detail-feedback", "skill-detail-description", "skill-detail-version", "skill-detail-source", "skill-detail-updated", "skill-detail-markdown", "skill-detail-edit", "skill-detail-more", "skill-detail-refine", "skill-export", "skill-submit-curated",
"skill-workspace", "skill-workspace-kicker", "skill-workspace-title", "skill-delete", "skill-builder", "skill-source-sidebar", "skill-source-step", "skill-target-step", "skill-selected-count", "skill-project-picker", "skill-project-label", "skill-project-filter", "skill-case-search", "skill-clear-selection", "skill-visible-select", "skill-selection-summary", "skill-case-scroll", "skill-case-grid", "skill-case-load-more",
"skill-run-evidence-step", "skill-run-evidence-count", "skill-run-evidence-list",
"skill-goal", "skill-use-vision", "skill-vision-toggle-note", "skill-vision-preview", "skill-advanced", "skill-text-provider-menu", "skill-vision-provider-menu", "skill-text-instruction", "skill-vision-instruction", "skill-restore-instructions", "skill-request-preview", "skill-generate", "skill-retry-vision", "skill-run-panel", "skill-generation-status", "skill-run-elapsed", "skill-stop-run", "skill-run-progress", "skill-run-stages", "skill-run-log", "skill-generation-feedback", "skill-draft-step", "skill-draft-editor", "skill-version-label", "skill-call-name", "skill-description", "skill-markdown", "skill-save", "skill-test", "skill-save-status", "skill-versions-step", "skill-version-list",
"skill-source-inspector-backdrop", "skill-source-inspector", "skill-source-inspector-title", "skill-source-inspector-close", "skill-source-select-all", "skill-source-clear", "skill-source-text-option", "skill-source-include-text", "skill-source-asset-list", "skill-source-cancel", "skill-source-apply",
- "skill-import-dialog", "skill-import-close", "skill-import-zip", "skill-import-folder"
+ "skill-import-dialog", "skill-import-close", "skill-import-zip", "skill-import-folder",
+ "skill-submission-dialog", "skill-submission-close", "skill-submission-author", "skill-submission-author-error", "skill-submission-summary", "skill-submission-summary-error", "skill-submission-rights", "skill-submission-rights-error", "skill-submission-refresh", "skill-submission-open", "skill-submission-feedback", "skill-submission-findings", "skill-submission-preview"
].map((id) => [camel(id), document.querySelector(`#${id}`)]));
let entries = [];
@@ -89,6 +97,7 @@ let runtimeOverrides = { text: null, vision: null };
let skillRuntimeSettings = null;
let activeSkillRun = null;
let visionPreferenceTouched = false;
+let curatedSubmissionSnapshot = null;
bindEvents();
await refreshState();
@@ -102,12 +111,21 @@ function bindEvents() {
elements.skillDetailEdit.addEventListener("click", () => navigateTo("editor", activeSkillId));
elements.skillDetailRefine.addEventListener("click", () => navigateTo("refine", activeSkillId));
elements.skillExport.addEventListener("click", () => safely(exportSkill)());
+ elements.skillSubmitCurated.addEventListener("click", () => runCuratedSubmissionAction(openCuratedSubmission));
elements.skillImport.addEventListener("click", () => elements.skillImportDialog.showModal());
elements.skillImportClose.addEventListener("click", () => elements.skillImportDialog.close());
elements.skillImportZip.addEventListener("click", () => elements.skillZipFile.click());
elements.skillImportFolder.addEventListener("click", () => elements.skillFolderFiles.click());
elements.skillZipFile.addEventListener("change", () => safely(importZip)());
elements.skillFolderFiles.addEventListener("change", () => safely(importFolder)());
+ elements.skillSubmissionClose.addEventListener("click", () => elements.skillSubmissionDialog.close());
+ elements.skillSubmissionRefresh.addEventListener("click", () => runCuratedSubmissionAction(refreshCuratedSubmission));
+ elements.skillSubmissionOpen.addEventListener("click", () => runCuratedSubmissionAction(downloadCuratedSubmission));
+ for (const field of [
+ elements.skillSubmissionAuthor,
+ elements.skillSubmissionSummary,
+ elements.skillSubmissionRights
+ ]) field.addEventListener("input", invalidateCuratedSubmission);
elements.skillCaseSearch.addEventListener("input", () => renderCases({ reset: true }));
elements.skillClearSelection.addEventListener("click", clearAllSourceSelections);
elements.skillVisibleSelect.addEventListener("click", toggleVisibleCases);
@@ -1026,16 +1044,18 @@ async function testSkill() {
async function exportSkill() {
const skill = activeSkill();
- const version = currentCreativeSkillVersion(skill);
- if (!skill || !version) return;
- const archive = await exportGeneratedSkillPackage({
- portableId: skill.portableId,
- description: skill.description,
- skillMarkdown: version.skillMarkdown,
- references: version.references,
- provenanceMarkdown: version.provenanceMarkdown
+ if (!skill) return;
+ const archive = await exportStoredSkillPackage(skill, { readFile: getMediaBlob });
+ await downloadBlob(archive, {
+ filename: `PromptDirector-Skill-${skill.portableId}.zip`,
+ saveAs: false,
+ failureMessage: t("Skill 导出失败")
});
- const url = URL.createObjectURL(archive);
+ setFeedback(elements.skillDetailFeedback, t("Skill 已导出"));
+}
+
+async function downloadBlob(blob, options = {}) {
+ const url = URL.createObjectURL(blob);
let downloadId = 0;
let finishDownload;
const completed = new Promise((resolve) => { finishDownload = resolve; });
@@ -1047,20 +1067,117 @@ async function exportSkill() {
try {
downloadId = await chrome.downloads.download({
url,
- filename: `PromptDirector-Skill-${skill.portableId}.zip`,
+ filename: options.filename,
conflictAction: "uniquify",
- saveAs: false
+ saveAs: options.saveAs === true
});
const [record] = await chrome.downloads.search({ id: downloadId });
const state = ["complete", "interrupted"].includes(record?.state) ? record.state : await completed;
- if (state !== "complete") throw new Error(t("Skill 导出失败"));
- setFeedback(elements.skillDetailFeedback, t("Skill 已导出"));
+ if (state !== "complete") throw new Error(options.failureMessage || t("下载失败"));
+ return downloadId;
} finally {
chrome.downloads.onChanged.removeListener(onChanged);
URL.revokeObjectURL(url);
}
}
+function invalidateCuratedSubmission() {
+ curatedSubmissionSnapshot = null;
+ elements.skillSubmissionOpen.disabled = true;
+ clearCuratedSubmissionErrors();
+}
+
+async function openCuratedSubmission() {
+ const skill = activeSkill();
+ if (!skill) return;
+ const stored = await chrome.storage.local.get(CURATED_SKILL_PUBLISHER_STORAGE_KEY);
+ curatedSubmissionSnapshot = null;
+ elements.skillSubmissionAuthor.value = String(stored[CURATED_SKILL_PUBLISHER_STORAGE_KEY] ?? "");
+ elements.skillSubmissionSummary.value = skill.description;
+ elements.skillSubmissionRights.checked = false;
+ clearCuratedSubmissionErrors();
+ elements.skillSubmissionPreview.replaceChildren();
+ elements.skillSubmissionFindings.hidden = true;
+ elements.skillSubmissionOpen.disabled = true;
+ setFeedback(elements.skillSubmissionFeedback, "填写署名并确认开放使用后,生成可逐字核对的公开快照。");
+ elements.skillSubmissionDialog.showModal();
+}
+
+async function refreshCuratedSubmission() {
+ const skill = activeSkill();
+ if (!skill) return;
+ if (!validateCuratedSubmissionFields()) return;
+ const snapshot = await buildCuratedSkillSnapshot(skill, {
+ author: elements.skillSubmissionAuthor.value,
+ summary: elements.skillSubmissionSummary.value,
+ rightsConfirmed: elements.skillSubmissionRights.checked
+ });
+ await chrome.storage.local.set({ [CURATED_SKILL_PUBLISHER_STORAGE_KEY]: elements.skillSubmissionAuthor.value.trim() });
+ curatedSubmissionSnapshot = snapshot;
+ elements.skillSubmissionPreview.replaceChildren(...snapshot.preview.map((file) => {
+ const detail = document.createElement("details");
+ detail.open = true;
+ detail.append(textEl("summary", `${file.path} · ${file.byteSize} bytes`), textEl("pre", file.text));
+ return detail;
+ }));
+ const list = elements.skillSubmissionFindings.querySelector("ul");
+ list.replaceChildren(...snapshot.findings.map((finding) => textEl("li", `${finding.path}:${finding.message}(${finding.excerpt})`)));
+ elements.skillSubmissionFindings.hidden = snapshot.findings.length === 0;
+ elements.skillSubmissionOpen.disabled = snapshot.findings.length > 0;
+ setFeedback(elements.skillSubmissionFeedback, snapshot.findings.length
+ ? "发现可能的隐私风险。快照没有被改写,请修改本地 Skill 后重新检查。"
+ : `已生成 ${snapshot.preview.length} 个纯文本文件;请逐一核对全文。`, snapshot.findings.length > 0);
+}
+
+async function downloadCuratedSubmission() {
+ if (!curatedSubmissionSnapshot) throw new Error("请先生成并检查公开快照");
+ const archive = await buildCuratedSkillSubmissionArchive(curatedSubmissionSnapshot);
+ await downloadBlob(archive, {
+ filename: `PromptDirector-Skill-Submission-${curatedSubmissionSnapshot.manifest.skillId}.zip`,
+ saveAs: true,
+ failureMessage: "精选 Skill 投稿包下载失败"
+ });
+ await chrome.tabs.create({ url: CURATED_SKILL_SUBMISSION_URL });
+ setFeedback(elements.skillSubmissionFeedback, "投稿包已下载,并已打开 GitHub 投稿页。请手动上传、核对并提交;不会自动发布。 ");
+}
+
+function clearCuratedSubmissionErrors() {
+ for (const [field, error] of [
+ [elements.skillSubmissionAuthor, elements.skillSubmissionAuthorError],
+ [elements.skillSubmissionSummary, elements.skillSubmissionSummaryError],
+ [elements.skillSubmissionRights, elements.skillSubmissionRightsError]
+ ]) {
+ field.removeAttribute("aria-invalid");
+ error.hidden = true;
+ error.textContent = "";
+ }
+}
+
+function validateCuratedSubmissionFields() {
+ clearCuratedSubmissionErrors();
+ const invalid = [];
+ if (!elements.skillSubmissionAuthor.value.trim()) invalid.push([elements.skillSubmissionAuthor, elements.skillSubmissionAuthorError, "请填写公开署名"]);
+ if (!elements.skillSubmissionSummary.value.trim()) invalid.push([elements.skillSubmissionSummary, elements.skillSubmissionSummaryError, "请填写公开摘要"]);
+ if (!elements.skillSubmissionRights.checked) invalid.push([elements.skillSubmissionRights, elements.skillSubmissionRightsError, "请确认开放使用范围"]);
+ for (const [field, error, message] of invalid) {
+ field.setAttribute("aria-invalid", "true");
+ error.textContent = message;
+ error.hidden = false;
+ }
+ if (!invalid.length) return true;
+ invalid[0][0].focus();
+ setFeedback(elements.skillSubmissionFeedback, "请先完成标出的公开信息。", true);
+ return false;
+}
+
+async function runCuratedSubmissionAction(action) {
+ try {
+ await action();
+ } catch (error) {
+ setFeedback(elements.skillSubmissionFeedback, error.message || "精选 Skill 投稿操作失败", true);
+ }
+}
+
async function importZip() {
const file = elements.skillZipFile.files?.[0];
elements.skillZipFile.value = "";
diff --git a/skills.html b/skills.html
index 2610612..7dd706e 100644
--- a/skills.html
+++ b/skills.html
@@ -22,7 +22,7 @@
<main class="skills-main">
<section id="skill-library" class="skill-library">
- <div class="skills-heading"><div><h1 data-i18n="创作 Skill 中心">创作 Skill 中心</h1><p id="skill-summary"></p></div><div class="skills-heading-actions"><button id="skill-import" class="button-secondary" type="button" data-i18n="导入">导入</button><button id="skill-create" type="button" data-i18n="新建 Skill">新建 Skill</button></div></div>
+ <div class="skills-heading"><div><h1 data-i18n="创作 Skill 中心">创作 Skill 中心</h1><p id="skill-summary"></p></div><div class="skills-heading-actions"><a class="button-secondary" href="curated-skills.html">精选 Skill</a><button id="skill-import" class="button-secondary" type="button" data-i18n="导入">导入</button><button id="skill-create" type="button" data-i18n="新建 Skill">新建 Skill</button></div></div>
<p id="skill-feedback" class="skill-feedback" role="status"></p>
<div id="skill-list" class="skill-grid"></div>
<div id="skill-empty" class="skill-empty" hidden><strong data-i18n="还没有创作 Skill">还没有创作 Skill</strong><p data-i18n="从你真正喜欢的案例中,按明确目标提炼一份可重复调用的方法。">从你真正喜欢的案例中,按明确目标提炼一份可重复调用的方法。</p><button id="skill-empty-create" type="button" data-i18n="创建第一份 Skill">创建第一份 Skill</button></div>
@@ -39,6 +39,7 @@
<div class="skill-detail-more-panel">
<button id="skill-detail-refine" class="button-secondary" type="button" data-i18n="用证据改进 Skill">用证据改进 Skill</button>
<button id="skill-export" class="button-secondary" type="button" data-i18n="导出 Skill">导出 Skill</button>
+ <button id="skill-submit-curated" class="button-secondary" type="button" data-i18n="投稿到精选 Skill">投稿到精选 Skill</button>
</div>
</details>
</div>
@@ -143,6 +144,21 @@
<p data-i18n="完整包会随私人备份保留;PromptDirector 只读取 SKILL.md 和 Markdown references,不执行脚本、程序、MCP 或二进制文件。">完整包会随私人备份保留;PromptDirector 只读取 SKILL.md 和 Markdown references,不执行脚本、程序、MCP 或二进制文件。</p>
<div><button id="skill-import-zip" type="button" data-i18n="选择 ZIP">选择 ZIP</button><button id="skill-import-folder" class="button-secondary" type="button" data-i18n="选择目录">选择目录</button></div>
</dialog>
+ <dialog id="skill-submission-dialog" class="skill-submission-dialog">
+ <header><div><small>公开投稿</small><h2>投稿到精选 Skill</h2></div><button id="skill-submission-close" class="icon-button" type="button" aria-label="关闭" title="关闭"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-x"></use></svg></button></header>
+ <p>投稿与普通导出相互独立。这里只生成可公开审核的纯文本快照,不包含脚本、二进制文件或默认的私人来源记录。</p>
+ <div class="skill-submission-fields">
+ <label><span>公开署名</span><input id="skill-submission-author" autocomplete="name" aria-describedby="skill-submission-author-error" /><small id="skill-submission-author-error" class="skill-submission-field-error" hidden></small></label>
+ <label class="skill-submission-summary"><span>公开摘要</span><textarea id="skill-submission-summary" rows="3" aria-describedby="skill-submission-summary-error"></textarea><small id="skill-submission-summary-error" class="skill-submission-field-error" hidden></small></label>
+ <label class="skill-submission-rights"><input id="skill-submission-rights" type="checkbox" aria-describedby="skill-submission-rights-error" /><span>允许其他用户在保留署名的前提下保存、使用和修改。</span></label>
+ <small id="skill-submission-rights-error" class="skill-submission-field-error skill-submission-rights-error" hidden></small>
+ <details class="skill-submission-license-details"><summary>了解公开使用规则</summary><p>投稿采用 CC BY 4.0:其他用户必须保留你的公开署名,并可保存、使用和修改这份 Skill。</p></details>
+ </div>
+ <div class="skill-submission-actions"><button id="skill-submission-refresh" class="button-secondary" type="button">生成并检查公开快照</button><button id="skill-submission-open" type="button" disabled>下载投稿包并打开 GitHub</button></div>
+ <p id="skill-submission-feedback" class="skill-feedback" role="status"></p>
+ <section id="skill-submission-findings" class="skill-submission-findings" hidden><h3>需要先处理的隐私风险</h3><ul></ul></section>
+ <section class="skill-submission-preview-shell"><h3>最终投稿文件与全文</h3><div id="skill-submission-preview" class="skill-submission-preview"></div></section>
+ </dialog>
<script type="module" src="skills-page.js"></script>
</body>
</html>
diff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/CHROME_WEB_STORE_SUBMISSION.md
index 90fb6e8..d1499e4 100644
--- a/store/CHROME_WEB_STORE_SUBMISSION.md
+++ b/store/CHROME_WEB_STORE_SUBMISSION.md
@@ -6,9 +6,9 @@ This file is the source-of-truth worksheet for the current PromptDirector manife
- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.
- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.
-- Current release candidate: `dist/PromptDirector-1.18.13.zip`.
-- Candidate size: `8,376,041` bytes.
-- Candidate SHA-256: `eb6d9281e4bfcdd879c1b4434691d4f4e93ad8b04ab3638132297f887b3499b0`.
+- Current release candidate: `dist/PromptDirector-1.18.16.zip`.
+- Candidate size: `8,462,460` bytes.
+- Candidate SHA-256: `49f6bd04d05fd5c6ef8515fe6307e0d130d08196e04698a7afd82d4cca5ebc05`.
- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest.
## Store listing
diff --git a/sync-model.js b/sync-model.js
index be0cbd7..8f1ad28 100644
--- a/sync-model.js
+++ b/sync-model.js
@@ -6,7 +6,8 @@ export const SYNC_SNAPSHOT_FORMAT = "prompt-director-sync-state";
export const SYNC_SNAPSHOT_VERSION = 1;
export const DEFAULT_SYNC_RETENTION = 10;
export const SYNC_ERROR_CODES = Object.freeze({
- LOCATION_NOT_FOUND: "location_not_found"
+ LOCATION_NOT_FOUND: "location_not_found",
+ SNAPSHOT_CORRUPT: "sync_snapshot_corrupt"
});
const SYNC_LOCATION_NOT_FOUND_MESSAGE = "同步文件夹中的文件或目录不存在,请重新选择同步文件夹后再同步";
@@ -37,7 +38,7 @@ export function normalizeSyncSettings(value = {}) {
const deviceId = cleanId(value.deviceId) || `device:${crypto.randomUUID()}`;
const storedError = syncErrorDetails(value.lastError);
const storedCode = cleanText(value.lastErrorCode);
- const lastErrorCode = storedCode === SYNC_ERROR_CODES.LOCATION_NOT_FOUND
+ const lastErrorCode = Object.values(SYNC_ERROR_CODES).includes(storedCode)
? storedCode
: storedError.code;
return {
@@ -53,10 +54,44 @@ export function normalizeSyncSettings(value = {}) {
};
}
+export function normalizeSyncMeta(value = {}) {
+ const assetRefs = {};
+ for (const [assetId, reference] of Object.entries(value?.assetRefs ?? {})) {
+ if (!cleanId(assetId) || !validSyncObjectId(reference?.objectId)) continue;
+ assetRefs[cleanId(assetId)] = {
+ objectId: reference.objectId,
+ contentType: cleanText(reference.contentType) || "application/octet-stream"
+ };
+ }
+ return {
+ logicalClock: Math.max(0, Math.floor(Number(value?.logicalClock) || 0)),
+ records: value?.records && typeof value.records === "object" ? structuredClone(value.records) : {},
+ assetRefs,
+ localDirty: value?.localDirty === true,
+ dirtyAssetIds: [...new Set((Array.isArray(value?.dirtyAssetIds) ? value.dirtyAssetIds : [])
+ .map(cleanId).filter(Boolean))]
+ };
+}
+
+export function markSyncMetaDirty(value = {}, assetIds = []) {
+ const meta = normalizeSyncMeta(value);
+ return {
+ ...meta,
+ localDirty: true,
+ dirtyAssetIds: [...new Set([
+ ...meta.dirtyAssetIds,
+ ...(Array.isArray(assetIds) ? assetIds : [assetIds]).map(cleanId).filter(Boolean)
+ ])]
+ };
+}
+
export function syncErrorDetails(value) {
const objectValue = value && typeof value === "object" ? value : null;
const name = cleanText(objectValue?.name);
const message = cleanText(objectValue?.message ?? value);
+ if (objectValue?.code === SYNC_ERROR_CODES.SNAPSHOT_CORRUPT) {
+ return { code: SYNC_ERROR_CODES.SNAPSHOT_CORRUPT, message: message || "同步目录包含损坏的正式状态文件,本地资料未被修改" };
+ }
if (name === "NotFoundError" || LEGACY_LOCATION_NOT_FOUND_PATTERN.test(message)) {
return {
code: SYNC_ERROR_CODES.LOCATION_NOT_FOUND,
@@ -79,6 +114,68 @@ export function collectSyncImageReferences(stateValue = {}) {
return references;
}
+export function collectSyncAssets(stateValue = {}) {
+ const assets = [];
+ const seen = new Set();
+ for (const asset of stateStoredAssets(stateValue)) {
+ const id = storedAssetId(asset);
+ if (!id || seen.has(id)) continue;
+ seen.add(id);
+ assets.push({
+ id,
+ storageMode: cleanText(asset?.storageMode) || "managed",
+ contentType: cleanText(asset?.syncContentType) || cleanText(asset?.mimeType) || "application/octet-stream",
+ objectId: validSyncObjectId(asset?.syncObjectId) ? asset.syncObjectId : ""
+ });
+ }
+ return assets;
+}
+
+export function syncObjectReferencesFromRecords(records = {}) {
+ if (!records || typeof records !== "object") return {};
+ const restoredState = restoreState(records);
+ return {
+ ...collectSyncImageReferences(restoredState.state),
+ ...restoredState.imageRefs
+ };
+}
+
+export function sameRevisionRecords(left = {}, right = {}) {
+ const leftKeys = Object.keys(left).sort();
+ const rightKeys = Object.keys(right).sort();
+ if (leftKeys.length !== rightKeys.length || leftKeys.some((key, index) => key !== rightKeys[index])) return false;
+ return leftKeys.every((key) => {
+ const before = left[key];
+ const after = right[key];
+ return before?.revisionId === after?.revisionId &&
+ cleanText(before?.deletedAt) === cleanText(after?.deletedAt) &&
+ before?.fingerprint === after?.fingerprint;
+ });
+}
+
+export function summarizeRevisionChanges(beforeRecords = {}, afterRecords = {}, conflicts = []) {
+ const summary = { added: 0, updated: 0, deleted: 0, conflicts: conflicts.length, byEntity: {} };
+ const keys = new Set([...Object.keys(beforeRecords ?? {}), ...Object.keys(afterRecords ?? {})]);
+ for (const key of keys) {
+ const before = beforeRecords?.[key];
+ const after = afterRecords?.[key];
+ if (before?.revisionId === after?.revisionId) continue;
+ const entityType = splitKey(key)[0] || "unknown";
+ const bucket = summary.byEntity[entityType] ??= { added: 0, updated: 0, deleted: 0 };
+ if ((!before || before.deletedAt) && after && !after.deletedAt) {
+ summary.added += 1;
+ bucket.added += 1;
+ } else if (before && !before.deletedAt && (!after || after.deletedAt)) {
+ summary.deleted += 1;
+ bucket.deleted += 1;
+ } else {
+ summary.updated += 1;
+ bucket.updated += 1;
+ }
+ }
+ return summary;
+}
+
export function attachSyncImageReferences(stateValue = {}, references = {}) {
const state = structuredClone(stateValue);
for (const asset of stateStoredAssets(state)) {
diff --git a/sync-vault.js b/sync-vault.js
index f2e3069..6d7e08d 100644
--- a/sync-vault.js
+++ b/sync-vault.js
@@ -13,6 +13,7 @@ import {
SYNC_SNAPSHOT_FORMAT,
SYNC_SNAPSHOT_VERSION
} from "./sync-model.js";
+import { assetFormatsForMimeType } from "./asset-formats.js";
export const SYNC_DIRECTORY_NAME = "PromptDirector-Sync";
const HEADER_FILENAME = "vault.json";
@@ -60,27 +61,40 @@ export async function openSyncVaultWithKey(rootDirectory, key, expectedVaultId =
return { rootDirectory, directory, header, key };
}
-export async function listSyncSnapshots(vault) {
+export async function listSyncSnapshots(vault, options = {}) {
validateVault(vault);
- const devices = await vault.directory.getDirectoryHandle("devices", { create: true });
+ throwIfAborted(options.signal);
+ const devices = await vault.directory.getDirectoryHandle("devices");
const snapshots = [];
let encryptedFileCount = 0;
+ const corruptFiles = [];
for await (const device of devices.values()) {
+ throwIfAborted(options.signal);
if (device.kind !== "directory") continue;
for await (const fileHandle of device.values()) {
+ throwIfAborted(options.signal);
if (fileHandle.kind !== "file" || !fileHandle.name.endsWith(".pds")) continue;
encryptedFileCount += 1;
try {
const encrypted = await readJsonHandle(fileHandle);
+ throwIfAborted(options.signal);
const snapshot = await decryptVaultValue(encrypted, vault.key);
if (snapshot?.format !== SYNC_SNAPSHOT_FORMAT || snapshot.version !== SYNC_SNAPSHOT_VERSION) {
throw new Error("状态版本无效");
}
snapshots.push(snapshot);
- } catch {
+ } catch (error) {
+ if (isAbortError(error)) throw error;
+ corruptFiles.push(`${device.name}/${fileHandle.name}`);
}
}
}
+ if (corruptFiles.length) {
+ const error = new Error(`同步目录包含损坏的正式状态文件:${corruptFiles.join("、")};本地资料未被修改`);
+ error.code = "sync_snapshot_corrupt";
+ error.corruptFiles = corruptFiles;
+ throw error;
+ }
if (encryptedFileCount && !snapshots.length) {
throw new Error("同步目录中没有可读取的健康版本,本地资料未被修改");
}
@@ -92,6 +106,7 @@ export async function listSyncSnapshots(vault) {
export async function writeSyncSnapshot(vault, snapshot, options = {}) {
validateVault(vault);
+ throwIfAborted(options.signal);
if (snapshot?.format !== SYNC_SNAPSHOT_FORMAT || snapshot.version !== SYNC_SNAPSHOT_VERSION) {
throw new Error("待写入的同步状态无效");
}
@@ -99,6 +114,7 @@ export async function writeSyncSnapshot(vault, snapshot, options = {}) {
const deviceName = safeFilename(snapshot.deviceId);
const device = await devices.getDirectoryHandle(deviceName, { create: true });
const encrypted = await encryptVaultValue(snapshot, vault.key);
+ throwIfAborted(options.signal);
const filename = `${String(snapshot.logicalClock).padStart(12, "0")}-${safeFilename(snapshot.snapshotId)}.pds`;
await writeJsonAtomic(device, filename, encrypted);
await pruneDeviceVersions(device, Math.max(1, Number(options.retentionCount) || DEFAULT_SYNC_RETENTION));
@@ -108,12 +124,15 @@ export async function writeSyncSnapshot(vault, snapshot, options = {}) {
export async function writeSyncObject(vault, blob, options = {}) {
validateVault(vault);
validateSyncMedia(blob);
+ throwIfAborted(options.signal);
const objects = await vault.directory.getDirectoryHandle("objects", { create: true });
const chunkBytes = Math.max(1, Number(options.chunkBytes) || DEFAULT_OBJECT_CHUNK_BYTES);
const chunks = [];
for (let offset = 0, index = 0; offset < blob.size; offset += chunkBytes, index += 1) {
+ throwIfAborted(options.signal);
const chunk = blob.slice(offset, Math.min(blob.size, offset + chunkBytes), "application/octet-stream");
const chunkId = await sha256Hex(chunk);
+ throwIfAborted(options.signal);
const filename = `${chunkId}.pdc`;
if (!await hasFile(objects, filename)) {
await writeJsonAtomic(objects, filename, await encryptVaultBlob(chunk, vault.key));
@@ -123,6 +142,7 @@ export async function writeSyncObject(vault, blob, options = {}) {
}
const manifest = { format: "prompt-director-sync-object", version: 2, contentType: blob.type, byteSize: blob.size, chunks };
const objectId = await sha256Hex(JSON.stringify(manifest));
+ throwIfAborted(options.signal);
const filename = `${objectId}.pdm`;
if (!await hasFile(objects, filename)) {
await writeJsonAtomic(objects, filename, await encryptVaultValue(manifest, vault.key));
@@ -130,12 +150,14 @@ export async function writeSyncObject(vault, blob, options = {}) {
return objectId;
}
-export async function readSyncObject(vault, objectId) {
+export async function readSyncObject(vault, objectId, options = {}) {
validateVault(vault);
+ throwIfAborted(options.signal);
if (!/^[a-f0-9]{64}$/.test(String(objectId ?? ""))) throw new Error("同步媒体编号无效");
const objects = await vault.directory.getDirectoryHandle("objects", { create: true });
try {
const manifest = await decryptVaultValue(await readJsonFile(objects, `${objectId}.pdm`), vault.key);
+ throwIfAborted(options.signal);
if (manifest?.format !== "prompt-director-sync-object" || manifest.version !== 2 || !Array.isArray(manifest.chunks)) {
throw new Error("同步媒体清单无效");
}
@@ -144,8 +166,10 @@ export async function readSyncObject(vault, objectId) {
const chunks = [];
let byteSize = 0;
for (const chunk of manifest.chunks) {
+ throwIfAborted(options.signal);
if (!/^[a-f0-9]{64}$/.test(String(chunk?.id ?? ""))) throw new Error("同步媒体分块编号无效");
const blob = await decryptVaultBlob(await readJsonFile(objects, `${chunk.id}.pdc`), vault.key);
+ throwIfAborted(options.signal);
if (blob.size !== chunk.byteSize || await sha256Hex(blob) !== chunk.id) throw new Error("同步媒体分块已损坏");
chunks.push(blob);
byteSize += blob.size;
@@ -164,8 +188,8 @@ export async function readSyncObject(vault, objectId) {
function validateSyncMedia(blob) {
if (!(blob instanceof Blob) || !blob.size) throw new Error("同步媒体无效");
- if (!(blob.type.startsWith("image/") || blob.type.startsWith("video/") ||
- ["application/pdf", "text/plain", "text/markdown", "text/html"].includes(blob.type))) {
+ const type = String(blob.type || "application/octet-stream").toLocaleLowerCase("en-US");
+ if (type !== "application/octet-stream" && !assetFormatsForMimeType(type).length) {
throw new Error("同步对象不是受支持的媒体");
}
}
@@ -243,3 +267,13 @@ function validateVault(value) {
function isNotFound(error) {
return error?.name === "NotFoundError";
}
+
+function throwIfAborted(signal) {
+ if (!signal?.aborted) return;
+ if (typeof signal.throwIfAborted === "function") signal.throwIfAborted();
+ throw new DOMException("同步已取消", "AbortError");
+}
+
+function isAbortError(error) {
+ return error?.name === "AbortError";
+}
diff --git a/test/ai-provider-module.test.js b/test/ai-provider-module.test.js
index 0b9a846..fd40916 100644
--- a/test/ai-provider-module.test.js
+++ b/test/ai-provider-module.test.js
@@ -20,7 +20,7 @@ function jsonResponse(payload, status = 200, headers = {}) {
});
}
-test("DeepSeek discovery treats identity-only models as text protocol capability, never guessed media capability", async () => {
+test("DeepSeek identity-only discovery keeps models task-neutral and never guesses capability from names", async () => {
const calls = [];
const module = createAiProviderModule({ fetchImpl: async (url, options) => {
calls.push({ url, options });
@@ -34,12 +34,39 @@ test("DeepSeek discovery treats identity-only models as text protocol capability
});
assert.equal(calls[0].url, "https://api.deepseek.com/models");
assert.equal(result.models.length, 2);
- assert.equal(result.models[0].confidence, "protocol_inferred");
- assert.deepEqual(result.models[0].tasks, ["textTags", "skillExtraction", "creativePlanning"]);
+ assert.equal(result.models[0].confidence, "manual_unverified");
+ assert.deepEqual(result.models[0].tasks, []);
assert.equal(result.models[1].tasks.includes("videoGeneration"), false);
assert.equal(result.cache.etag, '"models-v1"');
});
+test("identity discovery automatically classifies standard declared modalities without using model names", async () => {
+ const module = createAiProviderModule({ fetchImpl: async () => jsonResponse({ data: [
+ {
+ id: "opaque-account-model",
+ input_modalities: ["text", "image"],
+ output_modalities: ["text"]
+ },
+ {
+ id: "looks-like-vision-but-declared-text-only",
+ input_modalities: ["text"],
+ output_modalities: ["text"]
+ }
+ ] }) });
+ const result = await module.discoverModels({
+ id: "deepseek",
+ endpoint: "https://api.deepseek.com/chat/completions",
+ apiKey: "secret",
+ protocol: "chat_completions"
+ });
+
+ assert.equal(result.models[0].confidence, "declared");
+ assert.deepEqual(result.models[0].tasks, [
+ "textTags", "skillExtraction", "creativePlanning", "imageAnalysis"
+ ]);
+ assert.equal(result.models[1].tasks.includes("imageAnalysis"), false);
+});
+
test("Kimi discovery uses its declared catalog fields without inventing generation capabilities", async () => {
const calls = [];
const module = createAiProviderModule({ fetchImpl: async (url, options) => {
@@ -174,6 +201,21 @@ test("discovery failure stays visible and does not erase the last in-memory cata
assert.equal(module.describeCapabilities("deepseek", "available-model").id, "available-model");
});
+test("a configured model missing from a successful empty catalog is marked unavailable", async () => {
+ const module = createAiProviderModule({ fetchImpl: async () => jsonResponse({ data: [] }) });
+ const result = await module.discoverModels({
+ id: "deepseek",
+ endpoint: "https://api.deepseek.com/chat/completions",
+ apiKey: "secret",
+ protocol: "chat_completions",
+ models: { imageAnalysis: "previously-visible-model" }
+ });
+
+ assert.equal(result.models.length, 1);
+ assert.equal(result.models[0].id, "previously-visible-model");
+ assert.equal(result.models[0].status, "unavailable");
+});
+
test("xAI discovery combines language, image, and video model endpoints using declared modalities", async () => {
const module = createAiProviderModule({ fetchImpl: async (url) => {
if (url.endsWith("/language-models")) return jsonResponse({ models: [{
diff --git a/test/ai-provider-registry.test.js b/test/ai-provider-registry.test.js
index d14f244..31408a1 100644
--- a/test/ai-provider-registry.test.js
+++ b/test/ai-provider-registry.test.js
@@ -3,7 +3,9 @@ import assert from "node:assert/strict";
import {
AI_ASSIGNMENT_TASKS,
+ availableAiModelsForTask,
availableAiProvidersForTask,
+ createAiTaskAssignment,
mergeAiProviderRegistry,
normalizeAiProviderRegistry,
normalizeAiTaskAssignments,
@@ -60,11 +62,105 @@ test("provider presets are the single model-free source for official and aggrega
), true);
assert.equal(Object.hasOwn(getAiProviderPreset("kimi"), "models"), false);
assert.equal(getAiProviderPreset("gemini").capabilities.includes("imageGeneration"), true);
+ assert.equal(getAiProviderPreset("deepseek").capabilities.includes("imageAnalysis"), true);
+ assert.equal(getAiProviderPreset("deepseek").structuredOutput, "json_object");
assert.deepEqual(getAiProviderPreset("gemini").catalogRequiredTasks, ["imageGeneration"]);
assert.equal(getAiProviderPreset("openrouter").category, "aggregator");
assert.equal(getAiProviderPreset("missing"), null);
});
+test("task model candidates separate declared catalog capability from explicit manual assignment", () => {
+ const registry = normalizeAiProviderRegistry({ providers: {
+ deepseek: {
+ apiKey: "deepseek-secret",
+ consent: true,
+ discoveredModels: [
+ { id: "opaque-account-model", confidence: "manual_unverified", source: "provider_models", tasks: [] },
+ {
+ id: "declared-vision", confidence: "declared", source: "provider_models",
+ tasks: ["textTags", "skillExtraction", "creativePlanning", "imageAnalysis"],
+ inputModalities: ["text", "image"], outputModalities: ["text"]
+ },
+ {
+ id: "declared-text", confidence: "declared", source: "provider_models",
+ tasks: ["textTags", "skillExtraction", "creativePlanning"],
+ inputModalities: ["text"], outputModalities: ["text"]
+ }
+ ]
+ },
+ openai: {
+ apiKey: "openai-secret",
+ discoveredModels: [{
+ id: "task-neutral-account-model", confidence: "manual_unverified",
+ source: "provider_models", tasks: []
+ }]
+ }
+ } });
+
+ assert.deepEqual(availableAiModelsForTask("imageAnalysis", registry.providers.deepseek).map((model) => ({
+ id: model.id, evidence: model.assignmentEvidence
+ })), [
+ { id: "opaque-account-model", evidence: "manual_unverified" },
+ { id: "declared-vision", evidence: "declared" }
+ ]);
+ assert.deepEqual(createAiTaskAssignment(
+ "imageAnalysis", "deepseek", "opaque-account-model", registry
+ ), {
+ providerId: "deepseek",
+ model: "opaque-account-model",
+ evidence: "manual_unverified"
+ });
+ assert.deepEqual(normalizeAiTaskAssignments({
+ imageAnalysis: { providerId: "deepseek", model: "opaque-account-model" }
+ }, registry).imageAnalysis, {
+ providerId: "deepseek",
+ model: "opaque-account-model",
+ evidence: "manual_unverified"
+ });
+ assert.throws(() => createAiTaskAssignment(
+ "imageAnalysis", "deepseek", "declared-text", registry
+ ), /目录声明.*不支持图片分析/);
+ assert.deepEqual(availableAiModelsForTask("imageGeneration", registry.providers.openai), []);
+});
+
+test("a manually assigned catalog-visible DeepSeek model resolves for image analysis and disappears safely", () => {
+ const source = {
+ providers: {
+ deepseek: {
+ apiKey: "deepseek-secret",
+ consent: true,
+ models: { imageAnalysis: "opaque-account-model" },
+ discoveredModels: [{
+ id: "opaque-account-model", status: "available", confidence: "manual_unverified",
+ source: "provider_models", tasks: []
+ }]
+ }
+ }
+ };
+ const registry = normalizeAiProviderRegistry(source);
+ const assignments = normalizeAiTaskAssignments({
+ imageAnalysis: {
+ providerId: "deepseek", model: "opaque-account-model", evidence: "manual_unverified"
+ }
+ });
+
+ assert.deepEqual(availableAiProvidersForTask("imageAnalysis", registry).map((item) => item.id), ["deepseek"]);
+ assert.deepEqual(resolveAiProviderAssignment("imageAnalysis", registry, assignments), {
+ taskId: "imageAnalysis", providerId: "deepseek", provider: "DeepSeek", model: "opaque-account-model"
+ });
+
+ source.providers.deepseek.discoveredModels[0].status = "unavailable";
+ assert.throws(() => resolveAiProviderAssignment(
+ "imageAnalysis", normalizeAiProviderRegistry(source), assignments
+ ), /已下架|不可用/);
+
+ source.providers.deepseek.discoveredModels = [];
+ source.providers.deepseek.discovery = { discoveredAt: "2026-08-23T00:00:00.000Z" };
+ assert.throws(() => resolveAiProviderAssignment(
+ "imageAnalysis", normalizeAiProviderRegistry(source), assignments
+ ), /当前模型目录中没有/);
+});
+
test("registry v4 exposes provider categories and leaves all new-install tasks unassigned", () => {
const registry = normalizeAiProviderRegistry({ providers: {
kimi: { discovery: { etag: "catalog-version" } }
@@ -204,6 +300,32 @@ test("a disappeared selected model is blocked instead of silently replaced", ()
assert.equal(assignments.videoGeneration.model, "openai-video");
});
+test("an explicitly configured generation model remains assignable until a successful catalog refresh", () => {
+ const registry = normalizeAiProviderRegistry({ providers: {
+ openai: {
+ apiKey: "openai-key",
+ consent: true,
+ models: { imageGeneration: "openai-account-image-model" }
+ }
+ } });
+ const profile = registry.providers.openai;
+ assert.deepEqual(
+ availableAiModelsForTask("imageGeneration", profile).map((model) => model.id),
+ ["openai-account-image-model"]
+ );
+ assert.equal(
+ createAiTaskAssignment("imageGeneration", "openai", "openai-account-image-model", registry).model,
+ "openai-account-image-model"
+ );
+
+ profile.discovery.discoveredAt = "2026-08-23T00:00:00.000Z";
+ assert.deepEqual(availableAiModelsForTask("imageGeneration", profile), []);
+ assert.throws(
+ () => createAiTaskAssignment("imageGeneration", "openai", "openai-account-image-model", registry),
+ /当前模型目录中没有/
+ );
+});
+
test("custom media keeps its configured image tasks after registry normalization", () => {
const registry = normalizeAiProviderRegistry({ providers: {
"custom-media": {
diff --git a/test/ai-runtime.test.js b/test/ai-runtime.test.js
index ef57b17..763eba6 100644
--- a/test/ai-runtime.test.js
+++ b/test/ai-runtime.test.js
@@ -12,10 +12,10 @@ import {
} from "../ai-runtime.js";
test("Composer and background share one AI runtime protocol version", () => {
- assert.equal(AI_RUNTIME_PROTOCOL_VERSION, 1);
- assert.equal(requireAiRuntimeProtocolVersion(1), true);
+ assert.equal(AI_RUNTIME_PROTOCOL_VERSION, 2);
+ assert.equal(requireAiRuntimeProtocolVersion(2), true);
assert.throws(() => requireAiRuntimeProtocolVersion(undefined), /扩展后台不是同一版本/);
- assert.throws(() => requireAiRuntimeProtocolVersion(0), /没有发起付费请求/);
+ assert.throws(() => requireAiRuntimeProtocolVersion(1), /没有发起付费请求/);
});
const storedConfiguration = {
@@ -82,6 +82,78 @@ test("runtime projections are derived views and task resolvers keep credentials
assert.equal(vision.openai.model, "openai-vision");
});
+test("DeepSeek image analysis projects the selected account model through its compatible vision protocol", () => {
+ const configuration = aiConfigurationFromStorage({
+ aiProviderRegistry: { providers: {
+ deepseek: {
+ apiKey: "deepseek-key",
+ consent: true,
+ models: { imageAnalysis: "opaque-account-model" },
+ discoveredModels: [{
+ id: "opaque-account-model", status: "available", confidence: "manual_unverified",
+ source: "provider_models", tasks: []
+ }]
+ }
+ } },
+ aiTaskAssignments: {
+ imageAnalysis: {
+ providerId: "deepseek", model: "opaque-account-model", evidence: "manual_unverified"
+ }
+ }
+ });
+
+ const vision = resolveVisionTaskSettings("imageAnalysis", configuration);
+ assert.equal(vision.activeProvider, "compatible");
+ assert.equal(vision.compatible.endpoint, "https://api.deepseek.com/chat/completions");
+ assert.equal(vision.compatible.model, "opaque-account-model");
+ assert.equal(vision.compatible.apiKey, "deepseek-key");
+ assert.equal(vision.compatible.structuredOutput, "json_object");
+
+ const projected = projectAiRuntime(configuration).visionSettings;
+ assert.equal(projected.activeProvider, "compatible");
+ assert.equal(projected.compatible.endpoint, "https://api.deepseek.com/chat/completions");
+ assert.equal(projected.compatible.model, "opaque-account-model");
+ assert.equal(projected.compatible.structuredOutput, "json_object");
+});
+
+test("changing the image-analysis assignment does not erase generation services", () => {
+ const configuration = aiConfigurationFromStorage({
+ aiProviderRegistry: { providers: {
+ deepseek: {
+ apiKey: "deepseek-key", consent: true,
+ models: { imageAnalysis: "deepseek-vision" }
+ },
+ openai: {
+ apiKey: "openai-key", consent: true,
+ models: { imageAnalysis: "openai-vision", imageGeneration: "openai-image" }
+ },
+ "custom-media": {
+ endpoint: "https://media.example/v1/chat/completions",
+ apiKey: "compatible-key", consent: true,
+ models: { imageAnalysis: "compatible-vision", imageGeneration: "compatible-image" },
+ imageGeneration: {
+ protocol: "images_generations",
+ endpoint: "https://media.example/v1/images/generations",
+ apiKey: "compatible-image-key",
+ model: "compatible-image"
+ }
+ }
+ } },
+ aiTaskAssignments: {
+ imageAnalysis: { providerId: "deepseek", model: "deepseek-vision" },
+ imageGeneration: { providerId: "custom-media", model: "compatible-image" }
+ }
+ });
+
+ const runtime = projectAiRuntime(configuration);
+ assert.equal(runtime.visionSettings.compatible.model, "deepseek-vision");
+ assert.equal(runtime.visionSettings.openai.apiKey, "openai-key");
+ assert.equal(runtime.visionSettings.openai.model, "openai-vision");
+ assert.equal(runtime.visionSettings.compatible.apiKey, "deepseek-key");
+ assert.equal(runtime.visionSettings.compatible.imageGeneration.apiKey, "compatible-image-key");
+ assert.equal(runtime.visionSettings.compatible.imageGeneration.model, "compatible-image");
+});
+
test("new-install runtime previews remain unassigned instead of inventing providers or models", () => {
const configuration = aiConfigurationFromStorage({});
const runtime = projectAiRuntime(configuration);
diff --git a/test/ai_provider_registry_e2e.py b/test/ai_provider_registry_e2e.py
index 6d2de25..48758e2 100644
--- a/test/ai_provider_registry_e2e.py
+++ b/test/ai_provider_registry_e2e.py
@@ -1,10 +1,11 @@
from __future__ import annotations
+import json
import re
from playwright.sync_api import expect
-from e2e_support import extension_session
+from e2e_support import base_entry, extension_session
TASK_IDS = {
@@ -17,6 +18,261 @@ TASK_IDS = {
"videoGeneration",
}
+PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+DIMENSIONS = ["subject", "scene", "action", "style", "camera", "light", "mood", "sound", "output", "workflow"]
+
+
+def assignment_routes(assignments: dict) -> dict:
+ return {
+ task_id: {
+ "providerId": value.get("providerId", ""),
+ "model": value.get("model", ""),
+ }
+ for task_id, value in assignments.items()
+ }
+
+
+def complete_visual_analysis() -> dict:
+ return {
+ "description": "中央主体位于深色背景中。",
+ "canvas": {
+ "width": 1,
+ "height": 1,
+ "aspectRatio": "1:1",
+ "orientation": "square",
+ "dominantColors": [{"hex": "#101820", "coveragePercent": 70, "source": "estimated"}],
+ },
+ "elements": [{
+ "id": "subject-1",
+ "label": "中央主体",
+ "category": "subject",
+ "box_2d": [150, 250, 850, 750],
+ "coveragePercent": 35,
+ "depthLayer": "foreground",
+ "occludes": [],
+ "occludedBy": [],
+ "relationships": ["位于画面中央"],
+ "visualAttributes": ["清晰轮廓"],
+ }],
+ "dimensions": [{
+ "id": dimension,
+ "applicable": dimension != "sound",
+ "facts": [] if dimension == "sound" else [f"{dimension} 可见事实"],
+ "measurements": [],
+ } for dimension in DIMENSIONS],
+ "OCR": [],
+ "reconstructionPrompt": "深色背景中的中央主体,保持清晰轮廓和居中构图。",
+ "limitations": ["无法确认画外信息"],
+ "completeness": {"checkedRegions": ["四角", "主体", "背景", "文字"], "omittedVisibleElements": []},
+ "tags": [],
+ }
+
+
+def assert_deepseek_dynamic_image_analysis() -> None:
+ catalog = {"visible": True}
+ vision_requests: list[dict] = []
+ openai_paid_requests: list[str] = []
+ model_id = "opaque-account-model-2026"
+
+ def mock_deepseek(route) -> None:
+ if route.request.method == "GET" and route.request.url == "https://api.deepseek.com/models":
+ models = [{"id": model_id}] if catalog["visible"] else []
+ route.fulfill(
+ status=200,
+ content_type="application/json",
+ body=json.dumps({"data": models}),
+ )
+ return
+ if route.request.method == "POST" and route.request.url == "https://api.deepseek.com/chat/completions":
+ payload = route.request.post_data_json
+ vision_requests.append(payload)
+ route.fulfill(
+ status=200,
+ content_type="application/json",
+ body=json.dumps({
+ "model": model_id,
+ "choices": [{"message": {"content": json.dumps(complete_visual_analysis(), ensure_ascii=False)}}],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 20, "total_tokens": 30},
+ }, ensure_ascii=False),
+ )
+ return
+ route.fulfill(status=500, content_type="application/json", body='{"error":{"message":"unexpected DeepSeek request"}}')
+
+ def block_openai(route) -> None:
+ if route.request.method == "GET" and route.request.url == "https://api.openai.com/v1/models":
+ route.fulfill(
+ status=200,
+ content_type="application/json",
+ body='{"data":[{"id":"declared-openai-vision","input_modalities":["text","image"],"output_modalities":["text"]}]}',
+ )
+ return
+ openai_paid_requests.append(route.request.url)
+ route.fulfill(status=500, content_type="application/json", body='{"error":{"message":"unexpected fallback"}}')
+
+ entry = base_entry(
+ "deepseek-dynamic-vision",
+ "动态模型图片分析",
+ "只用于本地浏览器验收。",
+ "content:prompt:image",
+ )
+ entry["mediaAssets"] = [{
+ "id": "deepseek-dynamic-image",
+ "kind": "image",
+ "usage": "content",
+ "storageMode": "managed",
+ "mimeType": "image/png",
+ "width": 1,
+ "height": 1,
+ "byteSize": 68,
+ }]
+ entry["primaryMediaId"] = "deepseek-dynamic-image"
+
+ with extension_session("prompt-director-deepseek-vision-", viewport={"width": 1280, "height": 900}) as run:
+ run.context.route("https://api.deepseek.com/**", mock_deepseek)
+ run.context.route("https://api.openai.com/**", block_openai)
+ setup = run.open_page("collector.html")
+ run.seed_storage(setup, {
+ "schemaVersion": 24,
+ "entries": [entry],
+ "uiPreferences": {"locale": "zh-CN", "theme": "system", "motion": "system"},
+ "aiProviderRegistry": {
+ "version": 4,
+ "providers": {
+ "deepseek": {"apiKey": "deepseek-e2e-key", "consent": True},
+ "openai": {
+ "apiKey": "openai-e2e-key",
+ "consent": True,
+ "models": {"imageAnalysis": "declared-openai-vision"},
+ "discoveredModels": [{
+ "id": "declared-openai-vision",
+ "name": "OpenAI 对照模型",
+ "status": "available",
+ "confidence": "declared",
+ "source": "fixture",
+ "tasks": ["imageAnalysis"],
+ "inputModalities": ["text", "image"],
+ "outputModalities": ["text"],
+ }],
+ },
+ },
+ },
+ "aiTaskAssignments": {},
+ })
+ setup.evaluate(
+ f"""async () => {{
+ const {{saveMediaBlob}} = await import(chrome.runtime.getURL('media-store.js'));
+ const bytes = Uint8Array.from(atob('{PNG}'), value => value.charCodeAt(0));
+ await saveMediaBlob('deepseek-dynamic-image', new Blob([bytes], {{type: 'image/png'}}), {{checkCapacity: false}});
+ }}"""
+ )
+
+ library = run.open_page("library.html", wait_until="networkidle")
+ library.wait_for_timeout(1_000)
+ library_state = library.locator("body").get_attribute("data-library-state")
+ assert library_state == "ready", {
+ "libraryState": library_state,
+ "pageErrors": run.page_errors,
+ "loadingText": library.locator("#library-loading").text_content(),
+ }
+ library.locator("#open-settings").click()
+ library.locator('[data-settings-tab="ai"]').click()
+ library.locator('[data-ai-routing-tab="providers"]').click()
+ deepseek_row = library.locator('[data-provider-id="deepseek"]')
+ deepseek_row.get_by_role("button", name="刷新模型").click()
+ expect(library.locator("#feedback")).to_contain_text("DeepSeek 已发现 1 个模型")
+ expect(deepseek_row).to_contain_text("模型目录已读取 · 1 个模型")
+
+ library.locator('[data-ai-routing-tab="tasks"]').click()
+ image_task = library.locator("#ai-assignment-list .ai-assignment-row", has_text="图片分析")
+ image_task.get_by_role("button", name="配置").click()
+ dialog = library.locator("#promptdirector-app-dialog")
+ provider_select = dialog.locator('[data-field-id="providerId"] select')
+ model_select = dialog.locator('[data-field-id="model"] select')
+ provider_select.select_option("deepseek")
+ expect(model_select).to_have_value(model_id)
+ expect(model_select.locator("option")).to_have_text(model_id)
+ expect(dialog.locator(".model-capability-help")).to_have_count(1)
+ expect(dialog.locator(".model-capability-help")).to_have_text("当前模型未声明这项能力;是否可用以真实执行结果为准")
+ expect(dialog).not_to_contain_text("实验")
+ dialog.get_by_role("button", name="保存任务默认").click()
+ expect(dialog).to_be_hidden()
+ expect(image_task).to_contain_text(f"DeepSeek · {model_id}")
+
+ stored_assignment = library.evaluate(
+ "() => chrome.storage.local.get('aiTaskAssignments').then(value => value.aiTaskAssignments.imageAnalysis)"
+ )
+ assert stored_assignment == {
+ "providerId": "deepseek",
+ "model": model_id,
+ "evidence": "manual_unverified",
+ }, stored_assignment
+ runtime = library.evaluate(
+ "() => chrome.runtime.sendMessage({type: 'GET_AI_TASK_RUNTIME', taskId: 'imageAnalysis'})"
+ )
+ assert runtime["assignment"] == stored_assignment, runtime
+ assert runtime["visionSettings"]["compatible"]["structuredOutput"] == "json_object", runtime
+ assert runtime["runtimeDescriptor"]["capabilities"]["image"] is None, runtime
+
+ analyzed = library.evaluate(
+ """async () => chrome.runtime.sendMessage({
+ type: 'ANALYZE_ENTRY_IMAGE',
+ entryId: 'deepseek-dynamic-vision',
+ visualId: 'deepseek-dynamic-image',
+ outputLocale: 'zh-CN'
+ })"""
+ )
+ assert analyzed["ok"] is True, analyzed
+ assert len(vision_requests) == 1, vision_requests
+ request = vision_requests[0]
+ assert request["model"] == model_id, request
+ assert request["response_format"] == {"type": "json_object"}, request
+ content = request["messages"][0]["content"]
+ assert [item["type"] for item in content] == ["text", "image_url"], content
+ assert "JSON property names are case-sensitive" in content[0]["text"], content[0]
+ assert '\"ocr\":{\"type\":\"array\"' in content[0]["text"], content[0]
+ assert content[1]["image_url"]["url"].startswith("data:image/png;base64,"), content
+ assert not openai_paid_requests, openai_paid_requests
+
+ catalog["visible"] = False
+ library.locator('[data-ai-routing-tab="providers"]').click()
+ deepseek_row.get_by_role("button", name="刷新模型").click()
+ expect(deepseek_row).to_contain_text("1 个下架或当前不可用")
+ library.locator('[data-ai-routing-tab="tasks"]').click()
+ expect(image_task).to_contain_text(f"DeepSeek · {model_id}")
+ expect(image_task).to_contain_text("已下架或当前不可用")
+
+ disappeared = library.evaluate(
+ """async () => {
+ try {
+ return await chrome.runtime.sendMessage({
+ type: 'ANALYZE_ENTRY_IMAGE',
+ entryId: 'deepseek-dynamic-vision',
+ visualId: 'deepseek-dynamic-image',
+ outputLocale: 'zh-CN'
+ });
+ } catch (error) {
+ return {ok: false, rejected: true, message: error.message};
+ }
+ }"""
+ )
+ assert disappeared["ok"] is False, disappeared
+ assert "已下架" in disappeared["message"] or "不可用" in disappeared["message"], disappeared
+ assert len(vision_requests) == 1, vision_requests
+ assert not openai_paid_requests, openai_paid_requests
+ final_state = library.evaluate(
+ "() => chrome.storage.local.get(['aiProviderRegistry', 'aiTaskAssignments'])"
+ )
+ assert final_state["aiTaskAssignments"]["imageAnalysis"] == stored_assignment, final_state
+ assert final_state["aiProviderRegistry"]["providers"]["deepseek"]["discoveredModels"][0]["status"] == "unavailable", final_state
+
+ print({
+ "manualDeepSeekImageAssignment": True,
+ "requestFormat": "image_url+json_object",
+ "disappearedModelBlocked": True,
+ "silentFallbackRequests": len(openai_paid_requests),
+ "realPaidRequests": 0,
+ })
+
def open_ai_settings(run):
library = run.open_page("library.html", wait_until="networkidle")
@@ -103,7 +359,9 @@ def assert_english_ai_settings() -> None:
library.locator("#ai-assignment-list .ai-assignment-row").first.get_by_role("button", name="Configure").click()
dialog = library.locator("#promptdirector-app-dialog")
expect(dialog).not_to_contain_text(chinese, use_inner_text=True)
- expect(library.locator("#feedback")).to_contain_text("No connected service has a catalog model explicitly supporting Text tags")
+ expect(library.locator("#feedback")).to_contain_text(
+ "No connected model can be assigned to Text tags. Connect a service and refresh its model catalog first."
+ )
dialog.locator(".app-dialog-close").click()
library.locator('[data-ai-routing-tab="providers"]').click()
@@ -120,6 +378,7 @@ def assert_english_ai_settings() -> None:
def main() -> None:
assert_new_install_defaults()
assert_english_ai_settings()
+ assert_deepseek_dynamic_image_analysis()
with extension_session("prompt-director-ai-registry-", viewport={"width": 1280, "height": 900}) as run:
model_authorizations: list[str] = []
gemini_model_requests: list[dict[str, str]] = []
@@ -251,21 +510,35 @@ def main() -> None:
assignments_before_rules = library.evaluate("() => chrome.storage.local.get('aiTaskAssignments').then(value => value.aiTaskAssignments)")
library.locator("#analysis-instructions-zh").fill("只保存统一 Registry 的文字分析规则")
library.locator("#ai-settings-form").get_by_role("button", name="保存分析规则").click()
- expect(library.locator("#feedback")).to_contain_text("分析规则已保存")
+ library.wait_for_function(
+ """expected => chrome.storage.local.get('aiPreferences').then(value =>
+ value.aiPreferences?.textInstructionsByLocale?.['zh-CN'] === expected)""",
+ arg="只保存统一 Registry 的文字分析规则",
+ )
library.locator('[data-analysis-kind="vision"]').click()
expect(library.locator("#vision-instructions-zh")).to_be_visible()
expect(library.locator("#vision-settings-status")).to_contain_text("规则保存在本机")
library.locator("#vision-instructions-zh").fill("只保存统一 Registry 的图片分析规则")
library.locator("#vision-settings-form").get_by_role("button", name="保存分析规则").click()
- expect(library.locator("#feedback")).to_contain_text("分析规则已保存")
+ library.wait_for_function(
+ """expected => chrome.storage.local.get('aiPreferences').then(value =>
+ value.aiPreferences?.visionInstructionsByLocale?.['zh-CN'] === expected)""",
+ arg="只保存统一 Registry 的图片分析规则",
+ )
saved_preferences = library.evaluate("() => chrome.storage.local.get(['aiPreferences', 'aiTaskAssignments'])")
assert saved_preferences["aiPreferences"]["textInstructionsByLocale"]["zh-CN"] == "只保存统一 Registry 的文字分析规则"
assert saved_preferences["aiPreferences"]["visionInstructionsByLocale"]["zh-CN"] == "只保存统一 Registry 的图片分析规则"
- assert saved_preferences["aiTaskAssignments"] == assignments_before_rules
+ assert assignment_routes(saved_preferences["aiTaskAssignments"]) == assignment_routes(assignments_before_rules), {
+ "before": assignments_before_rules,
+ "after": saved_preferences["aiTaskAssignments"],
+ }
image_runtime = library.evaluate("() => chrome.runtime.sendMessage({type: 'GET_AI_TASK_RUNTIME', taskId: 'imageAnalysis'})")
assert image_runtime["ok"] is True, image_runtime
- assert image_runtime["assignment"] == {"providerId": "custom-media", "model": "gpt-5.6-terra"}, image_runtime
+ assert assignment_routes({"imageAnalysis": image_runtime["assignment"]})["imageAnalysis"] == {
+ "providerId": "custom-media", "model": "gpt-5.6-terra"
+ }, image_runtime
+ assert image_runtime["assignment"]["evidence"] == "manual_unverified", image_runtime
library.locator("#open-ai-routing").click()
dialog = library.locator("#promptdirector-app-dialog")
@@ -322,6 +595,12 @@ def main() -> None:
expect(image_endpoint).to_be_visible()
expect(image_endpoint).to_have_value("https://www.micuapi.ai/v1/images/generations")
expect(dialog.locator("#promptdirector-app-dialog-provider_custom_media_imageEditsEndpoint")).to_have_value("https://www.micuapi.ai/v1/images/edits")
+ image_model = dialog.locator("#promptdirector-app-dialog-provider_custom_media_model_imageGeneration")
+ expect(image_model).to_be_visible()
+ expect(image_model).to_have_value("gpt-image-2")
+ expect(dialog.locator("#promptdirector-app-dialog-provider_custom_media_imageSizes")).to_have_value(
+ "1024x1024, 1280x720, 720x1280, 1024x1536, 1536x1024, 2048x2048, 2048x1152, 1152x2048"
+ )
assert image_key.bounding_box()["y"] < image_endpoint.bounding_box()["y"], "生图 Key 必须位于高级接口字段之前"
expect(dialog).to_contain_text("能力声明,不是本轮输出值")
assignments_before_save = library.evaluate("() => chrome.storage.local.get('aiTaskAssignments').then(value => value.aiTaskAssignments)")
@@ -338,7 +617,7 @@ def main() -> None:
custom_media = saved_keys["aiProviderRegistry"]["providers"]["custom-media"]
assert custom_media["apiKey"] == "replacement-analysis-secret"
assert custom_media["imageGeneration"]["apiKey"] == "replacement-image-secret"
- assert saved_keys["aiTaskAssignments"] == assignments_before_save
+ assert assignment_routes(saved_keys["aiTaskAssignments"]) == assignment_routes(assignments_before_save)
library.locator('[data-provider-id="openai"]').get_by_role("button", name="编辑配置").click()
openai_dialog = library.locator("#promptdirector-app-dialog")
@@ -355,18 +634,23 @@ def main() -> None:
expect(openai_dialog).to_be_hidden()
openai_saved = library.evaluate("() => chrome.storage.local.get(['aiProviderRegistry', 'aiTaskAssignments'])")
assert openai_saved["aiProviderRegistry"]["providers"]["openai"]["models"]["imageGeneration"] == "openai-account-image-model"
- assert openai_saved["aiTaskAssignments"] == openai_assignments_before_save
+ assert openai_saved["aiProviderRegistry"]["providers"]["openai"]["discovery"]["discoveredAt"]
+ openai_catalog = {
+ model["id"]: model["status"]
+ for model in openai_saved["aiProviderRegistry"]["providers"]["openai"]["discoveredModels"]
+ }
+ assert openai_catalog == {
+ "gpt-text-catalog-only": "available",
+ "openai-account-image-model": "unavailable",
+ }, openai_catalog
+ assert assignment_routes(openai_saved["aiTaskAssignments"]) == assignment_routes(openai_assignments_before_save)
library.locator('[data-ai-routing-tab="tasks"]').click()
generation_task = library.locator("#ai-assignment-list .ai-assignment-row", has_text="图片生成")
generation_task.get_by_role("button", name="更换").click()
generation_dialog = library.locator("#promptdirector-app-dialog")
- generation_dialog.locator('[data-field-id="providerId"] select').select_option("openai")
- expect(generation_dialog.locator('[data-field-id="model"] select')).to_have_value("openai-account-image-model")
- expect(generation_dialog.locator('[data-field-id="model"]')).to_contain_text("手动声明,未验证")
- generation_dialog.locator(".app-dialog-close").click()
- expect(generation_dialog).to_be_visible()
- expect(generation_dialog.locator(".app-dialog-status")).to_contain_text("未保存的更改")
+ expect(generation_dialog.locator('[data-field-id="providerId"] option[value="openai"]')).to_have_count(0)
+ expect(generation_dialog).not_to_contain_text("openai-account-image-model")
generation_dialog.locator(".app-dialog-close").click()
expect(generation_dialog).to_be_hidden()
@@ -382,7 +666,7 @@ def main() -> None:
stored = library.evaluate("() => chrome.storage.local.get(['aiProviderRegistry', 'aiTaskAssignments'])")
assert stored["aiProviderRegistry"]["providers"]["deepseek"]["apiKey"] == "deepseek-secret"
assert set(stored["aiTaskAssignments"].keys()) == TASK_IDS
- assert stored["aiTaskAssignments"] == assignments_before_save
+ assert assignment_routes(stored["aiTaskAssignments"]) == assignment_routes(assignments_before_save)
assignments_before_nano = stored["aiTaskAssignments"]
library.locator('[data-ai-routing-tab="providers"]').click()
@@ -423,11 +707,11 @@ def main() -> None:
assert nano_saved["aiTaskAssignments"]["imageGeneration"] == {
"providerId": "gemini", "model": "gemini-3.1-flash-image"
}
- assert {
+ assert assignment_routes({
task: value for task, value in nano_saved["aiTaskAssignments"].items() if task != "imageGeneration"
- } == {
+ }) == assignment_routes({
task: value for task, value in assignments_before_nano.items() if task != "imageGeneration"
- }
+ })
public_state = library.evaluate("() => chrome.runtime.sendMessage({type: 'GET_STATE'})")
assert "gemini-secret" not in str(public_state)
diff --git a/test/capture-runtime-wiring.test.js b/test/capture-runtime-wiring.test.js
index fb8b24d..4e06e53 100644
--- a/test/capture-runtime-wiring.test.js
+++ b/test/capture-runtime-wiring.test.js
@@ -8,27 +8,23 @@ test("the collector live-refreshes on draft storage changes", async () => {
assert.match(source, /changes\.captureDraft/);
});
-test("capture workspace first paint does not await automatic synchronization", async () => {
+test("opening the capture workspace never starts synchronization", async () => {
const source = await readFile(new URL("../background.js", import.meta.url), "utf8");
const start = source.indexOf('case "GET_CAPTURE_WORKSPACE"');
const end = source.indexOf('case "GET_DATA_SAFETY_STATUS"', start);
const branch = source.slice(start, end);
- assert.doesNotMatch(branch, /await scheduleAutomaticSync/);
- assert.match(branch, /scheduleAutomaticSync\(\)/);
+ assert.match(branch, /return enqueueCapture\(async \(\) => captureWorkspace\(\)\)/);
+ assert.doesNotMatch(branch, /scheduleAutomaticSync|scheduleIdleSync|synchronizeNow|manualSyncController|SYNC_NOW/);
});
-test("library state is read before automatic sync enters the shared write queue", async () => {
+test("reading library state never starts synchronization", async () => {
const source = await readFile(new URL("../background.js", import.meta.url), "utf8");
const start = source.indexOf('case "GET_STATE"');
const end = source.indexOf('case "GET_CAPTURE_WORKSPACE"', start);
const branch = source.slice(start, end);
- assert.ok(branch.indexOf("const stateRead = enqueue") < branch.indexOf("scheduleAutomaticSync()"));
- const scheduler = source.slice(
- source.indexOf("function scheduleAutomaticSync"),
- source.indexOf("async function connectSyncFolder")
- );
- assert.match(scheduler, /automaticSyncScheduled/);
- assert.match(scheduler, /enqueue\(\(\) => synchronizeNow\("open"\)\)/);
+ assert.match(branch, /return enqueue\(async \(\) => \(\{ ok: true,/);
+ assert.doesNotMatch(branch, /scheduleAutomaticSync|scheduleIdleSync|synchronizeNow|manualSyncController|SYNC_NOW/);
+ assert.doesNotMatch(source, /function scheduleAutomaticSync|function scheduleIdleSync/);
});
test("draft edits and save share one lightweight queue so the last capture cannot miss the commit", async () => {
@@ -62,3 +58,11 @@ test("a text-bearing captured post is classified from its text instead of its vi
assert.match(save, /candidate\.sourceFacts\.pageType === "post" && base\.text/);
assert.match(save, /classificationMediaAssets/);
});
+
+test("restoring an overwritten screenshot marks that existing media id dirty", async () => {
+ const source = await readFile(new URL("../background.js", import.meta.url), "utf8");
+ const start = source.indexOf("async function undoLastSave()");
+ const end = source.indexOf("async function deleteEntry", start);
+ const undo = source.slice(start, end);
+ assert.match(undo, /dirtyAssetIds:\s*\[current\.id\]/);
+});
diff --git a/test/compatible-provider-presets.test.js b/test/compatible-provider-presets.test.js
new file mode 100644
index 0000000..03c323f
--- /dev/null
+++ b/test/compatible-provider-presets.test.js
@@ -0,0 +1,36 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ MICU_COMPATIBLE_PROVIDER_PRESET,
+ compatibleImageSizesFor,
+ compatibleProviderPresetForEndpoint
+} from "../compatible-provider-presets.js";
+
+test("Micu preset is the shared source for settings endpoints and model-specific sizes", () => {
+ const preset = MICU_COMPATIBLE_PROVIDER_PRESET;
+ assert.equal(compatibleProviderPresetForEndpoint(preset.endpoint), preset);
+ assert.deepEqual(compatibleImageSizesFor(preset.endpoint, {
+ protocol: preset.imageGeneration.protocol,
+ model: "gpt-image-2",
+ sizes: []
+ }), [
+ "1024x1024", "1280x720", "720x1280", "1024x1536", "1536x1024",
+ "2048x2048", "2048x1152", "1152x2048"
+ ]);
+ assert.deepEqual(compatibleImageSizesFor(preset.endpoint, {
+ protocol: preset.imageGeneration.protocol,
+ model: "gpt-image-2-openai",
+ sizes: []
+ }).slice(-2), ["3840x2160", "2160x3840"]);
+});
+
+test("unknown compatible endpoints keep only their declared sizes", () => {
+ const image = { protocol: "images_generations", model: "gpt-image-2", sizes: [] };
+ assert.equal(compatibleProviderPresetForEndpoint("https://images.example.com/v1/responses"), null);
+ assert.deepEqual(compatibleImageSizesFor("https://images.example.com/v1/responses", image), []);
+ assert.deepEqual(compatibleImageSizesFor("https://images.example.com/v1/responses", {
+ ...image,
+ sizes: ["1536x1024"]
+ }), ["1536x1024"]);
+});
diff --git a/test/composer-page.test.js b/test/composer-page.test.js
index eee46e6..db7f238 100644
--- a/test/composer-page.test.js
+++ b/test/composer-page.test.js
@@ -79,7 +79,7 @@ test("composer reference selection is visual while Skill management stays on its
assert.doesNotMatch(composerJs, /extractProjectMethod/);
assert.match(skillsJs, /extractCreativeSkillDraft/);
assert.match(skillsJs, /parseSkillArchive/);
- assert.match(skillsJs, /exportGeneratedSkillPackage|skillDetailExport/);
+ assert.match(skillsJs, /exportStoredSkillPackage|skillDetailExport/);
assert.match(composerJs, /findCreativeSkillsBySlashQuery/);
assert.match(composerJs, /createAppliedSkillSnapshot/);
assert.match(composerJs, /replaceComposerSessionUrl\(response\.session\.id\)/);
diff --git a/test/composer-service.test.js b/test/composer-service.test.js
index ce15e57..fd016ab 100644
--- a/test/composer-service.test.js
+++ b/test/composer-service.test.js
@@ -885,9 +885,9 @@ test("Micu without selected images uses generations with explicit stable output
test("compatible reference edits use the recorded model limit before any paid request", async () => {
const fourK = visualSettings();
- fourK.vision.compatible.imageGeneration.model = "gpt-image-2-pro";
+ fourK.vision.compatible.imageGeneration.model = "gpt-image-2-openai";
fourK.vision.compatible.imageGeneration.size = "3840x2160";
- fourK.vision.providerProfiles["custom-media"].discoveredModels[0].id = "gpt-image-2-pro";
+ fourK.vision.providerProfiles["custom-media"].discoveredModels[0].id = "gpt-image-2-openai";
await assert.rejects(() => executeComposerTurnWithService({
session: referenceSession("compatible", "create_image"), userMessage: "", composerSettings: settings,
route: "compose", instruction: "保持参考职责"
@@ -905,14 +905,24 @@ test("compatible reference edits use the recorded model limit before any paid re
}, visualSettings(), images, { fetchImpl: async () => { throw new Error("不应调用"); } }), /最多读取 6 张参考图/);
});
-test("image availability explains the missing Micu capability instead of exposing only a disabled switch", () => {
+test("image availability explains missing reference editing instead of exposing only a disabled switch", () => {
const session = referenceSession("compatible", "text_prompt");
const missingEdits = visualSettings();
missingEdits.vision.compatible.imageGeneration.editsEndpoint = "";
assert.match(composerImageAvailability(session.aiProfile, missingEdits.vision, session).message, /图片编辑接口/);
+});
+
+test("verified Micu sizes enable image generation without duplicated size settings", () => {
+ const session = referenceSession("compatible", "text_prompt");
const missingSize = visualSettings();
missingSize.vision.compatible.imageGeneration.sizes = [];
- assert.match(composerImageAvailability(session.aiProfile, missingSize.vision, session).message, /服务支持的尺寸选项/);
+ const capability = composerServiceCapabilities(session.aiProfile, missingSize.vision).image;
+ assert.equal(capability.generate, true);
+ assert.equal(composerImageAvailability(session.aiProfile, missingSize.vision, session).available, true);
+ assert.deepEqual(capability.parameters.find((item) => item.key === "size").options.map((item) => item.value), [
+ "1024x1024", "1280x720", "720x1280", "1024x1536", "1536x1024",
+ "2048x2048", "2048x1152", "1152x2048"
+ ]);
});
test("image capability contracts expose only protocol-declared parameters", () => {
@@ -926,7 +936,8 @@ test("image capability contracts expose only protocol-declared parameters", () =
const micu = composerServiceCapabilities({ serviceId: "compatible", model: "gpt-5.4-mini" }, values).image;
assert.deepEqual(micu.parameters.map((item) => item.key), ["size"]);
assert.deepEqual(micu.parameters[0].options.map((item) => item.value), [
- "1024x1024", "1280x720", "1536x1024", "2048x2048", "2048x1152", "1152x2048"
+ "1024x1024", "1280x720", "720x1280", "1024x1536", "1536x1024",
+ "2048x2048", "2048x1152", "1152x2048"
]);
assert.equal(micu.references.maxItems, 6);
assert.equal(micu.references.source, "observed_error");
@@ -934,7 +945,7 @@ test("image capability contracts expose only protocol-declared parameters", () =
test("verified Micu image models expose their official sizes without guessing for other compatible services", () => {
const pro = visualSettings();
- pro.vision.compatible.imageGeneration.model = "gpt-image-2-pro";
+ pro.vision.compatible.imageGeneration.model = "gpt-image-2-openai";
const proSizes = composerServiceCapabilities({ serviceId: "compatible", model: "gpt-5.4-mini" }, pro.vision)
.image.parameters.find((item) => item.key === "size").options.map((item) => item.value);
assert.deepEqual(proSizes.slice(-2), ["3840x2160", "2160x3840"]);
@@ -948,6 +959,11 @@ test("verified Micu image models expose their official sizes without guessing fo
const genericSizes = composerServiceCapabilities({ serviceId: "compatible", model: "vision-model" }, generic.vision)
.image.parameters.find((item) => item.key === "size").options.map((item) => item.value);
assert.deepEqual(genericSizes, ["1536x1024"]);
+
+ generic.vision.compatible.imageGeneration.sizes = [];
+ const blocked = composerServiceCapabilities({ serviceId: "compatible", model: "vision-model" }, generic.vision).image;
+ assert.equal(blocked.generate, false);
+ assert.match(composerImageAvailability({ serviceId: "compatible", model: "vision-model" }, generic.vision, referenceSession("compatible")).message, /服务支持的尺寸选项/);
});
test("unknown reference limits never become zero while explicit unsupported state blocks only conditioned images", () => {
diff --git a/test/composer_generation_e2e.py b/test/composer_generation_e2e.py
index f5ef24c..691db5e 100644
--- a/test/composer_generation_e2e.py
+++ b/test/composer_generation_e2e.py
@@ -525,7 +525,13 @@ def main() -> None:
CreativeServiceHandler.release_image.clear()
composer.locator("#composer-options summary").click()
expect(composer.locator("#composer-create-image")).to_be_enabled()
+ expect(composer.locator("#composer-generation-settings")).to_be_visible()
+ expect(composer.locator("#composer-image-size-field")).to_be_visible()
+ composer.locator("#composer-image-size").select_option("1536x1024")
+ expect(composer.locator("#composer-image-size")).to_have_value("1536x1024")
+ assert current_session(composer)["generationParameters"]["size"] == "1536x1024"
composer.locator("#composer-create-image").check()
+ expect(composer.locator("#composer-image-size")).to_have_value("1536x1024")
composer.locator("#composer-options summary").click()
expect(composer.locator("#composer-model-label")).to_have_text("OpenAI · 生图")
composer.locator("#composer-model-trigger").click()
@@ -535,8 +541,8 @@ def main() -> None:
expect(composer.locator("#composer-generation-settings")).to_be_visible()
expect(composer.locator("#composer-generation-settings-title")).to_have_text("本轮图片参数")
expect(composer.locator("#composer-image-size-field")).to_be_visible()
- expect(composer.locator("#composer-image-size")).to_have_value("auto")
- expect(composer.locator('#composer-image-size option[data-incompatible="true"]')).to_have_text("auto(当前模型不支持,请重选)")
+ expect(composer.locator("#composer-image-size")).to_have_value("1536x1024")
+ expect(composer.locator('#composer-image-size option[data-incompatible="true"]')).to_have_text("1536x1024(当前模型不支持,请重选)")
expect(composer.locator("#composer-generation-parameter-note")).to_contain_text("不受当前服务支持")
expect(composer.locator("#composer-image-size")).to_be_enabled()
supported_size = composer.locator("#composer-image-size").evaluate(
@@ -552,6 +558,10 @@ def main() -> None:
composer.locator("#composer-action").click()
try:
expect(composer.locator(".composer-session-running")).to_be_visible()
+ running_row = composer.locator(".composer-session-item:has(.composer-session-running)")
+ running_row.hover()
+ running_row.locator(".composer-session-menu > summary").click()
+ expect(running_row.get_by_role("menuitem", name="删除", exact=True)).to_be_disabled()
except AssertionError:
diagnostic = composer.evaluate(
"""async () => ({
@@ -622,6 +632,8 @@ def main() -> None:
]) == 2
assert local_requests[2]["content_type"].startswith("multipart/form-data; boundary=")
assert local_requests[2]["body"].count(b'name="image[]"') == 2
+ assert b'name="model"' in local_requests[2]["body"] and b"local-image-test" in local_requests[2]["body"]
+ assert b'name="size"' in local_requests[2]["body"] and supported_size.encode() in local_requests[2]["body"]
creative_runs = composer.evaluate("() => chrome.storage.local.get('creativeRuns').then(value => value.creativeRuns)")
assert len(creative_runs) == 1
assert len(creative_runs[0]["outputs"]) == 1
diff --git a/test/composer_session_layout_e2e.py b/test/composer_session_layout_e2e.py
index 1cf9726..12130dd 100644
--- a/test/composer_session_layout_e2e.py
+++ b/test/composer_session_layout_e2e.py
@@ -2,14 +2,17 @@ from __future__ import annotations
from datetime import datetime, timedelta, timezone
+from playwright.sync_api import expect
+
from e2e_support import extension_session
def session_value(index: int) -> dict:
- timestamp = (datetime(2026, 8, 6, tzinfo=timezone.utc) + timedelta(minutes=index)).isoformat()
+ day_offsets = [0, 1, 3, 10]
+ timestamp = (datetime.now(timezone.utc) - timedelta(days=day_offsets[index % len(day_offsets)], minutes=index)).isoformat()
return {
"id": f"layout-session-{index}",
- "title": f"布局对话 {index:02d}",
+ "title": f"布局对话 {index:02d}" + (" · 这是一个用于验证单行省略效果的特别长会话标题" if index == 0 else ""),
"targetType": "image",
"updatedAt": timestamp,
"messages": [{
@@ -67,6 +70,19 @@ def main() -> None:
run.seed_storage(setup, {"schemaVersion": 24, "composerSessions": sessions})
composer = run.open_page("composer.html?session=layout-session-0", wait_until="networkidle")
+ expect(composer.locator(".composer-session-group-label")).to_have_text(["今天", "昨天", "近 7 天", "更早"])
+ long_title = composer.locator('.composer-session-item[data-session-id="layout-session-0"] strong')
+ assert long_title.evaluate("node => node.scrollWidth > node.clientWidth")
+ menu = composer.locator('.composer-session-item[data-session-id="layout-session-1"] .composer-session-menu')
+ menu.locator("xpath=..").hover()
+ menu.locator("summary").click()
+ expect(menu.get_by_role("menuitem", name="删除", exact=True)).to_be_visible()
+ menu.get_by_role("menuitem", name="删除", exact=True).click()
+ delete_dialog = composer.locator("#promptdirector-app-dialog")
+ expect(delete_dialog).to_contain_text("删除这段对话?")
+ delete_dialog.get_by_role("button", name="取消", exact=True).click()
+ expect(delete_dialog).to_have_count(0)
+
desktop_first = geometry(composer)
for index in range(1, 30):
composer.locator(".composer-session-item > button:first-child", has_text=f"布局对话 {index:02d}").click()
diff --git a/test/creative-skill-package.test.js b/test/creative-skill-package.test.js
index 1c5ba11..d31e69e 100644
--- a/test/creative-skill-package.test.js
+++ b/test/creative-skill-package.test.js
@@ -7,6 +7,7 @@ import {
buildSkillMarkdown,
detectSkillDependencies,
exportGeneratedSkillPackage,
+ exportStoredSkillPackage,
parseSkillArchive,
parseSkillFiles,
parseSkillMarkdown
@@ -49,6 +50,28 @@ test("external packages retain every file but expose only safe Markdown referenc
assert.deepEqual(parsed.dependencies, ["scripts"]);
});
+test("ordinary export preserves every stored external package byte and path", async () => {
+ const blobs = new Map([
+ ["skill-file:markdown", new Blob(["---\nname: exact-copy\ndescription: Exact.\n---\n\n# Method\n"])],
+ ["skill-file:script", new Blob(["print('unchanged')\n"], { type: "text/x-python" })],
+ ["skill-file:asset", new Blob([new Uint8Array([0, 255, 1, 254])], { type: "application/octet-stream" })]
+ ]);
+ const archive = await exportStoredSkillPackage({
+ portableId: "exact-copy",
+ packageFiles: [
+ { path: "vendor/SKILL.md", assetId: "skill-file:markdown", byteSize: blobs.get("skill-file:markdown").size },
+ { path: "vendor/scripts/tool.py", assetId: "skill-file:script", byteSize: blobs.get("skill-file:script").size },
+ { path: "vendor/assets/sample.bin", assetId: "skill-file:asset", byteSize: 0 }
+ ]
+ }, { readFile: (assetId) => blobs.get(assetId) });
+ const parsed = await parseSkillArchive(archive);
+ assert.deepEqual([...parsed.files.keys()], ["vendor/SKILL.md", "vendor/scripts/tool.py", "vendor/assets/sample.bin"]);
+ assert.deepEqual(
+ new Uint8Array(await parsed.files.get("vendor/assets/sample.bin").arrayBuffer()),
+ new Uint8Array([0, 255, 1, 254])
+ );
+});
+
test("package validation rejects traversal, duplicate SKILL.md, and damaged ZIP", async () => {
await assert.rejects(() => parseSkillFiles(new Map([["../SKILL.md", new Blob(["x"])]])), /不安全/);
await assert.rejects(() => parseSkillFiles(new Map([
diff --git a/test/creative-skills.test.js b/test/creative-skills.test.js
index 0ba1118..5a9469e 100644
--- a/test/creative-skills.test.js
+++ b/test/creative-skills.test.js
@@ -79,6 +79,24 @@ test("deleting a skill returns package assets for transactional cleanup", () =>
assert.equal(removed.skill.packageFiles[0].assetId, "skill-file:tool");
});
+test("curated origin survives normalization and local version edits", () => {
+ const created = createSkill(createCreativeSkillsState(), "精选方法", {
+ curatedOrigin: {
+ catalogId: "[email protected]",
+ skillId: "composition",
+ version: "1.0.0",
+ sha256: "a".repeat(64),
+ installedAt: "2026-08-23T00:00:00.000Z"
+ }
+ });
+ const updated = saveCreativeSkillVersion(created.state, created.skill.id, {
+ skillMarkdown: "# 本地修改\n\nKeep this local edit."
+ }, { versionId: "version:local", now: "2026-08-23T01:00:00.000Z" });
+ assert.equal(updated.skill.curatedOrigin.skillId, "composition");
+ assert.equal(updated.skill.curatedOrigin.version, "1.0.0");
+ assert.match(updated.skill.versions.at(-1).skillMarkdown, /本地修改/);
+});
+
test("full-library imports preserve versions and remap conflicting Skill identities", () => {
const local = createSkill(createCreativeSkillsState(), "国风视觉", { portableId: "guofeng-visual" });
const external = createCreativeSkill(createCreativeSkillsState(), {
diff --git a/test/creative_skills_e2e.py b/test/creative_skills_e2e.py
index 8ac9068..d2d255d 100644
--- a/test/creative_skills_e2e.py
+++ b/test/creative_skills_e2e.py
@@ -95,7 +95,7 @@ Run `scripts/helper.py` before applying the composition guidance.
session.context.route("https://api.deepseek.com/**", mock_deepseek)
skills = session.open_page("skills.html")
runtime = skills.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_AI_TASK_RUNTIME', taskId: 'skillExtraction'})")
- assert runtime["aiRuntimeProtocolVersion"] == 1
+ assert runtime["aiRuntimeProtocolVersion"] == 2
assert runtime["runtimeDescriptor"]["providerLabel"] == "DeepSeek"
assert runtime["runtimeDescriptor"]["model"] == "deepseek-v4-flash"
overridden = skills.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_AI_TASK_RUNTIME', taskId: 'skillExtraction', assignment: {providerId: 'xai', model: 'grok-skill'}})")
@@ -314,26 +314,29 @@ Run `scripts/helper.py` before applying the composition guidance.
composer.locator("#composer-reference-open").click()
composer.locator("#composer-reference-tab-skills").click()
expect(composer.locator("#composer-projects-panel")).to_be_visible()
- expect(composer.locator(".composer-project-card")).to_have_count(2)
+ expect(composer.locator(".composer-skill-card")).to_have_count(2)
composer.screenshot(path="/tmp/promptdirector-composer-skills-after.png")
skill_workspace_layout = composer.evaluate("""() => {
const body = document.querySelector('.composer-reference-body').getBoundingClientRect();
const panel = document.querySelector('#composer-projects-panel').getBoundingClientRect();
const descriptions = [...document.querySelectorAll('.composer-project-state')];
- const cards = [...document.querySelectorAll('.composer-project-card')];
+ const cards = [...document.querySelectorAll('.composer-skill-card')];
+ const tabs = document.querySelector('.composer-reference-tabs').getBoundingClientRect();
return {
mode: document.querySelector('#composer-reference-workspace').dataset.mode,
panelRatio: panel.width / body.width,
descriptionClamp: descriptions.map((item) => getComputedStyle(item).webkitLineClamp),
maxCardHeight: Math.max(...cards.map((item) => item.getBoundingClientRect().height)),
+ tabsWidth: tabs.width,
pageWidth: document.documentElement.scrollWidth,
viewportWidth: innerWidth
};
}""")
assert skill_workspace_layout["mode"] == "skills", skill_workspace_layout
assert skill_workspace_layout["panelRatio"] >= 0.75, skill_workspace_layout
- assert set(skill_workspace_layout["descriptionClamp"]) == {"3"}, skill_workspace_layout
- assert skill_workspace_layout["maxCardHeight"] < 240, skill_workspace_layout
+ assert set(skill_workspace_layout["descriptionClamp"]) == {"2"}, skill_workspace_layout
+ assert skill_workspace_layout["maxCardHeight"] < 220, skill_workspace_layout
+ assert skill_workspace_layout["tabsWidth"] < 180, skill_workspace_layout
assert skill_workspace_layout["pageWidth"] <= skill_workspace_layout["viewportWidth"], skill_workspace_layout
composer.locator("#composer-reference-close").click()
composer.locator("#composer-instruction").fill("/external")
diff --git a/test/curated-skill-catalog.test.js b/test/curated-skill-catalog.test.js
new file mode 100644
index 0000000..4fda878
--- /dev/null
+++ b/test/curated-skill-catalog.test.js
@@ -0,0 +1,73 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { createZipBlob } from "../zip.js";
+import {
+ normalizeCuratedSkillCatalog,
+ validateCuratedSkillPackage,
+ verifyCuratedSkillPackageBlob
+} from "../curated-skill-catalog.js";
+import { sha256Hex } from "../sync-crypto.js";
+
+async function fixture() {
+ const skill = new Blob(["---\nname: composition-method\ndescription: Compose clearly.\n---\n\n# Method\n\nUse depth.\n"]);
+ const archive = await createZipBlob([{ name: "SKILL.md", data: skill }]);
+ const sha256 = await sha256Hex(archive);
+ const item = {
+ skillId: "composition-method",
+ version: "1.0.0",
+ title: "Composition Method",
+ callName: "composition-method",
+ authorId: "creator-one",
+ author: "Creator One",
+ license: "CC BY 4.0",
+ reviewStatus: "approved",
+ reviewedAt: "2026-08-23T00:00:00.000Z",
+ summary: "A reusable composition method.",
+ downloadUrl: "https://github.com/wchao6891/PromptDirector-Curated/releases/download/skills/composition-method.zip",
+ sha256,
+ archiveBytes: archive.size,
+ order: 1
+ };
+ return { archive, item };
+}
+
+test("curated Skill catalog requires stable identity, version, author, license, review and summary", async () => {
+ const { item } = await fixture();
+ const catalog = normalizeCuratedSkillCatalog({
+ format: "prompt-director-curated-skills",
+ version: 1,
+ updatedAt: "2026-08-23T00:00:00.000Z",
+ skills: [item]
+ });
+ assert.equal(catalog.skills[0].skillId, "composition-method");
+ assert.equal(catalog.skills[0].reviewStatus, "approved");
+ assert.throws(() => normalizeCuratedSkillCatalog({ ...catalog, skills: [{ ...item, license: "" }] }), /必填字段/);
+});
+
+test("curated Skill catalog accepts a readable multilingual call name without relaxing local safety boundaries", async () => {
+ const { item } = await fixture();
+ const catalogValue = (callName) => ({
+ format: "prompt-director-curated-skills",
+ version: 1,
+ updatedAt: "2026-08-23T00:00:00.000Z",
+ skills: [{ ...item, callName }]
+ });
+ assert.equal(normalizeCuratedSkillCatalog(catalogValue("中式意境巨构")).skills[0].callName, "中式意境巨构");
+ for (const callName of ["bad/name", "bad\\name", "bad\u0000name", "构".repeat(81)]) {
+ assert.throws(() => normalizeCuratedSkillCatalog(catalogValue(callName)), /必填字段|校验值/);
+ }
+});
+
+test("verified curated Skill packages accept only SKILL.md and UTF-8 Markdown references", async () => {
+ const { archive, item } = await fixture();
+ await verifyCuratedSkillPackageBlob(archive, item.sha256, item.archiveBytes);
+ const parsed = await validateCuratedSkillPackage(item, archive);
+ assert.equal(parsed.name, "composition-method");
+ const unsafe = await createZipBlob([
+ { name: "SKILL.md", data: new Blob(["---\nname: unsafe\ndescription: Unsafe.\n---\n\n# Unsafe\n"]) },
+ { name: "scripts/run.sh", data: new Blob(["echo no"]) }
+ ]);
+ await assert.rejects(() => validateCuratedSkillPackage({ ...item, skillId: "unsafe", callName: "unsafe" }, unsafe), /不允许的文件/);
+});
diff --git a/test/curated-skill-install.test.js b/test/curated-skill-install.test.js
new file mode 100644
index 0000000..d6b3a86
--- /dev/null
+++ b/test/curated-skill-install.test.js
@@ -0,0 +1,99 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { installCuratedSkillTransaction, planCuratedSkillInstall } from "../curated-skill-install.js";
+
+const item = { id: "[email protected]", skillId: "composition", version: "1.0.0", sha256: "a".repeat(64) };
+const parsed = {
+ name: "composition",
+ description: "Compose clearly.",
+ body: "# Method\n\nUse depth.",
+ references: [],
+ files: new Map([["SKILL.md", new Blob(["skill"])]]),
+ dependencies: [],
+ requiresTextModeConfirmation: false
+};
+
+test("same curated Skill version is idempotent while a new version becomes a separate safe copy", () => {
+ const state = { version: 1, items: [{
+ id: "local:one", callName: "composition", portableId: "composition", currentVersionId: "version:local",
+ versions: [{ id: "version:local", skillMarkdown: "# locally edited", createdAt: "2026-08-23T00:00:00.000Z" }],
+ curatedOrigin: { skillId: "composition", version: "1.0.0", catalogId: "[email protected]" }
+ }] };
+ assert.equal(planCuratedSkillInstall(state, item).action, "already-installed");
+ assert.equal(planCuratedSkillInstall(state, { ...item, id: "[email protected]", version: "1.1.0" }).action, "install-update-copy");
+});
+
+test("install saves files before metadata and rolls all new files back when metadata commit fails", async () => {
+ const events = [];
+ await assert.rejects(() => installCuratedSkillTransaction({
+ state: { version: 1, items: [] }, item, parsed,
+ assetIdFactory: () => "skill-file:new",
+ saveBlob: async (id) => { events.push(`save:${id}`); },
+ deleteBlobs: async (ids) => { events.push(`delete:${ids.join(",")}`); },
+ createSkill: async () => { events.push("commit"); throw new Error("commit failed"); }
+ }), /commit failed/);
+ assert.deepEqual(events, ["save:skill-file:new", "commit", "delete:skill-file:new"]);
+});
+
+test("install uses the reviewed catalog call name while keeping the package name as the portable id", async () => {
+ let created;
+ await installCuratedSkillTransaction({
+ state: { version: 1, items: [] },
+ item: { ...item, callName: "中式意境巨构" },
+ parsed,
+ assetIdFactory: () => "skill-file:new",
+ saveBlob: async () => undefined,
+ deleteBlobs: async () => undefined,
+ createSkill: async (skill) => { created = skill; return { skill }; }
+ });
+ assert.equal(created.callName, "中式意境巨构");
+ assert.equal(created.portableId, "composition");
+});
+
+test("install safely renames a reviewed call name that conflicts with a local Skill", async () => {
+ const reviewedName = "构".repeat(80);
+ let created;
+ await installCuratedSkillTransaction({
+ state: { version: 1, items: [{
+ id: "local:existing", callName: reviewedName, portableId: "local-composition", currentVersionId: "v1",
+ versions: [{ id: "v1", skillMarkdown: "# 本地方法", createdAt: "2026-08-23T00:00:00.000Z" }]
+ }] },
+ item: { ...item, callName: reviewedName },
+ parsed,
+ assetIdFactory: () => "skill-file:new",
+ saveBlob: async () => undefined,
+ deleteBlobs: async () => undefined,
+ createSkill: async (skill) => { created = skill; return { skill }; }
+ });
+ assert.equal(created.callName, `${"构".repeat(78)} 2`);
+ assert.equal(created.callName.length, 80);
+ assert.equal(created.portableId, "composition");
+});
+
+test("idempotent install performs no file or metadata writes", async () => {
+ const state = { version: 1, items: [{
+ id: "local:one", callName: "composition", portableId: "composition", currentVersionId: "v1",
+ versions: [{ id: "v1", skillMarkdown: "# Method", createdAt: "2026-08-23T00:00:00.000Z" }],
+ curatedOrigin: { skillId: "composition", version: "1.0.0", catalogId: "[email protected]" }
+ }] };
+ let writes = 0;
+ const result = await installCuratedSkillTransaction({
+ state, item, parsed,
+ saveBlob: async () => { writes += 1; },
+ deleteBlobs: async () => { writes += 1; },
+ createSkill: async () => { writes += 1; }
+ });
+ assert.equal(result.status, "already-installed");
+ assert.equal(writes, 0);
+});
+
+test("rollback failure is visible instead of hiding orphaned temporary files", async () => {
+ await assert.rejects(() => installCuratedSkillTransaction({
+ state: { version: 1, items: [] }, item, parsed,
+ assetIdFactory: () => "skill-file:new",
+ saveBlob: async () => undefined,
+ deleteBlobs: async () => { throw new Error("cleanup failed"); },
+ createSkill: async () => { throw new Error("commit failed"); }
+ }), /回滚未完成/);
+});
diff --git a/test/curated-skill-navigation.test.js b/test/curated-skill-navigation.test.js
new file mode 100644
index 0000000..9ee873c
--- /dev/null
+++ b/test/curated-skill-navigation.test.js
@@ -0,0 +1,92 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+async function sources() {
+ const [casesHtml, skillsHtml, curatedSkillPage, skillsPage, skillsCenter, foundation, composerPage, composerStyle] = await Promise.all([
+ readFile(new URL("../curated.html", import.meta.url), "utf8"),
+ readFile(new URL("../curated-skills.html", import.meta.url), "utf8"),
+ readFile(new URL("../curated-skill-page.js", import.meta.url), "utf8"),
+ readFile(new URL("../skills-page.js", import.meta.url), "utf8"),
+ readFile(new URL("../skills.html", import.meta.url), "utf8"),
+ readFile(new URL("../ui-foundation.css", import.meta.url), "utf8"),
+ readFile(new URL("../composer-page.js", import.meta.url), "utf8"),
+ readFile(new URL("../composer-page.css", import.meta.url), "utf8")
+ ]);
+ return { casesHtml, skillsHtml, curatedSkillPage, skillsPage, skillsCenter, foundation, composerPage, composerStyle };
+}
+
+test("curated cases and curated Skills are independent sibling pages", async () => {
+ const { casesHtml, skillsHtml, skillsCenter } = await sources();
+ assert.match(casesHtml, /href="curated-skills\.html"[^>]*>精选 Skill</);
+ assert.match(skillsHtml, /href="curated\.html"[^>]*>精选案例</);
+ assert.match(skillsHtml, /aria-current="page"[^>]*>精选 Skill</);
+ assert.match(skillsHtml, /id="return-library"/);
+ assert.match(skillsHtml, /src="curated-skill-page\.js"/);
+ assert.match(skillsCenter, /href="curated-skills\.html">精选 Skill</);
+});
+
+test("ordinary lossless export and curated submission are separate Skill detail actions", async () => {
+ const { skillsCenter, skillsPage } = await sources();
+ assert.match(skillsCenter, /id="skill-export"[^>]*data-i18n="导出 Skill"/);
+ assert.match(skillsCenter, /id="skill-submit-curated"[^>]*data-i18n="投稿到精选 Skill"/);
+ assert.match(skillsCenter, /id="skill-submission-dialog"/);
+ assert.match(skillsCenter, /id="skill-submission-preview"/);
+ assert.match(skillsCenter, /id="skill-submission-findings"/);
+ assert.match(skillsPage, /exportStoredSkillPackage\(skill, \{ readFile: getMediaBlob \}\)/);
+ assert.match(skillsPage, /buildCuratedSkillSnapshot/);
+ assert.match(skillsPage, /buildCuratedSkillSubmissionArchive/);
+ assert.match(skillsPage, /chrome\.tabs\.create\(\{ url: CURATED_SKILL_SUBMISSION_URL \}\)/);
+ assert.match(skillsPage, /from "\.\/curated-config\.js"/);
+ assert.doesNotMatch(skillsPage, /github\.rest|issues\.create|auto.?publish/i);
+ for (const hiddenMaintenanceField of ["skill-submission-id", "skill-submission-version", "skill-submission-author-id", "skill-submission-license"]) {
+ assert.doesNotMatch(skillsCenter, new RegExp(`id="${hiddenMaintenanceField}"`));
+ }
+ assert.match(skillsCenter, /id="skill-submission-author"/);
+ assert.match(skillsCenter, /id="skill-submission-summary"/);
+ assert.match(skillsCenter, /id="skill-submission-rights"[^>]*type="checkbox"/);
+ assert.match(skillsCenter, /允许其他用户在保留署名的前提下保存、使用和修改/);
+ assert.match(skillsPage, /chrome\.storage\.local\.(?:get|set)/);
+});
+
+test("curated Skill page verifies bytes and installs through the rollback transaction", async () => {
+ const { curatedSkillPage } = await sources();
+ assert.match(curatedSkillPage, /normalizeCuratedSkillCatalog/);
+ assert.match(curatedSkillPage, /fetchCuratedPackage/);
+ assert.match(curatedSkillPage, /verifyCuratedSkillPackageBlob/);
+ assert.match(curatedSkillPage, /validateCuratedSkillPackage/);
+ assert.match(curatedSkillPage, /installCuratedSkillTransaction/);
+ assert.match(curatedSkillPage, /saveSkillPackageBlob/);
+ assert.match(curatedSkillPage, /deleteMediaBlobs/);
+ assert.match(curatedSkillPage, /type: "CREATE_CREATIVE_SKILL"/);
+ assert.doesNotMatch(curatedSkillPage, /innerHTML|insertAdjacentHTML|eval\(|new Function/);
+});
+
+test("curated Skill page distinguishes load failure, an empty catalog, and no search results", async () => {
+ const { curatedSkillPage } = await sources();
+ assert.match(curatedSkillPage, /function catalogFailureReason/);
+ assert.match(curatedSkillPage, /function clearSearch/);
+ assert.match(curatedSkillPage, /精选 Skill 目录暂时为空/);
+ assert.match(curatedSkillPage, /没有匹配的精选 Skill/);
+ assert.match(curatedSkillPage, /清空搜索/);
+ assert.match(curatedSkillPage, /暂时无法读取精选 Skill/);
+ assert.doesNotMatch(curatedSkillPage, /showStatus\(error\.message/);
+});
+
+test("Skill discovery surfaces share one compact visual contract and keep maintenance facts secondary", async () => {
+ const { casesHtml, skillsHtml, curatedSkillPage, foundation, composerPage, composerStyle } = await sources();
+ assert.match(foundation, /\.ui-segmented\s*\{/);
+ assert.match(foundation, /\.ui-segmented-item\s*\{/);
+ assert.match(foundation, /\.ui-skill-card\s*\{/);
+ assert.match(casesHtml, /curated-sections ui-segmented/);
+ assert.match(skillsHtml, /curated-sections ui-segmented/);
+ assert.match(skillsHtml, /placeholder="搜索 Skill 或用途"/);
+ assert.match(curatedSkillPage, /ui-skill-card curated-skill-card/);
+ assert.match(curatedSkillPage, /查看说明/);
+ assert.match(curatedSkillPage, /保存到本地/);
+ assert.match(curatedSkillPage, /版本与许可/);
+ assert.match(curatedSkillPage, /curated-skill-maintenance/);
+ assert.match(curatedSkillPage, /removeDuplicateTitleHeading/);
+ assert.match(composerPage, /ui-skill-card composer-skill-card/);
+ assert.match(composerStyle, /\.composer-skill-card/);
+});
diff --git a/test/curated-skill-package.test.js b/test/curated-skill-package.test.js
new file mode 100644
index 0000000..9db2dbf
--- /dev/null
+++ b/test/curated-skill-package.test.js
@@ -0,0 +1,97 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ buildCuratedSkillSnapshot,
+ buildCuratedSkillSubmissionArchive
+} from "../curated-skill-package.js";
+import { currentCreativeSkillVersion, createCreativeSkill, createCreativeSkillsState } from "../creative-skills.js";
+import { readZipBlob } from "../zip.js";
+
+function fixture(overrides = {}) {
+ return createCreativeSkill(createCreativeSkillsState(), {
+ callName: "构图方法",
+ portableId: "composition-method",
+ description: "把主体层级组织成清晰画面。",
+ skillMarkdown: "# 构图方法\n\n保持主体清晰。",
+ references: [{ path: "references/guide.md", markdown: "# Guide\n\nUse depth.", runtime: true }],
+ provenanceMarkdown: "# 私人来源\n\n/Users/private/cases.md"
+ }, { id: "local:one", versionId: "version:one", now: "2026-08-23T00:00:00.000Z" }).skill;
+}
+
+test("curated submission snapshot is text-only, exact-previewable, and excludes private provenance by default", async () => {
+ const skill = fixture();
+ const snapshot = await buildCuratedSkillSnapshot(skill, {
+ author: "Creator One",
+ summary: "A reusable composition method.",
+ rightsConfirmed: true
+ });
+ assert.deepEqual([...snapshot.files.keys()], ["SKILL.md", "references/guide.md"]);
+ assert.equal(snapshot.findings.length, 0);
+ assert.doesNotMatch(await snapshot.files.get("SKILL.md").text(), /私人来源|\/Users\/private/);
+ assert.equal(snapshot.manifest.reviewStatus, "pending");
+ assert.equal(snapshot.manifest.skillId, "composition-method");
+ assert.equal(snapshot.manifest.callName, "构图方法");
+ assert.equal(snapshot.manifest.author, "Creator One");
+ assert.equal(snapshot.manifest.license, "CC BY 4.0");
+ assert.equal("authorId" in snapshot.manifest, false);
+ assert.equal("skillVersion" in snapshot.manifest, false);
+ assert.equal(snapshot.preview[0].text, await snapshot.files.get("SKILL.md").text());
+ assert.equal(currentCreativeSkillVersion(skill).provenanceMarkdown.includes("private"), true);
+});
+
+test("privacy findings are reported without mutating the final preview", async () => {
+ const skill = fixture();
+ skill.versions[0].skillMarkdown = "# Method\n\nAPI_KEY=\"secret-value-123456\", /Users/alice/private.md, [email protected]";
+ const snapshot = await buildCuratedSkillSnapshot(skill, {
+ author: "Creator One",
+ summary: "A reusable composition method.",
+ rightsConfirmed: true
+ });
+ assert.deepEqual(new Set(snapshot.findings.map((item) => item.kind)), new Set(["credential", "local-path", "personal-identifier"]));
+ assert.match(snapshot.preview[0].text, /secret-value-123456/);
+ assert.match(snapshot.preview[0].text, /\/Users\/alice/);
+ await assert.rejects(() => buildCuratedSkillSubmissionArchive(snapshot), /隐私风险/);
+});
+
+test("submission archive contains a manifest and the reviewed text payload only", async () => {
+ const snapshot = await buildCuratedSkillSnapshot(fixture(), {
+ author: "Creator One",
+ summary: "A reusable composition method.",
+ rightsConfirmed: true
+ });
+ const archive = await buildCuratedSkillSubmissionArchive(snapshot);
+ const outer = await readZipBlob(archive);
+ assert.deepEqual([...outer.keys()], ["submission.json", "payload.zip"]);
+ const manifest = JSON.parse(await outer.get("submission.json").text());
+ assert.equal(manifest.format, "prompt-director-curated-skill-submission");
+ assert.equal(manifest.version, 1);
+ assert.equal(manifest.license, "CC BY 4.0");
+ assert.equal("authorId" in manifest, false);
+ assert.equal("skillVersion" in manifest, false);
+ const payload = await readZipBlob(outer.get("payload.zip"));
+ assert.deepEqual([...payload.keys()], ["SKILL.md", "references/guide.md"]);
+});
+
+test("curated submission rejects missing public consent and derives its stable id from the Skill", async () => {
+ await assert.rejects(() => buildCuratedSkillSnapshot(fixture(), {
+ author: "Creator One",
+ summary: "A reusable composition method.",
+ rightsConfirmed: false,
+ publicSkillId: "user-overridden-id"
+ }), /允许其他用户/);
+
+ const snapshot = await buildCuratedSkillSnapshot(fixture(), {
+ author: "Creator One",
+ summary: "A reusable composition method.",
+ rightsConfirmed: true,
+ publicSkillId: "user-overridden-id",
+ publicVersion: "99.0.0",
+ authorId: "hidden-maintenance-field",
+ license: "MIT"
+ });
+ assert.equal(snapshot.manifest.skillId, "composition-method");
+ assert.equal(snapshot.manifest.license, "CC BY 4.0");
+ assert.equal("authorId" in snapshot.manifest, false);
+ assert.equal("skillVersion" in snapshot.manifest, false);
+});
diff --git a/test/curated_skills_install_e2e.py b/test/curated_skills_install_e2e.py
new file mode 100644
index 0000000..ab4f209
--- /dev/null
+++ b/test/curated_skills_install_e2e.py
@@ -0,0 +1,241 @@
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import zipfile
+
+from playwright.sync_api import expect
+
+from e2e_support import extension_session
+
+
+CATALOG_URL = "https://wchao6891.github.io/PromptDirector-Curated/skills-catalog.json"
+GOOD_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/skills/good-skill.zip"
+ROLLBACK_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/skills/rollback-skill.zip"
+UNSAFE_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/skills/unsafe-skill.zip"
+
+
+def skill_archive(name: str, description: str, body: str, *, unsafe_script: bool = False) -> bytes:
+ stream = io.BytesIO()
+ skill_markdown = f"---\nname: {name}\ndescription: {description}\n---\n\n{body}\n"
+ with zipfile.ZipFile(stream, "w", zipfile.ZIP_DEFLATED) as archive:
+ archive.writestr("SKILL.md", skill_markdown)
+ archive.writestr("references/guide.md", "# Guide\n\nKeep the subject readable.\n")
+ if unsafe_script:
+ archive.writestr("scripts/run.sh", "echo should-never-run\n")
+ return stream.getvalue()
+
+
+def catalog_item(*, catalog_id: str, skill_id: str, title: str, download_url: str, archive: bytes, order: int, call_name: str | None = None) -> dict:
+ return {
+ "id": catalog_id,
+ "skillId": skill_id,
+ "version": "1.0.0",
+ "title": title,
+ "callName": call_name or skill_id,
+ "authorId": "synthetic-author",
+ "author": "合成测试作者",
+ "license": "CC BY 4.0",
+ "reviewStatus": "approved",
+ "reviewedAt": "2026-08-23T00:00:00.000Z",
+ "summary": f"{title} 的合成测试摘要。",
+ "downloadUrl": download_url,
+ "sha256": hashlib.sha256(archive).hexdigest(),
+ "archiveBytes": len(archive),
+ "order": order,
+ }
+
+
+def persisted_snapshot(page) -> dict:
+ return page.evaluate(
+ """async () => {
+ const stored = await chrome.storage.local.get('creativeSkills');
+ const skills = stored.creativeSkills?.items ?? [];
+ const database = await new Promise((resolve, reject) => {
+ const request = indexedDB.open('prompt-case-collector');
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ const keys = await new Promise((resolve, reject) => {
+ const request = database.transaction('media', 'readonly').objectStore('media').getAllKeys();
+ request.onsuccess = () => resolve(request.result.map(String).sort());
+ request.onerror = () => reject(request.error);
+ });
+ const {getMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
+ const files = [];
+ for (const skill of skills) {
+ for (const file of skill.packageFiles ?? []) {
+ const blob = await getMediaBlob(file.assetId);
+ files.push({
+ skillId: skill.curatedOrigin?.skillId ?? '',
+ path: file.path,
+ assetId: file.assetId,
+ size: blob?.size ?? -1,
+ text: blob ? await blob.text() : ''
+ });
+ }
+ }
+ database.close();
+ return {skills, keys, files};
+ }"""
+ )
+
+
+def main() -> None:
+ good_archive = skill_archive("good-skill", "A safe synthetic Skill.", "# 安全精选 Skill\n\n## 使用方法\n\nUse clear hierarchy.")
+ rollback_archive = skill_archive("rollback-skill", "A rollback fixture.", "# Rollback method\n\nKeep local work intact.")
+ unsafe_archive = skill_archive("unsafe-skill", "An unsafe fixture.", "# Unsafe method\n\nThis text itself is inert.", unsafe_script=True)
+ items = [
+ catalog_item(catalog_id="[email protected]", skill_id="good-skill", title="安全精选 Skill", call_name="中式意境巨构", download_url=GOOD_URL, archive=good_archive, order=1),
+ catalog_item(catalog_id="[email protected]", skill_id="rollback-skill", title="回滚精选 Skill", download_url=ROLLBACK_URL, archive=rollback_archive, order=2),
+ catalog_item(catalog_id="[email protected]", skill_id="unsafe-skill", title="不安全精选 Skill", download_url=UNSAFE_URL, archive=unsafe_archive, order=3),
+ ]
+ catalog = {
+ "format": "prompt-director-curated-skills",
+ "version": 1,
+ "updatedAt": "2026-08-23T00:00:00.000Z",
+ "skills": items,
+ }
+ requests: list[str] = []
+
+ with extension_session("prompt-director-curated-skills-install-", viewport={"width": 1280, "height": 900}) as session:
+ session.context.route("https://**", lambda route: route.abort("blockedbyclient"))
+
+ def fulfill(url: str, content_type: str, body) -> None:
+ def handler(route) -> None:
+ requests.append(route.request.url)
+ route.fulfill(status=200, content_type=content_type, body=body)
+ session.context.route(url, handler)
+
+ fulfill(CATALOG_URL, "application/json", json.dumps(catalog, ensure_ascii=False))
+ fulfill(GOOD_URL, "application/zip", good_archive)
+ fulfill(ROLLBACK_URL, "application/zip", rollback_archive)
+ fulfill(UNSAFE_URL, "application/zip", unsafe_archive)
+
+ setup = session.open_page("collector.html")
+ session.seed_storage(setup, {
+ "schemaVersion": 24,
+ "creativeSkills": {"version": 1, "items": []},
+ "uiPreferences": {"locale": "zh-CN", "theme": "light", "motion": "none"},
+ })
+ setup.close()
+
+ page = session.open_page("curated-skills.html")
+ expect(page.locator(".curated-skill-card")).to_have_count(3)
+ assert requests == [CATALOG_URL], requests
+
+ good_card = page.locator(".curated-skill-card").filter(has=page.get_by_role("heading", name="安全精选 Skill", exact=True))
+ card_copy = good_card.text_content()
+ assert "合成测试作者" not in card_copy, card_copy
+ assert "CC BY 4.0" not in card_copy, card_copy
+ assert "v1.0.0" not in card_copy, card_copy
+ assert "/中式意境巨构" not in card_copy, card_copy
+ save = good_card.get_by_role("button", name="保存到本地", exact=True)
+ save.click()
+ expect(page.locator("#skill-toast")).to_have_text("精选 Skill 已保存到本地")
+
+ first = persisted_snapshot(page)
+ assert len(first["skills"]) == 1, first
+ saved_skill = first["skills"][0]
+ assert saved_skill["callName"] == "中式意境巨构", saved_skill
+ assert saved_skill["portableId"] == "good-skill", saved_skill
+ assert saved_skill["curatedOrigin"]["skillId"] == "good-skill", saved_skill
+ assert saved_skill["curatedOrigin"]["version"] == "1.0.0", saved_skill
+ assert [file["path"] for file in saved_skill["packageFiles"]] == ["SKILL.md", "references/guide.md"], saved_skill
+ assert len(first["keys"]) == 2, first
+ assert first["keys"] == sorted(file["assetId"] for file in saved_skill["packageFiles"]), first
+ saved_text = {file["path"]: file["text"] for file in first["files"]}
+ assert "Use clear hierarchy." in saved_text["SKILL.md"], saved_text
+ assert saved_text["references/guide.md"] == "# Guide\n\nKeep the subject readable.\n", saved_text
+
+ good_card = page.locator(".curated-skill-card").filter(has=page.get_by_role("heading", name="安全精选 Skill", exact=True))
+ good_card.get_by_role("button", name="查看说明", exact=True).click()
+ expect(page.locator("#skill-detail-dialog")).to_be_visible()
+ expect(page.locator(".curated-skill-markdown")).to_contain_text("使用方法")
+ expect(page.locator(".curated-skill-markdown h1")).to_have_count(0)
+ maintenance = page.locator(".curated-skill-maintenance")
+ expect(maintenance).not_to_have_attribute("open", "")
+ expect(maintenance.get_by_text("许可:CC BY 4.0", exact=True)).to_be_hidden()
+ maintenance.locator("summary").click()
+ expect(maintenance.get_by_text("许可:CC BY 4.0", exact=True)).to_be_visible()
+
+ # Force a second click through the real handler so the idempotent transaction is exercised,
+ # rather than only accepting the disabled UI as evidence.
+ already_saved = page.locator("#skill-detail-dialog").get_by_role("button", name="已保存")
+ expect(already_saved).to_be_disabled()
+ already_saved.evaluate("button => { button.disabled = false; }")
+ already_saved.click()
+ expect(page.locator("#skill-toast")).to_have_text("这个版本已经在本地")
+ second = persisted_snapshot(page)
+ assert len(second["skills"]) == 1, second
+ assert second["keys"] == first["keys"], {"first": first, "second": second}
+
+ page.locator("#skill-detail-close").click()
+ patched = page.evaluate(
+ """() => {
+ const original = chrome.runtime.sendMessage;
+ window.__promptDirectorOriginalSendMessage = original;
+ chrome.runtime.sendMessage = (...args) => args[0]?.type === 'CREATE_CREATIVE_SKILL'
+ ? Promise.resolve({ok: false, message: '模拟元数据提交失败'})
+ : original.apply(chrome.runtime, args);
+ return chrome.runtime.sendMessage !== original;
+ }"""
+ )
+ assert patched is True
+ page.locator(".curated-skill-card", has_text="回滚精选 Skill").get_by_role("button", name="保存到本地", exact=True).click()
+ expect(page.locator("#skill-toast")).to_have_text("模拟元数据提交失败")
+ rolled_back = persisted_snapshot(page)
+ assert len(rolled_back["skills"]) == 1, rolled_back
+ assert rolled_back["keys"] == first["keys"], {"before": first, "after": rolled_back}
+
+ page.evaluate("chrome.runtime.sendMessage = window.__promptDirectorOriginalSendMessage")
+ unsafe_card = page.locator(".curated-skill-card", has_text="不安全精选 Skill")
+ unsafe_card.get_by_role("button", name="保存到本地", exact=True).click()
+ expect(page.locator("#skill-toast")).to_contain_text("包含不允许的文件")
+ after_unsafe = persisted_snapshot(page)
+ assert len(after_unsafe["skills"]) == 1, after_unsafe
+ assert after_unsafe["keys"] == first["keys"], {"before": first, "after": after_unsafe}
+
+ assert requests == [CATALOG_URL, GOOD_URL, ROLLBACK_URL, UNSAFE_URL], requests
+
+ page.evaluate("""async () => chrome.storage.local.set({
+ uiPreferences: {locale: 'en', theme: 'dark', motion: 'none'}
+ })""")
+ page.set_viewport_size({"width": 390, "height": 844})
+ page.reload(wait_until="domcontentloaded")
+ expect(page.locator("html")).to_have_attribute("data-theme", "dark")
+ expect(page.locator(".curated-skill-card")).to_have_count(3)
+ expect(page.locator("#skill-search")).to_have_attribute("placeholder", "Search by Skill or purpose")
+ page.locator(".curated-skill-card").first.hover()
+ mobile_visual = page.evaluate("""() => {
+ const card = document.querySelector('.curated-skill-card');
+ const title = card.querySelector('.ui-skill-card-title');
+ const nav = document.querySelector('.curated-sections');
+ return {
+ pageWidth: document.documentElement.scrollWidth,
+ viewportWidth: innerWidth,
+ cardHeight: card.getBoundingClientRect().height,
+ cardBackground: getComputedStyle(card).backgroundColor,
+ titleSize: getComputedStyle(title).fontSize,
+ navWidth: nav.getBoundingClientRect().width
+ };
+ }""")
+ assert mobile_visual["pageWidth"] == mobile_visual["viewportWidth"] == 390, mobile_visual
+ assert 152 <= mobile_visual["cardHeight"] < 220, mobile_visual
+ assert mobile_visual["titleSize"] == "17px", mobile_visual
+ assert mobile_visual["navWidth"] < 230, mobile_visual
+ assert mobile_visual["cardBackground"] != "rgb(209, 254, 23)", mobile_visual
+ print({
+ "installedSkills": len(after_unsafe["skills"]),
+ "storedPackageFiles": len(after_unsafe["keys"]),
+ "sameVersionIdempotent": True,
+ "metadataFailureRolledBack": True,
+ "unsafePackageRejected": True,
+ "mobileDarkVisualContract": mobile_visual,
+ "externalNetworkRequests": 0,
+ })
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/data-safety-ui.test.js b/test/data-safety-ui.test.js
index 3dcc15e..f98766e 100644
--- a/test/data-safety-ui.test.js
+++ b/test/data-safety-ui.test.js
@@ -21,18 +21,19 @@ test("whole-library portable ZIP backup is removed while selected-case sharing r
assert.doesNotMatch(exporter, /exportState\s*=\s*sharing\s*\?/);
});
-test("connecting a sync folder replaces stale status before the full library is encrypted", async () => {
+test("connecting a sync folder immediately states that it only verifies access", async () => {
const library = await readFile(new URL("../library.js", import.meta.url), "utf8");
const actionBody = library.slice(
library.indexOf("async function runDataSafetyAction"),
library.indexOf("function showDataSafetyFeedback")
);
const sendIndex = actionBody.indexOf("await chrome.runtime.sendMessage(message)");
- const pendingIndex = actionBody.indexOf('showDataSafetyFeedback(t("正在加密并写入同步文件夹');
+ const pendingIndex = actionBody.indexOf('showDataSafetyFeedback("正在验证文件夹与密码,不会读取或合并资料…")');
assert.ok(pendingIndex >= 0, "连接同步时必须立即替换旧的备份或授权提示");
- assert.ok(pendingIndex < sendIndex, "大资料库开始加密前必须先显示连接状态");
+ assert.ok(pendingIndex < sendIndex, "验证文件夹前必须先显示准确状态");
assert.match(actionBody, /button\.textContent\s*=\s*t\("正在连接…"\)/);
+ assert.doesNotMatch(actionBody, /正在加密并写入同步文件夹|正在解锁并合并同步资料/);
});
test("a missing sync location shows a localized recovery action instead of the browser error", async () => {
diff --git a/test/i18n.test.js b/test/i18n.test.js
index b363ece..d6a4412 100644
--- a/test/i18n.test.js
+++ b/test/i18n.test.js
@@ -13,7 +13,7 @@ test("manifest locale catalogs expose the same message keys", async () => {
});
test("every static HTML i18n marker has an English translation", async () => {
- for (const path of ["../collector.html", "../library.html", "../composer.html", "../skills.html", "../curated.html"]) {
+ for (const path of ["../collector.html", "../library.html", "../composer.html", "../skills.html", "../curated.html", "../curated-skills.html"]) {
const html = await readFile(new URL(path, import.meta.url), "utf8");
const keys = [...html.matchAll(/data-i18n(?:-placeholder|-aria-label|-title)?="([^"]+)"/g)].map((match) => match[1]);
const missing = [...new Set(keys.filter((key) => !hasEnglishTranslation(key)))];
diff --git a/test/library-navigation.test.js b/test/library-navigation.test.js
index 48fdece..b05e1b7 100644
--- a/test/library-navigation.test.js
+++ b/test/library-navigation.test.js
@@ -118,7 +118,7 @@ test("Skill details keep creation primary and place refine and export in one Mor
assert.match(skillsHtml, /id="skill-detail-more"/);
assert.match(skillsHtml, /id="skill-export"/);
assert.match(skillsSource, /function exportSkill/);
- assert.match(skillsSource, /exportGeneratedSkillPackage/);
+ assert.match(skillsSource, /exportStoredSkillPackage/);
assert.match(skillsSource, /elements\.skillSearch\.hidden = !listView/);
assert.match(skillsSource, /elements\.skillImport\.hidden = !listView/);
assert.match(skillsSource, /elements\.skillCreate\.hidden = !listView/);
@@ -127,3 +127,13 @@ test("Skill details keep creation primary and place refine and export in one Mor
assert.match(skillsHtml, /id="skill-detail-refine"/);
assert.doesNotMatch(skillsHtml, /PORTABLE CREATIVE METHODS|CREATIVE SKILL|IMPORT SKILL|VERSIONS/);
});
+
+test("model options stay concise and put capability uncertainty below the selected field once", () => {
+ const optionsSource = source.slice(source.indexOf("function discoveredModelOptions"), source.indexOf("function taskModelOptions"));
+ assert.doesNotMatch(optionsSource, /厂商声明|协议确认|由你分配|首次执行时验证/);
+ assert.match(optionsSource, /model\.name \|\| model\.id/);
+ assert.match(optionsSource, /modelPriceLabel\(model\.pricing\)/);
+ assert.match(source, /function modelAssignmentHelp/);
+ assert.match(source, /model-capability-help/);
+ assert.match(source, /当前模型未声明这项能力;是否可用以真实执行结果为准/);
+});
diff --git a/test/library_discovery_e2e.py b/test/library_discovery_e2e.py
index 61fb25c..692059e 100644
--- a/test/library_discovery_e2e.py
+++ b/test/library_discovery_e2e.py
@@ -125,6 +125,7 @@ def main() -> None:
)
assert next_hit
library.locator("#detail-next").click()
+ expect(library.locator("#detail-drawer")).not_to_have_attribute("data-entry-id", initial_entry_id)
second_entry_id = library.locator("#detail-drawer").get_attribute("data-entry-id")
assert second_entry_id != initial_entry_id
library.locator("#detail-prev").click()
diff --git a/test/manual-sync.test.js b/test/manual-sync.test.js
new file mode 100644
index 0000000..828478f
--- /dev/null
+++ b/test/manual-sync.test.js
@@ -0,0 +1,350 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { createManualSyncController } from "../manual-sync.js";
+import { createRevisionSnapshot } from "../sync-model.js";
+
+test("a second unchanged manual sync performs zero media snapshot and metadata writes", async () => {
+ const fixture = await createFixture();
+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ fixture.resetCounts();
+
+ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+
+ assert.equal(result.upToDate, true);
+ assert.deepEqual(fixture.counts(), {
+ stateReads: 0,
+ mediaReads: 0,
+ mediaWrites: 0,
+ mediaDeletes: 0,
+ objectWrites: 0,
+ objectReads: 0,
+ snapshotWrites: 0,
+ metadataWrites: 0
+ });
+ assert.equal(fixture.controller.status().state, "up-to-date");
+});
+
+test("legacy sync metadata recovers object references from revision records", async () => {
+ const fixture = await createFixture();
+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ fixture.meta.assetRefs = {};
+ fixture.resetCounts();
+
+ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+
+ assert.equal(result.upToDate, true);
+ assert.equal(result.mediaCount, 1);
+ assert.equal(fixture.counts().mediaReads, 0);
+ assert.equal(fixture.counts().objectWrites, 0);
+ assert.equal(fixture.counts().snapshotWrites, 0);
+ assert.equal(fixture.counts().metadataWrites, 0);
+});
+
+test("only a newly added managed asset is read and uploaded", async () => {
+ const fixture = await createFixture();
+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ fixture.state.entries.push(entry("two", "asset:two"));
+ fixture.media.set("asset:two", new Blob(["two"], { type: "image/webp" }));
+ fixture.meta.localDirty = true;
+ fixture.meta.dirtyAssetIds = ["asset:two"];
+ fixture.resetCounts();
+
+ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+
+ assert.equal(result.ok, true);
+ assert.equal(result.upToDate, false);
+ assert.equal(fixture.counts().mediaReads, 1);
+ assert.equal(fixture.counts().objectWrites, 1);
+ assert.equal(fixture.counts().snapshotWrites, 1);
+ assert.equal(fixture.counts().metadataWrites, 1);
+ assert.equal(result.changeSummary.byEntity.entry.added, 1);
+ assert.equal(result.effects.localBusinessChanged, false);
+});
+
+test("metadata-only edits reuse the previous media object without reading its blob", async () => {
+ const fixture = await createFixture();
+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ fixture.state.entries[0].title = "renamed";
+ fixture.meta.localDirty = true;
+ fixture.resetCounts();
+
+ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+
+ assert.equal(result.ok, true);
+ assert.equal(fixture.counts().mediaReads, 0);
+ assert.equal(fixture.counts().objectWrites, 0);
+ assert.equal(fixture.counts().snapshotWrites, 1);
+ assert.equal(fixture.counts().metadataWrites, 1);
+ assert.equal(result.changeSummary.byEntity.entry.updated, 1);
+ assert.equal(result.effects.localBusinessChanged, false);
+});
+
+test("a reverted local edit clears its pending marker without publishing a snapshot", async () => {
+ const fixture = await createFixture();
+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ fixture.meta.localDirty = true;
+ fixture.resetCounts();
+
+ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+
+ assert.equal(result.upToDate, true);
+ assert.equal(fixture.counts().mediaReads, 0);
+ assert.equal(fixture.counts().objectWrites, 0);
+ assert.equal(fixture.counts().snapshotWrites, 0);
+ assert.equal(fixture.counts().metadataWrites, 1);
+ assert.equal(fixture.meta.localDirty, false);
+});
+
+test("remote additions report that local business data changed exactly once", async () => {
+ const fixture = await createFixture();
+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ const remotePrepared = state([entry("one", "asset:one"), entry("remote", "asset:remote")]);
+ remotePrepared.entries[0].mediaAssets[0].syncObjectId = fixture.meta.assetRefs["asset:one"].objectId;
+ remotePrepared.entries[0].mediaAssets[0].syncContentType = "image/webp";
+ remotePrepared.entries[1].mediaAssets[0].syncObjectId = "b".repeat(64);
+ remotePrepared.entries[1].mediaAssets[0].syncContentType = "image/webp";
+ fixture.remoteSnapshots.push(await createRevisionSnapshot(remotePrepared, {
+ deviceId: "device-b",
+ logicalClock: fixture.meta.logicalClock + 1,
+ baseSnapshot: {
+ format: "prompt-director-sync-state",
+ version: 1,
+ records: fixture.meta.records
+ }
+ }));
+ fixture.objects.set("b".repeat(64), new Blob(["remote"], { type: "image/webp" }));
+ fixture.resetCounts();
+
+ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+
+ assert.equal(result.ok, true);
+ assert.equal(result.effects.localBusinessChanged, true);
+ assert.equal(result.effects.localMediaCommitted, 1);
+ assert.equal(result.appliedChangeSummary.byEntity.entry.added, 1);
+ assert.equal(fixture.counts().mediaWrites, 1);
+ assert.equal(fixture.state.entries.some((item) => item.id === "remote"), true);
+});
+
+test("cancel rolls media restoration back and exposes a stable canceled terminal state", async () => {
+ const fixture = await createFixture();
+ await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ const remoteState = state([entry("one", "asset:one"), entry("remote", "asset:remote")]);
+ const remotePrepared = structuredClone(remoteState);
+ remotePrepared.entries[0].mediaAssets[0].syncObjectId = fixture.meta.assetRefs["asset:one"].objectId;
+ remotePrepared.entries[0].mediaAssets[0].syncContentType = "image/webp";
+ remotePrepared.entries[1].mediaAssets[0].syncObjectId = "b".repeat(64);
+ remotePrepared.entries[1].mediaAssets[0].syncContentType = "image/webp";
+ fixture.remoteSnapshots.push(await createRevisionSnapshot(remotePrepared, {
+ deviceId: "device-b",
+ logicalClock: fixture.meta.logicalClock + 1,
+ baseSnapshot: {
+ format: "prompt-director-sync-state",
+ version: 1,
+ records: fixture.meta.records
+ }
+ }));
+ fixture.objects.set("b".repeat(64), new Blob(["remote"], { type: "image/webp" }));
+ fixture.resetCounts();
+ fixture.pauseObjectRead = true;
+
+ const pending = fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ await fixture.objectReadStarted;
+ assert.equal(fixture.controller.cancel(), true);
+ fixture.resumeObjectRead();
+ const result = await pending;
+
+ assert.equal(result.canceled, true);
+ assert.equal(fixture.controller.status().state, "canceled");
+ assert.equal(fixture.controller.status().active, false);
+ assert.equal(fixture.controller.status().terminal, true);
+ assert.equal(fixture.controller.status().pendingCount, 0);
+ assert.equal(fixture.controller.status().runningCount, 0);
+ assert.equal(fixture.media.has("asset:remote"), false);
+ assert.equal(fixture.counts().snapshotWrites, 0);
+ assert.equal(fixture.counts().metadataWrites, 0);
+});
+
+test("repeated start calls share one active manual run and never queue a second run", async () => {
+ const fixture = await createFixture();
+ fixture.pauseSnapshotList = true;
+ const first = fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ await fixture.snapshotListStarted;
+ const second = fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ assert.equal(first, second);
+ assert.equal(fixture.controller.status().pendingCount, 0);
+ assert.equal(fixture.controller.status().runningCount, 1);
+ fixture.resumeSnapshotList();
+ await first;
+ assert.equal(fixture.listCalls, 1);
+ assert.equal(fixture.controller.status().active, false);
+});
+
+test("cancel is rejected after the atomic commit point has started", async () => {
+ const fixture = await createFixture();
+ fixture.pauseCommit = true;
+ const pending = fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ await fixture.commitStarted;
+
+ assert.equal(fixture.controller.status().phase, "committing");
+ assert.equal(fixture.controller.cancel(), false);
+ fixture.resumeCommit();
+ const result = await pending;
+ assert.equal(result.ok, true);
+ assert.equal(result.canceled, false);
+ assert.equal(fixture.controller.status().state, "success");
+});
+
+async function createFixture() {
+ let count = emptyCounts();
+ let stateValue = state([entry("one", "asset:one")]);
+ let metaValue = { logicalClock: 0, records: {}, assetRefs: {}, localDirty: false, dirtyAssetIds: [] };
+ const remoteSnapshots = [];
+ const media = new Map([["asset:one", new Blob(["one"], { type: "image/webp" })]]);
+ const objects = new Map();
+ let pauseObjectRead = false;
+ let resumeObjectRead;
+ let objectReadStartedResolve;
+ let objectReadStarted = new Promise((resolve) => { objectReadStartedResolve = resolve; });
+ let pauseSnapshotList = false;
+ let resumeSnapshotList;
+ let snapshotListStartedResolve;
+ let snapshotListStarted = new Promise((resolve) => { snapshotListStartedResolve = resolve; });
+ let listCalls = 0;
+ let pauseCommit = false;
+ let resumeCommit;
+ let commitStartedResolve;
+ let commitStarted = new Promise((resolve) => { commitStartedResolve = resolve; });
+
+ const controller = createManualSyncController({
+ readState: async () => {
+ count.stateReads += 1;
+ return structuredClone(stateValue);
+ },
+ readMeta: async () => structuredClone(metaValue),
+ listSnapshots: async (_vault, { signal } = {}) => {
+ listCalls += 1;
+ if (pauseSnapshotList) {
+ snapshotListStartedResolve();
+ await new Promise((resolve) => { resumeSnapshotList = resolve; });
+ }
+ signal?.throwIfAborted();
+ return structuredClone(remoteSnapshots);
+ },
+ readMedia: async (id) => {
+ count.mediaReads += 1;
+ return media.get(id) ?? null;
+ },
+ writeMedia: async (id, blob) => {
+ count.mediaWrites += 1;
+ media.set(id, blob);
+ },
+ deleteMedia: async (id) => {
+ count.mediaDeletes += 1;
+ media.delete(id);
+ },
+ writeObject: async (_vault, blob, { signal } = {}) => {
+ signal?.throwIfAborted();
+ count.objectWrites += 1;
+ const objectId = blob.size === 3 && await blob.text() === "one" ? "a".repeat(64) : "c".repeat(64);
+ objects.set(objectId, blob);
+ return objectId;
+ },
+ readObject: async (_vault, objectId, { signal } = {}) => {
+ count.objectReads += 1;
+ if (pauseObjectRead) {
+ objectReadStartedResolve();
+ await new Promise((resolve) => { resumeObjectRead = resolve; });
+ }
+ signal?.throwIfAborted();
+ return objects.get(objectId);
+ },
+ writeSnapshot: async (_vault, snapshot) => {
+ count.snapshotWrites += 1;
+ remoteSnapshots.push(structuredClone(snapshot));
+ },
+ commit: async ({ state: nextState, meta }) => {
+ if (pauseCommit) {
+ commitStartedResolve();
+ await new Promise((resolve) => { resumeCommit = resolve; });
+ }
+ count.metadataWrites += 1;
+ stateValue = structuredClone(nextState);
+ metaValue = structuredClone(meta);
+ },
+ now: () => "2026-08-23T00:00:00.000Z"
+ });
+
+ const fixture = {
+ controller,
+ vault: { header: { vaultId: "vault:one" } },
+ settings: { enabled: true, vaultId: "vault:one", deviceId: "device-a", retentionCount: 10 },
+ remoteSnapshots,
+ media,
+ objects,
+ counts: () => ({ ...count }),
+ resetCounts: () => { count = emptyCounts(); },
+ get state() { return stateValue; },
+ get meta() { return metaValue; },
+ get objectReadStarted() { return objectReadStarted; },
+ resumeObjectRead: () => resumeObjectRead?.(),
+ get snapshotListStarted() { return snapshotListStarted; },
+ resumeSnapshotList: () => resumeSnapshotList?.(),
+ get listCalls() { return listCalls; }
+ };
+ Object.defineProperty(fixture, "pauseObjectRead", { set(value) { pauseObjectRead = value; } });
+ Object.defineProperty(fixture, "pauseSnapshotList", { set(value) { pauseSnapshotList = value; } });
+ Object.defineProperty(fixture, "pauseCommit", { set(value) { pauseCommit = value; } });
+ Object.defineProperty(fixture, "commitStarted", { get() { return commitStarted; } });
+ fixture.resumeCommit = () => resumeCommit?.();
+ return fixture;
+}
+
+function emptyCounts() {
+ return {
+ stateReads: 0,
+ mediaReads: 0,
+ mediaWrites: 0,
+ mediaDeletes: 0,
+ objectWrites: 0,
+ objectReads: 0,
+ snapshotWrites: 0,
+ metadataWrites: 0
+ };
+}
+
+function state(entries = []) {
+ return {
+ entries,
+ compoundCases: [],
+ organizerState: { version: 4, collections: [] },
+ taxonomy: { version: 14, revision: 1, nodes: [] },
+ facetCatalog: { version: 1, revision: 1, facets: [], nodes: [] },
+ classificationRules: [],
+ composerSettings: {},
+ composerSessions: [],
+ creativeExperimentSettings: {},
+ creativeRuns: [],
+ creativeSkills: { version: 1, items: [] },
+ trashState: { version: 1, items: [] },
+ settings: { libraryTitle: "PromptDirector" }
+ };
+}
+
+function entry(id, assetId) {
+ return {
+ id,
+ title: id,
+ text: id,
+ schemaVersion: 14,
+ mediaAssets: [{
+ id: assetId,
+ kind: "image",
+ usage: "content",
+ storageMode: "managed",
+ mimeType: "image/webp",
+ byteSize: id.length
+ }],
+ primaryMediaId: assetId
+ };
+}
diff --git a/test/manual_sync_e2e.py b/test/manual_sync_e2e.py
new file mode 100644
index 0000000..8dbd41c
--- /dev/null
+++ b/test/manual_sync_e2e.py
@@ -0,0 +1,162 @@
+from __future__ import annotations
+
+from e2e_support import base_entry, extension_session
+
+
+def main() -> None:
+ entry = base_entry("sync-case", "同步案例", "同步前内容", "content:image-case", 1)
+ entry["mediaAssets"] = [{
+ "id": "sync-asset",
+ "kind": "image",
+ "usage": "content",
+ "storageMode": "managed",
+ "mimeType": "image/webp",
+ "byteSize": 10,
+ }]
+ entry["primaryMediaId"] = "sync-asset"
+
+ with extension_session("prompt-director-manual-sync-") as session:
+ setup = session.open_page("collector.html")
+ install_probe(setup)
+ current_schema = setup.evaluate("async () => (await import(chrome.runtime.getURL('taxonomy.js'))).SCHEMA_VERSION")
+ session.seed_storage(setup, {"schemaVersion": current_schema, "entries": [entry]})
+ setup.evaluate(
+ """async () => {
+ const [{saveMediaBlob}, vaultApi, storeApi] = await Promise.all([
+ import(chrome.runtime.getURL('media-store.js')),
+ import(chrome.runtime.getURL('sync-vault.js')),
+ import(chrome.runtime.getURL('sync-store.js'))
+ ]);
+ await saveMediaBlob(
+ 'sync-asset',
+ new Blob(['sync-bytes'], {type: 'image/webp'}),
+ {checkCapacity: false}
+ );
+ const root = await navigator.storage.getDirectory();
+ const vault = await vaultApi.createOrUnlockSyncVault(root, 'manual-sync-password');
+ await storeApi.saveSyncDirectoryHandle(root);
+ await storeApi.saveSyncCryptoKey(vault.key);
+ await chrome.storage.local.set({
+ syncSettings: {
+ enabled: true,
+ vaultId: vault.header.vaultId,
+ deviceId: 'device-e2e',
+ retentionCount: 10
+ }
+ });
+ }"""
+ )
+
+ first = setup.evaluate("async () => chrome.runtime.sendMessage({type: 'SYNC_NOW'})")
+ assert first["ok"] is True and first["upToDate"] is False, first
+ assert first["mediaCount"] == 1, first
+ baseline = setup.evaluate("async () => window.__manualSyncProbe()")
+ assert baseline["snapshotCount"] == 1, baseline
+ assert baseline["status"]["runningCount"] == 0, baseline
+ assert baseline["status"]["pendingCount"] == 0, baseline
+
+ # Opening and reading product state must not schedule another run.
+ library = session.open_page("library.html", wait_until="networkidle")
+ library.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
+ library.wait_for_timeout(2_000)
+ after_open = setup.evaluate("async () => window.__manualSyncProbe()")
+ assert after_open["snapshotCount"] == baseline["snapshotCount"], after_open
+ assert after_open["meta"] == baseline["meta"], after_open
+
+ # A normal edit marks pending state but does not transfer until the next explicit run.
+ edited = library.evaluate(
+ """async () => chrome.runtime.sendMessage({
+ type: 'UPDATE_ENTRY_TITLE', entryId: 'sync-case', title: '同步后标题'
+ })"""
+ )
+ assert edited["ok"] is True, edited
+ library.wait_for_timeout(2_000)
+ pending = setup.evaluate("async () => window.__manualSyncProbe()")
+ assert pending["snapshotCount"] == baseline["snapshotCount"], pending
+ assert pending["meta"]["localDirty"] is True, pending
+
+ second = setup.evaluate("async () => chrome.runtime.sendMessage({type: 'SYNC_NOW'})")
+ assert second["ok"] is True and second["upToDate"] is False, second
+ assert second["changeSummary"]["byEntity"]["entry"]["updated"] == 1, second
+ after_edit_sync = setup.evaluate("async () => window.__manualSyncProbe()")
+ assert after_edit_sync["snapshotCount"] == baseline["snapshotCount"] + 1, after_edit_sync
+ assert after_edit_sync["meta"]["localDirty"] is False, after_edit_sync
+
+ # A third explicit run is a true no-op: no snapshot or local sync metadata changes.
+ third = setup.evaluate("async () => chrome.runtime.sendMessage({type: 'SYNC_NOW'})")
+ assert third["ok"] is True and third["upToDate"] is True, third
+ after_noop = setup.evaluate("async () => window.__manualSyncProbe()")
+ assert after_noop["snapshotCount"] == after_edit_sync["snapshotCount"], after_noop
+ assert after_noop["meta"] == after_edit_sync["meta"], after_noop
+
+ # A damaged formal snapshot blocks success; an atomic .partial is never treated as state.
+ setup.evaluate(
+ """async () => {
+ const root = await navigator.storage.getDirectory();
+ const devices = await root.getDirectoryHandle('PromptDirector-Sync')
+ .then((directory) => directory.getDirectoryHandle('devices'));
+ const device = await devices.getDirectoryHandle('device-e2e');
+ const partial = await device.getFileHandle('999999999998-writing.partial', {create: true});
+ const partialWriter = await partial.createWritable();
+ await partialWriter.write('incomplete');
+ await partialWriter.close();
+ const broken = await device.getFileHandle('999999999999-broken.pds', {create: true});
+ const brokenWriter = await broken.createWritable();
+ await brokenWriter.write('{broken');
+ await brokenWriter.close();
+ }"""
+ )
+ damaged = setup.evaluate("async () => chrome.runtime.sendMessage({type: 'SYNC_NOW'})")
+ assert damaged["ok"] is False and "损坏" in damaged["message"], damaged
+ damaged_state = setup.evaluate("async () => window.__manualSyncProbe()")
+ assert damaged_state["settings"]["lastErrorCode"] == "sync_snapshot_corrupt", damaged_state
+ assert damaged_state["snapshotCount"] == after_noop["snapshotCount"] + 1, damaged_state
+ assert damaged_state["status"]["state"] == "error", damaged_state
+ assert damaged_state["status"]["runningCount"] == 0, damaged_state
+ assert damaged_state["status"]["pendingCount"] == 0, damaged_state
+
+ print({
+ "manual_only": True,
+ "no_op_zero_snapshot": True,
+ "pending_local_changes": True,
+ "damaged_snapshot_blocked": True,
+ "terminal_quiet": True,
+ "snapshot_count": after_noop["snapshotCount"],
+ })
+
+
+def install_probe(page) -> None:
+ page.evaluate(
+ """() => {
+ window.__manualSyncChangedKeys = [];
+ chrome.storage.onChanged.addListener((changes, areaName) => {
+ if (areaName !== 'local') return;
+ window.__manualSyncChangedKeys.push(Object.keys(changes));
+ });
+ window.__manualSyncProbe = async () => {
+ const root = await navigator.storage.getDirectory();
+ const vault = await root.getDirectoryHandle('PromptDirector-Sync');
+ const devices = await vault.getDirectoryHandle('devices');
+ let snapshotCount = 0;
+ for await (const device of devices.values()) {
+ if (device.kind !== 'directory') continue;
+ for await (const file of device.values()) {
+ if (file.kind === 'file' && file.name.endsWith('.pds')) snapshotCount += 1;
+ }
+ }
+ const stored = await chrome.storage.local.get(['syncMeta', 'syncSettings']);
+ const status = await chrome.runtime.sendMessage({type: 'GET_SYNC_RUN_STATUS'});
+ return {
+ snapshotCount,
+ meta: stored.syncMeta,
+ settings: stored.syncSettings,
+ changedKeys: window.__manualSyncChangedKeys.splice(0),
+ status: status.syncStatus || status.status || status
+ };
+ };
+ }"""
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/projects_and_categories_e2e.py b/test/projects_and_categories_e2e.py
index f8218dc..7155609 100644
--- a/test/projects_and_categories_e2e.py
+++ b/test/projects_and_categories_e2e.py
@@ -79,11 +79,14 @@ def main() -> None:
? Promise.resolve({ok: false, message: '模拟项目排序保存失败'})
: window.__originalProjectSendMessage.call(chrome.runtime, message, ...rest);
}""")
- failed_source = library.locator(".project-row", has_text="辅助项目").bounding_box()
- failed_target = library.locator(".project-row", has_text="项目与分类验收").bounding_box()
+ failed_row = library.locator(".project-row", has_text="辅助项目")
+ failed_target_row = library.locator(".project-row", has_text="项目与分类验收")
+ expect(failed_row).to_be_visible()
+ expect(failed_target_row).to_be_visible()
+ failed_source = failed_row.bounding_box()
+ failed_target = failed_target_row.bounding_box()
assert failed_source and failed_target
failed_x = failed_source["x"] + failed_source["width"] / 2
- failed_row = library.locator(".project-row", has_text="辅助项目")
failed_row.dispatch_event("pointerdown", {"pointerId": 72, "pointerType": "mouse", "button": 0, "clientX": failed_x, "clientY": failed_source["y"] + failed_source["height"] / 2})
failed_row.dispatch_event("pointermove", {"pointerId": 72, "pointerType": "mouse", "button": -1, "clientX": failed_x, "clientY": failed_target["y"] + failed_target["height"] - 2})
failed_row.dispatch_event("pointerup", {"pointerId": 72, "pointerType": "mouse", "button": 0, "clientX": failed_x, "clientY": failed_target["y"] + failed_target["height"] - 2})
diff --git a/test/release-experience.test.js b/test/release-experience.test.js
index 399990e..ddbb29d 100644
--- a/test/release-experience.test.js
+++ b/test/release-experience.test.js
@@ -6,7 +6,7 @@ import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
-const pageScripts = ["library.js", "composer-page.js", "skills-page.js", "collector.js", "curated-page.js"];
+const pageScripts = ["library.js", "composer-page.js", "skills-page.js", "collector.js", "curated-page.js", "curated-skill-page.js"];
test("ordinary product pages use the shared branded dialog instead of browser prompts", async () => {
for (const filename of pageScripts) {
@@ -59,7 +59,7 @@ test("the selected toolbar mark has one lime SVG master and matching manifest PN
48: "assets/icons/icon-48.png",
128: "assets/icons/icon-128.png"
});
- const pages = await Promise.all(["library.html", "collector.html", "composer.html", "skills.html"]
+ const pages = await Promise.all(["library.html", "collector.html", "composer.html", "skills.html", "curated-skills.html"]
.map((name) => readFile(new URL(`../${name}`, import.meta.url), "utf8")));
for (const page of pages) assert.match(page, /assets\/icons\/icon-source\.svg/);
const { stdout } = await execFileAsync(process.execPath, ["tools/build-brand-icons.mjs", "--check"], {
diff --git a/test/run_e2e.py b/test/run_e2e.py
index 719002f..430fbe6 100644
--- a/test/run_e2e.py
+++ b/test/run_e2e.py
@@ -13,6 +13,7 @@ SCRIPTS = [
"library_core_e2e.py",
"library_navigation_e2e.py",
"curated_workflow_e2e.py",
+ "curated_skills_install_e2e.py",
"curated_video_workflow_e2e.py",
"library_import_ui_e2e.py",
"import_job_lifecycle_e2e.py",
@@ -32,6 +33,7 @@ SCRIPTS = [
"composer_temp_references_e2e.py",
"composer_session_layout_e2e.py",
"sharing_and_data_safety_e2e.py",
+ "manual_sync_e2e.py",
"region_and_smart_picker_e2e.py",
"smart_visual_picker_e2e.py",
"page_capture_e2e.py",
diff --git a/test/sync-model.test.js b/test/sync-model.test.js
index 3741ac3..0e828ce 100644
--- a/test/sync-model.test.js
+++ b/test/sync-model.test.js
@@ -7,11 +7,34 @@ import {
collectSyncImageReferences,
createRevisionSnapshot,
mergeRevisionSnapshots,
+ markSyncMetaDirty,
+ normalizeSyncMeta,
normalizeSyncSettings,
syncErrorDetails,
syncStateHasContent
} from "../sync-model.js";
+test("sync metadata keeps a durable local pending flag separate from changed media ids", () => {
+ const value = normalizeSyncMeta({
+ logicalClock: 2,
+ localDirty: true,
+ dirtyAssetIds: ["asset:one", "asset:one", ""],
+ assetRefs: { "asset:one": { objectId: "a".repeat(64), contentType: "image/webp" } }
+ });
+
+ assert.equal(value.localDirty, true);
+ assert.deepEqual(value.dirtyAssetIds, ["asset:one"]);
+ assert.equal(value.assetRefs["asset:one"].objectId, "a".repeat(64));
+});
+
+test("business writes mark local pending state and only named media as needing rehash", () => {
+ const first = markSyncMetaDirty({}, []);
+ const second = markSyncMetaDirty(first, ["asset:one", "asset:one"]);
+
+ assert.equal(second.localDirty, true);
+ assert.deepEqual(second.dirtyAssetIds, ["asset:one"]);
+});
+
test("merged image references are reused without reading and rewriting every local image", () => {
const objectId = "a".repeat(64);
const source = state([{
@@ -530,3 +553,13 @@ test("missing sync files become an actionable state instead of a persistent brow
message: "同步文件夹中的文件或目录不存在,请重新选择同步文件夹后再同步"
});
});
+
+test("damaged formal snapshots retain an actionable error code", () => {
+ const details = syncErrorDetails({
+ code: "sync_snapshot_corrupt",
+ message: "同步目录包含损坏的正式状态文件,本地资料未被修改"
+ });
+ assert.equal(details.code, "sync_snapshot_corrupt");
+ assert.match(details.message, /损坏/);
+ assert.equal(normalizeSyncSettings({ lastError: details.message, lastErrorCode: details.code }).lastErrorCode, "sync_snapshot_corrupt");
+});
diff --git a/test/sync-pipeline.test.js b/test/sync-pipeline.test.js
index dfcf61a..2573eec 100644
--- a/test/sync-pipeline.test.js
+++ b/test/sync-pipeline.test.js
@@ -2,34 +2,70 @@ import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
-test("a sync cycle uploads local images once and reuses their object references", async () => {
- const background = await readFile(new URL("../background.js", import.meta.url), "utf8");
- const cycle = background.slice(
- background.indexOf("async function synchronizeWithVault"),
- background.indexOf("async function prepareStateForSync")
- );
-
- assert.equal((cycle.match(/prepareStateForSync\(/g) ?? []).length, 1);
- assert.match(cycle, /const localImageRefs = collectSyncImageReferences\(localPrepared\)/);
- assert.match(cycle, /replaceImagesWithRollback/);
- assert.match(cycle, /syncedImageReplacements/);
- assert.match(cycle, /attachSyncImageReferences\(merged\.state, merged\.imageRefs\)/);
- assert.match(cycle, /synchronizedStatePayload/);
- assert.equal((cycle.match(/commitLocalChanges\(/g) ?? []).length, 1);
+test("background delegates the one explicit sync action to the manual controller", async () => {
+ const background = await source();
+ assert.match(background, /import\s*\{[^}]*createManualSyncController[^}]*\}\s*from\s*"\.\/manual-sync\.js"/s);
+ assert.match(background, /const manualSyncController\s*=\s*createManualSyncController\(/);
+
+ const syncNow = messageBranch(background, "SYNC_NOW", "DISCONNECT_SYNC_FOLDER");
+ assert.match(syncNow, /manualSyncController\.start\(/);
+ assert.doesNotMatch(syncNow, /schedule|setTimeout|synchronizeNow/);
+});
+
+test("sync cancellation and run status remain reachable while the write queue is busy", async () => {
+ const background = await source();
+ const status = messageBranch(background, "GET_SYNC_RUN_STATUS", "CANCEL_SYNC");
+ const cancel = messageBranch(background, "CANCEL_SYNC", "CONNECT_SYNC_FOLDER");
+
+ assert.match(status, /manualSyncController\.status\(\)/);
+ assert.doesNotMatch(status, /enqueue/);
+ assert.match(cancel, /manualSyncController\.cancel\(\)/);
+ assert.doesNotMatch(cancel, /enqueue/);
+});
+
+test("business writes persist pending state instead of scheduling background transfer", async () => {
+ const background = await source();
+ const commit = functionBody(background, "async function commitLocalChanges", "async function persistDomainState");
+
+ assert.match(commit, /markSyncMetaDirty/);
+ assert.match(commit, /SYNCED_STORAGE_KEYS/);
+ assert.match(commit, /syncApplyInProgress/);
+ assert.doesNotMatch(commit, /schedule|setTimeout|synchronize/);
+ assert.doesNotMatch(background, /function scheduleAutomaticSync|function scheduleIdleSync/);
});
-test("native missing-file failures are normalized before sync status is stored", async () => {
- const background = await readFile(new URL("../background.js", import.meta.url), "utf8");
- const syncAction = background.slice(
- background.indexOf("async function performSynchronization"),
- background.indexOf("async function synchronizeWithVault")
- );
- const recorder = background.slice(
- background.indexOf("async function recordSyncError"),
- background.indexOf("function normalizeSyncMeta")
- );
-
- assert.match(syncAction, /recordSyncError\(settings, error\)/);
+test("the former full-scan synchronization path is removed after controller wiring", async () => {
+ const background = await source();
+
+ assert.doesNotMatch(background, /async function synchronizeWithVault/);
+ assert.doesNotMatch(background, /async function prepareStateForSync/);
+ assert.doesNotMatch(background, /async function\* syncedImageReplacements/);
+});
+
+test("native missing-file and damaged-snapshot failures keep actionable status codes", async () => {
+ const background = await source();
+ const recorder = functionBody(background, "async function recordSyncError", "async function migrateLegacyScreenshots");
+
assert.match(recorder, /syncErrorDetails\(failure\)/);
assert.match(recorder, /lastErrorCode:\s*details\.code/);
});
+
+function source() {
+ return readFile(new URL("../background.js", import.meta.url), "utf8");
+}
+
+function messageBranch(sourceValue, type, nextType) {
+ const start = sourceValue.indexOf(`case "${type}"`);
+ assert.notEqual(start, -1, `${type} handler is missing`);
+ const end = sourceValue.indexOf(`case "${nextType}"`, start + 6);
+ assert.notEqual(end, -1, `${nextType} boundary is missing`);
+ return sourceValue.slice(start, end);
+}
+
+function functionBody(sourceValue, startMarker, endMarker) {
+ const start = sourceValue.indexOf(startMarker);
+ assert.notEqual(start, -1, `${startMarker} is missing`);
+ const end = sourceValue.indexOf(endMarker, start + startMarker.length);
+ assert.notEqual(end, -1, `${endMarker} boundary is missing`);
+ return sourceValue.slice(start, end);
+}
diff --git a/test/sync-vault.test.js b/test/sync-vault.test.js
index 3707fca..6cec109 100644
--- a/test/sync-vault.test.js
+++ b/test/sync-vault.test.js
@@ -46,7 +46,7 @@ test("large video objects are chunked deduplicated and reject one damaged chunk"
await assert.rejects(() => readSyncObject(vault, objectId), /JSON|损坏|解密|Unexpected/);
});
-test("damaged and incomplete state files are skipped when a healthy state exists", async () => {
+test("a damaged formal state blocks silent success while an incomplete atomic file is ignored", async () => {
const root = new MemoryDirectory("root");
const vault = await createOrUnlockSyncVault(root, "password-123");
const snapshot = await createRevisionSnapshot({ entries: [] }, { deviceId: "device:a", logicalClock: 1 });
@@ -59,11 +59,45 @@ test("damaged and incomplete state files are skipped when a healthy state exists
await writeText(device, "999-broken.pds", "{broken");
await writeText(device, "1000-unfinished.partial", "incomplete");
+ await assert.rejects(
+ () => listSyncSnapshots(vault),
+ (error) => error?.code === "sync_snapshot_corrupt" && /999-broken\.pds/.test(error.message)
+ );
+
+ device.entries.delete("999-broken.pds");
const snapshots = await listSyncSnapshots(vault);
assert.equal(snapshots.length, 1);
assert.equal(snapshots[0].snapshotId, snapshot.snapshotId);
});
+test("vault object operations honor cancellation before publishing a manifest", async () => {
+ const root = new MemoryDirectory("root");
+ const vault = await createOrUnlockSyncVault(root, "password-123");
+ const controller = new AbortController();
+ controller.abort();
+
+ await assert.rejects(
+ () => writeSyncObject(vault, new Blob(["audio"], { type: "audio/mpeg" }), { signal: controller.signal }),
+ (error) => error?.name === "AbortError"
+ );
+ const objects = await root.getDirectoryHandle("PromptDirector-Sync").then((directory) => directory.getDirectoryHandle("objects"));
+ assert.equal(objects.entries.size, 0);
+});
+
+test("encrypted sync keeps supported audio and inert external Skill files", async () => {
+ const root = new MemoryDirectory("root");
+ const vault = await createOrUnlockSyncVault(root, "password-123");
+ for (const blob of [
+ new Blob(["audio"], { type: "audio/mpeg" }),
+ new Blob(["binary asset"], { type: "application/octet-stream" })
+ ]) {
+ const objectId = await writeSyncObject(vault, blob);
+ const restored = await readSyncObject(vault, objectId);
+ assert.equal(await restored.text(), await blob.text());
+ assert.equal(restored.type, blob.type);
+ }
+});
+
test("a second profile can unlock the same folder but a wrong password cannot read it", async () => {
const root = new MemoryDirectory("root");
const first = await createOrUnlockSyncVault(root, "password-123");
diff --git a/test/theme-bootstrap.test.js b/test/theme-bootstrap.test.js
index 9b206f6..2a2a49a 100644
--- a/test/theme-bootstrap.test.js
+++ b/test/theme-bootstrap.test.js
@@ -8,6 +8,7 @@ const uiRuntime = await readFile(new URL("../i18n.js", import.meta.url), "utf8")
const pages = [
"library.html",
"curated.html",
+ "curated-skills.html",
"composer.html",
"skills.html",
"collector.html"
diff --git a/test/transient-menu.test.js b/test/transient-menu.test.js
index c871243..58210c3 100644
--- a/test/transient-menu.test.js
+++ b/test/transient-menu.test.js
@@ -14,7 +14,7 @@ test("transient menus share outside-click, action, peer-open, and Escape dismiss
assert.match(source, /closest\("button, a\[href\]"\)/);
assert.match(source, /!action\.closest\("\.package-preferences"\)/);
assert.match(library, /bindTransientMenus\(document, "\.package-menu, \.project-menu, \.detail-analysis-menu, \.detail-project-menu"\)/);
- assert.match(composer, /bindTransientMenus\(document, "\.composer-options"\)/);
+ assert.match(composer, /bindTransientMenus\(document, "\.composer-options, \.composer-session-menu"\)/);
assert.doesNotMatch(composer, /\.composer-result-more/);
});
diff --git a/test/ui-foundation.test.js b/test/ui-foundation.test.js
index ff4d6c6..6ff6132 100644
--- a/test/ui-foundation.test.js
+++ b/test/ui-foundation.test.js
@@ -18,6 +18,9 @@ test("shared visual foundation owns the locked dark theme and control scale", ()
assert.match(foundation, /--ui-control-radius:\s*4px/);
assert.match(foundation, /--ui-container-radius:\s*6px/);
assert.match(foundation, /button:active:not\(:disabled\)\s*\{\s*transform:\s*none/);
+ assert.match(foundation, /button,\s*\.button-primary,\s*\.button-secondary\s*\{/);
+ assert.match(foundation, /display:\s*inline-flex/);
+ assert.match(foundation, /text-decoration:\s*none/);
});
test("page styles keep domain layout without redefining shared theme roles", async () => {
diff --git a/test/ui_foundation_e2e.py b/test/ui_foundation_e2e.py
index f742b8a..9468081 100644
--- a/test/ui_foundation_e2e.py
+++ b/test/ui_foundation_e2e.py
@@ -5,7 +5,7 @@ from playwright.sync_api import expect
from e2e_support import extension_session
-PAGES = ["library.html", "composer.html", "skills.html", "curated.html", "collector.html"]
+PAGES = ["library.html", "composer.html", "skills.html", "curated.html", "curated-skills.html", "collector.html"]
def main() -> None:
diff --git a/test/vision.test.js b/test/vision.test.js
index 57595a4..2c61bbb 100644
--- a/test/vision.test.js
+++ b/test/vision.test.js
@@ -334,6 +334,83 @@ test("compatible request uses Chat Completions image messages and refuses redire
assert.equal(body.max_tokens, 12000);
});
+test("compatible json_object vision requests keep image input and local full-schema validation", async () => {
+ let body;
+ const input = {
+ imageDataUrl: "data:image/png;base64,AAAA",
+ catalog: createDefaultFacetCatalog(),
+ locale: "zh-CN",
+ settings: {
+ activeProvider: "compatible", consent: true,
+ compatible: {
+ protocol: "chat_completions",
+ structuredOutput: "json_object",
+ endpoint: "https://api.deepseek.com/chat/completions",
+ apiKey: "secret",
+ model: "opaque-account-model"
+ }
+ }
+ };
+ const success = await analyzeImageWithVision(input, async (_url, options) => {
+ body = JSON.parse(options.body);
+ return {
+ ok: true,
+ json: async () => ({
+ model: "opaque-account-model",
+ choices: [{ message: { content: JSON.stringify(completeVisionResult("一张完整分析。")) } }]
+ })
+ };
+ });
+
+ assert.deepEqual(body.response_format, { type: "json_object" });
+ assert.equal(body.messages[0].content.some((item) => item.type === "image_url"), true);
+ const instruction = body.messages[0].content.find((item) => item.type === "text").text;
+ assert.match(instruction, /JSON property names are case-sensitive/);
+ assert.match(instruction, /"ocr":\{"type":"array"/);
+ assert.equal(success.description, "一张完整分析。");
+
+ await assert.rejects(() => analyzeImageWithVision(input, async () => ({
+ ok: true,
+ json: async () => ({ choices: [{ message: { content: JSON.stringify({ description: "不完整" }) } }] })
+ })), /画布信息|缺少|必须/);
+});
+
+test("compatible empty vision results expose finish reasons without retrying or falling back", async () => {
+ const input = {
+ imageDataUrl: "data:image/png;base64,AAAA",
+ catalog: createDefaultFacetCatalog(),
+ settings: {
+ activeProvider: "compatible", consent: true,
+ compatible: {
+ protocol: "chat_completions",
+ structuredOutput: "json_object",
+ endpoint: "http://localhost:1234/v1/chat/completions",
+ model: "fixture-model"
+ }
+ }
+ };
+ const cases = [
+ ["length", /输出达到长度上限/],
+ ["content_filter", /内容过滤/],
+ ["insufficient_system_resource", /资源暂时不足/],
+ ["stop", /返回了空的 JSON 内容/],
+ [undefined, /响应缺少可用内容/]
+ ];
+ let calls = 0;
+ for (const [finishReason, expected] of cases) {
+ await assert.rejects(() => analyzeImageWithVision(input, async () => {
+ calls += 1;
+ return {
+ ok: true,
+ json: async () => ({
+ choices: [{ finish_reason: finishReason, message: { content: "" } }]
+ })
+ };
+ }), expected);
+ }
+ assert.equal(calls, cases.length);
+});
+
test("compatible Responses request sends the OpenAI image shape and parses structured output", async () => {
let captured;
const result = await analyzeImageWithVision({
diff --git a/test/visual-analysis.test.js b/test/visual-analysis.test.js
index ebbb926..246b6af 100644
--- a/test/visual-analysis.test.js
+++ b/test/visual-analysis.test.js
@@ -102,6 +102,24 @@ test("model box_2d uses yxyx order and converts once into the persisted V2 bbox"
assert.equal(VISUAL_MODEL_RESPONSE_SCHEMA.properties.elements.items.properties.bbox, undefined);
});
+test("known root field casing is normalized before strict visual validation", () => {
+ const response = completeModelResponse();
+ response.OCR = response.ocr;
+ delete response.ocr;
+ const result = normalizeVisualModelResponse(response, createDefaultFacetCatalog());
+ assert.equal(result.ocr[0].text, "PROMPT DIRECTOR");
+ assert.equal(Object.hasOwn(result, "OCR"), false);
+});
+
+test("root field casing conflicts and unknown fields remain rejected", () => {
+ const conflict = completeModelResponse();
+ conflict.OCR = conflict.ocr;
+ assert.throws(() => normalizeVisualModelResponse(conflict), /字段大小写冲突:ocr/);
+
+ const unknown = completeModelResponse({ audit: [] });
+ assert.throws(() => normalizeVisualModelResponse(unknown), /未允许字段:audit/);
+});
+
test("invalid model boxes fail without clipping or rewriting the saved analysis", () => {
const invalid = completeModelResponse();
invalid.elements[0].box_2d = [150, 250, 140, 900];
diff --git a/ui-foundation.css b/ui-foundation.css
index 8734a31..fdd64d4 100644
--- a/ui-foundation.css
+++ b/ui-foundation.css
@@ -144,8 +144,12 @@ body {
button, input, select, textarea { font: inherit; }
button,
-.button-primary {
+.button-primary,
+.button-secondary {
+ display: inline-flex;
min-height: var(--ui-control-height);
+ align-items: center;
+ justify-content: center;
border: 1px solid transparent;
border-radius: var(--ui-control-radius);
padding: 7px 12px;
@@ -155,6 +159,7 @@ button,
font-size: var(--ui-button-size);
font-weight: 750;
letter-spacing: 0;
+ text-decoration: none;
white-space: nowrap;
}
button:hover:not(:disabled),
@@ -183,6 +188,90 @@ button.compact {
padding: 5px 9px;
font-size: var(--ui-meta-size);
}
+.ui-segmented {
+ display: inline-flex;
+ width: max-content;
+ max-width: 100%;
+ align-items: center;
+ gap: 2px;
+ border: 1px solid var(--ui-border);
+ border-radius: var(--ui-container-radius);
+ padding: 2px;
+ background: var(--ui-surface);
+}
+.ui-segmented-item {
+ display: inline-flex;
+ min-height: 28px;
+ align-items: center;
+ justify-content: center;
+ border: 0;
+ border-radius: var(--ui-control-radius);
+ padding: 4px 10px;
+ color: var(--ui-muted);
+ background: transparent;
+ cursor: pointer;
+ font-size: var(--ui-meta-size);
+ font-weight: 750;
+ text-decoration: none;
+ white-space: nowrap;
+}
+.ui-segmented .ui-segmented-item:hover:not(:disabled) {
+ color: var(--ui-text);
+ background: var(--ui-hover);
+}
+.ui-segmented-item[aria-current="page"],
+.ui-segmented-item[aria-pressed="true"] {
+ color: var(--ui-text);
+ background: var(--ui-raised);
+ box-shadow: inset 0 0 0 1px var(--ui-accent);
+}
+.ui-skill-card {
+ display: flex;
+ min-width: 0;
+ min-height: 152px;
+ flex-direction: column;
+ gap: 10px;
+ border: 1px solid var(--ui-border);
+ border-radius: var(--ui-container-radius);
+ padding: 16px;
+ color: var(--ui-text);
+ background: var(--ui-surface);
+}
+.ui-skill-card:hover {
+ border-color: var(--ui-border-strong);
+ background: var(--ui-raised);
+ box-shadow: inset 2px 0 var(--ui-accent);
+}
+.ui-skill-card-title {
+ margin: 0;
+ overflow-wrap: anywhere;
+ font-size: 17px;
+ line-height: 1.35;
+}
+.ui-skill-card-summary {
+ display: -webkit-box;
+ flex: 1;
+ overflow: hidden;
+ margin: 0;
+ color: var(--ui-muted);
+ font-size: 12px;
+ font-weight: 400;
+ line-height: 1.55;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+}
+.ui-skill-card-actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 7px;
+ margin-top: auto;
+}
+.ui-skill-card-actions > :is(button, a) {
+ min-height: var(--ui-compact-height);
+ padding: 5px 9px;
+ font-size: var(--ui-meta-size);
+}
.icon-button {
display: inline-grid;
width: var(--ui-icon-size);
diff --git a/vision.js b/vision.js
index 44d9fae..6250945 100644
--- a/vision.js
+++ b/vision.js
@@ -6,17 +6,18 @@ import {
normalizeVisualModelResponse,
visualModelResponseSchema
} from "./visual-analysis.js";
+import { MICU_COMPATIBLE_PROVIDER_PRESET } from "./compatible-provider-presets.js";
export const VISION_ANALYSIS_VERSION = VISUAL_ANALYSIS_VERSION;
export const DEFAULT_VISION_MODEL = "gpt-5-mini";
export const OPENAI_RESPONSES_ENDPOINT = "https://api.openai.com/v1/responses";
export const OPENAI_VIDEOS_ENDPOINT = "https://api.openai.com/v1/videos";
-export const MICU_RESPONSES_ENDPOINT = "https://www.micuapi.ai/v1/responses";
-export const MICU_DEFAULT_CHAT_MODEL = "gpt-5.4-mini";
-export const MICU_IMAGE_GENERATIONS_ENDPOINT = "https://www.micuapi.ai/v1/images/generations";
-export const MICU_IMAGE_EDITS_ENDPOINT = "https://www.micuapi.ai/v1/images/edits";
-export const MICU_DEFAULT_IMAGE_MODEL = "gpt-image-2";
-export const MICU_DEFAULT_IMAGE_SIZE = "1536x1024";
+export const MICU_RESPONSES_ENDPOINT = MICU_COMPATIBLE_PROVIDER_PRESET.endpoint;
+export const MICU_DEFAULT_CHAT_MODEL = MICU_COMPATIBLE_PROVIDER_PRESET.defaultChatModel;
+export const MICU_IMAGE_GENERATIONS_ENDPOINT = MICU_COMPATIBLE_PROVIDER_PRESET.imageGeneration.endpoint;
+export const MICU_IMAGE_EDITS_ENDPOINT = MICU_COMPATIBLE_PROVIDER_PRESET.imageGeneration.editsEndpoint;
+export const MICU_DEFAULT_IMAGE_MODEL = MICU_COMPATIBLE_PROVIDER_PRESET.imageGeneration.defaultModel;
+export const MICU_DEFAULT_IMAGE_SIZE = MICU_COMPATIBLE_PROVIDER_PRESET.imageGeneration.defaultSize;
export const MICU_IMAGE_RESULT_PERMISSION = "https://oss.filenest.top/*";
export const MAX_VISION_TAGS = 6;
export const VISION_MAX_OUTPUT_TOKENS = 12000;
@@ -114,6 +115,7 @@ function normalizeCompatibleSettings(value = {}) {
}
return {
protocol: value?.protocol === "responses" ? "responses" : "chat_completions",
+ structuredOutput: value?.structuredOutput === "json_object" ? "json_object" : "json_schema",
endpoint,
model: String(value?.model ?? "").trim(),
apiKey,
@@ -190,6 +192,7 @@ export function mergeVisionSettings(currentValue = {}, incomingValue = {}) {
},
compatible: {
protocol: incoming.compatible?.protocol ?? current.compatible.protocol,
+ structuredOutput: incoming.compatible?.structuredOutput ?? current.compatible.structuredOutput,
endpoint: nextEndpoint,
model: incoming.compatible?.model ?? current.compatible.model,
apiKey: compatibleApiKey,
@@ -224,6 +227,7 @@ export function publicVisionSettings(value = {}) {
},
compatible: {
protocol: settings.compatible.protocol,
+ structuredOutput: settings.compatible.structuredOutput,
model: settings.compatible.model,
configured: Boolean(settings.compatible.endpoint && settings.compatible.model &&
(settings.compatible.apiKey || isLoopbackEndpoint(settings.compatible.endpoint))),
@@ -381,6 +385,7 @@ export async function visionAnalysisProfileFingerprint(settingsValue = {}, local
locale,
provider: settings.activeProvider,
protocol: provider.protocol || "responses",
+ structuredOutput: provider.structuredOutput || "json_schema",
model: provider.model,
maxOutputTokens: settings.maxOutputTokens,
instructions: settings.instructionsByLocale[locale]
@@ -434,29 +439,42 @@ async function requestCompatible(settings, imageDataUrl, instruction, fetchImpl,
}
const schema = options.schema ?? VISUAL_MODEL_RESPONSE_SCHEMA;
const schemaName = options.schemaName ?? "vision_analysis_box_2d_v1";
+ const structuredInstruction = settings.compatible.structuredOutput === "json_object"
+ ? `${instruction}\nJSON property names are case-sensitive. Return exactly one object matching this JSON Schema: ${JSON.stringify(schema)}`
+ : instruction;
const body = {
model: settings.compatible.model,
max_tokens: positiveTokenBudget(options.maxOutputTokens) || settings.maxOutputTokens,
- response_format: {
- type: "json_schema",
- json_schema: { name: schemaName, strict: true, schema }
- },
+ response_format: settings.compatible.structuredOutput === "json_object"
+ ? { type: "json_object" }
+ : { type: "json_schema", json_schema: { name: schemaName, strict: true, schema } },
messages: [{
role: "user",
content: [
- { type: "text", text: instruction },
+ { type: "text", text: structuredInstruction },
{ type: "image_url", image_url: { url: imageDataUrl, detail: "high" } }
]
}]
};
const payload = await requestJson(url, settings.compatible.apiKey, body, fetchImpl);
- const content = payload?.choices?.[0]?.message?.content;
+ const choice = payload?.choices?.[0];
+ const content = choice?.message?.content;
if (typeof content !== "string" || !content.trim()) {
- throw new Error(options.emptyResultMessage || "兼容服务没有返回可用的画面描述");
+ throw new Error(compatibleEmptyResultMessage(choice?.finish_reason, options.emptyResultMessage));
}
return { content, model: String(payload.model ?? settings.compatible.model), usage: normalizeCompatibleUsage(payload.usage) };
}
+function compatibleEmptyResultMessage(finishReason, fallback = "") {
+ const reason = String(finishReason ?? "").trim();
+ const prefix = String(fallback ?? "").trim();
+ if (reason === "length") return prefix ? `${prefix}:输出达到长度上限` : "兼容服务输出达到长度上限,JSON 可能被截断,本次没有写入";
+ if (reason === "content_filter") return prefix ? `${prefix}:内容过滤` : "兼容服务因内容过滤未返回分析结果,本次没有写入";
+ if (reason === "insufficient_system_resource") return prefix ? `${prefix}:资源暂时不足` : "兼容服务资源暂时不足,未返回分析结果,请手动重试";
+ if (reason === "stop") return prefix ? `${prefix}:返回了空的 JSON 内容` : "兼容服务返回了空的 JSON 内容,本次没有写入,请手动重试";
+ return prefix || "兼容服务响应缺少可用内容,本次没有写入";
+}
+
async function requestGeminiVision(provider, imageDataUrl, instruction, fetchImpl, options = {}) {
const match = imageDataUrl.match(/^data:(image\/[^;]+);base64,(.+)$/i);
if (!match) throw new Error("Gemini 图片输入格式无效");
diff --git a/visual-analysis.js b/visual-analysis.js
index ff35e80..c19ad36 100644
--- a/visual-analysis.js
+++ b/visual-analysis.js
@@ -24,6 +24,7 @@ const ROOT_FIELDS = new Set([
"description", "canvas", "elements", "dimensions", "ocr", "reconstructionPrompt",
"limitations", "completeness", "tags"
]);
+const ROOT_FIELDS_BY_CASE = new Map([...ROOT_FIELDS].map((field) => [field.toLocaleLowerCase("en-US"), field]));
const BBOX_SCHEMA = Object.freeze({
type: "object",
@@ -193,11 +194,12 @@ export function normalizeVisualModelResponse(value, catalogValue) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("视觉模型返回格式不正确,本次没有写入");
}
- const tagDiagnostics = partitionModelTags(value.tags, catalogValue);
+ const source = normalizeKnownRootFieldCasing(value);
+ const tagDiagnostics = partitionModelTags(source.tags, catalogValue);
const converted = {
- ...value,
- elements: (Array.isArray(value.elements) ? value.elements : []).map((item) => convertModelBox(item)),
- ocr: (Array.isArray(value.ocr) ? value.ocr : []).map((item) => convertModelBox(item)),
+ ...source,
+ elements: (Array.isArray(source.elements) ? source.elements : []).map((item) => convertModelBox(item)),
+ ocr: (Array.isArray(source.ocr) ? source.ocr : []).map((item) => convertModelBox(item)),
tags: tagDiagnostics.accepted
};
return {
@@ -206,6 +208,18 @@ export function normalizeVisualModelResponse(value, catalogValue) {
};
}
+function normalizeKnownRootFieldCasing(value) {
+ const normalized = {};
+ for (const [field, fieldValue] of Object.entries(value)) {
+ const canonical = ROOT_FIELDS_BY_CASE.get(field.toLocaleLowerCase("en-US")) || field;
+ if (Object.hasOwn(normalized, canonical)) {
+ throw new Error(`视觉分析字段大小写冲突:${canonical}`);
+ }
+ normalized[canonical] = fieldValue;
+ }
+ return normalized;
+}
+
export function normalizeVisualAnalysisV2(value, catalogValue) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("视觉模型返回格式不正确,本次没有写入");