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. 提示词导演

发布 PromptDirector 1.18.5 并收口采集与创作台状态

MigenAI4282ec49d2f2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 08e758c..9d71c62 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,14 @@
# Changelog
+## 1.18.5
+
+- 重做网页采集:先确认创作主体,再检查正文与媒体;同一列表批量采集不会进入详情页,也不会把未确认媒体静默写入案例。
+- 完整文章按原网页顺序保留标题、段落、列表、引用、代码、表格及相关媒体;安全文档可保存本地副本,未知文件只保留来源链接。
+- 精选案例恢复主资料库式浏览、详情查看、视频播放和选择性保存,保存内容真正进入个人本地资料库。
+- 创作台“参考”数量只统计案例;有原提示词或有效画面分析时,可完全不读图、不分析图片并以零图片载荷生成。
+- 修复生成完成后按钮仍显示运行状态的问题,并补充刷新竞态保护,完成后可以立即开始下一轮。
+- 参考图参与方式及其 token 影响已补齐中英文说明。
+
## 1.18.4
PromptDirector 从这个经过开源边界清理和完整验证的版本开始维护公开历史。
diff --git a/README.md b/README.md
index 16e9ce5..c0f18f4 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,9 @@ PromptDirector 是一个免费、开源、本地优先的 Chrome 扩展。它把
- 在图片优先的资料墙中搜索、筛选、标记和管理案例;
- 保存本地图片、视频、PDF、Markdown、TXT、HTML、视频时间点笔记和快速笔记;
- 将相关案例整理进项目、组合案例或分享包;
-- 从明确选中的参考资料生成可编辑的图片或视频提示词;
+- 浏览经过审核的精选案例,并把需要的内容保存进自己的本地资料库;
+- 把案例提炼成可复用的创作 Skill,在创作台组合案例、Skill 和临时附件;
+- 生成可编辑的图片或视频提示词,也可以连接自己的服务直接生成媒体;
- 使用可选的文字分析或画面分析,让资料更容易检索;
- 创建完整资料夹备份,或通过加密同步文件夹在自己的设备间恢复资料。
@@ -20,9 +22,9 @@ PromptDirector 是一个免费、开源、本地优先的 Chrome 扩展。它把
## 安装
-下载并解压本仓库源码,在 Chrome 或 Edge 的扩展管理页开启“开发者模式”,选择“加载已解压的扩展程序”,然后选择仓库根目录。
+优先从 [GitHub Releases](https://github.com/wchao6891/PromptDirector/releases) 下载最新 ZIP 并解压。在 Chrome 或 Edge 的扩展管理页开启“开发者模式”,选择“加载已解压的扩展程序”,然后选择解压后的目录。
-升级前请先在“更多 → 备份与同步”创建并验证完整资料夹备份。若扩展身份发生变化,请按[扩展身份迁移说明](docs/EXTENSION_ID_MIGRATION.md)恢复资料。
+升级前请先在“更多 → 备份与同步”创建并验证完整资料夹备份。当前 GitHub 包仍是开发身份包;换电脑、移动目录或扩展 ID 变化时,请按[扩展身份迁移说明](docs/EXTENSION_ID_MIGRATION.md)恢复资料。
## 从源码构建
diff --git a/ai-model-capabilities.js b/ai-model-capabilities.js
new file mode 100644
index 0000000..cf82d8d
--- /dev/null
+++ b/ai-model-capabilities.js
@@ -0,0 +1,91 @@
+const GOOGLE_IMAGE_GENERATION_SOURCE = Object.freeze({
+ authority: "Google AI for Developers",
+ document: "Gemini API image generation",
+ url: "https://ai.google.dev/gemini-api/docs/image-generation",
+ reviewedAt: "2026-08-12"
+});
+
+const STANDARD_ASPECT_RATIOS = Object.freeze([
+ "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"
+]);
+const FLASH_ASPECT_RATIOS = Object.freeze([
+ "1:1", "1:4", "1:8", "2:3", "3:2", "3:4", "4:1", "4:3", "4:5", "5:4", "8:1", "9:16", "16:9", "21:9"
+]);
+
+function googleImageModel(value) {
+ return Object.freeze({
+ ...value,
+ providerId: "gemini",
+ protocol: "gemini_interactions",
+ tasks: Object.freeze(["imageGeneration"]),
+ inputModalities: Object.freeze(["text", "image"]),
+ outputModalities: Object.freeze(["text", "image"]),
+ supportedParameters: Object.freeze([...value.supportedParameters]),
+ supportedResolutions: Object.freeze([...value.supportedResolutions]),
+ supportedAspectRatios: Object.freeze([...value.supportedAspectRatios]),
+ referenceImages: Object.freeze({ ...value.referenceImages }),
+ parameterDescriptors: Object.freeze(structuredClone(value.parameterDescriptors)),
+ source: GOOGLE_IMAGE_GENERATION_SOURCE
+ });
+}
+
+export const AI_MODEL_CAPABILITIES = Object.freeze([
+ googleImageModel({
+ id: "gemini-3.1-flash-lite-image",
+ supportedParameters: ["response_format", "aspect_ratio", "image_size"],
+ supportedResolutions: ["1K"],
+ supportedAspectRatios: STANDARD_ASPECT_RATIOS,
+ referenceImages: { supported: true, maxItems: 14, source: "declared", observedAt: "" },
+ parameterDescriptors: {
+ image_size: { values: ["1K"] },
+ aspect_ratio: { values: STANDARD_ASPECT_RATIOS },
+ reference_images: { maxItems: 14, objectReferences: 14 }
+ }
+ }),
+ googleImageModel({
+ id: "gemini-3.1-flash-image",
+ supportedParameters: ["response_format", "aspect_ratio", "image_size"],
+ supportedResolutions: ["512px", "1K", "2K", "4K"],
+ supportedAspectRatios: FLASH_ASPECT_RATIOS,
+ referenceImages: { supported: true, maxItems: 14, source: "declared", observedAt: "" },
+ parameterDescriptors: {
+ image_size: { values: ["512px", "1K", "2K", "4K"] },
+ aspect_ratio: { values: FLASH_ASPECT_RATIOS },
+ reference_images: { maxItems: 14, objectReferences: 10, characterReferences: 4 }
+ }
+ }),
+ googleImageModel({
+ id: "gemini-3-pro-image",
+ supportedParameters: ["response_format", "aspect_ratio", "image_size"],
+ supportedResolutions: ["1K", "2K", "4K"],
+ supportedAspectRatios: STANDARD_ASPECT_RATIOS,
+ referenceImages: { supported: true, maxItems: 14, source: "declared", observedAt: "" },
+ parameterDescriptors: {
+ image_size: { values: ["1K", "2K", "4K"] },
+ aspect_ratio: { values: STANDARD_ASPECT_RATIOS },
+ reference_images: { maxItems: 14, objectReferences: 6, characterReferences: 5, styleReferences: 3 }
+ }
+ }),
+ googleImageModel({
+ id: "gemini-2.5-flash-image",
+ supportedParameters: ["response_format", "aspect_ratio"],
+ supportedResolutions: ["1024px"],
+ supportedAspectRatios: STANDARD_ASPECT_RATIOS,
+ referenceImages: { supported: true, maxItems: 3, source: "declared", observedAt: "" },
+ parameterDescriptors: {
+ aspect_ratio: { values: STANDARD_ASPECT_RATIOS },
+ reference_images: { recommendedMaxItems: 3 }
+ }
+ })
+]);
+
+const MODEL_CAPABILITY_INDEX = new Map(
+ AI_MODEL_CAPABILITIES.map((item) => [`${item.providerId}:${item.id}`, item])
+);
+
+export function getAiModelCapability(providerIdValue, modelIdValue) {
+ const providerId = String(providerIdValue ?? "").trim();
+ const modelId = String(modelIdValue ?? "").trim().replace(/^models\//, "");
+ const capability = MODEL_CAPABILITY_INDEX.get(`${providerId}:${modelId}`);
+ return capability ? structuredClone(capability) : null;
+}
diff --git a/ai-provider-module.js b/ai-provider-module.js
index 18d54d4..c904d2e 100644
--- a/ai-provider-module.js
+++ b/ai-provider-module.js
@@ -1,7 +1,17 @@
import { boundedMediaBlobFromResponse } from "./bounded-media.js";
+import { getAiModelCapability } from "./ai-model-capabilities.js";
+import { getAiProviderPreset } from "./ai-provider-presets.js";
const TEXT_TASKS = Object.freeze(["textTags", "skillExtraction", "creativePlanning"]);
const ALL_TASKS = Object.freeze([...TEXT_TASKS, "imageAnalysis", "videoAnalysis", "imageGeneration", "videoGeneration"]);
+const DISCOVERY_ADAPTERS = Object.freeze({
+ identity: discoverIdentityModels,
+ kimi: discoverKimi,
+ xai: discoverXai,
+ openrouter: discoverOpenRouter,
+ gemini: discoverGemini,
+ configured_video: discoverConfiguredVideo
+});
export function createAiProviderModule(options = {}) {
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
@@ -80,17 +90,20 @@ export function createAiProviderModule(options = {}) {
}
async function discoverProviderModels(fetchImpl, profile, cache) {
- if (profile.id === "xai") return discoverXai(fetchImpl, profile, cache);
- if (profile.id === "openrouter") return discoverOpenRouter(fetchImpl, profile, cache);
- if (profile.id === "gemini") return discoverGemini(fetchImpl, profile, cache);
- if (["minimax", "volcengine"].includes(profile.id)) {
- return {
- models: configuredProtocolModels(profile, ["videoGeneration"]),
- cache: {},
- source: "configured_protocol"
- };
- }
- return discoverIdentityModels(fetchImpl, profile, cache);
+ const preset = getAiProviderPreset(profile.id);
+ const adapterId = clean(profile.discovery?.adapter) || preset?.discovery?.adapter || "identity";
+ const adapter = DISCOVERY_ADAPTERS[adapterId];
+ if (!adapter) throw new Error(`${profile.id} 的模型发现方式 ${adapterId} 尚未适配`);
+ const result = await adapter(fetchImpl, profile, cache);
+ if (result.notModified) return result;
+ const allowedTasks = preset ? new Set(preset.capabilities) : null;
+ return {
+ ...result,
+ models: result.models.map((model) => ({
+ ...model,
+ tasks: allowedTasks ? model.tasks.filter((task) => allowedTasks.has(task)) : model.tasks
+ }))
+ };
}
async function discoverIdentityModels(fetchImpl, profile, cache) {
@@ -98,8 +111,10 @@ 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 confidence = profile.id === "deepseek" || profile.id === "openai" ? "protocol_inferred" : "manual_unverified";
- const tasks = profile.id === "deepseek" || profile.id === "openai" ? TEXT_TASKS : [];
+ 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" })),
cache: response.cache,
@@ -107,6 +122,38 @@ async function discoverIdentityModels(fetchImpl, profile, cache) {
};
}
+async function discoverKimi(fetchImpl, profile, cache) {
+ const response = await modelRequest(fetchImpl, modelsEndpoint(profile.endpoint), profile, cache);
+ if (response.notModified) return response;
+ const list = requiredArrayFrom(response.payload, "Kimi 返回了当前版本尚未适配的模型列表结构", "data", "models");
+ return {
+ models: list.map((item) => {
+ const inputModalities = [
+ "text",
+ ...(item.supports_image_in === true ? ["image"] : []),
+ ...(item.supports_video_in === true ? ["video"] : [])
+ ];
+ return modelDescriptor(item, {
+ confidence: "declared",
+ tasks: tasksFromModalities(inputModalities, ["text"]),
+ inputModalities,
+ outputModalities: ["text"],
+ source: "kimi_models"
+ });
+ }),
+ cache: response.cache,
+ source: "kimi_models"
+ };
+}
+
+async function discoverConfiguredVideo(_fetchImpl, profile) {
+ return {
+ models: configuredProtocolModels(profile, ["videoGeneration"]),
+ cache: {},
+ source: "configured_protocol"
+ };
+}
+
async function discoverXai(fetchImpl, profile, cache) {
const base = apiBase(profile.endpoint, "/v1");
const definitions = [
@@ -159,20 +206,30 @@ async function discoverOpenRouter(fetchImpl, profile, cache) {
async function discoverGemini(fetchImpl, profile, cache) {
const base = apiBase(profile.endpoint, "");
- const separator = base.includes("?") ? "&" : "?";
- const url = `${base.replace(/\/$/, "")}/v1beta/models${profile.apiKey ? `${separator}key=${encodeURIComponent(profile.apiKey)}` : ""}`;
- const response = await modelRequest(fetchImpl, url, { ...profile, apiKey: "" }, cache);
+ const url = `${base.replace(/\/$/, "")}/v1beta/models`;
+ const response = await modelRequest(fetchImpl, url, profile, cache,
+ profile.apiKey ? { "x-goog-api-key": profile.apiKey } : {});
if (response.notModified) return response;
return {
models: requiredArrayFrom(response.payload, "Gemini 返回了当前版本尚未适配的模型列表结构", "models", "data").map((item) => {
const methods = stringArray(item.supportedGenerationMethods ?? item.supported_generation_methods);
const tasks = methods.includes("generateContent") ? [...TEXT_TASKS] : [];
if (methods.includes("predictLongRunning")) tasks.push("videoGeneration");
+ const id = clean(item.id ?? item.name).replace(/^models\//, "");
+ const officialCapability = getAiModelCapability("gemini", id);
+ if (officialCapability) tasks.push(...officialCapability.tasks);
return modelDescriptor(item, {
confidence: "declared",
tasks,
- source: "gemini_models",
- supportedMethods: methods
+ inputModalities: officialCapability?.inputModalities,
+ outputModalities: officialCapability?.outputModalities,
+ source: officialCapability ? "gemini_models+google_official_capabilities" : "gemini_models",
+ supportedMethods: methods,
+ supportedParameters: officialCapability?.supportedParameters,
+ parameterDescriptors: officialCapability?.parameterDescriptors,
+ supportedResolutions: officialCapability?.supportedResolutions,
+ supportedAspectRatios: officialCapability?.supportedAspectRatios,
+ referenceImages: officialCapability?.referenceImages
});
}),
cache: response.cache,
@@ -208,15 +265,16 @@ function modelDescriptor(item = {}, options = {}) {
tasks: uniqueTaskIds(options.tasks),
inputModalities: normalizeModalities(options.inputModalities),
outputModalities: normalizeModalities(options.outputModalities),
- supportedParameters: parameterDescriptors
+ supportedParameters: options.supportedParameters ?? (parameterDescriptors
? Object.keys(parameterDescriptors)
- : stringArray(item.supported_parameters ?? item.supportedParameters ?? item.allowed_passthrough_parameters),
- parameterDescriptors,
+ : stringArray(item.supported_parameters ?? item.supportedParameters ?? item.allowed_passthrough_parameters)),
+ parameterDescriptors: options.parameterDescriptors ?? parameterDescriptors,
supportedMethods: stringArray(options.supportedMethods),
contextLength: positiveNumber(item.context_length ?? item.contextLength),
pricing: cloneObject(item.pricing ?? item.pricing_skus),
- supportedResolutions: stringArray(item.supported_resolutions ?? item.supportedResolutions ?? parameterDescriptors?.resolution?.values),
- supportedAspectRatios: stringArray(item.supported_aspect_ratios ?? item.supportedAspectRatios ?? parameterDescriptors?.aspect_ratio?.values)
+ supportedResolutions: options.supportedResolutions ?? stringArray(item.supported_resolutions ?? item.supportedResolutions ?? parameterDescriptors?.resolution?.values),
+ supportedAspectRatios: options.supportedAspectRatios ?? stringArray(item.supported_aspect_ratios ?? item.supportedAspectRatios ?? parameterDescriptors?.aspect_ratio?.values),
+ referenceImages: options.referenceImages ? structuredClone(options.referenceImages) : undefined
};
return descriptor;
}
@@ -257,34 +315,45 @@ function mergeModels(...collections) {
merged.set(collection.id, structuredClone(collection));
continue;
}
+ const collectionHasStrongerMetadata = confidenceRank(collection.confidence) >= confidenceRank(before.confidence);
+ const metadataPrimary = collectionHasStrongerMetadata ? collection : before;
+ const metadataSecondary = collectionHasStrongerMetadata ? before : collection;
+ const trustedModels = [before, collection].filter((item) => item.confidence !== "manual_unverified");
merged.set(collection.id, {
...before,
...collection,
confidence: strongerConfidence(before.confidence, collection.confidence),
source: collection.confidence === "manual_unverified" && before.confidence !== "manual_unverified" ? before.source : collection.source,
- name: collection.name || before.name,
+ name: metadataPrimary.name || metadataSecondary.name,
tasks: uniqueTaskIds([...(before.tasks ?? []), ...(collection.tasks ?? [])]),
configuredTasks: uniqueTaskIds([...(before.configuredTasks ?? []), ...(collection.configuredTasks ?? [])]),
inputModalities: uniqueStrings([...(before.inputModalities ?? []), ...(collection.inputModalities ?? [])]),
outputModalities: uniqueStrings([...(before.outputModalities ?? []), ...(collection.outputModalities ?? [])]),
supportedParameters: uniqueStrings([...(before.supportedParameters ?? []), ...(collection.supportedParameters ?? [])]),
+ parameterDescriptors: cloneObject(metadataPrimary.parameterDescriptors ?? metadataSecondary.parameterDescriptors),
+ supportedMethods: uniqueStrings(trustedModels.flatMap((item) => item.supportedMethods ?? [])),
supportedResolutions: uniqueStrings([...(before.supportedResolutions ?? []), ...(collection.supportedResolutions ?? [])]),
supportedAspectRatios: uniqueStrings([...(before.supportedAspectRatios ?? []), ...(collection.supportedAspectRatios ?? [])]),
- pricing: collection.pricing ?? before.pricing
+ referenceImages: cloneObject(metadataPrimary.referenceImages ?? metadataSecondary.referenceImages),
+ contextLength: metadataPrimary.contextLength ?? metadataSecondary.contextLength,
+ pricing: metadataPrimary.pricing ?? metadataSecondary.pricing
});
}
return [...merged.values()];
}
function strongerConfidence(left, right) {
- const rank = { manual_unverified: 0, protocol_inferred: 1, declared: 2 };
- return (rank[right] ?? 0) > (rank[left] ?? 0) ? right : left;
+ return confidenceRank(right) > confidenceRank(left) ? right : left;
}
-async function modelRequest(fetchImpl, url, profile, cache = {}) {
+function confidenceRank(value) {
+ return ({ manual_unverified: 0, protocol_inferred: 1, declared: 2 })[value] ?? 0;
+}
+
+async function modelRequest(fetchImpl, url, profile, cache = {}, extraHeaders = {}) {
validateRemoteUrl(url);
- const headers = { Accept: "application/json" };
- if (profile.apiKey) headers.Authorization = `Bearer ${profile.apiKey}`;
+ const headers = { Accept: "application/json", ...extraHeaders };
+ if (profile.apiKey && !headers.Authorization && !headers["x-goog-api-key"]) headers.Authorization = `Bearer ${profile.apiKey}`;
if (cache.etag) headers["If-None-Match"] = cache.etag;
const response = await fetchImpl(url, { method: "GET", headers });
if (response.status === 304) return { notModified: true };
diff --git a/ai-provider-presets.js b/ai-provider-presets.js
new file mode 100644
index 0000000..0a2b7cc
--- /dev/null
+++ b/ai-provider-presets.js
@@ -0,0 +1,109 @@
+const TEXT_CAPABILITIES = Object.freeze(["textTags", "skillExtraction", "creativePlanning"]);
+
+function preset(value) {
+ return Object.freeze({
+ ...value,
+ discovery: Object.freeze({ ...value.discovery }),
+ capabilities: Object.freeze([...value.capabilities]),
+ catalogRequiredTasks: Object.freeze([...(value.catalogRequiredTasks ?? [])])
+ });
+}
+
+export const AI_PROVIDER_PRESETS = Object.freeze([
+ preset({
+ id: "deepseek",
+ label: "DeepSeek",
+ category: "official",
+ endpoint: "https://api.deepseek.com/chat/completions",
+ protocol: "chat_completions",
+ discovery: { adapter: "identity" },
+ capabilities: TEXT_CAPABILITIES
+ }),
+ preset({
+ id: "openai",
+ label: "OpenAI",
+ category: "official",
+ endpoint: "https://api.openai.com/v1/responses",
+ protocol: "responses",
+ discovery: { adapter: "identity" },
+ capabilities: [...TEXT_CAPABILITIES, "imageAnalysis", "imageGeneration", "videoGeneration"]
+ }),
+ preset({
+ id: "gemini",
+ label: "Google Gemini",
+ category: "official",
+ endpoint: "https://generativelanguage.googleapis.com",
+ protocol: "gemini",
+ discovery: { adapter: "gemini" },
+ capabilities: [...TEXT_CAPABILITIES, "imageAnalysis", "videoAnalysis", "imageGeneration", "videoGeneration"],
+ catalogRequiredTasks: ["imageGeneration"]
+ }),
+ preset({
+ id: "xai",
+ label: "xAI",
+ category: "official",
+ endpoint: "https://api.x.ai/v1",
+ protocol: "xai",
+ discovery: { adapter: "xai" },
+ capabilities: [...TEXT_CAPABILITIES, "imageAnalysis", "imageGeneration", "videoGeneration"]
+ }),
+ preset({
+ id: "kimi",
+ label: "Kimi",
+ category: "official",
+ endpoint: "https://api.moonshot.cn/v1/chat/completions",
+ protocol: "chat_completions",
+ discovery: { adapter: "kimi" },
+ capabilities: [...TEXT_CAPABILITIES, "imageAnalysis", "videoAnalysis"]
+ }),
+ preset({
+ id: "minimax",
+ label: "MiniMax",
+ category: "official",
+ endpoint: "https://api.minimaxi.com/v1",
+ protocol: "minimax_videos",
+ discovery: { adapter: "configured_video" },
+ capabilities: ["videoGeneration"]
+ }),
+ preset({
+ id: "volcengine",
+ label: "火山引擎",
+ category: "official",
+ endpoint: "https://ark.cn-beijing.volces.com/api/v3",
+ protocol: "ark_videos",
+ discovery: { adapter: "configured_video" },
+ capabilities: ["videoGeneration"]
+ }),
+ preset({
+ id: "openrouter",
+ label: "OpenRouter",
+ category: "aggregator",
+ endpoint: "https://openrouter.ai/api/v1",
+ protocol: "openrouter",
+ discovery: { adapter: "openrouter" },
+ capabilities: [...TEXT_CAPABILITIES, "imageAnalysis", "videoAnalysis", "imageGeneration", "videoGeneration"]
+ }),
+ preset({
+ id: "custom-text",
+ label: "自定义兼容服务(文字)",
+ category: "custom",
+ endpoint: "",
+ protocol: "chat_completions",
+ discovery: { adapter: "identity" },
+ capabilities: TEXT_CAPABILITIES
+ }),
+ preset({
+ id: "custom-media",
+ label: "自定义兼容服务(图片与生成)",
+ category: "custom",
+ endpoint: "",
+ protocol: "chat_completions",
+ discovery: { adapter: "identity" },
+ capabilities: ["imageAnalysis", "imageGeneration"]
+ })
+]);
+
+export function getAiProviderPreset(idValue) {
+ const id = String(idValue ?? "").trim();
+ return AI_PROVIDER_PRESETS.find((item) => item.id === id) ?? null;
+}
diff --git a/ai-provider-registry.js b/ai-provider-registry.js
index c09a033..af16ca9 100644
--- a/ai-provider-registry.js
+++ b/ai-provider-registry.js
@@ -1,6 +1,4 @@
-import { normalizeAiSettings } from "./deepseek.js";
-import { normalizeAiServiceProfiles, normalizeAiTaskRoutes } from "./ai-task-routing.js";
-import { normalizeVisionSettings } from "./vision.js";
+import { AI_PROVIDER_PRESETS, getAiProviderPreset } from "./ai-provider-presets.js";
export const AI_ASSIGNMENT_TASKS = Object.freeze([
{ id: "textTags", label: "文字标签" },
@@ -12,156 +10,32 @@ export const AI_ASSIGNMENT_TASKS = Object.freeze([
{ id: "videoGeneration", label: "视频生成" }
]);
-const PROVIDER_LABELS = Object.freeze({
- deepseek: "DeepSeek",
- openai: "OpenAI",
- gemini: "Google Gemini",
- xai: "xAI",
- openrouter: "OpenRouter",
- minimax: "MiniMax",
- volcengine: "火山引擎",
- custom: "自定义兼容服务",
+const CUSTOM_PROVIDER_LABELS = Object.freeze({
"custom-text": "自定义兼容服务(文字)",
"custom-media": "自定义兼容服务(图片与生成)"
});
-const DEFAULT_ASSIGNMENTS = Object.freeze({
- textTags: "deepseek",
- skillExtraction: "deepseek",
- creativePlanning: "deepseek",
- imageAnalysis: "openai",
- videoAnalysis: "gemini",
- imageGeneration: "openai",
- videoGeneration: "openai"
-});
-
-const BUILT_IN_CAPABILITIES = Object.freeze({
- deepseek: ["textTags", "skillExtraction", "creativePlanning"],
- openai: ["textTags", "skillExtraction", "creativePlanning", "imageAnalysis", "imageGeneration", "videoGeneration"],
- gemini: ["textTags", "skillExtraction", "creativePlanning", "imageAnalysis", "videoAnalysis", "videoGeneration"],
- xai: ["textTags", "skillExtraction", "creativePlanning", "imageAnalysis", "imageGeneration", "videoGeneration"],
- minimax: ["videoGeneration"],
- volcengine: ["videoGeneration"],
- "custom-text": ["textTags", "skillExtraction", "creativePlanning"],
- "custom-media": ["imageAnalysis", "imageGeneration"],
- custom: ["textTags", "skillExtraction", "creativePlanning", "imageAnalysis", "imageGeneration", "videoGeneration"]
-});
-
-const DEFAULT_PROVIDER_PROFILES = Object.freeze({
- deepseek: { endpoint: "https://api.deepseek.com/chat/completions", protocol: "chat_completions" },
- openai: { endpoint: "https://api.openai.com/v1/responses", protocol: "responses" },
- gemini: { endpoint: "https://generativelanguage.googleapis.com", protocol: "gemini" },
- xai: { endpoint: "https://api.x.ai/v1", protocol: "xai" },
- openrouter: { endpoint: "https://openrouter.ai/api/v1", protocol: "openrouter" },
- minimax: { endpoint: "https://api.minimaxi.com/v1", protocol: "minimax_videos" },
- volcengine: { endpoint: "https://ark.cn-beijing.volces.com/api/v3", protocol: "ark_videos" }
-});
-
-export function migrateLegacyAiConfiguration(value = {}) {
- const text = normalizeAiSettings(value.aiSettings);
- const vision = normalizeVisionSettings(value.visionSettings);
- const services = normalizeAiServiceProfiles(value.aiServiceProfiles);
- const routes = normalizeAiTaskRoutes(value.aiTaskRoutes);
- const providers = {
- deepseek: provider("deepseek", {
- endpoint: "https://api.deepseek.com/chat/completions",
- apiKey: text.apiKey,
- consent: text.consent,
- models: textTaskModels(text.analysisModel)
- }),
- openai: provider("openai", {
- endpoint: "https://api.openai.com/v1/responses",
- apiKey: vision.openai.apiKey,
- consent: vision.consent,
- models: {
- ...textTaskModels(vision.openai.model),
- imageAnalysis: vision.openai.model,
- imageGeneration: vision.openai.model,
- videoGeneration: vision.openai.videoGeneration.model
- },
- videoGeneration: vision.openai.videoGeneration
- }),
- gemini: provider("gemini", {
- endpoint: "https://generativelanguage.googleapis.com",
- apiKey: services.gemini.apiKey,
- models: { videoAnalysis: services.gemini.model }
- }),
- xai: provider("xai", {
- endpoint: "https://api.x.ai/v1",
- apiKey: services.xai.apiKey,
- consent: services.xai.mediaConsent,
- models: {
- ...textTaskModels(services.xai.textModel),
- imageAnalysis: services.xai.imageModel,
- imageGeneration: services.xai.imageModel,
- videoGeneration: services.xai.videoModel
- }
- })
- };
- if (text.compatible.endpoint || text.compatible.model || text.compatible.apiKey) {
- providers["custom-text"] = provider("custom-text", {
- endpoint: text.compatible.endpoint,
- apiKey: text.compatible.apiKey,
- consent: text.consent,
- protocol: "chat_completions",
- models: textTaskModels(text.compatible.model)
- });
- }
- const compatibleMedia = vision.compatible;
- if (compatibleMedia.endpoint || compatibleMedia.model || compatibleMedia.apiKey || compatibleMedia.imageGeneration.endpoint) {
- providers["custom-media"] = provider("custom-media", {
- endpoint: compatibleMedia.endpoint,
- apiKey: compatibleMedia.apiKey,
- consent: vision.consent,
- protocol: compatibleMedia.protocol,
- models: {
- imageAnalysis: compatibleMedia.model,
- imageGeneration: compatibleMedia.imageGeneration.model
- },
- imageGeneration: compatibleMedia.imageGeneration
- });
- }
- const registry = normalizeAiProviderRegistry({ providers });
- const textProvider = (routeId) => routes[routeId].serviceId === "xai"
- ? "xai"
- : text.activeProvider === "compatible" ? "custom-text" : "deepseek";
- const imageProvider = routes["image-analysis"].serviceId === "xai"
- ? "xai"
- : vision.activeProvider === "compatible" ? "custom-media" : "openai";
- const generationProvider = (taskId) => routes[taskId].serviceId === "xai"
- ? "xai"
- : vision.activeProvider === "compatible" ? "custom-media" : "openai";
- const assignments = normalizeAiTaskAssignments({
- textTags: assignment(textProvider("text-tags"), routes["text-tags"].model || text.analysisModel, registry),
- skillExtraction: assignment(textProvider("skill-extraction"), routes["skill-extraction"].model || text.analysisModel, registry),
- creativePlanning: assignment(textProvider("creative-planning"), routes["creative-planning"].model || text.analysisModel, registry),
- imageAnalysis: assignment(imageProvider, routes["image-analysis"].model, registry),
- videoAnalysis: assignment("gemini", routes["video-analysis"].model, registry),
- imageGeneration: assignment(generationProvider("image-generation"), routes["image-generation"].model, registry),
- videoGeneration: assignment(generationProvider("video-generation"), routes["video-generation"].model, registry)
- }, registry);
- return { registry, assignments };
-}
-
export function normalizeAiProviderRegistry(value = {}) {
const source = value?.providers && typeof value.providers === "object" ? value.providers : {};
const providers = {};
- for (const id of ["deepseek", "openai", "gemini", "xai", "openrouter", "minimax", "volcengine", "custom", "custom-text", "custom-media"]) {
- if (!source[id] && id === "custom") continue;
- providers[id] = provider(id, { ...(DEFAULT_PROVIDER_PROFILES[id] ?? {}), ...(source[id] ?? {}) });
+ const ids = AI_PROVIDER_PRESETS.map((item) => item.id);
+ for (const id of ids) {
+ const preset = getAiProviderPreset(id);
+ const saved = source[id] ?? {};
+ providers[id] = provider(id, {
+ ...(preset ?? {}),
+ ...saved,
+ discovery: { ...(preset?.discovery ?? {}), ...(saved.discovery ?? {}) }
+ });
}
- return { version: 3, providers };
+ return { version: 4, providers };
}
-export function normalizeAiTaskAssignments(value = {}, registryValue = {}) {
- const registry = normalizeAiProviderRegistry(registryValue);
+export function normalizeAiTaskAssignments(value = {}) {
return Object.fromEntries(AI_ASSIGNMENT_TASKS.map((task) => {
- const fallback = ["textTags", "skillExtraction", "creativePlanning"].includes(task.id) ? value?.text : null;
- const candidate = value?.[task.id] ?? fallback;
+ const candidate = value?.[task.id];
const source = candidate && typeof candidate === "object" ? candidate : {};
- const providerId = clean(source.providerId) || DEFAULT_ASSIGNMENTS[task.id];
- const profile = registry.providers[providerId];
- return [task.id, { providerId, model: clean(source.model) || clean(profile?.models?.[task.id]) }];
+ return [task.id, { providerId: clean(source.providerId), model: clean(source.model) }];
}));
}
@@ -172,10 +46,12 @@ export function publicAiProviderRegistry(value = {}) {
providers: Object.fromEntries(Object.entries(registry.providers).map(([id, profile]) => [id, {
id,
label: profile.label,
+ category: profile.category,
endpoint: profile.endpoint,
protocol: profile.protocol,
models: structuredClone(profile.models),
capabilities: [...profile.capabilities],
+ catalogRequiredTasks: [...profile.catalogRequiredTasks],
discoveredModels: structuredClone(profile.discoveredModels),
discovery: structuredClone(profile.discovery),
configured: profile.capabilities.some((taskId) => providerConfiguredForTask(profile, taskId)),
@@ -198,15 +74,16 @@ export function resolveAiProviderAssignment(taskId, registryValue = {}, assignme
if (!AI_ASSIGNMENT_TASKS.some((task) => task.id === taskId)) throw new Error("未知 AI 任务");
const registry = normalizeAiProviderRegistry(registryValue);
const raw = assignmentsValue?.[taskId] ?? {};
- const providerId = clean(raw.providerId) || DEFAULT_ASSIGNMENTS[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 model = clean(raw.model) || profile.models[taskId];
+ const model = clean(raw.model);
const discovered = profile.discoveredModels.find((item) => item.id === model);
if (discovered?.status === "unavailable") throw new Error(`${profile.label} 中已选模型已下架或当前账号不可用,请重新选择`);
- if (!providerConfiguredForTask(profile, taskId) || !model) 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 };
}
@@ -215,6 +92,7 @@ export function mergeAiProviderRegistry(currentValue = {}, incomingValue = {}) {
const incoming = incomingValue?.providers && typeof incomingValue.providers === "object" ? incomingValue.providers : {};
const providers = { ...current.providers };
for (const [id, update] of Object.entries(incoming)) {
+ if (!getAiProviderPreset(id)) continue;
const before = providers[id] ?? provider(id);
const endpointChanged = Object.hasOwn(update ?? {}, "endpoint") && clean(update.endpoint) !== before.endpoint;
const imageUpdate = update?.imageGeneration && typeof update.imageGeneration === "object" ? update.imageGeneration : null;
@@ -240,25 +118,22 @@ export function mergeAiProviderRegistry(currentValue = {}, incomingValue = {}) {
}
function provider(id, value = {}) {
- const legacyTextModel = clean(value?.models?.text);
+ const preset = getAiProviderPreset(id);
const models = Object.fromEntries(AI_ASSIGNMENT_TASKS.map((task) => [
task.id,
- clean(value?.models?.[task.id]) || (["textTags", "skillExtraction", "creativePlanning"].includes(task.id) ? legacyTextModel : "")
+ clean(value?.models?.[task.id])
]));
- const discoveredModels = normalizeDiscoveredModels(value?.discoveredModels);
- const declaredTasks = new Set(discoveredModels.flatMap((model) => model.tasks));
- const configuredTasks = configuredCustomCapabilities(id, value, models);
- const capabilities = [...new Set([
- ...(BUILT_IN_CAPABILITIES[id] ?? []),
- ...configuredTasks,
- ...AI_ASSIGNMENT_TASKS.map((task) => task.id).filter((taskId) => value?.capabilities?.includes(taskId)),
- ...declaredTasks
- ])];
+ const discoveredModels = normalizeDiscoveredModels(value?.discoveredModels).map((model) => ({
+ ...model,
+ tasks: preset ? model.tasks.filter((taskId) => preset.capabilities.includes(taskId)) : model.tasks
+ }));
+ const capabilities = [...(preset?.capabilities ?? [])];
return {
id,
- label: clean(value?.label) || PROVIDER_LABELS[id] || "自定义兼容服务",
- endpoint: clean(value?.endpoint),
- protocol: clean(value?.protocol) || "native",
+ label: clean(value?.label) || preset?.label || CUSTOM_PROVIDER_LABELS[id] || "自定义兼容服务",
+ category: preset?.category ?? "custom",
+ endpoint: clean(value?.endpoint) || preset?.endpoint || "",
+ protocol: clean(value?.protocol) || preset?.protocol || "native",
apiKey: clean(value?.apiKey),
credentialConfigured: Object.hasOwn(value ?? {}, "apiKey")
? Boolean(clean(value?.apiKey) || isLoopback(value?.endpoint))
@@ -266,6 +141,7 @@ function provider(id, value = {}) {
consent: value?.consent === true,
models,
capabilities,
+ catalogRequiredTasks: [...(preset?.catalogRequiredTasks ?? [])],
discoveredModels,
discovery: normalizeDiscovery(value?.discovery),
imageGeneration: value?.imageGeneration && typeof value.imageGeneration === "object" ? structuredClone(value.imageGeneration) : null,
@@ -285,6 +161,7 @@ function normalizeDiscoveredModels(values) {
outputModalities: cleanArray(item?.outputModalities),
supportedParameters: cleanArray(item?.supportedParameters),
parameterDescriptors: item?.parameterDescriptors && typeof item.parameterDescriptors === "object" ? structuredClone(item.parameterDescriptors) : null,
+ supportedMethods: cleanArray(item?.supportedMethods),
supportedResolutions: cleanArray(item?.supportedResolutions),
supportedAspectRatios: cleanArray(item?.supportedAspectRatios),
referenceImages: normalizeReferenceImages(item?.referenceImages),
@@ -293,20 +170,6 @@ function normalizeDiscoveredModels(values) {
})).filter((item) => item.id);
}
-function configuredCustomCapabilities(id, value, models) {
- if (id === "custom-text") {
- return ["textTags", "skillExtraction", "creativePlanning"].filter((taskId) => Boolean(models[taskId]));
- }
- if (id === "custom-media") {
- return [
- ...(models.imageAnalysis && value?.endpoint ? ["imageAnalysis"] : []),
- ...(models.imageGeneration && (value?.imageGeneration?.endpoint || value?.imageGeneration?.protocol === "responses_tool")
- ? ["imageGeneration"] : [])
- ];
- }
- return [];
-}
-
function normalizeReferenceImages(value) {
const source = value && typeof value === "object" ? value : {};
const maxItems = source.maxItems === null || source.maxItems === undefined || source.maxItems === ""
@@ -323,6 +186,7 @@ function normalizeReferenceImages(value) {
function normalizeDiscovery(value) {
return {
+ adapter: clean(value?.adapter),
discoveredAt: clean(value?.discoveredAt),
source: clean(value?.source),
etag: clean(value?.etag),
@@ -335,30 +199,30 @@ function cleanArray(value) {
return [...new Set((Array.isArray(value) ? value : []).map(clean).filter(Boolean))];
}
-function assignment(providerId, model) {
- return { providerId, model: clean(model) };
-}
-
-function textTaskModels(model) {
- return {
- textTags: clean(model),
- skillExtraction: clean(model),
- creativePlanning: clean(model)
- };
-}
-
-function providerConfiguredForTask(profile, taskId) {
+function providerConfiguredForTask(profile, taskId, selectedModel = "") {
const endpoint = taskId === "imageGeneration" ? profile.imageGeneration?.endpoint || profile.endpoint : profile.endpoint;
const dedicatedImageCredential = taskId === "imageGeneration" && requiresDedicatedImageCredential(profile);
const key = taskId === "imageGeneration"
? profile.imageGeneration?.apiKey || (dedicatedImageCredential ? "" : profile.apiKey)
: profile.apiKey;
- const model = profile.models[taskId];
- const discovered = profile.discoveredModels.find((item) => item.id === model);
+ const configuredModel = clean(selectedModel) || profile.models[taskId];
+ const discoveredCandidate = profile.discoveredModels.some((item) =>
+ item.status !== "unavailable" && item.tasks.includes(taskId)
+ );
+ const discovered = profile.discoveredModels.find((item) => item.id === configuredModel);
+ const catalogRequired = profile.catalogRequiredTasks.includes(taskId);
const savedCredential = dedicatedImageCredential
? Boolean(profile.imageGeneration?.apiKey || profile.imageGeneration?.credentialConfigured)
: profile.credentialConfigured;
- return Boolean(model && discovered?.status !== "unavailable" && (key || savedCredential || isLoopback(endpoint)));
+ return Boolean(
+ (catalogRequired
+ ? clean(selectedModel)
+ ? discovered?.status !== "unavailable" && discovered?.tasks.includes(taskId)
+ : discoveredCandidate
+ : configuredModel || discoveredCandidate)
+ && discovered?.status !== "unavailable"
+ && (key || savedCredential || isLoopback(endpoint))
+ );
}
function requiresDedicatedImageCredential(profile = {}) {
diff --git a/ai-runtime.js b/ai-runtime.js
index cd1fc2f..f7e557f 100644
--- a/ai-runtime.js
+++ b/ai-runtime.js
@@ -1,7 +1,6 @@
import { normalizeAiSettings } from "./deepseek.js";
import { normalizeVisionSettings } from "./vision.js";
import {
- migrateLegacyAiConfiguration,
normalizeAiProviderRegistry,
normalizeAiTaskAssignments,
resolveAiProviderAssignment
@@ -19,21 +18,17 @@ export function requireAiRuntimeProtocolVersion(value) {
}
export function aiConfigurationFromStorage(stored = {}) {
- const migrated = stored.aiProviderRegistry
- ? {
- registry: normalizeAiProviderRegistry(stored.aiProviderRegistry),
- assignments: normalizeAiTaskAssignments(stored.aiTaskAssignments, stored.aiProviderRegistry)
- }
- : migrateLegacyAiConfiguration(stored);
+ const registry = normalizeAiProviderRegistry(stored.aiProviderRegistry);
return {
- ...migrated,
- preferences: normalizeAiPreferences(stored.aiPreferences, stored)
+ registry,
+ assignments: normalizeAiTaskAssignments(stored.aiTaskAssignments, registry),
+ preferences: normalizeAiPreferences(stored.aiPreferences)
};
}
-export function normalizeAiPreferences(value = {}, legacy = {}) {
- const text = normalizeAiSettings(legacy.aiSettings);
- const vision = normalizeVisionSettings(legacy.visionSettings);
+export function normalizeAiPreferences(value = {}) {
+ const text = normalizeAiSettings();
+ const vision = normalizeVisionSettings();
const source = value && typeof value === "object" ? value : {};
return {
version: 1,
@@ -55,35 +50,41 @@ export function projectAiRuntime(configurationValue = {}) {
const configuration = normalizeConfiguration(configurationValue);
const { registry, assignments, preferences } = configuration;
const providers = registry.providers;
- const planning = settingsForTextAssignment(assignments.textTags, providers, preferences, false);
+ const planning = settingsForTextAssignment(assignments.creativePlanning, providers, preferences, false);
const openai = providers.openai;
- const compatible = providers["custom-media"] || providers.custom;
+ const compatible = providers["custom-media"];
const imageAnalysis = assignments.imageAnalysis;
const vision = normalizeVisionSettings({
- activeProvider: ["custom-media", "custom"].includes(imageAnalysis.providerId) ? "compatible" : "openai",
+ activeProvider: imageAnalysis.providerId === "custom-media" ? "compatible" : "openai",
consent: true,
autoAnalyzeImports: preferences.autoAnalyzeImports,
instructionsByLocale: preferences.visionInstructionsByLocale,
openai: {
- model: assignments.imageAnalysis.providerId === "openai" ? assignments.imageAnalysis.model : openai?.models?.imageAnalysis,
+ model: assignments.imageAnalysis.providerId === "openai" ? assignments.imageAnalysis.model : "",
apiKey: usableKey(openai),
videoGeneration: {
...(openai?.videoGeneration ?? {}),
- model: openai?.models?.videoGeneration || openai?.videoGeneration?.model
+ model: assignments.videoGeneration.providerId === "openai" ? assignments.videoGeneration.model : ""
}
},
compatible: {
protocol: compatible?.protocol,
endpoint: compatible?.endpoint,
- model: compatible?.models?.imageAnalysis,
+ model: assignments.imageAnalysis.providerId === "custom-media" ? assignments.imageAnalysis.model : "",
apiKey: usableKey(compatible),
imageGeneration: {
...(compatible?.imageGeneration ?? {}),
- model: compatible?.models?.imageGeneration || compatible?.imageGeneration?.model,
+ model: assignments.imageGeneration.providerId === "custom-media" ? assignments.imageGeneration.model : "",
apiKey: usableKey(compatible, true, "imageGeneration")
}
}
});
+ if (!clean(imageAnalysis?.providerId)) {
+ vision.activeProvider = "compatible";
+ vision.openai.model = "";
+ vision.compatible.endpoint = "";
+ vision.compatible.model = "";
+ }
const xai = providers.xai;
return {
aiSettings: planning,
@@ -92,23 +93,29 @@ export function projectAiRuntime(configurationValue = {}) {
providerProfiles: providers,
xai: {
apiKey: usableKey(xai),
- textModel: xai?.models?.creativePlanning,
- imageModel: xai?.models?.imageGeneration || xai?.models?.imageAnalysis,
- videoModel: xai?.models?.videoGeneration,
+ 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
}
},
aiServiceProfiles: {
- gemini: { apiKey: usableKey(providers.gemini, false), model: providers.gemini?.models?.videoAnalysis },
+ gemini: {
+ apiKey: usableKey(providers.gemini, false),
+ model: assignments.videoAnalysis.providerId === "gemini" ? assignments.videoAnalysis.model : ""
+ },
xai: {
apiKey: usableKey(xai),
- textModel: xai?.models?.creativePlanning,
- imageModel: xai?.models?.imageGeneration || xai?.models?.imageAnalysis,
- videoModel: xai?.models?.videoGeneration,
+ 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
}
},
- aiTaskRoutes: legacyRuntimeRoutes(assignments),
aiTaskAssignments: assignments,
aiProviderRegistry: registry,
aiPreferences: preferences
@@ -133,11 +140,23 @@ export function resolveVisionTaskSettings(taskId, configurationValue = {}, optio
const resolved = options.requireConfigured === false
? configuration.assignments[taskId]
: resolveAiProviderAssignment(taskId, configuration.registry, configuration.assignments);
+ if (options.requireConfigured === false && !clean(resolved?.providerId)) {
+ const settings = normalizeVisionSettings({
+ activeProvider: "compatible",
+ consent: false,
+ autoAnalyzeImports: configuration.preferences.autoAnalyzeImports,
+ instructionsByLocale: configuration.preferences.visionInstructionsByLocale
+ });
+ settings.openai.model = "";
+ settings.compatible.endpoint = "";
+ settings.compatible.model = "";
+ return settings;
+ }
const profile = configuration.registry.providers[resolved.providerId];
if (options.requireConfigured !== false) requireConsent(profile, resolved.provider);
const openai = resolved.providerId === "openai";
const endpoint = chatEndpoint(profile);
- return normalizeVisionSettings({
+ const settings = normalizeVisionSettings({
activeProvider: openai ? "openai" : "compatible",
consent: true,
autoAnalyzeImports: configuration.preferences.autoAnalyzeImports,
@@ -165,6 +184,9 @@ export function resolveVisionTaskSettings(taskId, configurationValue = {}, optio
model: resolved.model
} : null
});
+ settings.openai.model = openai ? clean(resolved.model) : "";
+ settings.compatible.model = openai ? "" : clean(resolved.model);
+ return settings;
}
export function resolveVideoAnalysisTask(configurationValue = {}) {
@@ -174,35 +196,31 @@ export function resolveVideoAnalysisTask(configurationValue = {}) {
requireConsent(profile, resolved.provider);
return {
...resolved,
+ providerLabel: resolved.provider,
+ protocol: profile.protocol,
apiKey: profile.apiKey,
endpoint: profile.endpoint
};
}
-export function legacyRuntimeRoutes(assignmentsValue = {}) {
- const assignments = assignmentsValue && typeof assignmentsValue === "object" ? assignmentsValue : {};
- const route = (taskId, fallback) => ({
- serviceId: assignments[taskId]?.providerId === "xai" ? "xai" : fallback,
- model: clean(assignments[taskId]?.model)
- });
- return {
- "text-tags": route("textTags", "current-text"),
- "skill-extraction": route("skillExtraction", "current-text"),
- "creative-planning": route("creativePlanning", "current-text"),
- "image-analysis": route("imageAnalysis", "current-vision"),
- "video-analysis": { serviceId: assignments.videoAnalysis?.providerId || "gemini", model: clean(assignments.videoAnalysis?.model) },
- "image-generation": route("imageGeneration", "current-vision"),
- "video-generation": route("videoGeneration", "current-vision")
- };
-}
-
function settingsForTextAssignment(assignmentValue, providers, preferences, strict) {
- const providerId = clean(assignmentValue?.providerId) || "deepseek";
- const profile = providers[providerId] || providers.deepseek;
+ const providerId = clean(assignmentValue?.providerId);
+ if (!providerId) {
+ if (strict) throw new Error("文字任务尚未分配 AI 服务");
+ const settings = normalizeAiSettings({
+ activeProvider: "compatible",
+ consent: false,
+ analysisInstructionsByLocale: preferences.textInstructionsByLocale,
+ compatible: { endpoint: "", model: "", apiKey: "" }
+ });
+ settings.analysisModel = "";
+ return settings;
+ }
+ const profile = providers[providerId];
if (strict) requireConsent(profile, profile?.label || providerId);
- const model = clean(assignmentValue?.model) || profile?.models?.textTags || profile?.models?.creativePlanning;
+ const model = clean(assignmentValue?.model);
const deepseek = providerId === "deepseek";
- return normalizeAiSettings({
+ const settings = normalizeAiSettings({
activeProvider: deepseek ? "deepseek" : "compatible",
apiKey: deepseek ? profile?.apiKey : "",
analysisModel: deepseek ? model : undefined,
@@ -214,6 +232,9 @@ function settingsForTextAssignment(assignmentValue, providers, preferences, stri
apiKey: profile?.apiKey
}
});
+ settings.analysisModel = model;
+ settings.compatible.model = deepseek ? "" : model;
+ return settings;
}
function normalizeConfiguration(value = {}) {
diff --git a/ai-service-profiles.js b/ai-service-profiles.js
new file mode 100644
index 0000000..545561f
--- /dev/null
+++ b/ai-service-profiles.js
@@ -0,0 +1,39 @@
+export function normalizeAiServiceProfiles(value = {}) {
+ const source = value && typeof value === "object" ? value : {};
+ return {
+ gemini: {
+ apiKey: clean(source.gemini?.apiKey),
+ model: clean(source.gemini?.model)
+ },
+ xai: {
+ apiKey: clean(source.xai?.apiKey),
+ textModel: clean(source.xai?.textModel),
+ imageModel: clean(source.xai?.imageModel),
+ videoModel: clean(source.xai?.videoModel),
+ mediaConsent: source.xai?.mediaConsent === true
+ }
+ };
+}
+
+export function publicAiServiceProfiles(value = {}) {
+ const profiles = normalizeAiServiceProfiles(value);
+ return {
+ gemini: {
+ model: profiles.gemini.model,
+ configured: Boolean(profiles.gemini.apiKey && profiles.gemini.model)
+ },
+ xai: {
+ textModel: profiles.xai.textModel,
+ imageModel: profiles.xai.imageModel,
+ videoModel: profiles.xai.videoModel,
+ mediaConsent: profiles.xai.mediaConsent,
+ configured: Boolean(profiles.xai.apiKey && (
+ profiles.xai.textModel || profiles.xai.imageModel || profiles.xai.videoModel
+ ))
+ }
+ };
+}
+
+function clean(value) {
+ return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").trim();
+}
diff --git a/ai-task-routing.js b/ai-task-routing.js
deleted file mode 100644
index 3fb70d9..0000000
--- a/ai-task-routing.js
+++ /dev/null
@@ -1,111 +0,0 @@
-export const AI_TASKS = Object.freeze([
- { id: "text-tags", label: "文字标签", services: ["current-text", "xai"] },
- { id: "image-analysis", label: "图片分析", services: ["current-vision", "xai"] },
- { id: "video-analysis", label: "视频分析", services: ["gemini"] },
- { id: "skill-extraction", label: "Skill 提炼", services: ["current-text", "xai"] },
- { id: "creative-planning", label: "创作规划", services: ["current-text", "xai"] },
- { id: "image-generation", label: "图片生成", services: ["current-vision", "xai"] },
- { id: "video-generation", label: "视频生成", services: ["current-vision", "xai"] }
-]);
-
-export const AI_SERVICE_LABELS = Object.freeze({
- "current-text": "当前文字服务",
- "current-vision": "当前图片与生成服务",
- gemini: "Google Gemini",
- xai: "xAI"
-});
-
-export const GEMINI_API_ORIGIN = "https://generativelanguage.googleapis.com/*";
-export const XAI_API_ORIGIN = "https://*.x.ai/*";
-
-export function normalizeAiServiceProfiles(value = {}) {
- const source = value && typeof value === "object" ? value : {};
- return {
- gemini: {
- apiKey: clean(source.gemini?.apiKey),
- model: clean(source.gemini?.model)
- },
- xai: {
- apiKey: clean(source.xai?.apiKey),
- textModel: clean(source.xai?.textModel),
- imageModel: clean(source.xai?.imageModel),
- videoModel: clean(source.xai?.videoModel),
- mediaConsent: source.xai?.mediaConsent === true
- }
- };
-}
-
-export function mergeAiServiceProfiles(currentValue = {}, incomingValue = {}) {
- const current = normalizeAiServiceProfiles(currentValue);
- const incoming = incomingValue && typeof incomingValue === "object" ? incomingValue : {};
- const next = normalizeAiServiceProfiles({
- gemini: {
- apiKey: clean(incoming.gemini?.apiKey) || current.gemini.apiKey,
- model: Object.hasOwn(incoming.gemini ?? {}, "model") ? incoming.gemini.model : current.gemini.model
- },
- xai: {
- apiKey: clean(incoming.xai?.apiKey) || current.xai.apiKey,
- textModel: Object.hasOwn(incoming.xai ?? {}, "textModel") ? incoming.xai.textModel : current.xai.textModel,
- imageModel: Object.hasOwn(incoming.xai ?? {}, "imageModel") ? incoming.xai.imageModel : current.xai.imageModel,
- videoModel: Object.hasOwn(incoming.xai ?? {}, "videoModel") ? incoming.xai.videoModel : current.xai.videoModel,
- mediaConsent: Object.hasOwn(incoming.xai ?? {}, "mediaConsent") ? incoming.xai.mediaConsent === true : current.xai.mediaConsent
- }
- });
- if (incoming.clearApiKey === "gemini") next.gemini.apiKey = "";
- if (incoming.clearApiKey === "xai") next.xai.apiKey = "";
- return next;
-}
-
-export function publicAiServiceProfiles(value = {}) {
- const profiles = normalizeAiServiceProfiles(value);
- return {
- gemini: { model: profiles.gemini.model, configured: Boolean(profiles.gemini.apiKey && profiles.gemini.model) },
- xai: {
- textModel: profiles.xai.textModel,
- imageModel: profiles.xai.imageModel,
- videoModel: profiles.xai.videoModel,
- mediaConsent: profiles.xai.mediaConsent,
- configured: Boolean(profiles.xai.apiKey && (profiles.xai.textModel || profiles.xai.imageModel || profiles.xai.videoModel))
- }
- };
-}
-
-export function normalizeAiTaskRoutes(value = {}) {
- const source = value && typeof value === "object" ? value : {};
- return Object.fromEntries(AI_TASKS.map((task) => {
- const requested = clean(source[task.id]?.serviceId ?? source[task.id]);
- const serviceId = task.services.includes(requested) ? requested : task.services[0];
- return [task.id, { serviceId, model: clean(source[task.id]?.model) }];
- }));
-}
-
-export function resolveAiTaskRoute(taskId, routesValue = {}, context = {}) {
- const task = AI_TASKS.find((item) => item.id === taskId);
- if (!task) throw new Error("未知 AI 任务");
- const route = normalizeAiTaskRoutes(routesValue)[task.id];
- const profiles = normalizeAiServiceProfiles(context.profiles);
- const currentText = context.currentText ?? {};
- const currentVision = context.currentVision ?? {};
- if (route.serviceId === "gemini") {
- if (!profiles.gemini.apiKey || !(route.model || profiles.gemini.model)) throw new Error("视频分析需要先配置 Gemini API Key 和模型");
- return { taskId, serviceId: "gemini", provider: "Google Gemini", model: route.model || profiles.gemini.model };
- }
- if (route.serviceId === "xai") {
- const profileModel = taskId === "video-generation"
- ? profiles.xai.videoModel
- : taskId.includes("image") ? profiles.xai.imageModel : profiles.xai.textModel;
- const model = route.model || profileModel;
- if (!profiles.xai.apiKey || !model) throw new Error("所选任务需要先配置 xAI API Key 和对应模型");
- return { taskId, serviceId: "xai", provider: "xAI", model };
- }
- if (route.serviceId === "current-vision") {
- if (!currentVision.configured) throw new Error("当前图片与生成服务尚未完成配置");
- return { taskId, serviceId: route.serviceId, provider: currentVision.provider || "当前图片与生成服务", model: route.model || currentVision.model };
- }
- if (!currentText.configured) throw new Error("当前文字服务尚未完成配置");
- return { taskId, serviceId: route.serviceId, provider: currentText.provider || "当前文字服务", model: route.model || currentText.model };
-}
-
-function clean(value) {
- return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").trim();
-}
diff --git a/article-document.js b/article-document.js
new file mode 100644
index 0000000..a9bd345
--- /dev/null
+++ b/article-document.js
@@ -0,0 +1,124 @@
+export const ARTICLE_DOCUMENT_VERSION = 1;
+
+const TEXT_BLOCK_KINDS = new Set(["heading", "paragraph", "list", "quote", "code", "table"]);
+const ASSET_BLOCK_KINDS = new Set(["image", "video", "document"]);
+const BLOCK_KINDS = new Set([...TEXT_BLOCK_KINDS, ...ASSET_BLOCK_KINDS, "link"]);
+
+export function normalizeArticleDocument(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const seen = new Set();
+ const blocks = (Array.isArray(value.blocks) ? value.blocks : []).flatMap((block, index) => {
+ const normalized = normalizeArticleBlock(block, index);
+ if (!normalized || seen.has(normalized.id)) return [];
+ seen.add(normalized.id);
+ return [normalized];
+ }).sort((left, right) => left.sourceOrder - right.sourceOrder);
+ if (!blocks.length) return null;
+ return { version: ARTICLE_DOCUMENT_VERSION, blocks };
+}
+
+export function articleDocumentText(value) {
+ const documentValue = normalizeArticleDocument(value);
+ if (!documentValue) return "";
+ return documentValue.blocks
+ .filter((block) => TEXT_BLOCK_KINDS.has(block.kind))
+ .map((block) => block.text)
+ .filter(Boolean)
+ .join("\n\n");
+}
+
+export function remapArticleDocumentAssets(value, assetIdMapValue) {
+ const documentValue = normalizeArticleDocument(value);
+ if (!documentValue) return null;
+ const assetIdMap = assetIdMapValue instanceof Map
+ ? assetIdMapValue
+ : new Map(Object.entries(assetIdMapValue && typeof assetIdMapValue === "object" ? assetIdMapValue : {}));
+ return normalizeArticleDocument({
+ ...documentValue,
+ blocks: documentValue.blocks.map((block) => block.assetId && assetIdMap.has(block.assetId)
+ ? { ...block, assetId: clean(assetIdMap.get(block.assetId)) }
+ : block)
+ });
+}
+
+export function finalizeArticleDocumentAssets(value, assetIdMapValue) {
+ const documentValue = normalizeArticleDocument(value);
+ if (!documentValue) return null;
+ const assetIdMap = assetIdMapValue instanceof Map
+ ? assetIdMapValue
+ : new Map(Object.entries(assetIdMapValue && typeof assetIdMapValue === "object" ? assetIdMapValue : {}));
+ return normalizeArticleDocument({
+ ...documentValue,
+ blocks: documentValue.blocks.map((block) => {
+ if (!block.assetId) return block;
+ const mapped = clean(assetIdMap.get(block.assetId));
+ if (mapped) return { ...block, assetId: mapped };
+ const { assetId: _assetId, ...referenceOnly } = block;
+ return referenceOnly;
+ })
+ });
+}
+
+export function removeArticleDocumentAsset(value, assetIdValue) {
+ const documentValue = normalizeArticleDocument(value);
+ if (!documentValue) return null;
+ const assetId = clean(assetIdValue);
+ return normalizeArticleDocument({
+ ...documentValue,
+ blocks: documentValue.blocks.filter((block) => block.assetId !== assetId)
+ });
+}
+
+function normalizeArticleBlock(value, index) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const kind = BLOCK_KINDS.has(value.kind) ? value.kind : "";
+ if (!kind) return null;
+ const id = clean(value.id) || `article-block:${index + 1}`;
+ const text = cleanMultiline(value.text);
+ const assetId = clean(value.assetId);
+ const sourceUrl = safeHttpUrl(value.sourceUrl || value.url);
+ if (TEXT_BLOCK_KINDS.has(kind) && !text) return null;
+ if (ASSET_BLOCK_KINDS.has(kind) && !assetId && !sourceUrl) return null;
+ if (kind === "link" && !sourceUrl) return null;
+ const sourceOrderValue = Number(value.sourceOrder);
+ const sourceOrder = Number.isSafeInteger(sourceOrderValue) && sourceOrderValue >= 0 ? sourceOrderValue : index;
+ const label = clean(value.label);
+ const mimeType = clean(value.mimeType).toLocaleLowerCase("en-US");
+ const block = {
+ id,
+ kind,
+ sourceOrder,
+ ...(text ? { text } : {}),
+ ...(assetId ? { assetId } : {}),
+ ...(sourceUrl ? { sourceUrl } : {}),
+ ...(label ? { label } : {}),
+ ...(mimeType ? { mimeType } : {})
+ };
+ if (kind === "heading") block.level = Math.min(6, Math.max(1, Math.trunc(Number(value.level) || 2)));
+ if (kind === "list") block.ordered = value.ordered === true;
+ if (kind === "video" && safeHttpUrl(value.posterUrl)) block.posterUrl = safeHttpUrl(value.posterUrl);
+ return block;
+}
+
+function safeHttpUrl(value) {
+ try {
+ const url = new URL(String(value ?? "").trim());
+ return ["http:", "https:"].includes(url.protocol) ? url.href : "";
+ } catch {
+ return "";
+ }
+}
+
+function clean(value) {
+ return String(value ?? "").replace(/[\u0000-\u001f\u007f]/gu, " ").trim();
+}
+
+function cleanMultiline(value) {
+ return String(value ?? "")
+ .replace(/\r\n?/gu, "\n")
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, " ")
+ .replace(/[\t ]+/gu, " ")
+ .replace(/ *\n */gu, "\n")
+ .replace(/\n{3,}/gu, "\n\n")
+ .trim();
+}
diff --git a/background.js b/background.js
index fca3154..7742d19 100644
--- a/background.js
+++ b/background.js
@@ -1,4 +1,5 @@
import { showPageToast } from "./capture-region.js";
+import { articleDocumentText, finalizeArticleDocumentAssets } from "./article-document.js";
import {
classifyContent,
classifyImportedMedia,
@@ -44,8 +45,6 @@ import {
ANALYSIS_PROMPT_VERSION,
analysisProfileFingerprint,
analysisTaxonomyPrompt,
- mergeAiSettings,
- normalizeAiSettings,
publicAiSettings,
summarizeVisualSetWithAi
} from "./deepseek.js";
@@ -170,6 +169,8 @@ import {
selectLibraryPackage,
selectProjectPackage
} from "./library-package.js";
+import { mergeCuratedLibraryPackage } from "./curated-import.js";
+import { prepareCuratedSubmissionState } from "./curated-submission.js";
import {
createCollection,
deleteCollection,
@@ -211,19 +212,38 @@ import {
createCaptureDraft,
draftParts,
draftSourcePages,
- draftText
+ draftText,
+ sourceContextForUrl
} from "./capture-draft.js";
import { createCaptureWorkspace } from "./capture-workspace.js";
import {
applyPageCaptureSelections,
+ combinePageCaptureCandidates,
collectPageCaptureSnapshot,
+ mergePageCaptureRegionEdit,
PAGE_CAPTURE_ADAPTERS,
- normalizePageCaptureBatch
+ PAGE_CAPTURE_PLATFORM_ADAPTERS,
+ normalizePageCaptureBatch,
+ normalizePageCaptureCandidate,
+ pageCaptureMediaFetchCandidates,
+ resolvePageCaptureImage
} from "./page-capture.js";
-import { fetchBoundedMedia } from "./bounded-media.js";
-import { PAGE_CAPTURE_LIMITS, PORTABLE_LIBRARY_LIMITS } from "./resource-limits.js";
-import { publicAiServiceProfiles } from "./ai-task-routing.js";
import {
+ collectPageCaptureSitePayload,
+ installPageCaptureSiteObserver,
+ normalizePageCaptureSitePayload
+} from "./page-capture-site-adapters.js";
+import { boundedMediaBlobFromResponse, fetchBoundedMedia, isSupportedDocumentMimeType } from "./bounded-media.js";
+import {
+ discardPageSessionMedia,
+ PAGE_SESSION_MEDIA_CHUNK_BYTES,
+ preparePageSessionMedia,
+ readPageSessionMediaChunk
+} from "./page-session-media.js";
+import { PAGE_CAPTURE_LIMITS, PAGE_CAPTURE_QUALITY_LIMITS, PORTABLE_LIBRARY_LIMITS } from "./resource-limits.js";
+import { publicAiServiceProfiles } from "./ai-service-profiles.js";
+import {
+ availableAiProvidersForTask,
mergeAiProviderRegistry,
normalizeAiTaskAssignments,
publicAiProviderRegistry
@@ -238,6 +258,7 @@ import {
resolveVisionTaskSettings
} from "./ai-runtime.js";
import {
+ analyzeVideoWithChatCompletions,
analyzeVideoWithGemini,
analyzeVideoWithOpenRouter,
requireVideoAnalysisConfirmation
@@ -264,10 +285,6 @@ import {
analyzeImageWithVision,
blobToDataUrl,
imageFingerprint,
- mergeVisionSettings,
- normalizeVisionSettings,
- permissionPatternForVisionSettings,
- probeCompatibleModels,
publicVisionSettings
} from "./vision.js";
import {
@@ -321,10 +338,6 @@ const STORAGE_KEYS = Object.freeze({
classificationResetBackup: "classificationResetBackup",
facetMigrationBackup: "creativeFacetMigrationBackupV5",
facetUndo: "facetUndo",
- aiSettings: "aiSettings",
- visionSettings: "visionSettings",
- aiServiceProfiles: "aiServiceProfiles",
- aiTaskRoutes: "aiTaskRoutes",
aiProviderRegistry: "aiProviderRegistry",
aiTaskAssignments: "aiTaskAssignments",
aiPreferences: "aiPreferences",
@@ -373,6 +386,11 @@ let automaticSyncScheduled = false;
let creatingOffscreenDocument = null;
let visionAnalysisInFlight = false;
const aiProviderModule = createAiProviderModule();
+const VIDEO_ANALYSIS_ADAPTERS = Object.freeze({
+ gemini: analyzeVideoWithGemini,
+ chat_completions: analyzeVideoWithChatCompletions,
+ openrouter: analyzeVideoWithOpenRouter
+});
let activePageCapture = null;
let syncInFlight = null;
let syncApplyInProgress = false;
@@ -392,7 +410,8 @@ const captureRuntime = createCaptureWorkspace({
captureDraftStorageKey: STORAGE_KEYS.captureDraft,
uiPreferencesStorageKey: STORAGE_KEYS.uiPreferences,
ensureOffscreenDocument,
- deleteVisual: deleteScreenshotBlob
+ deleteVisual: deleteScreenshotBlob,
+ resolveSourceContext: resolveCaptureSourceContext
});
chrome.runtime.onInstalled.addListener(async () => {
@@ -445,7 +464,8 @@ chrome.runtime.onConnect.addListener((port) => {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.target === "offscreen") return false;
const interaction = {
- sidePanelOpening: openCreativeResultSidePanel(message, sender)
+ sidePanelOpening: openCreativeResultSidePanel(message, sender),
+ sender
};
handleMessage(message, interaction)
.then(sendResponse)
@@ -508,11 +528,19 @@ async function handleMessage(message, interaction = {}) {
case "CANCEL_REGION_CAPTURE":
return captureRuntime.dispatch("cancel-region-capture", { sessionId: message.sessionId });
case "START_PAGE_CAPTURE":
- return enqueueCapture(async () => startPageCapture(message.mode));
+ return enqueueCapture(async () => startPageCapture(message.mode, message.targetCount));
case "CANCEL_PAGE_CAPTURE":
return cancelPageCapture(message.sessionId);
+ case "PREVIEW_PAGE_CAPTURE_REGION":
+ return previewPageCaptureRegion(message.tabId, message.marker);
+ case "CLEAR_PAGE_CAPTURE_MARKERS":
+ return clearPageCaptureMarkers(message.tabId, message.removeRegionMarkers !== false);
+ case "EDIT_PAGE_CAPTURE_REGION":
+ return editPageCaptureRegion(message.tabId, message.candidate, message.mode);
case "COMMIT_PAGE_CAPTURE":
return enqueueCapture(async () => enqueue(async () => commitPageCapture(message.batch)));
+ case "PAGE_CAPTURE_VIEWPORT_FALLBACKS":
+ return capturePageCaptureViewportFallbacks(message, interaction.sender);
case "SMART_VISUAL_SELECTION_CHANGED":
case "SMART_VISUAL_SELECTION_ENDED":
case "REGION_CAPTURE_CHANGED":
@@ -575,6 +603,8 @@ async function handleMessage(message, interaction = {}) {
return enqueue(async () => exportArchive(await readState(), message.entryIds));
case "EXPORT_PROJECT":
return enqueue(async () => exportProjectArchive(await readState(), message.collectionId));
+ case "EXPORT_CURATED_SUBMISSION":
+ return enqueue(async () => exportCuratedSubmission(await readState(), message));
case "EXPORT_CREATIVE_EXPERIMENTS":
return enqueue(async () => exportCreativeExperiments(await readState()));
case "PREVIEW_CREATIVE_EXPERIMENT_IMPORT":
@@ -587,6 +617,10 @@ async function handleMessage(message, interaction = {}) {
}));
case "APPLY_LIBRARY_IMPORT":
return enqueue(async () => applyLibraryImport(await readState(), message));
+ case "PREVIEW_CURATED_IMPORT":
+ return enqueue(async () => previewCuratedImport(await readState(), message));
+ case "APPLY_CURATED_IMPORT":
+ return enqueue(async () => applyCuratedImport(await readState(), message));
case "UPDATE_SETTINGS":
return enqueue(async () => {
const state = await readState();
@@ -605,12 +639,6 @@ async function handleMessage(message, interaction = {}) {
await commitLocalChanges({ [STORAGE_KEYS.uiPreferences]: uiPreferences });
return { ok: true, uiPreferences };
});
- case "UPDATE_AI_SETTINGS":
- case "UPDATE_AI_TEXT_PROVIDER":
- return enqueue(async () => updateAiTextProvider(message.settings));
- case "UPDATE_VISION_SETTINGS":
- case "UPDATE_AI_VISION_PROVIDER":
- return enqueue(async () => updateAiVisionProvider(message.settings));
case "UPDATE_AI_PROVIDER_CONFIGURATION":
return enqueue(async () => updateAiProviderConfiguration(message));
case "VERIFY_AI_IMAGE_GENERATION_CREDENTIAL":
@@ -618,11 +646,9 @@ async function handleMessage(message, interaction = {}) {
case "DISCOVER_AI_PROVIDER_MODELS":
return discoverAiProviderModels(message.providerId, message.force === true);
case "GET_AI_TASK_RUNTIME":
- return enqueue(async () => getAiTaskRuntime(message.taskId, message.allowUnconfigured === true));
+ return enqueue(async () => getAiTaskRuntime(message.taskId, message.allowUnconfigured === true, message.assignment));
case "GET_COMPOSER_AI_RUNTIME":
return enqueue(async () => getComposerAiRuntime());
- case "PROBE_VISION_MODELS":
- return enqueue(async () => probeVisionModels(message.settings));
case "GET_COMPOSER_SESSION":
return enqueue(async () => getComposerSession(message.sessionId));
case "START_CREATIVE_JOB":
@@ -879,43 +905,110 @@ async function captureWorkspace() {
};
}
-async function startPageCapture(mode = "loaded") {
+async function startPageCapture(mode = "loaded", targetCountValue = 0) {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab?.id || !/^https?:/iu.test(tab.url || "")) {
return { ok: false, message: "请先切换到需要采集的普通网页" };
}
+ await clearPageCaptureMarkers(tab.id, true).catch(() => undefined);
const sessionId = crypto.randomUUID();
- activePageCapture = { sessionId, tabId: tab.id };
- await chrome.runtime.sendMessage({ type: "PAGE_CAPTURE_CHANGED", sessionId, phase: mode === "whole" ? "scanning" : "starting" }).catch(() => undefined);
- let result;
+ const listMode = mode === "list";
+ const targetCount = listMode
+ ? Math.min(PAGE_CAPTURE_LIMITS.maxCandidates, Math.max(1, Math.trunc(Number(targetCountValue) || 1)))
+ : 0;
+ activePageCapture = { sessionId, tabId: tab.id, cancelled: false };
+ await chrome.runtime.sendMessage({ type: "PAGE_CAPTURE_CHANGED", sessionId, phase: mode === "whole" || listMode ? "scanning" : "starting" }).catch(() => undefined);
+ const originalUrl = tab.url;
+ let result = null;
+ let stopReason = "";
try {
- await chrome.scripting.executeScript({
- target: { tabId: tab.id },
- files: ["vendor/document-ingestion/Readability.js"]
- });
- [result] = await chrome.scripting.executeScript({
- target: { tabId: tab.id },
- func: collectPageCaptureSnapshot,
- args: [{
+ if (!listMode) {
+ result = { result: await collectPageCaptureTab(tab, {
sessionId,
- adapters: PAGE_CAPTURE_ADAPTERS,
mode: mode === "whole" ? "whole" : "loaded",
- maxCandidates: PAGE_CAPTURE_LIMITS.maxCandidates,
- maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate,
- maxScrollSteps: PAGE_CAPTURE_LIMITS.maxScrollSteps,
- maxInlinePixelDataCharacters: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters
- }]
- });
+ maxCandidates: mode === "loaded" ? PAGE_CAPTURE_QUALITY_LIMITS.maxRegionCandidates : PAGE_CAPTURE_LIMITS.maxCandidates
+ }) };
+ } else {
+ const candidates = new Map();
+ let currentTab = tab;
+ let adapter = "";
+ for (let pageIndex = 0; pageIndex < targetCount && !activePageCapture?.cancelled; pageIndex += 1) {
+ const snapshot = await collectPageCaptureTab(currentTab, { sessionId, mode: "whole", maxCandidates: targetCount });
+ if (!adapter) adapter = snapshot.adapter;
+ else if (snapshot.adapter !== adapter) {
+ stopReason = "layout-changed";
+ break;
+ }
+ const before = candidates.size;
+ for (const candidate of snapshot.candidates || []) {
+ const key = `${candidate.canonicalUrl || ""}\n${candidate.sourceFacts?.itemId || ""}\n${candidate.title || ""}`;
+ if (!candidates.has(key)) candidates.set(key, candidate);
+ if (candidates.size >= targetCount) break;
+ }
+ if (candidates.size >= targetCount) {
+ stopReason = "target-reached";
+ break;
+ }
+ const nextUrl = await findNextPageCaptureListUrl(currentTab.id, currentTab.url);
+ if (activePageCapture?.cancelled) {
+ stopReason = "cancelled";
+ break;
+ }
+ if (!nextUrl) {
+ stopReason = candidates.size === before ? "no-new-items" : "no-next-page";
+ break;
+ }
+ try {
+ await chrome.tabs.update(currentTab.id, { url: nextUrl });
+ await waitForPageCaptureTab(currentTab.id, nextUrl);
+ currentTab = await chrome.tabs.get(currentTab.id);
+ } catch {
+ stopReason = "pagination-failed";
+ break;
+ }
+ }
+ if (activePageCapture?.cancelled) stopReason = "cancelled";
+ result = { result: {
+ id: sessionId,
+ sourceUrl: originalUrl,
+ adapter,
+ candidates: [...candidates.values()].slice(0, targetCount),
+ capturedAt: new Date().toISOString()
+ } };
+ }
} finally {
+ if (listMode) {
+ try {
+ const current = await chrome.tabs.get(tab.id);
+ if (current.url !== originalUrl) {
+ await chrome.tabs.update(tab.id, { url: originalUrl });
+ await waitForPageCaptureTab(tab.id, originalUrl);
+ }
+ } catch {
+ }
+ }
activePageCapture = null;
}
const batch = normalizePageCaptureBatch({
...result?.result,
+ ...(listMode ? {
+ captureMode: "list",
+ saveMode: "",
+ targetCount,
+ stopReason: stopReason || ((result?.result?.candidates?.length || 0) >= targetCount ? "target-reached" : "no-new-items"),
+ candidates: (result?.result?.candidates || []).slice(0, targetCount)
+ } : {}),
tabId: tab.id,
status: "preview"
});
if (!batch.candidates.length) {
- return { ok: false, message: "当前网页没有识别到可保存的正文、作品或媒体" };
+ const jimengHome = /^https:\/\/jimeng\.jianying\.com\/ai-tool\/home(?:\/|$)/iu.test(tab.url);
+ return {
+ ok: false,
+ message: jimengHome
+ ? "即梦主页作品信息尚未完整取得,请刷新页面后再次扫描"
+ : "当前网页没有识别到可保存的正文、作品或媒体"
+ };
}
return {
ok: true,
@@ -924,9 +1017,187 @@ async function startPageCapture(mode = "loaded") {
};
}
+async function collectPageCaptureTab(tab, options) {
+ let siteData = await readPageCaptureSiteData(tab);
+ await chrome.scripting.executeScript({
+ target: { tabId: tab.id },
+ files: ["vendor/document-ingestion/Readability.js"]
+ });
+ const [injected] = await chrome.scripting.executeScript({
+ target: { tabId: tab.id },
+ func: collectPageCaptureSnapshot,
+ args: [{
+ sessionId: options.sessionId,
+ adapters: PAGE_CAPTURE_ADAPTERS,
+ platformAdapters: PAGE_CAPTURE_PLATFORM_ADAPTERS,
+ mode: options.mode,
+ maxCandidates: options.maxCandidates,
+ maxRegionCandidates: PAGE_CAPTURE_QUALITY_LIMITS.maxRegionCandidates,
+ maxContentTargets: PAGE_CAPTURE_QUALITY_LIMITS.maxContentTargetsPerCandidate,
+ maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate,
+ maxScrollSteps: PAGE_CAPTURE_LIMITS.maxScrollSteps,
+ maxInlinePixelDataCharacters: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters,
+ editedRegion: options.editedRegion || null,
+ siteData
+ }]
+ });
+ let snapshot = injected?.result || {};
+ if (siteData?.pageKind === "feed") {
+ siteData = await readPageCaptureSiteData(tab, { installObserver: false }) || siteData;
+ snapshot = { ...snapshot, candidates: siteData.candidates, siteStatus: siteData.completeness };
+ }
+ return addVisiblePageCaptureFallbacks(snapshot, tab);
+}
+
+async function findNextPageCaptureListUrl(tabId, currentUrlValue) {
+ try {
+ const [result] = await chrome.scripting.executeScript({
+ target: { tabId },
+ func: () => {
+ const direct = document.querySelector('a[rel~="next"]');
+ const paginationLinks = [...document.querySelectorAll('nav[aria-label*="pagination" i] a[href],[role="navigation"] a[href],[class*="pagination"] a[href]')];
+ const next = direct || paginationLinks.find((link) => /^(?:next|下一页|下页|后页|›|»|→)$/iu.test(String(link.textContent || link.getAttribute("aria-label") || link.title || "").trim()));
+ return next?.href || "";
+ }
+ });
+ const nextUrl = new URL(result?.result || "", currentUrlValue);
+ const currentUrl = new URL(currentUrlValue);
+ return nextUrl.origin === currentUrl.origin && nextUrl.href !== currentUrl.href ? nextUrl.href : "";
+ } catch {
+ return "";
+ }
+}
+
+async function waitForPageCaptureTab(tabId, expectedUrl) {
+ const current = await chrome.tabs.get(tabId);
+ if (current.status === "complete" && current.url === expectedUrl) return;
+ await new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ chrome.tabs.onUpdated.removeListener(onUpdated);
+ reject(new Error("列表翻页超时"));
+ }, PAGE_CAPTURE_LIMITS.navigationTimeoutMs);
+ const onUpdated = (updatedTabId, changeInfo, updatedTab) => {
+ if (updatedTabId !== tabId || changeInfo.status !== "complete" || updatedTab.url !== expectedUrl) return;
+ clearTimeout(timeout);
+ chrome.tabs.onUpdated.removeListener(onUpdated);
+ resolve();
+ };
+ chrome.tabs.onUpdated.addListener(onUpdated);
+ });
+}
+
+async function readPageCaptureSiteData(tab, { installObserver = true } = {}) {
+ if (!tab?.id || !/^https?:/iu.test(tab.url || "")) return null;
+ try {
+ if (installObserver) {
+ await chrome.scripting.executeScript({
+ target: { tabId: tab.id },
+ world: "MAIN",
+ func: installPageCaptureSiteObserver,
+ args: [{
+ maxCandidates: PAGE_CAPTURE_LIMITS.maxCandidates,
+ maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate
+ }]
+ });
+ }
+ const [sitePayloadResult] = await chrome.scripting.executeScript({
+ target: { tabId: tab.id },
+ world: "MAIN",
+ func: collectPageCaptureSitePayload,
+ args: [{
+ maxCandidates: PAGE_CAPTURE_LIMITS.maxCandidates,
+ maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate,
+ maxTextCharacters: PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes
+ }]
+ });
+ return normalizePageCaptureSitePayload(sitePayloadResult?.result, tab.url);
+ } catch {
+ return null;
+ }
+}
+
+async function resolveCaptureSourceContext(tab) {
+ const siteData = await readPageCaptureSiteData(tab);
+ const candidates = Array.isArray(siteData?.candidates)
+ ? siteData.candidates
+ : siteData?.sourceFacts ? [siteData] : [];
+ if (!candidates.length) return null;
+ let workId = "";
+ try {
+ const lastPart = new URL(tab.url).pathname.split("/").filter(Boolean).at(-1) || "";
+ if (/^\d{8,32}$/u.test(lastPart)) workId = lastPart;
+ } catch {
+ }
+ const candidate = candidates.find((item) => item.sourceFacts?.itemId === workId) || (candidates.length === 1 ? candidates[0] : null);
+ if (!candidate) return null;
+ return {
+ canonicalUrl: candidate.canonicalUrl,
+ displayTitle: candidate.displayTitle || candidate.title,
+ completeness: candidate.completeness,
+ sourceFacts: candidate.sourceFacts
+ };
+}
+
+async function addVisiblePageCaptureFallbacks(snapshot, tab) {
+ const positions = [];
+ const candidates = (Array.isArray(snapshot?.candidates) ? snapshot.candidates : []).map((candidate, candidateIndex) => ({
+ ...candidate,
+ media: (Array.isArray(candidate?.media) ? candidate.media : []).map((media, mediaIndex) => {
+ if (media.kind === "image" && media.fallbackRect && !media.dataUrl) positions.push({ candidateIndex, mediaIndex, selection: media.fallbackRect });
+ return media;
+ })
+ }));
+ if (!positions.length || !Number.isInteger(tab.windowId)) return { ...snapshot, candidates };
+ try {
+ const [current] = await chrome.tabs.query({ active: true, windowId: tab.windowId });
+ if (current?.id !== tab.id) return { ...snapshot, candidates };
+ const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, { format: "png" });
+ await ensureOffscreenDocument();
+ const response = await chrome.runtime.sendMessage({
+ target: "offscreen",
+ type: "CROP_PAGE_CAPTURE_PREVIEWS",
+ dataUrl,
+ selections: positions.map((item) => item.selection),
+ maxDataUrlCharacters: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters
+ });
+ if (!response?.ok || response.dataUrls?.length !== positions.length) return { ...snapshot, candidates };
+ response.dataUrls.forEach((pixelData, index) => {
+ if (!pixelData) return;
+ const position = positions[index];
+ candidates[position.candidateIndex].media[position.mediaIndex] = {
+ ...candidates[position.candidateIndex].media[position.mediaIndex],
+ dataUrl: pixelData,
+ previewDataUrl: pixelData
+ };
+ });
+ } catch {
+ }
+ return { ...snapshot, candidates };
+}
+
+async function capturePageCaptureViewportFallbacks(message, sender) {
+ if (!activePageCapture || message?.sessionId !== activePageCapture.sessionId || sender?.tab?.id !== activePageCapture.tabId) {
+ return { ok: false, message: "整页扫描会话已经结束" };
+ }
+ const selections = (Array.isArray(message?.selections) ? message.selections : []).slice(0, PAGE_CAPTURE_LIMITS.maxCandidates);
+ if (!selections.length || !Number.isInteger(sender.tab.windowId)) return { ok: true, dataUrls: [] };
+ const [activeTab] = await chrome.tabs.query({ active: true, windowId: sender.tab.windowId });
+ if (activeTab?.id !== sender.tab.id) return { ok: false, message: "扫描页面已不在前台" };
+ const dataUrl = await chrome.tabs.captureVisibleTab(sender.tab.windowId, { format: "png" });
+ await ensureOffscreenDocument();
+ return chrome.runtime.sendMessage({
+ target: "offscreen",
+ type: "CROP_PAGE_CAPTURE_PREVIEWS",
+ dataUrl,
+ selections,
+ maxDataUrlCharacters: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters
+ });
+}
+
async function cancelPageCapture(sessionIdValue) {
const sessionId = String(sessionIdValue ?? "").trim();
if (!activePageCapture || sessionId && sessionId !== activePageCapture.sessionId) return { ok: false, message: "整页扫描已经结束" };
+ activePageCapture.cancelled = true;
try {
const response = await chrome.tabs.sendMessage(activePageCapture.tabId, {
type: "PROMPTDIRECTOR_PAGE_CAPTURE", sessionId: activePageCapture.sessionId, action: "cancel"
@@ -937,9 +1208,329 @@ async function cancelPageCapture(sessionIdValue) {
}
}
+async function previewPageCaptureRegion(tabIdValue, markerValue) {
+ const tabId = Number(tabIdValue);
+ if (!Number.isInteger(tabId)) return { ok: false, message: "采集页面已经关闭" };
+ try {
+ const [result] = await chrome.scripting.executeScript({
+ target: { tabId },
+ func: renderPageCaptureRegionPreview,
+ args: [String(markerValue || "")]
+ });
+ return result?.result
+ ? { ok: true }
+ : { ok: false, message: markerValue ? "原网页区域已经变化,请重新扫描" : "区域高亮已关闭" };
+ } catch {
+ return { ok: false, message: "无法在当前网页显示区域高亮" };
+ }
+}
+
+async function clearPageCaptureMarkers(tabIdValue, removeRegionMarkers = true) {
+ const tabId = Number(tabIdValue);
+ if (!Number.isInteger(tabId)) return { ok: false, message: "采集页面已经关闭" };
+ try {
+ await chrome.scripting.executeScript({
+ target: { tabId },
+ func: clearPageCapturePageState,
+ args: [{ removeRegionMarkers, removePreview: true, removeEditor: true }]
+ });
+ return { ok: true };
+ } catch {
+ return { ok: false, message: "采集页面已经关闭或刷新" };
+ }
+}
+
+async function clearPageCaptureEditorMarkers(tabIdValue) {
+ const tabId = Number(tabIdValue);
+ if (!Number.isInteger(tabId)) return;
+ await chrome.scripting.executeScript({
+ target: { tabId },
+ func: clearPageCapturePageState,
+ args: [{ removeRegionMarkers: false, removePreview: false, removeEditor: true }]
+ });
+}
+
+function clearPageCapturePageState(optionsValue = {}) {
+ const options = optionsValue && typeof optionsValue === "object" ? optionsValue : {};
+ if (options.removePreview !== false) document.getElementById("promptdirector-page-capture-region-preview")?.remove();
+ if (options.removeEditor !== false) document.getElementById("promptdirector-page-capture-region-editor")?.remove();
+ for (const element of document.querySelectorAll("[data-promptdirector-page-edit-include],[data-promptdirector-page-edit-exclude],[data-promptdirector-page-edit-hover]")) {
+ element.removeAttribute("data-promptdirector-page-edit-include");
+ element.removeAttribute("data-promptdirector-page-edit-exclude");
+ element.removeAttribute("data-promptdirector-page-edit-hover");
+ }
+ if (options.removeRegionMarkers) {
+ for (const element of document.querySelectorAll("[data-promptdirector-capture-region]")) {
+ element.removeAttribute("data-promptdirector-capture-region");
+ }
+ }
+ return true;
+}
+
+async function editPageCaptureRegion(tabIdValue, candidateValue, modeValue) {
+ const tabId = Number(tabIdValue);
+ const candidate = normalizePageCaptureCandidate(candidateValue);
+ const mode = modeValue === "exclude" ? "exclude" : "include";
+ if (!Number.isInteger(tabId) || !candidate?.region?.marker) return { ok: false, message: "请先确认一个仍在当前网页中的主体" };
+ const token = crypto.randomUUID();
+ try {
+ const [result] = await chrome.scripting.executeScript({
+ target: { tabId },
+ func: runPageCaptureRegionEditor,
+ args: [candidate.region.marker, mode, token, candidate.region.edits || [], candidate.region.contentTargets || []]
+ });
+ if (!result?.result?.ok) return result?.result || { ok: false, message: "网页区域修正已取消" };
+ if (!result.result.changed) return { ok: false, cancelled: true, message: "没有修改主体区域" };
+ const tab = await chrome.tabs.get(tabId);
+ const snapshot = await collectPageCaptureTab(tab, {
+ sessionId: `edit:${token}`,
+ mode: "loaded",
+ maxCandidates: 1,
+ editedRegion: { marker: candidate.region.marker, token, region: { ...candidate.region, edits: result.result.edits || [] } }
+ });
+ const revised = snapshot.candidates?.[0];
+ if (!revised) return { ok: false, message: "修正后的区域没有可保存内容,原结果保持不变" };
+ return {
+ ok: true,
+ candidate: mergePageCaptureRegionEdit(candidate, revised),
+ message: mode === "include" ? "已加入遗漏区域并重建文章预览" : "已排除错误区域并重建文章预览"
+ };
+ } catch (error) {
+ return { ok: false, message: userMessage(error) || "无法修正当前网页区域" };
+ } finally {
+ await clearPageCaptureEditorMarkers(tabId).catch(() => undefined);
+ }
+}
+
+function runPageCaptureRegionEditor(markerValue, modeValue, tokenValue, priorEditsValue, contentTargetsValue) {
+ const overlayId = "promptdirector-page-capture-region-editor";
+ document.getElementById(overlayId)?.remove();
+ const marker = String(markerValue || "");
+ const mode = modeValue === "exclude" ? "exclude" : "include";
+ const token = String(tokenValue || "");
+ const baseRoot = [...document.querySelectorAll("[data-promptdirector-capture-region]")]
+ .find((element) => element.getAttribute("data-promptdirector-capture-region") === marker);
+ if (!baseRoot || !token) return { ok: false, message: "原网页区域已经变化,请重新扫描" };
+ const includeAttribute = "data-promptdirector-page-edit-include";
+ const excludeAttribute = "data-promptdirector-page-edit-exclude";
+ const hoverAttribute = "data-promptdirector-page-edit-hover";
+ const priorEdits = (Array.isArray(priorEditsValue) ? priorEditsValue : []).filter((edit) => ["include", "exclude"].includes(edit?.mode) && typeof edit?.path === "string");
+ const contentTargets = (Array.isArray(contentTargetsValue) ? contentTargetsValue : []).filter((target) =>
+ typeof target?.path === "string" && ["text", "image", "video", "document", "group"].includes(target?.kind));
+ let edits = priorEdits.map((edit) => ({ mode: edit.mode, path: edit.path }));
+ let groupMode = false;
+ const root = document.createElement("div");
+ root.id = overlayId;
+ root.setAttribute("role", "dialog");
+ root.setAttribute("aria-label", mode === "include" ? "添加遗漏区域" : "排除错误区域");
+ Object.assign(root.style, {
+ position: "fixed", left: "16px", right: "16px", top: "16px", zIndex: "2147483647",
+ display: "flex", alignItems: "center", gap: "8px", padding: "10px 12px",
+ border: "1px solid rgba(255,255,255,.22)", borderRadius: "10px", color: "#fff",
+ background: "rgba(18,20,22,.96)", boxShadow: "0 12px 40px rgba(0,0,0,.42)",
+ font: "600 13px/1.4 -apple-system,BlinkMacSystemFont,sans-serif"
+ });
+ const copy = document.createElement("span");
+ copy.style.flex = "1";
+ copy.textContent = mode === "include"
+ ? "添加遗漏:点击正文、图片、视频或下载区,可连续选择"
+ : "排除错误:点击主体内不需要的段落、图片或区域,可连续选择";
+ const count = document.createElement("span");
+ const makeButton = (label) => {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.textContent = label;
+ Object.assign(button.style, { border: "1px solid rgba(255,255,255,.25)", borderRadius: "7px", padding: "6px 10px", color: "#fff", background: "rgba(255,255,255,.1)", cursor: "pointer" });
+ return button;
+ };
+ const undo = makeButton("撤销");
+ const group = makeButton("整组选择");
+ const cancel = makeButton("取消");
+ const finish = makeButton("完成");
+ finish.style.background = "#86a31d";
+ root.append(copy, count, group, undo, cancel, finish);
+ const style = document.createElement("style");
+ style.textContent = `[${includeAttribute}="${token}"]{outline:4px solid #8fcf3a!important;outline-offset:3px!important}[${excludeAttribute}="${token}"]{outline:4px solid #ff6b5f!important;outline-offset:3px!important;opacity:.48!important}[${hoverAttribute}="${token}"]{outline:3px dashed #ffd65c!important;outline-offset:2px!important}`;
+ root.append(style);
+ document.documentElement.append(root);
+ baseRoot.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" });
+ const changes = [];
+ const targetSelector = "img,video,iframe,a[download],a[href$='.pdf' i],a[href$='.md' i],a[href$='.txt' i],a[href$='.rtf' i],h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,table,figure,article,section,div";
+ const updateCount = () => {
+ count.textContent = `本次修改 ${changes.length} 处`;
+ undo.disabled = !changes.length;
+ };
+ const elementPath = (element) => {
+ const parts = [];
+ let current = element;
+ while (current && current.nodeType === 1) {
+ const tag = current.tagName.toLocaleLowerCase("en-US");
+ const siblings = [...(current.parentElement?.children || [])].filter((item) => item.tagName === current.tagName);
+ parts.unshift(`${tag}:nth-of-type(${Math.max(1, siblings.indexOf(current) + 1)})`);
+ if (current === document.body) break;
+ current = current.parentElement;
+ }
+ return parts.join(" > ");
+ };
+ const applyEdits = () => {
+ document.querySelectorAll(`[${includeAttribute}],[${excludeAttribute}]`).forEach((element) => {
+ element.removeAttribute(includeAttribute);
+ element.removeAttribute(excludeAttribute);
+ });
+ for (const edit of edits) {
+ let element = null;
+ try { element = document.querySelector(edit.path); } catch { continue; }
+ if (!element) continue;
+ element.removeAttribute(edit.mode === "include" ? excludeAttribute : includeAttribute);
+ element.setAttribute(edit.mode === "include" ? includeAttribute : excludeAttribute, token);
+ }
+ };
+ const resolvedTargets = contentTargets.flatMap((target) => {
+ try {
+ const element = document.querySelector(target.path);
+ return element ? [{ ...target, element }] : [];
+ } catch {
+ return [];
+ }
+ });
+ const elementDepth = (element) => {
+ let depth = 0;
+ for (let current = element; current?.parentElement; current = current.parentElement) depth += 1;
+ return depth;
+ };
+ const meaningfulFallback = (eventTarget) => {
+ const closest = eventTarget.closest?.(targetSelector);
+ if (!closest) return null;
+ if (!closest.matches?.("div")) return closest;
+ const text = String(closest.innerText || closest.textContent || "").replace(/\s+/gu, " ").trim();
+ const hasMediaOrResource = Boolean(closest.querySelector?.("img,video,iframe,a[download],a[href$='.pdf' i],a[href$='.md' i],a[href$='.txt' i],a[href$='.rtf' i]"));
+ const hasDirectText = [...(closest.childNodes || [])].some((node) => node.nodeType === 3 && String(node.textContent || "").trim());
+ return hasDirectText || hasMediaOrResource || text ? closest : null;
+ };
+ const cleanup = (restore) => {
+ document.removeEventListener("click", onClick, true);
+ document.removeEventListener("keydown", onKeydown, true);
+ document.removeEventListener("pointerover", onPointerOver, true);
+ if (restore) {
+ edits = priorEdits.map((edit) => ({ mode: edit.mode, path: edit.path }));
+ applyEdits();
+ }
+ root.remove();
+ };
+ const targetFor = (eventTarget) => {
+ if (!(eventTarget instanceof Element)) return null;
+ const matching = resolvedTargets.filter((target) => target.element === eventTarget || target.element.contains?.(eventTarget));
+ const leaf = matching.filter((target) => target.kind !== "group").sort((left, right) => elementDepth(right.element) - elementDepth(left.element))[0];
+ const selectedTarget = groupMode
+ ? matching.filter((target) => target.kind === "group" && (!leaf?.groupId || target.id === leaf.groupId))
+ .sort((left, right) => elementDepth(right.element) - elementDepth(left.element))[0]
+ : leaf;
+ const element = selectedTarget?.element || meaningfulFallback(eventTarget);
+ if (!element || root.contains(element) || element.closest("nav,header,footer,[role=navigation],[role=banner],[role=contentinfo]")) return null;
+ if (mode === "exclude" && (!baseRoot.contains(element) || element === baseRoot)) return null;
+ if (mode === "include" && baseRoot.contains(element) && element.getAttribute(excludeAttribute) !== token) return null;
+ return element;
+ };
+ const onPointerOver = (event) => {
+ document.querySelectorAll(`[${hoverAttribute}]`).forEach((element) => element.removeAttribute(hoverAttribute));
+ const element = targetFor(event.target);
+ if (element) element.setAttribute(hoverAttribute, token);
+ };
+ const onClick = (event) => {
+ const element = targetFor(event.target);
+ if (!element) return;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ const edit = { mode, path: elementPath(element) };
+ edits.push(edit);
+ changes.push(edit);
+ applyEdits();
+ updateCount();
+ };
+ const onKeydown = (event) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ cancel.click();
+ };
+ document.addEventListener("click", onClick, true);
+ document.addEventListener("keydown", onKeydown, true);
+ document.addEventListener("pointerover", onPointerOver, true);
+ applyEdits();
+ updateCount();
+ return new Promise((resolve) => {
+ group.addEventListener("click", (event) => {
+ event.stopPropagation();
+ groupMode = !groupMode;
+ group.textContent = groupMode ? "整组选择:开" : "整组选择";
+ group.style.background = groupMode ? "#5f7613" : "rgba(255,255,255,.1)";
+ });
+ undo.addEventListener("click", (event) => {
+ event.stopPropagation();
+ if (changes.pop()) edits.pop();
+ applyEdits();
+ updateCount();
+ });
+ cancel.addEventListener("click", (event) => {
+ event.stopPropagation();
+ cleanup(true);
+ resolve({ ok: false, cancelled: true, message: "网页区域修正已取消" });
+ });
+ finish.addEventListener("click", (event) => {
+ event.stopPropagation();
+ const changed = changes.length > 0;
+ cleanup(false);
+ resolve({ ok: true, changed, token, edits });
+ });
+ });
+}
+
+function renderPageCaptureRegionPreview(markerValue) {
+ const overlayId = "promptdirector-page-capture-region-preview";
+ document.getElementById(overlayId)?.remove();
+ const marker = String(markerValue || "");
+ if (!marker) return true;
+ const target = [...document.querySelectorAll("[data-promptdirector-capture-region]")]
+ .find((element) => element.getAttribute("data-promptdirector-capture-region") === marker);
+ if (!target) return false;
+ target.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" });
+ const rect = target.getBoundingClientRect();
+ const overlay = document.createElement("div");
+ overlay.id = overlayId;
+ overlay.setAttribute("aria-hidden", "true");
+ Object.assign(overlay.style, {
+ position: "fixed",
+ left: `${Math.max(0, rect.left)}px`,
+ top: `${Math.max(0, rect.top)}px`,
+ width: `${Math.max(1, Math.min(window.innerWidth, rect.right) - Math.max(0, rect.left))}px`,
+ height: `${Math.max(1, Math.min(window.innerHeight, rect.bottom) - Math.max(0, rect.top))}px`,
+ border: "3px solid Highlight",
+ borderRadius: "8px",
+ background: "color-mix(in srgb, Highlight 12%, transparent)",
+ boxSizing: "border-box",
+ pointerEvents: "none",
+ zIndex: "2147483647"
+ });
+ document.documentElement.append(overlay);
+ return true;
+}
+
async function commitPageCapture(batchValue) {
- const batch = normalizePageCaptureBatch(batchValue);
- const selected = applyPageCaptureSelections(batch);
+ let batch = normalizePageCaptureBatch(batchValue);
+ if (Number.isInteger(batch.tabId) && batch.candidates.some((candidate) => candidate.media.some((media) => media.fallbackRect && !media.dataUrl))) {
+ try {
+ const tab = await chrome.tabs.get(batch.tabId);
+ batch = normalizePageCaptureBatch(await addVisiblePageCaptureFallbacks(batch, tab));
+ } catch {
+ }
+ }
+ let selected = applyPageCaptureSelections(batch);
+ if (batch.captureMode === "list" && batch.saveMode === "combined" && selected.length) {
+ const combined = combinePageCaptureCandidates(selected, {
+ title: batch.combinedTitle,
+ canonicalUrl: batch.sourceUrl
+ });
+ selected = combined ? [combined] : [];
+ }
if (!selected.length) return { ok: false, message: "请至少选择一项网页内容" };
const state = await readState();
const results = [];
@@ -955,66 +1546,135 @@ async function commitPageCapture(batchValue) {
continue;
}
const mediaAssets = [];
+ const articleAssetIds = new Map();
const warnings = [];
for (const media of candidate.media) {
+ if (media.kind === "document") {
+ if (!isSupportedDocumentMimeType(media.mimeType)) {
+ warnings.push(`${media.filename || media.alt || media.url}:已保留来源链接,未知或高风险文件不会自动下载`);
+ continue;
+ }
+ const assetId = crypto.randomUUID();
+ try {
+ const blob = await fetchBoundedMedia(media.url, {
+ kind: "document",
+ expectedMimeType: media.mimeType,
+ maxBytes: PORTABLE_LIBRARY_LIMITS.maxFileBytes,
+ timeoutMs: 60_000,
+ accept: "application/pdf,text/markdown,text/plain,text/html,application/rtf,text/rtf,application/x-rtf"
+ });
+ const contentHash = await sha256Blob(blob);
+ const existing = entries.flatMap(entryMediaAssets).find((asset) => asset.contentHash === contentHash);
+ if (existing) {
+ if (!mediaAssets.some((asset) => asset.id === existing.id)) mediaAssets.push(existing);
+ articleAssetIds.set(media.id, existing.id);
+ warnings.push(`已复用重复文档:${media.filename || media.alt || media.url}`);
+ continue;
+ }
+ await saveMediaBlob(assetId, blob);
+ savedAssetIds.push(assetId);
+ const documentAsset = {
+ id: assetId,
+ kind: "document",
+ storageMode: "managed",
+ sourceUrl: media.url,
+ sourceTitle: media.filename || media.sourceTitle || media.alt || candidate.title,
+ sourceAuthor: media.sourceAuthor || candidate.sourceFacts.author,
+ originalWorkUrl: media.originalWorkUrl || candidate.canonicalUrl,
+ mimeType: blob.type,
+ byteSize: blob.size,
+ contentHash,
+ extractedTextFormat: ["text/markdown", "text/html", "application/rtf", "text/rtf", "application/x-rtf"].includes(blob.type) ? "markdown" : "plain",
+ capturedAt: new Date().toISOString(),
+ reviewStatus: "verified"
+ };
+ mediaAssets.push(documentAsset);
+ articleAssetIds.set(media.id, documentAsset.id);
+ } catch (error) {
+ warnings.push(`${media.filename || media.alt || media.url}:本地副本未保存,已保留来源链接(${userMessage(error)})`);
+ }
+ continue;
+ }
if (media.kind === "video") {
const referenceUrl = media.url || candidate.canonicalUrl;
const provider = detectMediaReferenceProvider(referenceUrl);
const playbackMode = ["youtube", "vimeo", "bilibili", "douyin", "x"].includes(provider) ? "embed" : "source";
- mediaAssets.push({
+ const videoAsset = {
id: crypto.randomUUID(),
kind: "video",
storageMode: "reference",
sourceUrl: referenceUrl,
- sourceTitle: candidate.title,
+ sourceTitle: media.sourceTitle || candidate.title,
+ sourceAuthor: media.sourceAuthor || candidate.sourceFacts.author,
+ originalWorkUrl: media.originalWorkUrl || candidate.canonicalUrl,
width: media.width,
height: media.height,
capturedAt: new Date().toISOString(),
playbackCapability: playbackMode === "embed" ? "embedded" : "external",
reference: { url: referenceUrl, provider, playbackMode },
reviewStatus: "verified"
- });
+ };
+ mediaAssets.push(videoAsset);
+ articleAssetIds.set(media.id, videoAsset.id);
continue;
}
const assetId = crypto.randomUUID();
try {
- const blob = media.dataUrl
- ? await dataUrlToImageBlob(media.dataUrl)
- : await fetchBoundedMedia(media.url, {
+ const resolved = await resolvePageCaptureImage(media, {
+ sessionMediaAllowed: batch.sessionMediaAllowed,
+ fetchMedia: async (url) => {
+ let metadata = null;
+ const blob = await fetchBoundedMedia(url, {
kind: "image",
maxBytes: PORTABLE_LIBRARY_LIMITS.maxImageBytes,
+ maxPixels: PORTABLE_LIBRARY_LIMITS.maxImagePixels,
timeoutMs: 60_000,
- accept: "image/avif,image/webp,image/png,image/jpeg,image/gif"
+ accept: "image/avif,image/webp,image/png,image/jpeg,image/gif",
+ onMetadata: (value) => { metadata = value; }
});
+ return { blob, metadata };
+ },
+ fetchSessionMedia: async (url) => fetchSelectedPageSessionImage(batch, candidate, url),
+ decodeDataUrl: dataUrlToImageBlob
+ });
+ const blob = resolved.blob;
const contentHash = await sha256Blob(blob);
const existing = entries.flatMap(entryMediaAssets).find((asset) => asset.contentHash === contentHash);
if (existing) {
- warnings.push(`已跳过重复媒体:${media.alt || media.url}`);
+ if (!mediaAssets.some((asset) => asset.id === existing.id)) mediaAssets.push(existing);
+ articleAssetIds.set(media.id, existing.id);
+ warnings.push(`已复用重复媒体:${media.alt || media.url}`);
continue;
}
await saveMediaBlob(assetId, blob);
savedAssetIds.push(assetId);
- mediaAssets.push({
+ const imageAsset = {
id: assetId,
kind: "image",
storageMode: "managed",
- sourceUrl: media.url || candidate.canonicalUrl,
- sourceTitle: media.alt || candidate.title,
+ sourceUrl: resolved.sourceUrl || media.url || candidate.canonicalUrl,
+ sourceTitle: media.sourceTitle || media.alt || candidate.title,
+ sourceAuthor: media.sourceAuthor || candidate.sourceFacts.author,
+ originalWorkUrl: media.originalWorkUrl || candidate.canonicalUrl,
mimeType: blob.type,
byteSize: blob.size,
- width: media.width,
- height: media.height,
+ width: resolved.metadata?.width || media.width,
+ height: resolved.metadata?.height || media.height,
contentHash,
- captureMethod: media.captureMethod,
+ captureMethod: resolved.captureMethod || media.captureMethod,
capturedAt: new Date().toISOString(),
reviewStatus: "verified"
- });
+ };
+ mediaAssets.push(imageAsset);
+ articleAssetIds.set(media.id, imageAsset.id);
+ if (resolved.usedPixelFallback) warnings.push(`${media.alt || candidate.title}:原图不可用,已保存页面可见画面`);
} catch (error) {
warnings.push(`${media.alt || media.url}:${userMessage(error)}`);
}
}
+ const articleText = articleDocumentText(candidate.articleDocument);
const base = buildEntry({
- text: candidate.contentText || candidate.excerpt,
+ text: articleText || candidate.contentText || candidate.excerpt,
title: candidate.title,
url: candidate.canonicalUrl,
allowEmptyText: mediaAssets.length > 0
@@ -1023,14 +1683,16 @@ async function commitPageCapture(batchValue) {
results.push({ candidateId: candidate.id, status: "failed", title: candidate.title, warnings: [...warnings, "没有可保存的正文或媒体"] });
continue;
}
+ const classificationMediaAssets = candidate.sourceFacts.pageType === "post" && base.text ? [] : mediaAssets;
const entry = normalizeEntryMedia({
...base,
schemaVersion: SCHEMA_VERSION,
+ articleDocument: finalizeArticleDocumentAssets(candidate.articleDocument, articleAssetIds),
sourceFacts: candidate.sourceFacts,
sourcePages: [{ url: candidate.canonicalUrl, title: candidate.title }],
mediaAssets,
primaryMediaId: mediaAssets.find((asset) => asset.kind === "image")?.id || mediaAssets[0]?.id || "",
- classification: classifyContent({ ...base, mediaAssets }, state.classificationRules, state.taxonomy),
+ classification: classifyContent({ ...base, mediaAssets: classificationMediaAssets }, state.classificationRules, state.taxonomy),
customLabels: [], metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
});
@@ -1065,6 +1727,88 @@ async function commitPageCapture(batchValue) {
}
}
+async function fetchSelectedPageSessionImage(batch, candidate, value) {
+ if (!Number.isInteger(batch?.tabId)) throw new Error("原网页标签页已经不可用");
+ const tab = await chrome.tabs.get(batch.tabId);
+ let currentOrigin;
+ let capturedOrigin;
+ try {
+ currentOrigin = new URL(tab.url).origin;
+ capturedOrigin = new URL(batch.sourceUrl || candidate.canonicalUrl).origin;
+ } catch {
+ throw new Error("原网页地址已经不可用");
+ }
+ if (currentOrigin !== capturedOrigin) throw new Error("原网页已经跳转,未使用页面登录状态读取媒体");
+ const allowedUrls = pageCaptureMediaFetchCandidatesForSession(candidate, value);
+ if (!allowedUrls.includes(value)) throw new Error("页面媒体地址不在已选择内容中");
+ const token = crypto.randomUUID();
+ try {
+ const [preparedResult] = await chrome.scripting.executeScript({
+ target: { tabId: batch.tabId },
+ world: "MAIN",
+ func: preparePageSessionMedia,
+ args: [{
+ token,
+ url: value,
+ allowedUrls,
+ maxBytes: PORTABLE_LIBRARY_LIMITS.maxImageBytes,
+ chunkBytes: PAGE_SESSION_MEDIA_CHUNK_BYTES
+ }]
+ });
+ const prepared = preparedResult?.result;
+ if (!prepared || prepared.token !== token || !Number.isSafeInteger(prepared.chunkCount) || prepared.chunkCount <= 0) {
+ throw new Error("页面没有返回有效媒体");
+ }
+ const chunks = [];
+ let totalBytes = 0;
+ for (let index = 0; index < prepared.chunkCount; index += 1) {
+ const [chunkResult] = await chrome.scripting.executeScript({
+ target: { tabId: batch.tabId },
+ world: "MAIN",
+ func: readPageSessionMediaChunk,
+ args: [{ token, index }]
+ });
+ const binary = globalThis.atob(String(chunkResult?.result || ""));
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
+ totalBytes += bytes.byteLength;
+ if (totalBytes > PORTABLE_LIBRARY_LIMITS.maxImageBytes) throw new Error("页面媒体超过本地容量上限");
+ chunks.push(bytes);
+ }
+ if (totalBytes !== prepared.totalBytes) throw new Error("页面媒体传输不完整");
+ const combined = new Uint8Array(totalBytes);
+ let offset = 0;
+ for (const chunk of chunks) {
+ combined.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ let metadata = null;
+ const blob = await boundedMediaBlobFromResponse(new Response(combined, {
+ headers: { "content-type": String(prepared.contentType || "application/octet-stream") }
+ }), {
+ kind: "image",
+ maxBytes: PORTABLE_LIBRARY_LIMITS.maxImageBytes,
+ maxPixels: PORTABLE_LIBRARY_LIMITS.maxImagePixels,
+ onMetadata: (value) => { metadata = value; }
+ });
+ return { blob, metadata };
+ } finally {
+ await chrome.scripting.executeScript({
+ target: { tabId: batch.tabId },
+ world: "MAIN",
+ func: discardPageSessionMedia,
+ args: [{ token }]
+ }).catch(() => undefined);
+ }
+}
+
+function pageCaptureMediaFetchCandidatesForSession(candidate, selectedUrl) {
+ const urls = new Set();
+ for (const media of candidate?.media || []) {
+ for (const url of pageCaptureMediaFetchCandidates(media)) urls.add(url);
+ }
+ return urls.has(selectedUrl) ? [...urls] : [];
+}
+
async function startCaptureForCase(caseId, partEntryId = "") {
const current = await captureRuntime.getDraft();
if (current.fragments.length || current.visuals.length || current.targetCaseId) {
@@ -1332,13 +2076,15 @@ async function commitCaptureDraft(duplicateAction = "") {
.find((compound) => compound.id === draft.targetCaseId) ?? null;
if (targetCompound) return commitCaptureIntoCompound(draft, draftParts(draft), state, targetCompound);
const text = draftText(draft);
- const sourcePages = mergeSourcePages(draftSourcePages(draft), draft.visuals.map((visual) => ({
- url: visual.sourceUrl,
- title: visual.sourceTitle
- })));
+ const sourcePages = mergeSourcePages(draftSourcePages(draft), draft.visuals.map((visual) => {
+ const context = sourceContextForUrl(draft, visual.sourceUrl);
+ return { url: visual.sourceUrl, title: context?.displayTitle || visual.sourceTitle };
+ }));
const firstVisual = draft.visuals[0];
const sourceUrl = sourcePages[0]?.url || firstVisual?.sourceUrl || "";
- const sourceTitle = draft.title || sourcePages[0]?.title || firstVisual?.sourceTitle || "未命名案例";
+ const sourceContext = sourceContextForUrl(draft, sourceUrl);
+ const sourceFacts = sourceFactsForCaptureContext(sourceContext);
+ const sourceTitle = draft.title || sourceContext?.displayTitle || sourcePages[0]?.title || firstVisual?.sourceTitle || "未命名案例";
const candidateBase = buildEntry({ text, title: sourceTitle, url: sourceUrl, allowEmptyText: draft.visuals.length > 0 });
const explicitTarget = draft.targetCaseId
? state.entries.find((entryValue) => entryValue.id === draft.targetCaseId) ?? null
@@ -1357,6 +2103,7 @@ async function commitCaptureDraft(duplicateAction = "") {
entry = {
...markEntryTextChanged(entry, nextText),
sourcePages: mergeSourcePages(entry.sourcePages, sourcePages),
+ ...(sourceFacts ? { sourceFacts } : {}),
customLabels: draft.customLabelsExplicit ? uniqueNames(draft.customLabels) : uniqueNames(entry.customLabels)
};
if (draft.contentTypeExplicit && isValidContentPath(state.taxonomy, [draft.contentTypeId])) {
@@ -1376,6 +2123,7 @@ async function commitCaptureDraft(duplicateAction = "") {
schemaVersion: SCHEMA_VERSION,
title: sourceTitle,
sourcePages,
+ ...(sourceFacts ? { sourceFacts } : {}),
visuals: draft.visuals,
primaryVisualId: draft.primaryVisualId,
classification: draft.contentTypeExplicit && isValidContentPath(state.taxonomy, [draft.contentTypeId])
@@ -1477,6 +2225,7 @@ function mergeCapturePartIntoEntry(entryValue, part, draft, state) {
entry = {
...markEntryTextChanged(entry, nextText),
sourcePages: mergeSourcePages(entry.sourcePages, [{ url: part.sourceUrl, title: part.sourceTitle }]),
+ ...(sourceFactsForCaptureContext(part.sourceContext) ? { sourceFacts: sourceFactsForCaptureContext(part.sourceContext) } : {}),
customLabels: draft.customLabelsExplicit ? uniqueNames(draft.customLabels) : uniqueNames(entry.customLabels)
};
if (draft.contentTypeExplicit && isValidContentPath(state.taxonomy, [draft.contentTypeId])) {
@@ -1499,6 +2248,7 @@ function createEntryFromCapturePart(part, draft, state, options = {}) {
...base,
schemaVersion: SCHEMA_VERSION,
sourcePages: mergeSourcePages([], [{ url: part.sourceUrl, title: part.sourceTitle }]),
+ ...(sourceFactsForCaptureContext(part.sourceContext) ? { sourceFacts: sourceFactsForCaptureContext(part.sourceContext) } : {}),
visuals: part.visuals,
primaryVisualId: part.visuals.some((visual) => visual.id === draft.primaryVisualId)
? draft.primaryVisualId
@@ -1513,6 +2263,12 @@ function createEntryFromCapturePart(part, draft, state, options = {}) {
});
}
+function sourceFactsForCaptureContext(context) {
+ const facts = context?.sourceFacts;
+ if (!facts || typeof facts !== "object" || !String(facts.provider || facts.itemId || facts.author || "").trim()) return null;
+ return facts;
+}
+
function captureDraftClassification(draft, state) {
const text = draftText(draft);
const firstSource = draftSourcePages(draft)[0];
@@ -1761,12 +2517,6 @@ async function readState() {
stored[STORAGE_KEYS.aiTaskAssignments] = aiConfiguration.assignments;
stored[STORAGE_KEYS.aiPreferences] = aiConfiguration.preferences;
}
- if ([STORAGE_KEYS.aiSettings, STORAGE_KEYS.visionSettings, STORAGE_KEYS.aiServiceProfiles, STORAGE_KEYS.aiTaskRoutes]
- .some((key) => Object.hasOwn(stored, key))) {
- await chrome.storage.local.remove([
- STORAGE_KEYS.aiSettings, STORAGE_KEYS.visionSettings, STORAGE_KEYS.aiServiceProfiles, STORAGE_KEYS.aiTaskRoutes
- ]);
- }
const shouldMigrate = needsMigration(stored);
const migration = shouldMigrate ? migrateLibraryState(stored) : null;
let state = migration?.state ?? {
@@ -1848,7 +2598,6 @@ async function readState() {
aiSettings: publicAiSettings(aiRuntime.aiSettings),
visionSettings: publicVisionSettings(aiRuntime.visionSettings),
aiServiceProfiles: publicAiServiceProfiles(aiRuntime.aiServiceProfiles),
- aiTaskRoutes: aiRuntime.aiTaskRoutes,
aiProviderRegistry: publicAiProviderRegistry(aiConfiguration.registry),
aiTaskAssignments: aiConfiguration.assignments,
composerSettings: normalizeComposerSettings(stored[STORAGE_KEYS.composerSettings]),
@@ -2015,7 +2764,7 @@ async function creativeJobExecutionState() {
compoundCases: stored[STORAGE_KEYS.compoundCases],
facetCatalog: stored[STORAGE_KEYS.facetCatalog],
composerSettings: stored[STORAGE_KEYS.composerSettings],
- aiSettings: resolveTextTaskSettings("creativePlanning", aiConfigurationFromStorage(stored)),
+ aiSettings: aiRuntime.aiSettings,
visionSettings: aiRuntime.visionSettings,
aiServiceProfiles: aiRuntime.aiServiceProfiles,
aiTaskAssignments: aiRuntime.aiTaskAssignments
@@ -2203,7 +2952,7 @@ async function rememberObservedReferenceLimit(value) {
const configuration = await loadAiConfiguration();
const assignment = configuration.assignments.imageGeneration;
const profile = configuration.registry.providers[assignment?.providerId];
- const modelId = String(profile?.models?.imageGeneration ?? assignment?.model ?? "").trim();
+ const modelId = String(assignment?.model ?? "").trim();
if (!profile || !modelId) return;
const before = profile.discoveredModels.find((model) => model.id === modelId);
const descriptor = {
@@ -3407,16 +4156,30 @@ async function discoverAiProviderModels(providerIdValue, force = false) {
const profile = configuration.registry.providers[providerId];
if (!profile) throw new Error("没有找到要刷新的 AI 厂商");
if (!profile.endpoint || !profile.apiKey) throw new Error(`${profile.label} 需要先保存接口地址和 API Key`);
- const result = await aiProviderModule.discoverModels(profile, {
- etag: force ? "" : profile.discovery?.etag
- });
+ let result;
+ try {
+ result = await aiProviderModule.discoverModels(profile, {
+ etag: force ? "" : profile.discovery?.etag
+ });
+ } catch (error) {
+ const visibleError = discoveryErrorMessage(error, profile.apiKey);
+ await enqueue(async () => {
+ const current = await loadAiConfiguration();
+ const currentProfile = current.registry.providers[providerId];
+ if (!sameProviderConnection(currentProfile, profile)) return;
+ const registry = mergeAiProviderRegistry(current.registry, { providers: {
+ [providerId]: {
+ discovery: { ...currentProfile.discovery, error: visibleError }
+ }
+ } });
+ await persistAiConfiguration({ ...current, registry });
+ });
+ throw new Error(visibleError, { cause: error });
+ }
return enqueue(async () => {
const current = await loadAiConfiguration();
const currentProfile = current.registry.providers[providerId];
- if (!currentProfile
- || currentProfile.endpoint !== profile.endpoint
- || currentProfile.protocol !== profile.protocol
- || currentProfile.apiKey !== profile.apiKey) {
+ if (!sameProviderConnection(currentProfile, profile)) {
throw new Error(`${profile.label} 的连接已在模型读取期间变更,请重新刷新`);
}
const registry = mergeAiProviderRegistry(current.registry, { providers: {
@@ -3437,105 +4200,22 @@ async function discoverAiProviderModels(providerIdValue, force = false) {
});
}
-async function updateAiTextProvider(value = {}) {
- const current = await loadAiConfiguration();
- const { settings, credentialReset } = mergeAiSettings(projectAiRuntime(current).aiSettings, value);
- const providerId = settings.activeProvider === "compatible" ? "custom-text" : "deepseek";
- const source = settings.activeProvider === "compatible" ? settings.compatible : settings;
- const registry = mergeAiProviderRegistry(current.registry, { providers: {
- [providerId]: {
- endpoint: settings.activeProvider === "compatible" ? source.endpoint : "https://api.deepseek.com/chat/completions",
- protocol: "chat_completions",
- apiKey: source.apiKey,
- clearApiKey: value.clearApiKey === (settings.activeProvider === "compatible" ? "compatible" : "deepseek"),
- consent: settings.consent,
- models: { textTags: settings.activeProvider === "compatible" ? source.model : settings.analysisModel }
- }
- } });
- const configuration = {
- registry,
- assignments: normalizeAiTaskAssignments({
- ...current.assignments,
- textTags: { providerId, model: settings.activeProvider === "compatible" ? source.model : settings.analysisModel }
- }, registry),
- preferences: normalizeAiPreferences({
- ...current.preferences,
- textInstructionsByLocale: settings.analysisInstructionsByLocale
- })
- };
- await persistAiConfiguration(configuration);
- return aiConfigurationResponse(configuration, credentialReset
- ? "兼容接口域名已变更;旧 API Key 未沿用,请重新填写新服务的 Key"
- : "文字标签服务已保存");
+function sameProviderConnection(current, requested) {
+ return Boolean(current
+ && current.endpoint === requested.endpoint
+ && current.protocol === requested.protocol
+ && current.apiKey === requested.apiKey);
}
-async function updateAiVisionProvider(value = {}) {
- const current = await loadAiConfiguration();
- const { settings, credentialReset } = mergeVisionSettings(projectAiRuntime(current).visionSettings, value);
- permissionPatternForVisionSettings(settings);
- if (!settings[settings.activeProvider].model) throw new Error("请填写所选图片服务的模型名称");
- const providerId = settings.activeProvider === "compatible" ? "custom-media" : "openai";
- const clear = String(value.clearApiKey ?? "");
- const registry = mergeAiProviderRegistry(current.registry, { providers: {
- openai: {
- endpoint: "https://api.openai.com/v1/responses",
- apiKey: settings.openai.apiKey,
- clearApiKey: clear === "openai",
- consent: settings.consent,
- models: {
- imageAnalysis: settings.openai.model,
- videoGeneration: settings.openai.videoGeneration.model
- },
- videoGeneration: settings.openai.videoGeneration
- },
- "custom-media": {
- endpoint: settings.compatible.endpoint,
- protocol: settings.compatible.protocol,
- apiKey: settings.compatible.apiKey,
- clearApiKey: clear === "compatible",
- consent: settings.consent,
- models: {
- imageAnalysis: settings.compatible.model,
- imageGeneration: settings.compatible.imageGeneration.model
- },
- imageGeneration: {
- ...settings.compatible.imageGeneration,
- apiKey: clear === "compatible_image" ? "" : settings.compatible.imageGeneration.apiKey
- }
- }
- } });
- const assignments = { ...current.assignments, imageAnalysis: {
- providerId,
- model: providerId === "openai" ? settings.openai.model : settings.compatible.model
- } };
- for (const taskId of ["imageGeneration", "videoGeneration"]) {
- if (assignments[taskId]?.providerId === providerId) {
- assignments[taskId] = { ...assignments[taskId], model: registry.providers[providerId]?.models?.[taskId] };
- }
- }
- const configuration = {
- registry,
- assignments: normalizeAiTaskAssignments(assignments, registry),
- preferences: normalizeAiPreferences({
- ...current.preferences,
- visionInstructionsByLocale: settings.instructionsByLocale,
- autoAnalyzeImports: settings.autoAnalyzeImports
- })
- };
- const selected = registry.providers[providerId];
- if (configuration.preferences.autoAnalyzeImports && (!selected?.consent || !selected?.credentialConfigured)) {
- throw new Error("自动分析导入图片需要先完成视觉服务配置,并确认图片发送范围");
- }
- await persistAiConfiguration(configuration);
- return aiConfigurationResponse(configuration, credentialReset
- ? "兼容接口域名已变更;旧 API Key 未沿用,请重新填写新服务的 Key"
- : "图片视觉分析设置已保存");
+function discoveryErrorMessage(error, apiKey) {
+ const message = userMessage(error);
+ const secret = String(apiKey ?? "").trim();
+ return secret ? message.split(secret).join("[已隐藏 API Key]") : message;
}
async function loadAiConfiguration() {
const stored = await chrome.storage.local.get([
- STORAGE_KEYS.aiProviderRegistry, STORAGE_KEYS.aiTaskAssignments, STORAGE_KEYS.aiPreferences,
- STORAGE_KEYS.aiSettings, STORAGE_KEYS.visionSettings, STORAGE_KEYS.aiServiceProfiles, STORAGE_KEYS.aiTaskRoutes
+ STORAGE_KEYS.aiProviderRegistry, STORAGE_KEYS.aiTaskAssignments, STORAGE_KEYS.aiPreferences
]);
return aiConfigurationFromStorage(stored);
}
@@ -3546,9 +4226,6 @@ async function persistAiConfiguration(configuration) {
[STORAGE_KEYS.aiTaskAssignments]: configuration.assignments,
[STORAGE_KEYS.aiPreferences]: configuration.preferences
});
- await chrome.storage.local.remove([
- STORAGE_KEYS.aiSettings, STORAGE_KEYS.visionSettings, STORAGE_KEYS.aiServiceProfiles, STORAGE_KEYS.aiTaskRoutes
- ]);
}
function aiConfigurationResponse(configuration, message) {
@@ -3560,27 +4237,88 @@ function aiConfigurationResponse(configuration, message) {
aiTaskAssignments: configuration.assignments,
aiSettings: publicAiSettings(runtime.aiSettings),
visionSettings: publicVisionSettings(runtime.visionSettings),
- aiServiceProfiles: publicAiServiceProfiles(runtime.aiServiceProfiles),
- aiTaskRoutes: runtime.aiTaskRoutes
+ aiServiceProfiles: publicAiServiceProfiles(runtime.aiServiceProfiles)
};
}
-async function getAiTaskRuntime(taskIdValue, allowUnconfigured = false) {
+async function getAiTaskRuntime(taskIdValue, allowUnconfigured = false, assignmentOverride = null) {
const taskId = canonicalAiTaskId(taskIdValue);
- const configuration = await loadAiConfiguration();
+ const storedConfiguration = await loadAiConfiguration();
+ const requestedProviderId = String(assignmentOverride?.providerId ?? "").trim();
+ const requestedModel = String(assignmentOverride?.model ?? "").trim();
+ const configuration = requestedProviderId || requestedModel ? {
+ ...storedConfiguration,
+ assignments: normalizeAiTaskAssignments({
+ ...storedConfiguration.assignments,
+ [taskId]: {
+ providerId: requestedProviderId || storedConfiguration.assignments[taskId]?.providerId,
+ model: requestedModel || storedConfiguration.assignments[taskId]?.model
+ }
+ }, storedConfiguration.registry)
+ } : storedConfiguration;
const assignment = configuration.assignments[taskId];
const providerLabel = configuration.registry.providers[assignment?.providerId]?.label || assignment?.providerId;
+ const common = {
+ ok: true,
+ aiRuntimeProtocolVersion: AI_RUNTIME_PROTOCOL_VERSION,
+ taskId,
+ assignment,
+ providerLabel,
+ runtimeDescriptor: aiTaskRuntimeDescriptor(taskId, configuration),
+ availableProviders: aiTaskProviderOptions(taskId, configuration)
+ };
if (["textTags", "skillExtraction", "creativePlanning"].includes(taskId)) {
- return { ok: true, taskId, assignment, providerLabel, aiSettings: resolveTextTaskSettings(taskId, configuration, { requireConfigured: !allowUnconfigured }) };
+ return { ...common, aiSettings: resolveTextTaskSettings(taskId, configuration, { requireConfigured: !allowUnconfigured }) };
}
if (["imageAnalysis", "imageGeneration"].includes(taskId)) {
- return { ok: true, taskId, assignment, providerLabel, visionSettings: resolveVisionTaskSettings(taskId, configuration, { requireConfigured: !allowUnconfigured }) };
+ return { ...common, visionSettings: resolveVisionTaskSettings(taskId, configuration, { requireConfigured: !allowUnconfigured }) };
}
- if (taskId === "videoAnalysis") return { ok: true, taskId, videoAnalysis: resolveVideoAnalysisTask(configuration) };
- if (taskId === "videoGeneration") return { ok: true, taskId, runtime: projectAiRuntime(configuration) };
+ if (taskId === "videoAnalysis") {
+ if (allowUnconfigured && !assignment?.providerId) return { ...common, videoAnalysis: null };
+ return { ...common, videoAnalysis: resolveVideoAnalysisTask(configuration) };
+ }
+ if (taskId === "videoGeneration") return { ...common, runtime: projectAiRuntime(configuration) };
throw new Error("未知 AI 任务");
}
+function aiTaskProviderOptions(taskId, configuration) {
+ return availableAiProvidersForTask(taskId, configuration.registry).filter((provider) =>
+ configuration.registry.providers[provider.id]?.consent === true
+ ).map((provider) => {
+ 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)
+ ].filter(Boolean))];
+ return { id: provider.id, label: provider.label, models };
+ });
+}
+
+function aiTaskRuntimeDescriptor(taskId, configuration) {
+ const assignment = configuration.assignments[taskId] ?? {};
+ const profile = configuration.registry.providers[assignment.providerId] ?? {};
+ const model = (profile.discoveredModels ?? []).find((item) => item.id === assignment.model);
+ let endpointOrigin = "";
+ try { endpointOrigin = new URL(profile.endpoint).origin; } catch {}
+ const imageSupport = model?.inputModalities?.includes("image")
+ ? true
+ : model?.inputModalities?.length ? false : taskId === "imageAnalysis" ? null : false;
+ return {
+ providerId: assignment.providerId || "",
+ providerLabel: profile.label || assignment.providerId || "",
+ model: assignment.model || "",
+ endpointOrigin,
+ capabilities: {
+ text: true,
+ image: imageSupport,
+ imageSource: model?.confidence || "unknown",
+ maxImages: Number.isInteger(model?.referenceImages?.maxItems) ? model.referenceImages.maxItems : null
+ }
+ };
+}
+
async function getComposerAiRuntime() {
const configuration = await loadAiConfiguration();
return { ok: true, aiRuntimeProtocolVersion: AI_RUNTIME_PROTOCOL_VERSION, ...projectAiRuntime(configuration) };
@@ -3596,13 +4334,6 @@ function canonicalAiTaskId(value) {
return map[id] || id;
}
-async function probeVisionModels(value) {
- const current = projectAiRuntime(await loadAiConfiguration()).visionSettings;
- const { settings } = mergeVisionSettings(current, { activeProvider: "compatible", compatible: value });
- const result = await probeCompatibleModels(settings.compatible);
- return { ok: true, message: `连接成功 · 找到 ${result.models.length} 个模型`, ...result };
-}
-
async function analyzeEntryImage(entryId, visualIdValue, outputLocale, batchJobIdValue = "") {
if (visionAnalysisInFlight) return { ok: false, message: "已有一张图片正在分析,请等待完成" };
visionAnalysisInFlight = true;
@@ -3731,15 +4462,12 @@ async function analyzeEntryVideo(message) {
const videoBlob = asset.storageMode === "managed" ? await getMediaBlob(asset.id) : null;
if (asset.storageMode === "managed" && !videoBlob) return { ok: false, message: "本地视频文件缺失,无法分析" };
const sourceUrl = asset.reference?.url || asset.sourceUrl;
- const analyzeVideo = route.providerId === "gemini"
- ? analyzeVideoWithGemini
- : route.providerId === "openrouter"
- ? analyzeVideoWithOpenRouter
- : null;
+ const analyzeVideo = VIDEO_ANALYSIS_ADAPTERS[route.protocol];
if (!analyzeVideo) throw new Error(`${route.provider} 的视频理解请求协议当前版本尚未适配`);
const analysis = await analyzeVideo({
apiKey: route.apiKey,
endpoint: route.endpoint,
+ providerLabel: route.providerLabel,
model: route.model,
mode: message.mode,
customQuestion: message.customQuestion,
@@ -5045,6 +5773,53 @@ async function exportProjectArchive(state, collectionId) {
};
}
+async function exportCuratedSubmission(state, message = {}) {
+ const prepared = prepareCuratedSubmissionState(state, {
+ entryIds: message.entryIds,
+ collectionId: message.collectionId
+ });
+ await migrateLegacyScreenshots(prepared.entries);
+ await ensureOffscreenDocument();
+ const result = await chrome.runtime.sendMessage({
+ target: "offscreen",
+ type: "CREATE_CURATED_SUBMISSION_URLS",
+ ...prepared.state
+ });
+ if (!result?.ok || !Array.isArray(result.outputs) || !result.outputs.length) {
+ throw new Error(result?.message || "无法生成精选投稿包");
+ }
+ const downloadIds = [];
+ try {
+ for (const output of result.outputs) {
+ const downloadId = await chrome.downloads.download({
+ url: output.url,
+ filename: output.filename,
+ conflictAction: "uniquify",
+ saveAs: false
+ });
+ downloadIds.push(downloadId);
+ await waitForDownload(downloadId);
+ }
+ } finally {
+ await Promise.allSettled(result.outputs.map((output) => chrome.runtime.sendMessage({
+ target: "offscreen",
+ type: "REVOKE_BLOB_URL",
+ url: output.url
+ })));
+ }
+ return {
+ ok: true,
+ submissionId: result.submissionId,
+ count: result.caseCount,
+ mediaCount: result.mediaCount,
+ partCount: result.partCount,
+ downloadIds,
+ message: result.partCount > 1
+ ? `投稿包已生成,共 ${result.partCount} 个分卷`
+ : "投稿包已生成"
+ };
+}
+
async function exportCreativeExperiments(state) {
if (!state.creativeRuns.some((run) => run.outputs.length)) {
return { ok: false, message: "还没有可导出的真实生成结果" };
@@ -5171,6 +5946,61 @@ async function applyLibraryImport(state, message) {
};
}
+function previewCuratedImport(state, message) {
+ const result = mergeCuratedLibraryPackage(state, message.library, {
+ packageId: message.packageId,
+ projectName: message.projectName,
+ mode: message.mode
+ });
+ return curatedImportResponse(result);
+}
+
+async function applyCuratedImport(state, message) {
+ const result = mergeCuratedLibraryPackage(state, message.library, {
+ packageId: message.packageId,
+ projectName: message.projectName,
+ mode: message.mode,
+ entryIdMap: message.entryIdMap,
+ compoundIdMap: message.compoundIdMap,
+ visualIdMap: message.visualIdMap,
+ sessionIdMap: message.sessionIdMap,
+ runIdMap: message.runIdMap
+ });
+ await commitLocalChanges({
+ ...storagePayload(result.state),
+ [STORAGE_KEYS.settings]: normalizeSettings(result.state.settings ?? state.settings),
+ [STORAGE_KEYS.composerSettings]: normalizeComposerSettings(result.state.composerSettings ?? state.composerSettings),
+ [STORAGE_KEYS.composerSessions]: normalizeComposerSessions(result.state.composerSessions ?? state.composerSessions),
+ [STORAGE_KEYS.creativeExperimentSettings]: normalizeCreativeExperimentSettings(
+ result.state.creativeExperimentSettings ?? state.creativeExperimentSettings
+ ),
+ [STORAGE_KEYS.creativeRuns]: normalizeCreativeRuns(result.state.creativeRuns ?? state.creativeRuns),
+ [STORAGE_KEYS.creativeSkills]: normalizeCreativeSkillsState(result.state.creativeSkills ?? state.creativeSkills)
+ });
+ if (result.importedEntryIds.length) await queueAutomaticVisionAnalysis(result.importedEntryIds);
+ return curatedImportResponse(result);
+}
+
+function curatedImportResponse(result) {
+ return {
+ ok: true,
+ entryIdMap: result.entryIdMap,
+ compoundIdMap: result.compoundIdMap,
+ visualIdMap: result.visualIdMap,
+ sessionIdMap: result.sessionIdMap,
+ runIdMap: result.runIdMap,
+ importedCount: result.importedCount,
+ existingCount: result.existingCount,
+ sourceEntryIds: result.sourceEntryIds,
+ importedSourceEntryIds: result.importedSourceEntryIds,
+ entriesBySourceEntryId: result.entriesBySourceEntryId,
+ importedEntryIds: result.importedEntryIds,
+ importedVisualIds: result.importedVisualIds,
+ projectId: result.projectId,
+ count: result.state.entries.length
+ };
+}
+
function sharedArchivePath(outputPath) {
const normalized = normalizeSettings({ outputPath }).outputPath;
const separator = normalized.lastIndexOf("/");
diff --git a/bounded-media.js b/bounded-media.js
index 6376e9b..115bf2f 100644
--- a/bounded-media.js
+++ b/bounded-media.js
@@ -1,6 +1,16 @@
import { PORTABLE_LIBRARY_LIMITS } from "./resource-limits.js";
-const MEDIA_KINDS = new Set(["image", "video"]);
+const MEDIA_KINDS = new Set(["image", "video", "document"]);
+export const SUPPORTED_DOCUMENT_MIME_TYPES = Object.freeze([
+ "application/pdf",
+ "application/rtf",
+ "text/rtf",
+ "application/x-rtf",
+ "text/html",
+ "text/markdown",
+ "text/plain"
+]);
+const DOCUMENT_MIME_TYPES = new Set(SUPPORTED_DOCUMENT_MIME_TYPES);
export async function fetchBoundedMedia(value, options = {}) {
const url = assertRemoteMediaUrl(value, options);
@@ -39,14 +49,52 @@ export async function boundedMediaBlobFromResponse(response, options = {}) {
}
const bytes = await readBoundedBytes(response, maxBytes, options.controller);
const declaredType = cleanMimeType(response?.headers?.get?.("content-type"));
- const detectedType = detectMediaMimeType(bytes);
- const mimeType = detectedType || declaredType;
- if (!mimeType.startsWith(`${kind}/`) || !detectedType) {
+ const detectedType = kind === "document" ? detectDocumentMimeType(bytes) : detectMediaMimeType(bytes);
+ const mimeType = kind === "document"
+ ? verifiedDocumentMimeType(bytes, detectedType, declaredType, options.expectedMimeType)
+ : detectedType || declaredType;
+ if (kind !== "document" && (!mimeType.startsWith(`${kind}/`) || !detectedType)) {
throw new Error(`来源没有返回有效${kind === "image" ? "图片" : "视频"}文件`);
}
+ const dimensions = kind === "image" ? detectImageDimensions(bytes, mimeType) : null;
+ const maxPixels = positiveInteger(options.maxPixels, 0);
+ if (dimensions && maxPixels && dimensions.width * dimensions.height > maxPixels) {
+ throw new Error(`图片像素超过 ${maxPixels.toLocaleString("en-US")} 上限`);
+ }
+ options.onMetadata?.({ mimeType, ...(dimensions || {}) });
return new Blob([bytes], { type: mimeType });
}
+export function isSupportedDocumentMimeType(value) {
+ return DOCUMENT_MIME_TYPES.has(cleanMimeType(value));
+}
+
+export function detectImageDimensions(bytesValue, mimeTypeValue = "") {
+ const bytes = bytesValue instanceof Uint8Array ? bytesValue : new Uint8Array(bytesValue || []);
+ const mimeType = cleanMimeType(mimeTypeValue) || detectMediaMimeType(bytes);
+ if (mimeType === "image/png" && bytes.length >= 24) {
+ return { width: readUint32BE(bytes, 16), height: readUint32BE(bytes, 20) };
+ }
+ if (mimeType === "image/gif" && bytes.length >= 10) {
+ return { width: readUint16LE(bytes, 6), height: readUint16LE(bytes, 8) };
+ }
+ if (mimeType === "image/jpeg") return jpegDimensions(bytes);
+ if (mimeType === "image/webp" && bytes.length >= 30) {
+ const chunk = ascii(bytes, 12, 16);
+ if (chunk === "VP8X") {
+ return { width: 1 + readUint24LE(bytes, 24), height: 1 + readUint24LE(bytes, 27) };
+ }
+ if (chunk === "VP8L" && bytes[20] === 0x2f) {
+ const bits = bytes[21] | bytes[22] << 8 | bytes[23] << 16 | bytes[24] << 24;
+ return { width: (bits & 0x3fff) + 1, height: (bits >>> 14 & 0x3fff) + 1 };
+ }
+ if (chunk === "VP8 " && bytes.length >= 30 && matches(bytes.subarray(23), [0x9d, 0x01, 0x2a])) {
+ return { width: readUint16LE(bytes, 26) & 0x3fff, height: readUint16LE(bytes, 28) & 0x3fff };
+ }
+ }
+ return null;
+}
+
export function assertRemoteMediaUrl(value, options = {}) {
let url;
try { url = value instanceof URL ? new URL(value.href) : new URL(String(value ?? "")); }
@@ -101,6 +149,93 @@ function detectMediaMimeType(bytes) {
return "";
}
+function detectDocumentMimeType(bytes) {
+ if (ascii(bytes, 0, 5) === "%PDF-") return "application/pdf";
+ const prefix = decodedPrefix(bytes, 256).trimStart().toLocaleLowerCase("en-US");
+ if (prefix.startsWith("{\\rtf")) return "application/rtf";
+ if (/^(?:<!doctype\s+html\b|<html\b|<head\b|<body\b)/u.test(prefix)) return "text/html";
+ return "";
+}
+
+function verifiedDocumentMimeType(bytes, detectedType, declaredType, expectedTypeValue) {
+ const expectedType = cleanMimeType(expectedTypeValue);
+ if (expectedType && !isSupportedDocumentMimeType(expectedType)) {
+ throw new Error("来源不是支持的安全文档类型");
+ }
+ const declaredDocumentType = isSupportedDocumentMimeType(declaredType) ? declaredType : "";
+ const requestedType = expectedType || declaredDocumentType || detectedType;
+ if (!requestedType) throw new Error("来源不是支持的安全文档类型");
+ if (detectedType && !sameDocumentFamily(detectedType, requestedType)) {
+ throw new Error("来源没有返回有效文档文件");
+ }
+ if (["application/pdf", "text/html"].includes(requestedType) && detectedType !== requestedType) {
+ throw new Error("来源没有返回有效文档文件");
+ }
+ if (["application/rtf", "text/rtf", "application/x-rtf"].includes(requestedType) && detectedType !== "application/rtf") {
+ throw new Error("来源没有返回有效文档文件");
+ }
+ if (["text/plain", "text/markdown"].includes(requestedType) && !isSafeUtf8Text(bytes)) {
+ throw new Error("来源没有返回有效文档文件");
+ }
+ return requestedType;
+}
+
+function sameDocumentFamily(left, right) {
+ const rtf = new Set(["application/rtf", "text/rtf", "application/x-rtf"]);
+ return left === right || (rtf.has(left) && rtf.has(right));
+}
+
+function isSafeUtf8Text(bytes) {
+ let text;
+ try { text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
+ catch { return false; }
+ if (text.includes("\u0000")) return false;
+ let controls = 0;
+ for (const character of text) {
+ const code = character.codePointAt(0);
+ if ((code < 0x20 && ![0x09, 0x0a, 0x0d].includes(code)) || code === 0x7f) controls += 1;
+ }
+ return controls <= Math.max(1, Math.floor(text.length * 0.01));
+}
+
+function decodedPrefix(bytes, limit) {
+ try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, Math.min(bytes.length, limit))); }
+ catch { return ""; }
+}
+
+function jpegDimensions(bytes) {
+ let offset = 2;
+ while (offset + 8 < bytes.length) {
+ if (bytes[offset] !== 0xff) {
+ offset += 1;
+ continue;
+ }
+ const marker = bytes[offset + 1];
+ offset += 2;
+ if (marker === 0xd8 || marker === 0xd9) continue;
+ if (offset + 2 > bytes.length) break;
+ const length = bytes[offset] << 8 | bytes[offset + 1];
+ if (length < 2 || offset + length > bytes.length) break;
+ if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker)) {
+ return { width: bytes[offset + 5] << 8 | bytes[offset + 6], height: bytes[offset + 3] << 8 | bytes[offset + 4] };
+ }
+ offset += length;
+ }
+ return null;
+}
+
+function readUint32BE(bytes, offset) {
+ return (bytes[offset] * 0x1000000 + (bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3])) >>> 0;
+}
+
+function readUint16LE(bytes, offset) {
+ return bytes[offset] | bytes[offset + 1] << 8;
+}
+
+function readUint24LE(bytes, offset) {
+ return bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16;
+}
+
function matches(bytes, signature) {
return bytes.length >= signature.length && signature.every((value, index) => bytes[index] === value);
}
@@ -117,7 +252,9 @@ function mediaKind(value) {
}
function defaultLimit(kind) {
- return kind === "image" ? PORTABLE_LIBRARY_LIMITS.maxImageBytes : PORTABLE_LIBRARY_LIMITS.maxVideoBytes;
+ if (kind === "image") return PORTABLE_LIBRARY_LIMITS.maxImageBytes;
+ if (kind === "document") return PORTABLE_LIBRARY_LIMITS.maxFileBytes;
+ return PORTABLE_LIBRARY_LIMITS.maxVideoBytes;
}
function cleanMimeType(value) {
diff --git a/capture-draft.js b/capture-draft.js
index fcbcba7..fa84b29 100644
--- a/capture-draft.js
+++ b/capture-draft.js
@@ -1,12 +1,13 @@
import { normalizeVisual } from "./visuals.js";
import { uniqueNames } from "./facets.js";
-export const CAPTURE_DRAFT_VERSION = 2;
+export const CAPTURE_DRAFT_VERSION = 3;
export function createCaptureDraft(value = {}) {
const now = new Date().toISOString();
const fragments = uniqueFragments(value.fragments);
const visuals = uniqueDraftVisuals(value.visuals);
+ const sourceContexts = uniqueSourceContexts(value.sourceContexts);
const visualIds = new Set(visuals.map((item) => item.id));
return {
version: CAPTURE_DRAFT_VERSION,
@@ -16,6 +17,7 @@ export function createCaptureDraft(value = {}) {
title: clean(value.title),
fragments,
visuals,
+ sourceContexts,
primaryVisualId: visualIds.has(clean(value.primaryVisualId)) ? clean(value.primaryVisualId) : visuals[0]?.id || "",
primaryVisualExplicit: value.primaryVisualExplicit === true,
contentTypeId: clean(value.contentTypeId),
@@ -27,6 +29,20 @@ export function createCaptureDraft(value = {}) {
};
}
+export function addDraftSourceContext(draftValue, contextValue = {}) {
+ const draft = createCaptureDraft(draftValue);
+ const context = normalizeSourceContext(contextValue);
+ if (!context) return draft;
+ const wasEmpty = !draft.fragments.length && !draft.visuals.length;
+ draft.sourceContexts = [
+ ...draft.sourceContexts.filter((item) => item.canonicalUrl !== context.canonicalUrl),
+ context
+ ];
+ if (wasEmpty && context.displayTitle) draft.title = context.displayTitle;
+ touch(draft);
+ return draft;
+}
+
export function addDraftFragment(draftValue, fragmentValue = {}) {
const draft = createCaptureDraft(draftValue);
const fragment = normalizeFragment(fragmentValue);
@@ -126,13 +142,21 @@ export function captureTitleForSource(sourceUrlValue, sourceTitleValue) {
export function draftSourcePages(draftValue) {
const seen = new Set();
- return createCaptureDraft(draftValue).fragments.flatMap((item) => {
+ const draft = createCaptureDraft(draftValue);
+ return draft.fragments.flatMap((item) => {
if (!item.sourceUrl || seen.has(item.sourceUrl)) return [];
seen.add(item.sourceUrl);
- return [{ url: item.sourceUrl, title: item.sourceTitle }];
+ const context = sourceContextForUrl(draft, item.sourceUrl);
+ return [{ url: item.sourceUrl, title: context?.displayTitle || item.sourceTitle }];
});
}
+export function sourceContextForUrl(draftValue, sourceUrlValue) {
+ const sourceUrl = safeHttpUrl(sourceUrlValue);
+ if (!sourceUrl) return null;
+ return createCaptureDraft(draftValue).sourceContexts.find((item) => item.canonicalUrl === sourceUrl) ?? null;
+}
+
export function draftParts(draftValue) {
const draft = createCaptureDraft(draftValue);
const groups = new Map();
@@ -147,9 +171,11 @@ export function draftParts(draftValue) {
const sourceUrl = safeHttpUrl(item.value.sourceUrl);
const key = sourceUrl || "source:unknown";
if (!groups.has(key)) {
+ const sourceContext = sourceContextForUrl(draft, sourceUrl);
groups.set(key, {
sourceUrl,
- sourceTitle: clean(item.value.sourceTitle),
+ sourceTitle: sourceContext?.displayTitle || clean(item.value.sourceTitle),
+ sourceContext,
fragments: [],
visuals: []
});
@@ -164,6 +190,43 @@ export function draftParts(draftValue) {
}));
}
+function normalizeSourceContext(value = {}) {
+ const canonicalUrl = safeHttpUrl(value.canonicalUrl || value.url);
+ if (!canonicalUrl) return null;
+ const sourceFactsValue = value.sourceFacts && typeof value.sourceFacts === "object" ? value.sourceFacts : {};
+ const engagement = Object.fromEntries(Object.entries(sourceFactsValue.engagement || {}).flatMap(([key, amount]) => {
+ const number = Number(amount);
+ return clean(key) && Number.isFinite(number) && number >= 0 ? [[clean(key), number]] : [];
+ }));
+ return {
+ canonicalUrl,
+ displayTitle: clean(value.displayTitle || value.title),
+ completeness: value.completeness === "complete" ? "complete" : "partial",
+ sourceFacts: {
+ provider: clean(sourceFactsValue.provider),
+ pageType: clean(sourceFactsValue.pageType),
+ itemId: clean(sourceFactsValue.itemId),
+ author: clean(sourceFactsValue.author),
+ handle: clean(sourceFactsValue.handle),
+ publishedAt: validIso(sourceFactsValue.publishedAt),
+ model: clean(sourceFactsValue.model),
+ dimensions: clean(sourceFactsValue.dimensions),
+ engagement,
+ extractionMethod: clean(sourceFactsValue.extractionMethod),
+ status: sourceFactsValue.status === "complete" ? "complete" : "partial"
+ }
+ };
+}
+
+function uniqueSourceContexts(values) {
+ const byUrl = new Map();
+ for (const value of Array.isArray(values) ? values : []) {
+ const context = normalizeSourceContext(value);
+ if (context) byUrl.set(context.canonicalUrl, context);
+ }
+ return [...byUrl.values()];
+}
+
export function isMeaningfulCaptureDraft(draftValue) {
const draft = createCaptureDraft(draftValue);
return Boolean(draft.fragments.length || draft.visuals.length || draft.targetCaseId);
diff --git a/capture-permissions.js b/capture-permissions.js
index c91a0f9..a079808 100644
--- a/capture-permissions.js
+++ b/capture-permissions.js
@@ -1,5 +1,6 @@
export const CONTINUOUS_CAPTURE_ORIGINS = Object.freeze(["<all_urls>"]);
export const CLIPBOARD_READ_PERMISSIONS = Object.freeze(["clipboardRead"]);
+const CLIPBOARD_IMAGE_MIME_TYPES = Object.freeze(["image/png", "image/jpeg", "image/webp"]);
export function pagePermissionPattern(pageUrl) {
const url = new URL(String(pageUrl ?? ""));
@@ -35,7 +36,7 @@ export async function ensureClipboardReadPermission(permissionsApi) {
}));
}
-export async function readClipboardTextAfterFocus({
+export async function readClipboardContentAfterFocus({
clipboardApi = navigator.clipboard,
documentObject = document,
windowObject = window
@@ -45,13 +46,41 @@ export async function readClipboardTextAfterFocus({
}
await settleFocusedDocument(windowObject);
try {
- return await clipboardApi.readText();
+ return await readClipboardContent(clipboardApi);
} catch {
await settleFocusedDocument(windowObject);
- return clipboardApi.readText();
+ return readClipboardContent(clipboardApi);
}
}
+async function readClipboardContent(clipboardApi) {
+ if (typeof clipboardApi?.read !== "function") {
+ return {
+ text: typeof clipboardApi?.readText === "function" ? await clipboardApi.readText() : "",
+ image: null
+ };
+ }
+ const items = await clipboardApi.read();
+ let text = "";
+ let image = null;
+ for (const item of Array.isArray(items) ? items : []) {
+ const types = (Array.isArray(item?.types) ? item.types : []).map((type) => String(type).toLocaleLowerCase("en-US"));
+ if (!image) {
+ const imageType = CLIPBOARD_IMAGE_MIME_TYPES.find((type) => types.includes(type));
+ if (imageType) {
+ const value = await item.getType(imageType);
+ if (value instanceof Blob && value.size && value.type.toLocaleLowerCase("en-US") === imageType) image = value;
+ }
+ }
+ if (!text && types.includes("text/plain")) {
+ const value = await item.getType("text/plain");
+ if (value instanceof Blob) text = await value.text();
+ }
+ }
+ if (!text && !image && typeof clipboardApi.readText === "function") text = await clipboardApi.readText();
+ return { text, image };
+}
+
async function settleFocusedDocument(windowObject) {
await new Promise((resolve) => windowObject.requestAnimationFrame(() => windowObject.requestAnimationFrame(resolve)));
}
diff --git a/capture-workspace.js b/capture-workspace.js
index 2848cf1..de58c1d 100644
--- a/capture-workspace.js
+++ b/capture-workspace.js
@@ -7,6 +7,7 @@ import {
} from "./capture-region.js";
import {
addDraftFragment,
+ addDraftSourceContext,
addDraftVisual,
createCaptureDraft,
removeDraftFragment,
@@ -99,6 +100,7 @@ export function createCaptureWorkspace({
uiPreferencesStorageKey = "uiPreferences",
ensureOffscreenDocument,
deleteVisual,
+ resolveSourceContext = async () => null,
createId = () => globalThis.crypto.randomUUID(),
now = () => new Date().toISOString()
}) {
@@ -109,6 +111,7 @@ export function createCaptureWorkspace({
if (typeof ensureOffscreenDocument !== "function" || typeof deleteVisual !== "function") {
throw new Error("采集工作区缺少截图存储能力");
}
+ if (typeof resolveSourceContext !== "function") throw new Error("采集工作区来源解析器无效");
let activeVisualSelection = null;
let activeRegionCapture = null;
@@ -134,7 +137,7 @@ export function createCaptureWorkspace({
async function dispatch(action, payload = {}) {
switch (action) {
case "add-selection":
- return addSelection(payload.fragment);
+ return addSelection(payload.fragment, payload.sourceContext);
case "add-active-selection":
return addActiveSelection(payload.tabId);
case "try-active-selection":
@@ -194,11 +197,15 @@ export function createCaptureWorkspace({
target: { tabId: tab.id },
func: () => window.getSelection()?.toString() ?? ""
});
- const candidate = await createTextCandidate({ selection: result?.result, page: tab });
+ const sourceContext = await resolvedSourceContext(tab);
+ const candidate = await createTextCandidate({
+ selection: result?.result,
+ page: { ...tab, title: sourceContext?.displayTitle || tab.title }
+ });
if (!candidate) {
return { ok: true, added: false, reason: "empty-selection", message: "", draft: await readDraft() };
}
- const response = await addSelection(candidate);
+ const response = await addSelection(candidate, sourceContext);
return { ...response, candidateKind: candidate.kind };
} catch {
return {
@@ -220,11 +227,15 @@ export function createCaptureWorkspace({
target: { tabId: tab.id },
func: () => window.getSelection()?.toString() ?? ""
});
- const candidate = await createTextCandidate({ selection: result?.result, page: tab });
+ const sourceContext = await resolvedSourceContext(tab);
+ const candidate = await createTextCandidate({
+ selection: result?.result,
+ page: { ...tab, title: sourceContext?.displayTitle || tab.title }
+ });
if (!candidate) {
return { ok: true, added: false, reason: "empty-selection", message: "", draft: before };
}
- const response = await addSelection(candidate);
+ const response = await addSelection(candidate, sourceContext);
return { ...response, candidateKind: candidate.kind };
} catch {
return { ok: true, added: false, reason: "selection-unavailable", message: "", draft: before };
@@ -240,8 +251,9 @@ export function createCaptureWorkspace({
return { ...response, candidateKind: candidate.kind };
}
- async function addSelection(fragment) {
- const before = await readDraft();
+ async function addSelection(fragment, sourceContext = null) {
+ const storedDraft = await readDraft();
+ const before = sourceContext ? addDraftSourceContext(storedDraft, sourceContext) : storedDraft;
const wasEmpty = !before.fragments.length && !before.visuals.length;
const result = addDraftFragment(before, fragment);
if (!result.added) {
@@ -292,6 +304,7 @@ export function createCaptureWorkspace({
async function storeSelectedVisuals(tab, selection, before = null) {
const draftBefore = before ?? await readDraft();
+ const sourceContext = await resolvedSourceContext(tab);
const visualIds = selection.selections.map(() => createId());
try {
const visibleTab = await captureSelectedTab(tab, selection);
@@ -309,10 +322,12 @@ export function createCaptureWorkspace({
const capturedAt = now();
let draft = await readDraft();
+ if (sourceContext) draft = addDraftSourceContext(draft, sourceContext);
result.results.forEach((screenshot, index) => {
draft = addDraftVisual(draft, visualRecord({
id: visualIds[index],
tab,
+ sourceContext,
capturedAt,
screenshot
}));
@@ -460,15 +475,18 @@ export function createCaptureWorkspace({
}
const before = await readDraft();
+ const sourceContext = await resolvedSourceContext(tab);
const visualId = createId();
try {
const screenshot = await captureRegion(tab, visualId);
if (!screenshot) {
return { ok: true, message: "已取消截图,草稿没有改变", draft: await readDraft() };
}
- const draft = addDraftVisual(await readDraft(), visualRecord({
+ const current = sourceContext ? addDraftSourceContext(await readDraft(), sourceContext) : await readDraft();
+ const draft = addDraftVisual(current, visualRecord({
id: visualId,
tab,
+ sourceContext,
capturedAt: now(),
screenshot
}));
@@ -700,6 +718,15 @@ export function createCaptureWorkspace({
);
}
+ async function resolvedSourceContext(tab) {
+ try {
+ const context = await resolveSourceContext(tab);
+ return context && typeof context === "object" ? context : null;
+ } catch {
+ return null;
+ }
+ }
+
async function restorePage(tab, captureToken) {
if (!captureToken) return;
await chromeApi.scripting.executeScript({
@@ -710,11 +737,11 @@ export function createCaptureWorkspace({
}
}
-function visualRecord({ id, tab, capturedAt, screenshot }) {
+function visualRecord({ id, tab, sourceContext, capturedAt, screenshot }) {
return {
id,
sourceUrl: tab.url,
- sourceTitle: tab.title,
+ sourceTitle: sourceContext?.displayTitle || tab.title,
capturedAt,
width: screenshot.width,
height: screenshot.height,
diff --git a/collector.css b/collector.css
index c386bb8..533ef34 100644
--- a/collector.css
+++ b/collector.css
@@ -75,9 +75,9 @@ main {
border-radius: var(--ui-container-radius);
padding: 16px;
background: var(--card);
- box-shadow: inset 3px 0 var(--accent);
+ box-shadow: inset 2px 0 var(--selection-indicator);
}
-.smart-selection small { color: var(--accent); font-size: 10px; font-weight: 800; }
+.smart-selection small { color: var(--muted); font-size: 10px; font-weight: 800; }
.smart-selection h2 { margin: 3px 0 0; font-size: 18px; }
.smart-selection p { margin: 6px 0 0; color: var(--muted); font-size: 12px; line-height: 1.55; }
.smart-selection-warning { border: 1px solid color-mix(in srgb, var(--warning) 38%, var(--line)); border-radius: 6px; padding: 8px 9px; color: var(--warning) !important; background: color-mix(in srgb, var(--warning) 8%, transparent); }
@@ -136,25 +136,75 @@ main {
.page-capture h2 { margin: 2px 0 0; font-size: 16px; }
.page-capture small, .page-capture > p { color: var(--muted); font-size: 11px; }
.page-capture > p { margin: 0; line-height: 1.5; }
+.page-capture .page-capture-session-note { padding: 7px 9px; border: 1px solid var(--line); border-radius: 5px; color: var(--muted); background: var(--paper); }
.page-capture-bulk-actions { display: flex; flex-wrap: wrap; gap: 6px; }
.page-capture-bulk-actions button { width: auto; }
+.page-capture-list-setup, .page-capture-list-result { border: 1px solid var(--line); border-radius: 6px; padding: 9px; background: var(--paper); }
+.page-capture-list-setup summary { cursor: pointer; font-size: 12px; font-weight: 800; }
+.page-capture-list-setup > p, .page-capture-list-result > p { margin: 7px 0; color: var(--muted); font-size: 11px; line-height: 1.5; }
+.page-capture-list-setup label, .page-capture-list-result label { display: grid; gap: 5px; margin: 8px 0; color: var(--muted); font-size: 11px; }
+.page-capture-list-setup input, .page-capture-list-result input, .page-capture-list-result select { width: 100%; }
.page-capture-list { display: grid; max-height: min(56vh, 560px); overflow: auto; gap: 8px; }
.page-capture-item { display: grid; gap: 9px; border: 1px solid var(--line); border-radius: 6px; padding: 10px; background: var(--paper); }
+.page-capture-item.confirmed { border-color: var(--selection-edge); box-shadow: inset 3px 0 var(--selection-indicator); }
+.page-capture-item.structure-review { border-style: dashed; border-color: var(--warning, #b98a2e); }
+.page-capture-item > header { display: flex; align-items: start; justify-content: space-between; gap: 8px; }
.page-capture-item > header > div { display: grid; min-width: 0; gap: 3px; }
.page-capture-item strong { overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
.page-capture-component { display: grid; min-width: 0; align-items: start; gap: 8px; border: 1px solid var(--line); border-radius: 5px; padding: 8px; background: var(--card); cursor: pointer; }
.page-capture-component:hover { border-color: var(--line-strong); }
-.page-capture-component > input { margin-top: 3px; }
-.page-capture-text { grid-template-columns: auto minmax(0, 1fr); }
+.page-capture-text-section { display: grid; gap: 6px; }
+.page-capture-text-section > header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; padding: 0 2px; }
+.page-capture-text-list { display: grid; max-height: 260px; overflow: auto; gap: 6px; }
+.page-capture-text { grid-template-columns: minmax(0, 1fr); cursor: default; }
.page-capture-text > span { display: grid; min-width: 0; gap: 3px; }
.page-capture-text p { display: -webkit-box; margin: 2px 0 0; overflow: hidden; color: var(--muted); font-size: 11px; line-height: 1.55; -webkit-box-orient: vertical; -webkit-line-clamp: 3; }
+.page-capture-omissions { border: 1px dashed var(--line); border-radius: 5px; color: var(--muted); font-size: 11px; }
+.page-capture-omissions summary { padding: 8px; cursor: pointer; font-weight: 750; }
+.page-capture-omissions > div { display: grid; gap: 6px; padding: 0 8px 8px; }
+.page-capture-omissions p { margin: 0; line-height: 1.45; }
.page-capture-media-grid { display: grid; gap: 6px; }
-.page-capture-media { grid-template-columns: auto 54px minmax(0, 1fr); align-items: center; }
-.page-capture-media-preview { display: grid; width: 54px; height: 42px; overflow: hidden; place-items: center; border-radius: 4px; color: var(--muted); background: var(--raised); font-size: 9px; font-weight: 800; }
-.page-capture-media-preview img { display: block; width: 100%; height: 100%; object-fit: cover; }
+.page-capture-media { grid-template-columns: 88px minmax(0, 1fr); align-items: center; width: 100%; color: inherit; text-align: left; }
+.page-capture-media-preview { display: grid; width: 88px; height: 66px; overflow: hidden; place-items: center; border-radius: 4px; color: var(--muted); background: var(--raised); font-size: 9px; font-weight: 800; }
+.page-capture-media-preview img { display: block; width: 100%; height: 100%; object-fit: contain; }
.page-capture-media > span:last-child { display: grid; min-width: 0; gap: 3px; }
.page-capture-media small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.page-capture-actions { display: grid; grid-template-columns: 1fr 1.4fr; gap: 8px; }
+.page-capture-confirm { width: 100%; }
+.page-capture-media-review { display: grid; gap: 9px; border: 1px solid var(--selection-edge); border-radius: 6px; padding: 10px; background: var(--paper); }
+.page-capture-media-review[hidden] { display: none; }
+.page-capture-media-review > header { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
+.page-capture-media-review > p { margin: 0; color: var(--muted); font-size: 11px; line-height: 1.5; }
+.page-capture-media-review-list { display: grid; max-height: 240px; overflow: auto; gap: 6px; }
+.page-capture-media-review-item { display: grid; grid-template-columns: 72px minmax(0, 1fr) auto; align-items: center; gap: 8px; border: 1px solid var(--line); border-radius: 5px; padding: 6px; }
+.page-capture-media-review-item.media-excluded { opacity: .55; }
+.page-capture-media-review-preview { display: grid; width: 72px; height: 54px; overflow: hidden; place-items: center; border: 0; border-radius: 4px; padding: 0; background: var(--raised); }
+.page-capture-media-review-preview img { width: 100%; height: 100%; object-fit: contain; }
+.page-capture-media-review-item > span { display: grid; min-width: 0; gap: 3px; }
+.page-capture-media-review-item > span small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.page-capture-media-review-group { display: grid; gap: 6px; }
+.page-capture-media-review-group > summary { cursor: pointer; color: var(--muted); font-size: 11px; font-weight: 800; }
+.page-capture-media-review-group > div { display: grid; gap: 6px; margin-top: 6px; }
+.page-capture-article-media.media-excluded, .page-capture-article-resource.media-excluded { opacity: .4; text-decoration: line-through; }
+.page-capture-article-media.media-pending, .page-capture-article-resource.media-pending { outline: 1px dashed var(--selection-edge); }
+.page-capture-actions { display: grid; grid-template-columns: auto auto minmax(0, 1.4fr); gap: 8px; }
+.page-capture-media-viewer { width: min(92vw, 720px); max-width: 720px; border: 1px solid var(--line); border-radius: 10px; padding: 12px; color: var(--ink); background: var(--card); }
+.page-capture-media-viewer::backdrop { background: rgb(0 0 0 / 72%); }
+.page-capture-media-viewer > header, .page-capture-media-viewer > footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
+.page-capture-media-viewer > header > div { display: grid; gap: 3px; }
+.page-capture-media-viewer > p { margin: 8px 0; color: var(--muted); font-size: 11px; }
+.page-capture-media-viewer > footer { display: grid; grid-template-columns: 1fr 1fr; }
+.page-capture-media-stage { display: grid; min-height: 280px; max-height: 72vh; margin-top: 10px; overflow: hidden; place-items: center; border-radius: 7px; background: #090a0b; }
+.page-capture-media-stage img, .page-capture-media-stage video { display: block; max-width: 100%; max-height: 72vh; object-fit: contain; }
+.page-capture-article { display: grid; max-height: 420px; overflow: auto; gap: 10px; border: 1px solid var(--line); border-radius: 6px; padding: 12px; background: var(--card); }
+.page-capture-article > header { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; padding-bottom: 6px; border-bottom: 1px solid var(--line); }
+.page-capture-article h1, .page-capture-article h2, .page-capture-article h3, .page-capture-article h4, .page-capture-article h5, .page-capture-article h6 { margin: 4px 0 0; white-space: normal; }
+.page-capture-article p, .page-capture-article blockquote, .page-capture-article pre { margin: 0; color: var(--ink); font-size: 11px; line-height: 1.6; white-space: pre-wrap; }
+.page-capture-article blockquote { border-left: 3px solid var(--line-strong); padding-left: 9px; color: var(--muted); }
+.page-capture-article pre { overflow: auto; border-radius: 5px; padding: 8px; background: var(--raised); }
+.page-capture-article-media { display: grid; grid-template-columns: 96px minmax(0, 1fr); align-items: center; gap: 9px; width: 100%; color: inherit; text-align: left; }
+.page-capture-article-media .page-capture-media-preview { width: 96px; height: 72px; }
+.page-capture-article-resource { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 9px; border: 1px solid var(--line); border-radius: 5px; padding: 9px; color: inherit; background: var(--paper); text-align: left; }
+.page-capture-article-resource > span:first-child { display: grid; width: 38px; height: 38px; place-items: center; border-radius: 5px; color: var(--accent); background: var(--accent-soft); font-size: 10px; font-weight: 850; }
.capture-actions .other-capture-methods > button {
width: 100%;
height: 30px;
@@ -199,7 +249,8 @@ main {
.quick-preview { display: grid; gap: 8px; }
.quick-item {
display: grid;
- grid-template-columns: 42px 1fr;
+ grid-template-columns: 42px minmax(0, 1fr) auto;
+ align-items: start;
gap: 10px;
min-width: 0;
border: 1px solid var(--line);
@@ -234,7 +285,6 @@ main {
text-overflow: ellipsis;
white-space: nowrap;
}
-.quick-copy em { color: var(--accent); font-size: 10px; font-style: normal; font-weight: 700; }
.quick-visuals { grid-template-columns: 1fr; }
.quick-image-strip {
display: flex;
@@ -244,15 +294,49 @@ main {
padding-bottom: 2px;
scroll-snap-type: x proximity;
}
-.quick-image-strip img {
+.quick-image-item {
+ position: relative;
flex: 0 0 78px;
width: 78px;
+ scroll-snap-align: start;
+}
+.quick-image-item img {
+ display: block;
+ width: 100%;
height: 64px;
border: 1px solid var(--line);
border-radius: 9px;
object-fit: cover;
background: var(--soft);
- scroll-snap-align: start;
+}
+.quick-remove {
+ display: grid;
+ width: 28px;
+ min-width: 28px;
+ min-height: 28px;
+ place-items: center;
+ border-color: var(--line);
+ padding: 0;
+ color: var(--muted);
+ background: var(--paper);
+}
+.quick-remove:hover:not(:disabled) {
+ border-color: color-mix(in srgb, var(--danger) 32%, var(--line));
+ color: var(--danger);
+ background: color-mix(in srgb, var(--danger) 6%, var(--paper));
+}
+.quick-remove .ui-icon { width: 14px; height: 14px; }
+.quick-image-item .quick-remove {
+ position: absolute;
+ top: 4px;
+ right: 4px;
+ width: 24px;
+ min-width: 24px;
+ min-height: 24px;
+ border-color: color-mix(in srgb, var(--ink) 14%, transparent);
+ background: color-mix(in srgb, var(--paper) 88%, transparent);
+ box-shadow: 0 2px 7px rgba(20, 30, 25, .14);
+ backdrop-filter: blur(5px);
}
.save-metadata {
@@ -401,14 +485,10 @@ main {
.duplicate-panel .quiet { border-color: #c9ad64; color: #5c470d; background: transparent; }
#feedback {
- min-height: 19px;
- margin: 0;
- color: var(--accent);
- font-size: 11px;
- font-weight: 700;
- text-align: center;
+ --ui-feedback-bottom: 76px;
+ right: 14px;
+ max-width: min(360px, calc(100vw - 28px));
}
-#feedback.error { color: var(--danger); }
.collector-footer {
position: fixed;
@@ -459,7 +539,7 @@ main { gap: 12px; padding: 12px 12px 82px; }
.compact-capture-methods > summary { padding: 8px 10px; }
.quick-item { border-radius: 7px; box-shadow: none; }
.quick-item > strong { border-radius: 5px; color: var(--accent-ink); }
-.quick-image-strip img, .visual-card img { border-radius: 5px; }
+.quick-image-item img, .visual-card img { border-radius: 5px; }
.preview-heading > span { border-radius: 4px; }
.collector-footer { background: var(--paper); backdrop-filter: none; }
.collector-footer .primary { min-width: 140px; }
diff --git a/collector.html b/collector.html
index a29e101..859b315 100644
--- a/collector.html
+++ b/collector.html
@@ -39,7 +39,7 @@
<div id="normal-start" class="normal-start">
<div class="capture-actions" aria-label="从当前网页采集">
<button id="start-smart-visuals" class="primary smart-visuals" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-image"></use></svg><strong data-i18n="智能选图">智能选图</strong></button>
- <button id="start-selection" class="direct-selection" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-file-text"></use></svg><strong data-i18n="提取文字">提取文字</strong></button>
+ <button id="start-selection" class="direct-selection" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-file-text"></use></svg><strong data-i18n="提取文字/图片">提取文字/图片</strong></button>
<button id="start-page-capture" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-library"></use></svg><strong>网页采集</strong></button>
<div id="other-capture-methods" class="other-capture-methods">
<button id="start-screenshot" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-maximize-2"></use></svg><strong data-i18n="框选截图">框选截图</strong></button>
@@ -50,23 +50,56 @@
<section id="page-capture" class="page-capture" hidden aria-live="polite">
<header>
- <div><small>网页批量预检</small><h2 id="page-capture-title">已识别 0 项</h2></div>
+ <div><small>网页采集预检</small><h2 id="page-capture-title">已识别 0 个主体方案</h2></div>
<button id="page-capture-scan" class="button-secondary compact" type="button">扫描整页</button>
</header>
- <p id="page-capture-help">扫描不会自动保存。请确认正文、图片或视频。</p>
- <div class="page-capture-bulk-actions" aria-label="批量选择网页内容">
- <button id="page-capture-select-recommended" class="button-secondary compact" type="button">选择推荐内容</button>
- <button id="page-capture-select-text" class="button-secondary compact" type="button">只选正文</button>
- <button id="page-capture-select-images" class="button-secondary compact" type="button">选择全部图片</button>
- <button id="page-capture-clear" class="button-secondary compact" type="button">清空选择</button>
+ <p id="page-capture-help">先查看并修正网页区域,再确认一个创作主体。确认后会按原始顺序保存完整文章和相关资源。</p>
+ <p class="page-capture-session-note" data-i18n="公开原图失败时,只会使用当前网页已有登录状态读取已确认主体内的相关媒体;不会读取或保存登录信息。">公开原图失败时,只会使用当前网页已有登录状态读取已确认主体内的相关媒体;不会读取或保存登录信息。</p>
+ <div class="page-capture-bulk-actions" aria-label="主体区域确认">
+ <button id="page-capture-clear" class="button-secondary compact" type="button">取消主体确认</button>
+ <button id="page-capture-add-region" class="button-secondary compact" type="button">添加遗漏区域</button>
+ <button id="page-capture-exclude-region" class="button-secondary compact" type="button">排除错误区域</button>
+ <button id="page-capture-undo-region" class="button-secondary compact" type="button">撤销修正</button>
+ <button id="page-capture-reset-region" class="button-secondary compact" type="button">恢复自动识别</button>
</div>
+ <details id="page-capture-list-setup" class="page-capture-list-setup">
+ <summary>同一列表批量采集</summary>
+ <p>先确认上方一个代表案例,再输入目标数量。只滚动、加载当前列表或沿列表翻页,不进入详情页。</p>
+ <label><span>目标案例数</span><input id="page-capture-target-count" type="number" min="1" inputmode="numeric" placeholder="请输入数量" /></label>
+ <button id="page-capture-list-run" class="primary" type="button">按这个样本继续采集</button>
+ </details>
+ <section id="page-capture-list-result" class="page-capture-list-result" hidden>
+ <strong>批量保存方式</strong>
+ <p id="page-capture-list-summary"></p>
+ <label><span>保存形态</span><select id="page-capture-save-mode"><option value="">请选择</option><option value="multiple">分别保存多个案例</option><option value="combined">合并为一个案例</option></select></label>
+ <label id="page-capture-combined-title-row" hidden><span>合并案例标题</span><input id="page-capture-combined-title" autocomplete="off" placeholder="默认使用列表页标题" /></label>
+ </section>
<div id="page-capture-list" class="page-capture-list"></div>
+ <section id="page-capture-media-review" class="page-capture-media-review" hidden>
+ <header><strong>检查本次保存的媒体</strong><small id="page-capture-media-review-status">当前方案 0 项</small></header>
+ <p>正文内已定位媒体默认纳入;保存按钮就是最终授权。位置不确定的素材默认不选。</p>
+ <div id="page-capture-media-review-list" class="page-capture-media-review-list"></div>
+ </section>
<div class="page-capture-actions">
<button id="page-capture-cancel" class="button-secondary" type="button">取消</button>
- <button id="page-capture-save" class="primary" type="button">批量保存</button>
+ <button id="page-capture-save-text-only" class="button-secondary" type="button" hidden>只保存正文</button>
+ <button id="page-capture-save" class="primary" type="button">保存为一个案例</button>
</div>
</section>
+ <dialog id="page-capture-media-viewer" class="page-capture-media-viewer">
+ <header>
+ <div><small id="page-capture-media-position">媒体 0 / 0</small><strong id="page-capture-media-title">媒体预览</strong></div>
+ <button id="page-capture-media-close" class="quiet compact" type="button" aria-label="关闭媒体预览">关闭</button>
+ </header>
+ <div id="page-capture-media-stage" class="page-capture-media-stage"></div>
+ <p id="page-capture-media-meta"></p>
+ <footer>
+ <button id="page-capture-media-prev" class="button-secondary" type="button">上一项</button>
+ <button id="page-capture-media-next" class="button-secondary" type="button">下一项</button>
+ </footer>
+ </dialog>
+
<section id="region-capture-status" class="smart-selection region-capture-status" hidden aria-live="polite">
<div><small>框选截图</small><h2 id="region-capture-title">正在启动框选…</h2><p id="region-capture-help">请在网页中拖动选择画面;操作状态会持续显示在这里。</p></div>
<div class="smart-selection-actions"><button id="region-capture-cancel" class="button-secondary" type="button">取消框选</button></div>
@@ -107,7 +140,7 @@
</section>
<div class="add-more-actions">
<button id="add-smart-visuals" class="quiet" type="button">+ 智能选图</button>
- <button id="add-selection" class="quiet" type="button">+ 提取文字</button>
+ <button id="add-selection" class="quiet" type="button" data-i18n="+ 提取文字/图片">+ 提取文字/图片</button>
<button id="add-page-capture" class="quiet" type="button">+ 网页采集</button>
<details id="add-other-capture-methods" class="other-capture-methods compact-capture-methods">
<summary>智能选图无法识别?</summary>
@@ -140,7 +173,7 @@
</section>
</section>
- <p id="feedback" role="status" aria-live="polite"></p>
+ <p id="feedback" class="ui-feedback-toast" role="status" aria-live="polite"></p>
<footer id="collector-footer" class="collector-footer" hidden>
<button id="discard-draft" class="quiet" type="button">清空</button>
diff --git a/collector.js b/collector.js
index 3da7668..ee105be 100644
--- a/collector.js
+++ b/collector.js
@@ -1,22 +1,30 @@
-import { getScreenshotBlob } from "./image-store.js";
+import { deleteScreenshotBlob, getScreenshotBlob, saveScreenshotBlob } from "./image-store.js";
+import { addDraftFragment, addDraftVisual } from "./capture-draft.js";
+import { createTextCandidate } from "./capture-text-candidate.js";
import {
assignVisualPreviewSource,
collectorViewState
} from "./collector-view.js";
+import { prepareLocalMedia } from "./local-media.js";
import { runCaptureTransaction } from "./capture-workspace.js";
import {
ensureClipboardReadPermission,
- readClipboardTextAfterFocus
+ ensurePagePermission,
+ readClipboardContentAfterFocus
} from "./capture-permissions.js";
import { initializeUi, t } from "./i18n.js";
import { confirmAppAction } from "./ui-dialogs.js";
+import { createUiIcon } from "./ui-icons.js";
import { ingestHtmlDocument } from "./document-ingestion.js";
import {
applyPageCaptureSelections,
normalizePageCaptureBatch,
normalizePageCaptureSelection,
- pageCapturePermissionOrigins
+ pageCaptureDefaultMediaIds,
+ pageCapturePermissionOrigins,
+ pageCaptureStructureMatches
} from "./page-capture.js";
+import { PAGE_CAPTURE_LIMITS } from "./resource-limits.js";
await initializeUi();
@@ -27,8 +35,13 @@ const elements = Object.fromEntries([
"quick-preview", "result-prompt-title", "result-screenshot", "result-smart-visuals", "result-start", "save-draft", "save-other-inspiration",
"save-separate", "start-screenshot", "start-selection", "start-smart-visuals", "start-state", "normal-start",
"other-capture-methods", "add-other-capture-methods", "smart-selection", "smart-selection-count", "smart-selection-help", "smart-selection-warning", "smart-selection-cancel", "smart-selection-confirm",
- "start-page-capture", "add-page-capture", "page-capture", "page-capture-title", "page-capture-help", "page-capture-list", "page-capture-scan", "page-capture-cancel", "page-capture-save",
- "page-capture-select-recommended", "page-capture-select-text", "page-capture-select-images", "page-capture-clear",
+ "start-page-capture", "add-page-capture", "page-capture", "page-capture-title", "page-capture-help", "page-capture-list", "page-capture-scan", "page-capture-cancel", "page-capture-save", "page-capture-save-text-only",
+ "page-capture-clear", "page-capture-media-viewer", "page-capture-media-stage", "page-capture-media-position", "page-capture-media-title", "page-capture-media-meta",
+ "page-capture-media-review", "page-capture-media-review-status", "page-capture-media-review-list",
+ "page-capture-add-region", "page-capture-exclude-region", "page-capture-undo-region", "page-capture-reset-region",
+ "page-capture-media-close", "page-capture-media-prev", "page-capture-media-next",
+ "page-capture-list-setup", "page-capture-target-count", "page-capture-list-run", "page-capture-list-result", "page-capture-list-summary",
+ "page-capture-save-mode", "page-capture-combined-title-row", "page-capture-combined-title",
"region-capture-status", "region-capture-title", "region-capture-help", "region-capture-cancel",
"target-banner", "target-label", "visual-help", "visual-list", "visual-section"
].map((id) => [camel(id), document.getElementById(id)]));
@@ -49,7 +62,18 @@ let smartVisualCommitCreative = false;
let regionCaptureState = null;
let pageCaptureBatch = null;
let pageCaptureSession = null;
+let pageCaptureMediaView = null;
+let pageCaptureEditHistory = [];
+let pageCaptureOriginalCandidates = new Map();
const visualUrls = new Map();
+const FEEDBACK_DURATION_MS = 4000;
+const ERROR_FEEDBACK_DURATION_MS = 8000;
+let feedbackTimer = 0;
+const CLIPBOARD_IMAGE_EXTENSIONS = Object.freeze({
+ "image/png": "png",
+ "image/jpeg": "jpg",
+ "image/webp": "webp"
+});
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== "local" || !(changes.captureDraft || changes.activeCreativeResult || changes.composerSessions)) return;
@@ -58,27 +82,45 @@ chrome.storage.onChanged.addListener((changes, areaName) => {
await refresh();
await tryAutoSelection();
+elements.pageCaptureTargetCount.max = String(PAGE_CAPTURE_LIMITS.maxCandidates);
elements.openLibrary.addEventListener("click", () => void openLibraryTab());
window.addEventListener("focus", () => void tryAutoSelection());
-elements.startSelection.addEventListener("click", () => extractText(elements.startSelection));
+window.addEventListener("pagehide", () => void clearPageCaptureMarkers());
+elements.startSelection.addEventListener("click", () => extractClipboardOrSelection(elements.startSelection));
elements.startScreenshot.addEventListener("click", () => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.startScreenshot));
elements.startSmartVisuals.addEventListener("click", () => beginSmartVisualSelection(elements.startSmartVisuals));
elements.startPageCapture.addEventListener("click", () => startPageCapture("loaded", elements.startPageCapture));
elements.resultScreenshot.addEventListener("click", () => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.resultScreenshot, true));
elements.resultSmartVisuals.addEventListener("click", () => beginSmartVisualSelection(elements.resultSmartVisuals, true));
elements.saveOtherInspiration.addEventListener("click", () => clearActiveCreativeResult());
-elements.addSelection.addEventListener("click", () => extractText(elements.addSelection));
+elements.addSelection.addEventListener("click", () => extractClipboardOrSelection(elements.addSelection));
elements.addScreenshot.addEventListener("click", () => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.addScreenshot));
elements.addSmartVisuals.addEventListener("click", () => beginSmartVisualSelection(elements.addSmartVisuals));
elements.addPageCapture.addEventListener("click", () => startPageCapture("loaded", elements.addPageCapture));
-elements.pageCaptureScan.addEventListener("click", () => startPageCapture("whole", elements.pageCaptureScan));
+elements.pageCaptureScan.addEventListener("click", () => {
+ elements.pageCaptureListSetup.open = true;
+ elements.pageCaptureTargetCount.focus();
+});
+elements.pageCaptureListRun.addEventListener("click", () => startPageListCapture(elements.pageCaptureListRun));
+elements.pageCaptureSaveMode.addEventListener("change", () => {
+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, saveMode: elements.pageCaptureSaveMode.value });
+ render();
+});
+elements.pageCaptureCombinedTitle.addEventListener("change", () => {
+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, combinedTitle: elements.pageCaptureCombinedTitle.value });
+});
elements.pageCaptureCancel.addEventListener("click", cancelPageCapture);
-elements.pageCaptureSave.addEventListener("click", savePageCapture);
-elements.pageCaptureSelectRecommended.addEventListener("click", () => selectPageCaptureComponents("recommended"));
-elements.pageCaptureSelectText.addEventListener("click", () => selectPageCaptureComponents("text"));
-elements.pageCaptureSelectImages.addEventListener("click", () => selectPageCaptureComponents("images"));
-elements.pageCaptureClear.addEventListener("click", () => selectPageCaptureComponents("clear"));
+elements.pageCaptureSave.addEventListener("click", () => savePageCapture(false));
+elements.pageCaptureSaveTextOnly.addEventListener("click", () => savePageCapture(true));
+elements.pageCaptureClear.addEventListener("click", clearPageCaptureConfirmation);
+elements.pageCaptureAddRegion.addEventListener("click", () => editConfirmedPageCaptureRegion("include", elements.pageCaptureAddRegion));
+elements.pageCaptureExcludeRegion.addEventListener("click", () => editConfirmedPageCaptureRegion("exclude", elements.pageCaptureExcludeRegion));
+elements.pageCaptureUndoRegion.addEventListener("click", undoPageCaptureRegionEdit);
+elements.pageCaptureResetRegion.addEventListener("click", resetPageCaptureRegionEdit);
+elements.pageCaptureMediaClose.addEventListener("click", closePageCaptureMediaViewer);
+elements.pageCaptureMediaPrev.addEventListener("click", () => movePageCaptureMediaViewer(-1));
+elements.pageCaptureMediaNext.addEventListener("click", () => movePageCaptureMediaViewer(1));
elements.regionCaptureCancel.addEventListener("click", cancelRegionCapture);
elements.smartSelectionCancel.addEventListener("click", cancelSmartVisualSelection);
elements.smartSelectionConfirm.addEventListener("click", confirmSmartVisualSelection);
@@ -175,52 +217,102 @@ async function tryAutoSelection() {
}
}
-async function extractText(button) {
+async function extractClipboardOrSelection(button) {
await withButton(button, async () => {
try {
- const selection = await runCaptureTransaction({
- type: "ADD_ACTIVE_SELECTION_TO_DRAFT",
- chromeApi: chrome,
- onStatus: showFeedback
- });
- if (selection.captured?.added || selection.captured?.reason !== "empty-selection") {
+ let selection = null;
+ try {
+ selection = await runCaptureTransaction({
+ type: "ADD_ACTIVE_SELECTION_TO_DRAFT",
+ chromeApi: chrome,
+ onStatus: showFeedback
+ });
+ } catch {
+ }
+ if (selection && (selection.captured?.added || selection.captured?.reason !== "empty-selection")) {
draft = selection.draft;
showFeedback(selection.message || "已提取网页高亮文字");
await refresh();
return;
}
- showFeedback("当前网页没有高亮文字;Chrome 将询问一次剪贴板读取权限");
+ showFeedback("当前网页没有可提取的高亮;Chrome 将询问一次剪贴板读取权限");
if (!await ensureClipboardReadPermission(chrome.permissions)) {
- showFeedback("未获得剪贴板读取权限,未提取任何文字", true);
+ showFeedback("未获得剪贴板读取权限,未提取文字或图片", true);
return;
}
- let clipboardText;
+ let clipboardContent;
try {
- clipboardText = await readClipboardTextAfterFocus();
+ clipboardContent = await readClipboardContentAfterFocus();
} catch {
showFeedback("剪贴板读取失败,请保持采集台获得焦点后再试", true);
return;
}
- const response = await chrome.runtime.sendMessage({
- type: "ADD_CLIPBOARD_TEXT_TO_DRAFT",
- text: clipboardText
- });
- if (!response?.ok || !response.added) {
- showFeedback(response?.message || "剪贴板里没有可提取的文字", true);
+ const response = await addClipboardContentToDraft(clipboardContent);
+ if (!response.added) {
+ showFeedback(response.message, true);
return;
}
draft = response.draft;
- showFeedback("已提取剪贴板文字");
+ showFeedback(response.message);
await refresh();
} catch (error) {
if (error?.draft) draft = error.draft;
if (draft) render();
- showFeedback(error.message || "文字提取失败", true);
+ showFeedback(error.message || "文字或图片提取失败", true);
}
});
}
+async function addClipboardContentToDraft({ text: clipboardText, image } = {}) {
+ let nextDraft = draft;
+ let addedText = false;
+ let addedImage = false;
+ let storedVisualId = "";
+ const candidate = await createTextCandidate({ clipboard: clipboardText });
+ if (candidate) {
+ const result = addDraftFragment(nextDraft, candidate);
+ nextDraft = result.draft;
+ addedText = result.added;
+ }
+ if (image instanceof Blob) {
+ const extension = CLIPBOARD_IMAGE_EXTENSIONS[image.type.toLocaleLowerCase("en-US")];
+ if (!extension) throw new Error("剪贴板图片格式暂不支持");
+ const visualId = crypto.randomUUID();
+ const prepared = await prepareLocalMedia(
+ new File([image], `clipboard.${extension}`, { type: image.type }),
+ visualId,
+ { estimateStorage: () => navigator.storage?.estimate?.() ?? {} }
+ );
+ const duplicate = prepared.asset.contentHash && nextDraft.visuals.some((visual) => visual.contentHash === prepared.asset.contentHash);
+ if (!duplicate) {
+ await saveScreenshotBlob(visualId, prepared.blob);
+ storedVisualId = visualId;
+ nextDraft = addDraftVisual(nextDraft, { ...prepared.asset, sourceTitle: "剪贴板" });
+ addedImage = true;
+ }
+ }
+ if (!addedText && !addedImage) {
+ return {
+ added: false,
+ message: candidate || image ? "剪贴板里的文字或图片已经在当前草稿中" : "剪贴板里没有可提取的文字或图片",
+ draft
+ };
+ }
+ try {
+ const response = await chrome.runtime.sendMessage({ type: "UPDATE_CAPTURE_DRAFT", draft: nextDraft });
+ if (!response?.ok) throw new Error(response?.message || "剪贴板内容没有写入草稿");
+ return {
+ added: true,
+ message: addedText && addedImage ? "已提取剪贴板文字和图片" : addedImage ? "已提取剪贴板图片" : "已提取剪贴板文字",
+ draft: response.draft
+ };
+ } catch (error) {
+ if (storedVisualId) await deleteScreenshotBlob(storedVisualId).catch(() => undefined);
+ throw error;
+ }
+}
+
function render() {
if (!draft) return;
const view = collectorViewState(draft, targetEntry, { organizing });
@@ -319,74 +411,189 @@ function render() {
function renderPageCapture() {
const selections = new Map(pageCaptureBatch.selections.map((selection) => [selection.candidateId, selection]));
- const selectedCount = pageCaptureBatch.selections.reduce((total, selection) => total + Number(selection.includeText) + selection.selectedMediaIds.length, 0);
- elements.pageCaptureTitle.textContent = t("已识别 {count} 项 · 已确认 {selected} 项内容", { count: pageCaptureBatch.candidates.length, selected: selectedCount });
+ const selectedCount = pageCaptureBatch.selections.length;
+ const listMode = pageCaptureBatch.captureMode === "list";
+ elements.pageCaptureTitle.textContent = t("已识别 {count} 个主体方案 · 已确认 {selected} 个", { count: pageCaptureBatch.candidates.length, selected: selectedCount });
elements.pageCaptureHelp.textContent = pageCaptureBatch.status === "scanning"
? t("正在扫描已加载内容;可随时停止,结束后会恢复原滚动位置。")
- : t("扫描不会自动保存。请确认正文、图片或视频,未勾选的内容不会进入案例库。");
- elements.pageCaptureSave.disabled = !selectedCount || pageCaptureBatch.status === "saving";
+ : t("先查看并修正网页区域,再确认一个创作主体。确认后会按原始顺序保存完整文章和相关资源。");
+ const selectedMediaCount = pageCaptureBatch.selections.reduce((count, selection) => count + selection.selectedMediaIds.length, 0);
+ const saveBlocked = !selectedCount || pageCaptureBatch.status === "saving" || (listMode && !["multiple", "combined"].includes(pageCaptureBatch.saveMode));
+ elements.pageCaptureSave.disabled = saveBlocked;
+ elements.pageCaptureSaveTextOnly.disabled = saveBlocked;
+ elements.pageCaptureSaveTextOnly.hidden = selectedMediaCount === 0;
+ elements.pageCaptureSave.textContent = listMode
+ ? selectedMediaCount
+ ? t("保存 {cases} 个案例 · 含 {media} 项媒体", { cases: selectedCount, media: selectedMediaCount })
+ : t("只保存 {count} 个正文案例", { count: selectedCount })
+ : selectedMediaCount ? t("保存案例 · 含 {count} 项媒体", { count: selectedMediaCount }) : t("只保存正文");
+ elements.pageCaptureScan.hidden = listMode;
+ elements.pageCaptureListSetup.hidden = listMode;
+ elements.pageCaptureListResult.hidden = !listMode;
+ if (listMode) {
+ const reviewCount = pageCaptureBatch.candidates.filter((candidate) => candidate.batchStructureStatus === "review").length;
+ elements.pageCaptureListSummary.textContent = t("目标 {target} 个,实际识别 {actual} 个。{reason}", {
+ target: pageCaptureBatch.targetCount,
+ actual: pageCaptureBatch.candidates.length,
+ reason: pageCaptureStopReasonLabel(pageCaptureBatch.stopReason)
+ }) + (reviewCount ? t(" · {count} 个结构不同的案例未自动加入,请单独确认。", { count: reviewCount }) : "");
+ if (document.activeElement !== elements.pageCaptureSaveMode) elements.pageCaptureSaveMode.value = pageCaptureBatch.saveMode;
+ elements.pageCaptureCombinedTitleRow.hidden = pageCaptureBatch.saveMode !== "combined";
+ if (document.activeElement !== elements.pageCaptureCombinedTitle) elements.pageCaptureCombinedTitle.value = pageCaptureBatch.combinedTitle;
+ }
elements.pageCaptureList.replaceChildren(...pageCaptureBatch.candidates.map((candidate) => {
const card = document.createElement("article");
- card.className = "page-capture-item";
+ const confirmed = selections.has(candidate.id);
+ card.className = `page-capture-item${confirmed ? " confirmed" : ""}`;
+ if (candidate.batchStructureStatus === "review") card.classList.add("structure-review");
const heading = document.createElement("header");
const copy = document.createElement("div");
const title = document.createElement("strong");
title.textContent = candidate.title;
const meta = document.createElement("small");
- meta.textContent = `${pageCaptureTypeLabel(candidate.pageType)} · ${hostname(candidate.canonicalUrl) || t("当前网页")}${candidate.sourceFacts.author ? ` · ${candidate.sourceFacts.author}` : ""}`;
+ const captureScope = candidate.extraction.scope === "selection" ? t("原网页选区") : pageCaptureExtractionLabel(candidate.extraction.method);
+ meta.textContent = `${pageCaptureTypeLabel(candidate.pageType)} · ${hostname(candidate.canonicalUrl) || t("当前网页")} · ${captureScope}${candidate.sourceFacts.author ? ` · ${candidate.sourceFacts.author}` : ""}${candidate.batchStructureStatus === "review" ? ` · ${t("结构需复核")}` : ""}`;
copy.append(title, meta);
+ const inspect = document.createElement("button");
+ inspect.type = "button";
+ inspect.className = "button-secondary compact page-capture-inspect";
+ inspect.textContent = t("查看网页区域");
+ inspect.addEventListener("click", () => previewPageCaptureRegion(candidate));
heading.append(copy);
+ if (!listMode) heading.append(inspect);
card.append(heading);
- const selection = selections.get(candidate.id) || { candidateId: candidate.id, includeText: false, selectedMediaIds: [] };
- if (candidate.contentText || candidate.excerpt) {
- const textChoice = document.createElement("label");
- textChoice.className = "page-capture-component page-capture-text";
- const input = document.createElement("input");
- input.type = "checkbox";
- input.checked = selection.includeText;
- input.addEventListener("change", () => updatePageCaptureSelection(candidate.id, { includeText: input.checked }));
- const textCopy = document.createElement("span");
- const words = [...String(candidate.contentText || candidate.excerpt)].length;
- textCopy.append(textNode("strong", t("正文")), textNode("small", t("{count} 字", { count: words })), textNode("p", candidate.excerpt || candidate.contentText.slice(0, 180)));
- textChoice.append(input, textCopy);
- card.append(textChoice);
- }
- if (candidate.media.length) {
- const mediaGrid = document.createElement("div");
- mediaGrid.className = "page-capture-media-grid";
- for (const media of candidate.media) {
- const mediaChoice = document.createElement("label");
- mediaChoice.className = "page-capture-component page-capture-media";
- const input = document.createElement("input");
- input.type = "checkbox";
- input.checked = selection.selectedMediaIds.includes(media.id);
- input.addEventListener("change", () => {
- const ids = new Set(selection.selectedMediaIds);
- if (input.checked) ids.add(media.id); else ids.delete(media.id);
- updatePageCaptureSelection(candidate.id, { selectedMediaIds: [...ids] });
- });
- const preview = document.createElement("span");
- preview.className = "page-capture-media-preview";
- const previewUrl = media.kind === "video" ? media.posterUrl : media.dataUrl || media.url;
- if (previewUrl) {
- const image = document.createElement("img");
- image.src = previewUrl;
- image.alt = "";
- image.referrerPolicy = "no-referrer";
- preview.append(image);
- } else {
- preview.textContent = media.kind === "video" ? "VIDEO" : "IMAGE";
- }
- const mediaCopy = document.createElement("span");
- const dimensions = media.width && media.height ? ` · ${media.width}×${media.height}` : "";
- mediaCopy.append(textNode("strong", media.kind === "video" ? t("视频引用") : t("图片")), textNode("small", `${media.alt || hostname(media.url || media.posterUrl) || t("可见媒体")}${dimensions}`));
- mediaChoice.append(input, preview, mediaCopy);
- mediaGrid.append(mediaChoice);
- }
- card.append(mediaGrid);
+ card.append(createPageCaptureArticlePreview(candidate, selections.get(candidate.id)));
+ if (candidate.possibleOmissions?.length) {
+ const omissions = document.createElement("details");
+ omissions.className = "page-capture-omissions";
+ const summary = document.createElement("summary");
+ summary.textContent = t("可能遗漏({count})", { count: candidate.possibleOmissions.length });
+ const list = document.createElement("div");
+ list.append(...candidate.possibleOmissions.map((item) => {
+ const block = document.createElement("p");
+ block.textContent = item.text;
+ return block;
+ }));
+ omissions.append(summary, list);
+ card.append(omissions);
}
+ const confirm = document.createElement("button");
+ confirm.type = "button";
+ confirm.className = confirmed ? "button-secondary page-capture-confirm" : "primary page-capture-confirm";
+ confirm.textContent = listMode && confirmed ? t("移除此案例") : confirmed ? t("已确认这个主体") : t("确认这个主体");
+ confirm.disabled = confirmed && !listMode;
+ confirm.addEventListener("click", () => listMode && confirmed ? removePageCaptureCandidate(candidate.id) : confirmPageCaptureCandidate(candidate));
+ card.append(confirm);
return card;
}));
+ const canEditRegion = !listMode && selectedCount === 1;
+ elements.pageCaptureAddRegion.disabled = !canEditRegion;
+ elements.pageCaptureExcludeRegion.disabled = !canEditRegion;
+ elements.pageCaptureUndoRegion.disabled = !canEditRegion || !pageCaptureEditHistory.length;
+ elements.pageCaptureResetRegion.disabled = !canEditRegion || !pageCaptureEditHistory.length;
+ elements.pageCaptureAddRegion.hidden = listMode;
+ elements.pageCaptureExcludeRegion.hidden = listMode;
+ elements.pageCaptureUndoRegion.hidden = listMode;
+ elements.pageCaptureResetRegion.hidden = listMode;
+ renderPageCaptureMediaReview(selections);
+}
+
+function createPageCaptureArticlePreview(candidate, selection) {
+ const section = document.createElement("section");
+ section.className = "page-capture-article";
+ const heading = document.createElement("header");
+ const blocks = candidate.articleDocument?.blocks?.length
+ ? candidate.articleDocument.blocks
+ : [
+ ...candidate.textBlocks.map((block, sourceOrder) => ({ ...block, kind: block.kind === "section" ? "paragraph" : block.kind, sourceOrder })),
+ ...candidate.media.filter((media) => media.placement === "inline").map((media, index) => ({ id: `fallback:${media.id}`, kind: media.kind, assetId: media.id, sourceUrl: media.url, label: media.alt, sourceOrder: candidate.textBlocks.length + index }))
+ ];
+ heading.append(
+ textNode("strong", candidate.extraction.scope === "selection" ? t("原网页选区") : "完整文章预览"),
+ textNode("small", `${blocks.length} 个有序内容块`)
+ );
+ section.append(heading);
+ const mediaById = new Map(candidate.media.map((media) => [media.id, media]));
+ for (const block of blocks.toSorted((left, right) => left.sourceOrder - right.sourceOrder)) {
+ const media = block.assetId ? mediaById.get(block.assetId) : null;
+ if (["image", "video"].includes(block.kind)) {
+ section.append(createPageCaptureArticleMedia(candidate, media, block, selection));
+ continue;
+ }
+ if (["document", "link"].includes(block.kind)) {
+ section.append(createPageCaptureArticleResource(media, block, selection));
+ continue;
+ }
+ const tagName = block.kind === "heading" ? `h${Math.min(6, Math.max(1, Number(block.level) || 2))}`
+ : block.kind === "quote" ? "blockquote" : block.kind === "code" ? "pre" : "p";
+ const node = textNode(tagName, block.text || "");
+ if (block.kind === "list") node.textContent = block.text.split("\n").map((item) => `• ${item}`).join("\n");
+ section.append(node);
+ }
+ return section;
+}
+
+function createPageCaptureArticleMedia(candidate, media, block, selection) {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "page-capture-article-media";
+ setPageCaptureMediaDecisionClass(button, media?.id, selection);
+ const mediaIndex = media ? candidate.media.findIndex((item) => item.id === media.id) : -1;
+ if (mediaIndex >= 0) button.addEventListener("click", () => openPageCaptureMediaViewer(candidate, mediaIndex));
+ else if (block.sourceUrl) button.addEventListener("click", () => openPageCaptureArticleUrl(block.sourceUrl));
+ const preview = document.createElement("span");
+ preview.className = "page-capture-media-preview";
+ const previewUrl = media?.kind === "video" ? media.posterUrl : media?.previewDataUrl || media?.dataUrl || media?.url || block.posterUrl || block.sourceUrl;
+ if (previewUrl) {
+ const image = document.createElement("img");
+ image.src = previewUrl;
+ image.alt = "";
+ image.referrerPolicy = "no-referrer";
+ image.addEventListener("error", () => {
+ preview.replaceChildren(textNode("span", t("预览不可用")));
+ button.classList.add("preview-unavailable");
+ }, { once: true });
+ preview.append(image);
+ } else preview.textContent = block.kind === "video" ? "VIDEO" : t("预览不可用");
+ const copy = document.createElement("span");
+ const evidence = [];
+ if (media?.width && media?.height) evidence.push(`${media.width}×${media.height}`);
+ if (media?.declaredWidth) evidence.push(t("候选 {count}px", { count: media.declaredWidth }));
+ else if (media?.density > 1) evidence.push(t("候选 {count}x", { count: media.density }));
+ if (media?.kind === "image") evidence.push(pageCaptureMediaSourceLabel(media.sourceKind, media.captureMethod));
+ copy.append(
+ textNode("strong", block.kind === "video" ? t("视频引用") : t("图片")),
+ textNode("small", [block.label || media?.alt || hostname(block.sourceUrl || media?.url) || t("可见媒体"), ...evidence].filter(Boolean).join(" · "))
+ );
+ button.append(preview, copy);
+ return button;
+}
+
+function createPageCaptureArticleResource(media, block, selection) {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "page-capture-article-resource";
+ if (block.kind === "document") setPageCaptureMediaDecisionClass(button, media?.id, selection);
+ const sourceUrl = block.sourceUrl || media?.url || "";
+ button.disabled = !sourceUrl;
+ if (sourceUrl) button.addEventListener("click", () => openPageCaptureArticleUrl(sourceUrl));
+ button.append(
+ textNode("span", block.kind === "document" ? "DOC" : "LINK"),
+ textNode("span", block.label || media?.filename || hostname(sourceUrl) || "下载资源")
+ );
+ return button;
+}
+
+function openPageCaptureArticleUrl(url) {
+ chrome.tabs.create({ url, active: true }).catch(() => showFeedback("无法打开这个文章资源", true));
+}
+
+function removePageCaptureCandidate(candidateId) {
+ pageCaptureBatch = normalizePageCaptureBatch({
+ ...pageCaptureBatch,
+ selections: pageCaptureBatch.selections.filter((item) => item.candidateId !== candidateId)
+ });
+ render();
}
function textNode(tagName, value) {
@@ -395,72 +602,303 @@ function textNode(tagName, value) {
return node;
}
-function updatePageCaptureSelection(candidateId, patch) {
- const current = pageCaptureBatch.selections.find((item) => item.candidateId === candidateId)
- || { candidateId, includeText: false, selectedMediaIds: [] };
- const next = normalizePageCaptureSelection({ ...current, ...patch }, pageCaptureBatch.candidates);
+function confirmPageCaptureCandidate(candidate) {
+ const next = normalizePageCaptureSelection({
+ candidateId: candidate.id,
+ selectedTextBlockIds: candidate.textBlocks.map((item) => item.id),
+ selectedMediaIds: pageCaptureDefaultMediaIds(candidate),
+ mediaDecision: "pending"
+ }, pageCaptureBatch.candidates);
pageCaptureBatch = normalizePageCaptureBatch({
...pageCaptureBatch,
- selections: [...pageCaptureBatch.selections.filter((item) => item.candidateId !== candidateId), ...(next ? [next] : [])]
+ selections: next ? [next] : []
});
+ previewPageCaptureRegion(candidate);
render();
}
-function selectPageCaptureComponents(mode) {
- const current = new Map(pageCaptureBatch.selections.map((item) => [item.candidateId, item]));
- const selections = pageCaptureBatch.candidates.flatMap((candidate) => {
- if (mode === "clear") return [];
- const previous = current.get(candidate.id) || { candidateId: candidate.id, includeText: false, selectedMediaIds: [] };
- const value = mode === "text"
- ? { candidateId: candidate.id, includeText: Boolean(candidate.contentText || candidate.excerpt), selectedMediaIds: [] }
- : mode === "images"
- ? { ...previous, selectedMediaIds: candidate.media.filter((item) => item.kind === "image").map((item) => item.id) }
- : {
- candidateId: candidate.id,
- includeText: Boolean(candidate.contentText || candidate.excerpt),
- selectedMediaIds: candidate.media.map((item) => item.id)
- };
- const selection = normalizePageCaptureSelection(value, pageCaptureBatch.candidates);
- return selection ? [selection] : [];
+function clearPageCaptureConfirmation() {
+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, selections: [] });
+ previewPageCaptureRegion(null);
+ render();
+}
+
+function previewPageCaptureRegion(candidate) {
+ chrome.runtime.sendMessage({
+ type: "PREVIEW_PAGE_CAPTURE_REGION",
+ tabId: pageCaptureBatch?.tabId,
+ marker: candidate?.region?.marker || ""
+ }).catch(() => undefined);
+}
+
+async function editConfirmedPageCaptureRegion(mode, button) {
+ const selectedId = pageCaptureBatch?.selections?.[0]?.candidateId;
+ const candidate = pageCaptureBatch?.candidates?.find((item) => item.id === selectedId);
+ if (!candidate) return showFeedback("请先确认一个主体方案", true);
+ await withButton(button, async () => {
+ const response = await chrome.runtime.sendMessage({
+ type: "EDIT_PAGE_CAPTURE_REGION",
+ tabId: pageCaptureBatch.tabId,
+ candidate,
+ mode
+ });
+ if (!response?.ok) {
+ if (!response?.cancelled) showFeedback(response?.message || "网页区域没有修改", true);
+ return;
+ }
+ pageCaptureEditHistory.push({ candidateId: candidate.id, candidate: structuredClone(candidate) });
+ replacePageCaptureCandidate(response.candidate);
+ showFeedback(response.message);
+ });
+}
+
+function replacePageCaptureCandidate(candidate) {
+ const candidates = pageCaptureBatch.candidates.map((item) => item.id === candidate.id ? candidate : item);
+ const selection = normalizePageCaptureSelection({
+ candidateId: candidate.id,
+ selectedTextBlockIds: candidate.textBlocks.map((item) => item.id),
+ selectedMediaIds: pageCaptureDefaultMediaIds(candidate),
+ mediaDecision: "pending"
+ }, candidates);
+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, candidates, selections: selection ? [selection] : [] });
+ previewPageCaptureRegion(candidate);
+ render();
+}
+
+function renderPageCaptureMediaReview(selections) {
+ const selected = pageCaptureBatch.candidates.flatMap((candidate) => {
+ const selection = selections.get(candidate.id);
+ return selection ? candidate.media.map((media, mediaIndex) => ({ candidate, media, mediaIndex, selection })) : [];
+ });
+ elements.pageCaptureMediaReview.hidden = pageCaptureBatch.selections.length === 0;
+ if (!pageCaptureBatch.selections.length) {
+ elements.pageCaptureMediaReviewList.replaceChildren();
+ return;
+ }
+ const proposedCount = pageCaptureBatch.selections.reduce((count, selection) => count + selection.selectedMediaIds.length, 0);
+ elements.pageCaptureMediaReviewStatus.textContent = selected.length
+ ? t("保存时将确认 {count} 项媒体", { count: proposedCount })
+ : t("未识别到媒体,可返回网页补选");
+ const createRow = ({ candidate, media, mediaIndex, selection }) => {
+ const row = document.createElement("div");
+ row.className = "page-capture-media-review-item";
+ setPageCaptureMediaDecisionClass(row, media.id, selection);
+ const preview = document.createElement("button");
+ preview.type = "button";
+ preview.className = "page-capture-media-review-preview";
+ preview.addEventListener("click", () => openPageCaptureMediaViewer(candidate, mediaIndex));
+ const previewUrl = media.kind === "video" ? media.posterUrl : media.previewDataUrl || media.dataUrl || media.url;
+ if (previewUrl) {
+ const image = document.createElement("img");
+ image.src = previewUrl;
+ image.alt = "";
+ image.referrerPolicy = "no-referrer";
+ image.addEventListener("error", () => preview.replaceChildren(textNode("span", t("预览不可用"))), { once: true });
+ preview.append(image);
+ } else preview.append(textNode("span", media.kind === "video" ? "VIDEO" : "DOC"));
+ const copy = document.createElement("span");
+ copy.append(
+ textNode("strong", media.kind === "video" ? t("视频") : media.kind === "document" ? t("文档") : media.captureMethod === "pixel-fallback" ? t("页面截图") : t("图片")),
+ textNode("small", media.alt || media.filename || hostname(media.url || media.posterUrl) || t("可见媒体"))
+ );
+ const toggle = document.createElement("button");
+ toggle.type = "button";
+ toggle.className = "button-secondary compact";
+ const included = selection.mediaDecision !== "none" && selection.selectedMediaIds.includes(media.id);
+ toggle.textContent = included ? t("排除") : t("恢复");
+ toggle.addEventListener("click", () => updatePageCaptureMediaSelection(candidate.id, media.id));
+ row.append(preview, copy, toggle);
+ return row;
+ };
+ const inline = selected.filter(({ media }) => media.placement === "inline");
+ const unplaced = selected.filter(({ media }) => media.placement !== "inline");
+ const nodes = inline.map(createRow);
+ if (unplaced.length) {
+ const group = document.createElement("details");
+ group.className = "page-capture-media-review-group";
+ const summary = document.createElement("summary");
+ summary.textContent = t("可能遗漏媒体({count})", { count: unplaced.length });
+ const list = document.createElement("div");
+ list.append(...unplaced.map(createRow));
+ group.append(summary, list);
+ nodes.push(group);
+ }
+ elements.pageCaptureMediaReviewList.replaceChildren(...nodes);
+}
+
+function setPageCaptureMediaDecisionClass(node, mediaId, selection) {
+ if (!selection || !mediaId) return;
+ const included = selection.mediaDecision !== "none" && selection.selectedMediaIds.includes(mediaId);
+ node.classList.add(included ? "media-proposed" : "media-excluded");
+ if (selection.mediaDecision === "pending") node.classList.add("media-pending");
+}
+
+function updatePageCaptureMediaSelection(candidateId, mediaId) {
+ const selections = pageCaptureBatch.selections.map((selection) => {
+ if (selection.candidateId !== candidateId) return selection;
+ const selected = new Set(selection.mediaDecision === "none" ? [] : selection.selectedMediaIds);
+ if (selected.has(mediaId)) selected.delete(mediaId);
+ else selected.add(mediaId);
+ return { ...selection, selectedMediaIds: [...selected], mediaDecision: "pending" };
});
pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, selections });
render();
}
+function finalizePageCaptureSelectionsForSave(batchValue, textOnly = false) {
+ const batch = normalizePageCaptureBatch(batchValue);
+ return normalizePageCaptureBatch({
+ ...batch,
+ selections: batch.selections.map((selection) => {
+ const selectedMediaIds = textOnly ? [] : selection.selectedMediaIds;
+ return {
+ ...selection,
+ selectedMediaIds,
+ mediaDecision: selectedMediaIds.length ? "confirmed" : "none"
+ };
+ })
+ });
+}
+
+function undoPageCaptureRegionEdit() {
+ const previous = pageCaptureEditHistory.pop();
+ if (!previous) return;
+ replacePageCaptureCandidate(previous.candidate);
+ showFeedback("已撤销上一次主体修正");
+}
+
+function resetPageCaptureRegionEdit() {
+ const selectedId = pageCaptureBatch?.selections?.[0]?.candidateId;
+ const original = pageCaptureOriginalCandidates.get(selectedId);
+ if (!original) return;
+ pageCaptureEditHistory = [];
+ replacePageCaptureCandidate(structuredClone(original));
+ showFeedback("已恢复本次扫描的自动识别结果");
+}
+
+function openPageCaptureMediaViewer(candidate, mediaIndex) {
+ pageCaptureMediaView = { candidateId: candidate.id, mediaIndex };
+ renderPageCaptureMediaViewer();
+ if (!elements.pageCaptureMediaViewer.open) elements.pageCaptureMediaViewer.showModal();
+}
+
+function closePageCaptureMediaViewer() {
+ pageCaptureMediaView = null;
+ elements.pageCaptureMediaStage.replaceChildren();
+ if (elements.pageCaptureMediaViewer.open) elements.pageCaptureMediaViewer.close();
+}
+
+function movePageCaptureMediaViewer(offset) {
+ const candidate = pageCaptureBatch?.candidates.find((item) => item.id === pageCaptureMediaView?.candidateId);
+ if (!candidate?.media.length) return;
+ pageCaptureMediaView.mediaIndex = (pageCaptureMediaView.mediaIndex + offset + candidate.media.length) % candidate.media.length;
+ renderPageCaptureMediaViewer();
+}
+
+function renderPageCaptureMediaViewer() {
+ const candidate = pageCaptureBatch?.candidates.find((item) => item.id === pageCaptureMediaView?.candidateId);
+ const media = candidate?.media[pageCaptureMediaView?.mediaIndex];
+ if (!media) return closePageCaptureMediaViewer();
+ const sourceUrl = media.kind === "video" ? media.url : media.previewDataUrl || media.dataUrl || media.url;
+ const visual = document.createElement(media.kind === "video" ? "video" : "img");
+ visual.src = sourceUrl || media.posterUrl || "";
+ visual.setAttribute("referrerpolicy", "no-referrer");
+ if (media.kind === "video") {
+ visual.controls = true;
+ visual.poster = media.posterUrl || "";
+ } else {
+ visual.alt = media.alt || candidate.title;
+ }
+ elements.pageCaptureMediaStage.replaceChildren(visual);
+ elements.pageCaptureMediaPosition.textContent = t("媒体 {current} / {count}", { current: pageCaptureMediaView.mediaIndex + 1, count: candidate.media.length });
+ elements.pageCaptureMediaTitle.textContent = media.alt || candidate.title;
+ elements.pageCaptureMediaMeta.textContent = [
+ media.width && media.height ? `${media.width}×${media.height}` : "",
+ pageCaptureMediaSourceLabel(media.sourceKind, media.captureMethod),
+ hostname(media.url || media.posterUrl)
+ ].filter(Boolean).join(" · ");
+ elements.pageCaptureMediaPrev.disabled = candidate.media.length < 2;
+ elements.pageCaptureMediaNext.disabled = candidate.media.length < 2;
+}
+
+function pageCaptureStopReasonLabel(value) {
+ return ({
+ "target-reached": t("已达到目标数量。"),
+ "no-new-items": t("列表没有新增案例,已按实际数量结束。"),
+ "no-next-page": t("没有可继续的列表页,已按实际数量结束。"),
+ "layout-changed": t("列表结构发生变化,已停止。"),
+ "pagination-failed": t("列表翻页失败,已按当前结果结束。"),
+ cancelled: t("采集已由用户停止。")
+ })[value] || t("已按当前列表可识别结果结束。");
+}
+
+function pageCaptureExtractionLabel(value) {
+ return ({ readability: t("智能正文"), structured: t("结构化正文"), page: t("页面正文") })[value] || t("页面正文");
+}
+
+function pageCaptureMediaSourceLabel(value, captureMethod = "") {
+ if (captureMethod === "pixel-fallback") return t("页面可见画面");
+ return ({
+ "site-original": t("站点原图"),
+ structured: t("结构化原图"),
+ "picture-srcset": t("picture 响应图"),
+ "deferred-srcset": t("延迟加载原图"),
+ "deferred-src": t("延迟加载原图"),
+ "img-srcset": t("srcset 响应图"),
+ "css-background": t("CSS 背景图"),
+ current: t("页面当前图"),
+ source: t("页面当前图")
+ })[value] || t("页面当前图");
+}
+
async function cancelPageCapture() {
if (pageCaptureBatch?.status !== "scanning" || !pageCaptureSession?.sessionId) {
+ await clearPageCaptureMarkers();
pageCaptureBatch = null;
pageCaptureSession = null;
+ pageCaptureEditHistory = [];
+ pageCaptureOriginalCandidates = new Map();
return render();
}
const response = await chrome.runtime.sendMessage({ type: "CANCEL_PAGE_CAPTURE", sessionId: pageCaptureSession.sessionId });
+ await clearPageCaptureMarkers();
showFeedback(response?.message || t("正在停止整页扫描"), !response?.ok);
}
+async function clearPageCaptureMarkers() {
+ const tabId = pageCaptureBatch?.tabId;
+ if (!Number.isInteger(tabId)) return;
+ await chrome.runtime.sendMessage({ type: "CLEAR_PAGE_CAPTURE_MARKERS", tabId, removeRegionMarkers: true }).catch(() => undefined);
+}
+
function pageCaptureTypeLabel(value) {
return t(({ article: "文章", artwork: "作品", post: "帖子", gallery: "画廊", feed: "信息流", video: "视频", generic: "网页内容" })[value] || "网页内容");
}
function createQuickPreview() {
const nodes = [];
- if (draft.fragments.length) {
- const first = draft.fragments[0];
+ draft.fragments.forEach((fragment, index) => {
const card = div("quick-item quick-text");
const marker = text("Aa", "strong");
const copy = div("quick-copy");
- copy.append(text(first.text, "p"), text(first.sourceTitle || hostname(first.sourceUrl) || "当前网页", "small"));
- if (draft.fragments.length > 1) copy.append(text(`还有 ${draft.fragments.length - 1} 段文字`, "em"));
- card.append(marker, copy);
+ copy.append(text(fragment.text, "p"), text(fragment.sourceTitle || hostname(fragment.sourceUrl) || "当前网页", "small"));
+ const remove = createQuickRemoveButton(`删除第 ${index + 1} 段文字`, (button) =>
+ sendDraftAction(button, "REMOVE_CAPTURE_FRAGMENT", { fragmentId: fragment.id }));
+ card.append(marker, copy, remove);
nodes.push(card);
- }
+ });
if (draft.visuals.length) {
const card = div("quick-item quick-visuals");
const strip = div("quick-image-strip");
draft.visuals.forEach((visual, index) => {
+ const item = div("quick-image-item");
const image = document.createElement("img");
image.alt = visual.sourceTitle || `截图 ${index + 1}`;
loadVisual(image, visual.id);
- strip.append(image);
+ const remove = createQuickRemoveButton(`删除第 ${index + 1} 张图片`, (button) =>
+ sendDraftAction(button, "REMOVE_CAPTURE_VISUAL", { visualId: visual.id }));
+ item.append(image, remove);
+ strip.append(item);
});
const copy = div("quick-copy");
copy.append(text(`${draft.visuals.length} 张图片`, "strong"), text(draft.visuals[0].sourceTitle || hostname(draft.visuals[0].sourceUrl) || "当前网页", "small"));
@@ -470,6 +908,13 @@ function createQuickPreview() {
return nodes;
}
+function createQuickRemoveButton(ariaLabel, handler) {
+ const button = action("", handler, false, "quick-remove", ariaLabel);
+ button.title = ariaLabel;
+ button.append(createUiIcon("x"));
+ return button;
+}
+
function createFragmentCard(fragment, index, canReorder) {
const card = document.createElement("article");
card.className = "fragment-card";
@@ -602,22 +1047,52 @@ async function beginSmartVisualSelection(button, commitCreative = false) {
async function startPageCapture(mode, button) {
await withButton(button, async () => {
try {
+ const representative = mode === "list"
+ ? pageCaptureBatch?.candidates.find((candidate) => candidate.id === pageCaptureBatch.selections[0]?.candidateId) || null
+ : null;
+ const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
+ if (!tab?.url) throw new Error(t("请先切换到需要采集的普通网页"));
+ if (!await ensurePagePermission(tab.url, chrome.permissions)) {
+ throw new Error(t("没有获得当前网站权限,待保存内容没有改变"));
+ }
if (mode === "whole" && pageCaptureBatch) {
pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, status: "scanning" });
render();
}
- const response = await chrome.runtime.sendMessage({ type: "START_PAGE_CAPTURE", mode });
+ const targetCount = mode === "list" ? Number(elements.pageCaptureTargetCount.value) : 0;
+ const response = await chrome.runtime.sendMessage({ type: "START_PAGE_CAPTURE", mode, targetCount });
if (!response?.ok) throw new Error(response?.message || t("网页采集失败"));
const candidates = response.batch.candidates.map((candidate) => {
- if (!candidate.contentHtml) return candidate;
+ let contentText = candidate.contentText;
try {
- const documentResult = ingestHtmlDocument(candidate.contentHtml);
- return { ...candidate, contentText: documentResult.contentText || candidate.contentText };
+ if (candidate.contentHtml) contentText = ingestHtmlDocument(candidate.contentHtml).contentText || contentText;
} catch {
- return candidate;
}
+ const textBlocks = candidate.textBlocks.map((block) => {
+ if (!block.html) return block;
+ try {
+ return { ...block, text: ingestHtmlDocument(block.html).contentText || block.text };
+ } catch {
+ return block;
+ }
+ });
+ const normalized = { ...candidate, contentText, textBlocks };
+ return representative
+ ? { ...normalized, batchStructureStatus: pageCaptureStructureMatches(representative, normalized) ? "matched" : "review" }
+ : normalized;
});
- pageCaptureBatch = normalizePageCaptureBatch({ ...response.batch, candidates, status: "preview" });
+ const batch = normalizePageCaptureBatch({ ...response.batch, candidates, status: "preview" });
+ const selections = mode === "list"
+ ? batch.candidates.filter((candidate) => candidate.batchStructureStatus !== "review").map((candidate) => normalizePageCaptureSelection({
+ candidateId: candidate.id,
+ selectedTextBlockIds: candidate.textBlocks.map((item) => item.id),
+ selectedMediaIds: pageCaptureDefaultMediaIds(candidate),
+ mediaDecision: "pending"
+ }, batch.candidates)).filter(Boolean)
+ : batch.selections;
+ pageCaptureBatch = normalizePageCaptureBatch({ ...batch, selections });
+ pageCaptureEditHistory = [];
+ pageCaptureOriginalCandidates = new Map(pageCaptureBatch.candidates.map((candidate) => [candidate.id, structuredClone(candidate)]));
pageCaptureSession = null;
showFeedback(response.message);
render();
@@ -630,26 +1105,52 @@ async function startPageCapture(mode, button) {
});
}
-async function savePageCapture() {
+async function startPageListCapture(button) {
+ const targetCount = Number(elements.pageCaptureTargetCount.value);
+ if (!pageCaptureBatch?.selections.length) {
+ showFeedback(t("请先查看并确认一个代表案例,再开始列表采集"), true);
+ return;
+ }
+ if (!Number.isSafeInteger(targetCount) || targetCount < 1 || targetCount > PAGE_CAPTURE_LIMITS.maxCandidates) {
+ showFeedback(t("请输入 1 到 {count} 之间的目标案例数", { count: PAGE_CAPTURE_LIMITS.maxCandidates }), true);
+ return;
+ }
+ await startPageCapture("list", button);
+}
+
+async function savePageCapture(textOnly = false) {
if (!pageCaptureBatch) return;
- await withButton(elements.pageCaptureSave, async () => {
- const selected = applyPageCaptureSelections(pageCaptureBatch);
+ const trigger = textOnly ? elements.pageCaptureSaveTextOnly : elements.pageCaptureSave;
+ await withButton(trigger, async () => {
+ const reviewBatch = pageCaptureBatch;
+ const saveBatch = finalizePageCaptureSelectionsForSave(reviewBatch, textOnly);
+ const selected = applyPageCaptureSelections(saveBatch);
const origins = pageCapturePermissionOrigins(selected);
- pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, status: "saving" });
+ pageCaptureBatch = normalizePageCaptureBatch({ ...saveBatch, status: "saving" });
render();
try {
+ let sessionMediaAllowed = true;
if (origins.length) {
const granted = await chrome.permissions.request({ origins });
- if (!granted) showFeedback(t("媒体域名权限未获授权;仍会保存正文和可用引用,并逐项显示下载失败原因。"), true);
+ if (!granted) {
+ sessionMediaAllowed = false;
+ showFeedback(t("媒体域名权限未获授权;仍会保存正文和可用引用,并逐项显示下载失败原因。"), true);
+ }
}
- const response = await chrome.runtime.sendMessage({ type: "COMMIT_PAGE_CAPTURE", batch: pageCaptureBatch });
+ const response = await chrome.runtime.sendMessage({
+ type: "COMMIT_PAGE_CAPTURE",
+ batch: normalizePageCaptureBatch({ ...pageCaptureBatch, sessionMediaAllowed })
+ });
if (!response?.ok) throw new Error(response?.message || t("网页内容保存失败"));
const partial = response.results?.filter((item) => item.status === "partial" || item.status === "failed") || [];
+ await clearPageCaptureMarkers();
pageCaptureBatch = null;
+ pageCaptureEditHistory = [];
+ pageCaptureOriginalCandidates = new Map();
showFeedback(partial.length ? t("{message};{count} 项存在媒体下载问题", { message: response.message, count: partial.length }) : response.message, partial.length > 0);
await refresh();
} catch (error) {
- pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, status: "preview", error: error.message });
+ pageCaptureBatch = normalizePageCaptureBatch({ ...reviewBatch, status: "preview", error: error.message });
showFeedback(error.message || t("网页内容保存失败"), true);
render();
}
@@ -707,10 +1208,13 @@ async function clearActiveCreativeResult() {
}
async function sendDraftAction(button, type, payload = {}) {
+ const removedVisualUrl = type === "REMOVE_CAPTURE_VISUAL" ? visualUrls.get(payload.visualId) : "";
await withButton(button, async () => {
try {
const response = await chrome.runtime.sendMessage({ type, ...payload });
if (!response?.ok) throw new Error(response?.message || "内容更新失败");
+ if (removedVisualUrl) URL.revokeObjectURL(removedVisualUrl);
+ if (type === "REMOVE_CAPTURE_VISUAL") visualUrls.delete(payload.visualId);
draft = response.draft;
showFeedback(response.message || "待保存内容已更新");
await refresh();
@@ -828,8 +1332,18 @@ async function withButton(button, task) {
}
function showFeedback(message, error = false) {
- elements.feedback.textContent = message || "";
+ if (feedbackTimer) window.clearTimeout(feedbackTimer);
+ feedbackTimer = 0;
+ const value = message || "";
+ elements.feedback.textContent = value;
elements.feedback.classList.toggle("error", error);
+ if (value) {
+ feedbackTimer = window.setTimeout(() => {
+ elements.feedback.textContent = "";
+ elements.feedback.classList.remove("error");
+ feedbackTimer = 0;
+ }, error ? ERROR_FEEDBACK_DURATION_MS : FEEDBACK_DURATION_MS);
+ }
}
function action(label, handler, disabled = false, className = "", ariaLabel = "") {
diff --git a/composer-page.css b/composer-page.css
index e5241de..0dcf491 100644
--- a/composer-page.css
+++ b/composer-page.css
@@ -237,8 +237,10 @@
.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; }
.composer-reference-workspace[data-mode="references"] .composer-reference-body,
-.composer-reference-workspace[data-mode="methods"] .composer-reference-body { grid-template-columns: minmax(0, 1fr); }
-.composer-reference-workspace[data-mode="methods"] .composer-projects-panel { border-right: 0; }
+.composer-reference-workspace[data-mode="skills"] .composer-reference-body { grid-template-columns: minmax(0, 1fr); }
+.composer-reference-workspace[data-mode="skills"] .composer-projects-panel { border-right: 0; }
+.composer-reference-workspace[data-mode="skills"] .composer-reference-heading,
+.composer-reference-workspace[data-mode="skills"] .composer-project-list { width: min(1120px, 100%); margin-right: auto; margin-left: auto; }
.composer-projects-panel { min-height: 0; overflow: auto; border-right: 1px solid var(--line); padding: 22px 18px; background: var(--sidebar); }
.composer-case-picker { min-width: 0; min-height: 0; overflow: auto; padding: 22px clamp(18px, 3vw, 38px) 34px; }
.composer-reference-heading { display: flex; min-height: 42px; align-items: start; justify-content: space-between; gap: 18px; margin-bottom: 14px; }
@@ -249,12 +251,12 @@
.composer-reference-filters select, .composer-reference-filters input { min-height: 36px; font-size: 11px; }
.composer-reference-filters select { width: 160px; }
.composer-reference-search { width: min(320px, 36vw); }
-.composer-project-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 9px; }
-.composer-project-card { border: 1px solid var(--line); border-radius: 13px; padding: 12px; background: var(--card); }
+.composer-project-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); align-content: start; gap: 9px; }
+.composer-project-card { min-height: 154px; display: flex; flex-direction: column; border: 1px solid var(--line); border-radius: 13px; padding: 12px; background: var(--card); }
.composer-project-card > header { display: flex; align-items: start; justify-content: space-between; gap: 8px; }
.composer-project-card strong { font-size: 11px; }
.composer-project-card small { color: var(--muted); font-size: 9px; }
-.composer-project-card p { margin: 8px 0 0; color: var(--muted); font-size: 9px; line-height: 1.5; }
+.composer-project-card p { display: -webkit-box; flex: 1; overflow: hidden; margin: 8px 0 0; color: var(--muted); font-size: 9px; line-height: 1.5; -webkit-box-orient: vertical; -webkit-line-clamp: 3; }
.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); }
diff --git a/composer-page.js b/composer-page.js
index 24b83d5..2f1dc89 100644
--- a/composer-page.js
+++ b/composer-page.js
@@ -116,6 +116,7 @@ let creativeExperimentSettings = { enabled: false, autoAnalyze: false };
let composerSearchIndex = [];
let composerDocumentTextByEntryId = new Map();
let reuseRetrievedSourcesNextTurn = false;
+let creativeStateRefreshRevision = 0;
const imageWorkspace = createComposerImageWorkspace({
translate: t,
@@ -263,22 +264,31 @@ function bindEvents() {
}
async function refreshCreativeResultState() {
+ const revision = ++creativeStateRefreshRevision;
const response = await chrome.runtime.sendMessage({ type: "GET_STATE" });
- if (!response?.ok) return;
- physicalEntries = response.entries ?? physicalEntries;
- compoundCases = normalizeCompoundCases(response.compoundCases ?? compoundCases, physicalEntries);
- entries = materializeLogicalCases(physicalEntries, compoundCases);
- await rebuildComposerSearchIndex();
+ if (!response?.ok || revision !== creativeStateRefreshRevision) return;
+ const nextPhysicalEntries = response.entries ?? physicalEntries;
+ const nextCompoundCases = normalizeCompoundCases(response.compoundCases ?? compoundCases, nextPhysicalEntries);
+ const nextEntries = materializeLogicalCases(nextPhysicalEntries, nextCompoundCases);
creativeRuns = response.creativeRuns ?? creativeRuns;
creativeJobs = response.creativeJobs ?? creativeJobs;
creativeExperimentSettings = response.creativeExperimentSettings ?? creativeExperimentSettings;
creativeSkills = normalizeCreativeSkillsState(response.creativeSkills);
- await syncCreativeJobState();
- renderTimeline();
+ if (!await syncCreativeJobState(revision)) return;
+ renderActiveState();
renderSlashSkillMenu();
+
+ const searchState = await createComposerSearchState(nextEntries);
+ if (revision !== creativeStateRefreshRevision) return;
+ physicalEntries = nextPhysicalEntries;
+ compoundCases = nextCompoundCases;
+ entries = nextEntries;
+ composerDocumentTextByEntryId = searchState.documentTextByEntryId;
+ composerSearchIndex = searchState.searchIndex;
}
-async function syncCreativeJobState() {
+async function syncCreativeJobState(expectedRevision = null) {
+ const current = () => expectedRevision === null || expectedRevision === creativeStateRefreshRevision;
const items = Array.isArray(creativeJobs?.items) ? creativeJobs.items : [];
const active = items.find((item) => ["queued", "running"].includes(item.status)) ?? null;
lastCreativeJob = composerSession
@@ -287,6 +297,7 @@ async function syncCreativeJobState() {
if (active) {
if (!composerSession || composerSession.id === active.sessionId) {
const response = await chrome.runtime.sendMessage({ type: "GET_COMPOSER_SESSION", sessionId: active.sessionId });
+ if (!current()) return false;
if (!composerSession || composerSession.id === active.sessionId) {
composerSession = response?.ok ? response.session : active.request.session;
}
@@ -303,15 +314,17 @@ async function syncCreativeJobState() {
session: composerSession?.id === active.sessionId ? composerSession : active.request.session,
streamingText: ""
};
- return;
+ return true;
}
if (activeOperation?.durable) activeOperation = null;
- if (!lastCreativeJob || lastCreativeJob.sessionId !== composerSession?.id) return;
+ if (!lastCreativeJob || lastCreativeJob.sessionId !== composerSession?.id) return current();
const response = await chrome.runtime.sendMessage({ type: "GET_COMPOSER_SESSION", sessionId: composerSession.id });
+ if (!current()) return false;
if (response?.ok) composerSession = response.session;
if (["failed", "canceled", "interrupted"].includes(lastCreativeJob.status) && lastCreativeJob.error?.message) {
composerFeedback(lastCreativeJob.error.message, true);
}
+ return true;
}
async function initializeComposer() {
@@ -402,8 +415,8 @@ function renderComposer() {
elements.composerProductionReview.checked = composerSession.productionReviewEnabled;
elements.composerProductionReview.disabled = !["auto", "compose"].includes(composerSession.routeMode);
renderComposerAiProfile();
- elements.composerReferenceCount.textContent = String(composerSession.referenceSnapshots.length + composerSession.appliedSkills.length);
const libraryReferences = composerSession.referenceSnapshots.filter((reference) => reference.sourceType !== TEMP_REFERENCE_SOURCE_TYPES.temporary);
+ elements.composerReferenceCount.textContent = String(libraryReferences.length);
elements.composerAliases.replaceChildren(...libraryReferences.map(referenceAliasButton));
elements.composerAliases.hidden = libraryReferences.length === 0;
renderTempReferences();
@@ -1121,16 +1134,25 @@ function retrieveSourcesForTurn(session, search) {
}
async function rebuildComposerSearchIndex() {
- const documentIds = [...new Set(entries.flatMap((entry) => entryMediaAssets(entry))
+ const state = await createComposerSearchState(entries);
+ composerDocumentTextByEntryId = state.documentTextByEntryId;
+ composerSearchIndex = state.searchIndex;
+}
+
+async function createComposerSearchState(sourceEntries) {
+ const documentIds = [...new Set(sourceEntries.flatMap((entry) => entryMediaAssets(entry))
.filter((asset) => asset.kind === "document")
.map((asset) => asset.id))];
const derived = await Promise.all(documentIds.map(async (id) => [id, await getDerivedMedia(id).catch(() => null)]));
const documentText = new Map(derived.flatMap(([id, value]) => value?.searchText ? [[id, value.searchText]] : []));
- composerDocumentTextByEntryId = new Map(entries.flatMap((entry) => {
+ const documentTextByEntryId = new Map(sourceEntries.flatMap((entry) => {
const text = entryMediaAssets(entry).map((asset) => documentText.get(asset.id)).filter(Boolean).join("\n").trim();
return text ? [[entry.id, text]] : [];
}));
- composerSearchIndex = buildSearchIndex(entries, facetCatalog, documentText);
+ return {
+ documentTextByEntryId,
+ searchIndex: buildSearchIndex(sourceEntries, facetCatalog, documentText)
+ };
}
async function runAgentExecution(operation, settingsValue, route, instruction) {
@@ -1264,7 +1286,7 @@ function setActiveCreativeJob(job) {
function renderActiveState() {
renderSessions();
renderSendState();
- if (composerSession?.id === activeOperation?.sessionId) renderTimeline();
+ renderTimeline();
if (elements.composerReferenceWorkspace.hidden === false) renderProjects();
}
@@ -1403,14 +1425,27 @@ function renderImageGenerationSettings() {
const state = videoTask
? normalizeVideoGenerationRequest(generationProfile, composerVisionSettings, composerSession.generationParameters)
: normalizeImageGenerationRequest(generationProfile, composerVisionSettings, composerSession.generationParameters);
- renderGenerationParameterField(elements.composerImageSizeField, elements.composerImageSize, capability, "size", composerSession.generationParameters.size, { showAutomatic: true });
if (videoTask) {
+ renderGenerationParameterField(elements.composerImageSizeField, elements.composerImageSize, capability, "size", composerSession.generationParameters.size, {
+ showAutomatic: true,
+ fallbackLabel: "画幅与分辨率"
+ });
elements.composerImageQualityField.hidden = true;
elements.composerImageReferenceModeField.hidden = true;
- renderGenerationParameterField(elements.composerVideoDurationField, elements.composerVideoDuration, capability, "duration", composerSession.generationParameters.duration);
+ renderGenerationParameterField(elements.composerVideoDurationField, elements.composerVideoDuration, capability, "duration", composerSession.generationParameters.duration, {
+ fallbackLabel: "时长"
+ });
} else {
+ const primaryKey = generationParameterKey(capability, ["size", "aspectRatio"]);
+ const secondaryKey = generationParameterKey(capability, ["quality", "imageSize"]);
+ renderGenerationParameterField(elements.composerImageSizeField, elements.composerImageSize, capability, primaryKey, composerSession.generationParameters[primaryKey], {
+ showAutomatic: true,
+ fallbackLabel: "画幅与分辨率"
+ });
elements.composerVideoDurationField.hidden = true;
- renderGenerationParameterField(elements.composerImageQualityField, elements.composerImageQuality, capability, "quality", composerSession.generationParameters.quality);
+ renderGenerationParameterField(elements.composerImageQualityField, elements.composerImageQuality, capability, secondaryKey, composerSession.generationParameters[secondaryKey], {
+ fallbackLabel: "质量"
+ });
const referenceMode = imageReferenceModeAvailability(composerSession.referenceSnapshots);
elements.composerImageReferenceModeField.hidden = !composerSession.referenceSnapshots.some((item) => item.imageRefs?.length);
elements.composerImageReferenceMode.value = composerSession.imageReferenceMode;
@@ -1419,11 +1454,11 @@ function renderImageGenerationSettings() {
const messages = [
...state.issues,
...(!videoTask && !imageReferenceModeAvailability(composerSession.referenceSnapshots).canDisableImages
- ? [`还有 ${imageReferenceModeAvailability(composerSession.referenceSnapshots).missingAssetIds.length} 张参考图缺少有效独立分析,暂时必须带原图`]
+ ? [`还有 ${imageReferenceModeAvailability(composerSession.referenceSnapshots).missingAssetIds.length} 张参考图既没有案例提示词,也没有有效分析文字,暂时必须带原图`]
: []),
...(state.ignored.length ? [`当前服务不会发送:${state.ignored.join("、")}`] : [])
];
- elements.composerGenerationParameterNote.textContent = messages.join(";");
+ elements.composerGenerationParameterNote.textContent = messages.map(translateUiMessage).join(currentLocale() === "en" ? "; " : ";");
elements.composerGenerationParameterNote.classList.toggle("error", state.issues.length > 0);
}
@@ -1433,14 +1468,21 @@ async function updateImageReferenceMode() {
const availability = imageReferenceModeAvailability(composerSession.referenceSnapshots);
if (mode !== "conditioned" && !availability.canDisableImages) {
renderImageGenerationSettings();
- return composerFeedback(`还有 ${availability.missingAssetIds.length} 张参考图缺少有效独立分析,不能关闭垫图`, true);
+ return composerFeedback(`还有 ${availability.missingAssetIds.length} 张参考图既没有案例提示词,也没有有效分析文字,不能关闭原图`, true);
}
composerSession = await saveSession(createComposerSession({ ...composerSession, imageReferenceMode: mode }));
renderComposer();
}
-function renderGenerationParameterField(field, select, capability, key, selectedValue, { showAutomatic = false } = {}) {
+function generationParameterKey(capability, preferredKeys) {
+ return preferredKeys.find((key) => capability.parameters.some((item) => item.key === key)) ?? preferredKeys[0];
+}
+
+function renderGenerationParameterField(field, select, capability, key, selectedValue, { showAutomatic = false, fallbackLabel = "" } = {}) {
const parameter = capability.parameters.find((item) => item.key === key);
+ field.dataset.parameterKey = key;
+ const label = field.querySelector("span");
+ if (label) label.textContent = t(parameter?.label || fallbackLabel);
field.hidden = !parameter && !showAutomatic;
const supportedOptions = parameter?.options?.length
? parameter.options
@@ -1544,7 +1586,7 @@ function composerProfileForAssignment(assignment, fallback) {
: providerId === "openai" ? "openai"
: providerId === "xai" ? "xai"
: providerId.startsWith("custom") ? "compatible"
- : ["gemini", "openrouter", "minimax", "volcengine"].includes(providerId) ? providerId : "";
+ : ["kimi", "gemini", "openrouter", "minimax", "volcengine"].includes(providerId) ? providerId : "";
if (!serviceId) return normalizeComposerAiProfile(fallback);
return normalizeComposerAiProfile({ serviceId, model: assignment?.model, thinking: fallback?.thinking === true });
}
@@ -1552,13 +1594,24 @@ function composerProfileForAssignment(assignment, fallback) {
async function updateImageGenerationParameters() {
if (!composerSession || activeOperation || !["create_image", "create_video"].includes(composerSession.outputMode)) return;
const videoTask = composerSession.outputMode === "create_video";
+ const generationParameters = videoTask
+ ? {
+ ...composerSession.generationParameters,
+ size: elements.composerImageSize.value,
+ duration: elements.composerVideoDuration.value
+ }
+ : {
+ ...composerSession.generationParameters,
+ size: "",
+ aspectRatio: "",
+ quality: "",
+ imageSize: "",
+ [elements.composerImageSizeField.dataset.parameterKey || "size"]: elements.composerImageSize.value,
+ [elements.composerImageQualityField.dataset.parameterKey || "quality"]: elements.composerImageQuality.value
+ };
composerSession = await saveSession(createComposerSession({
...composerSession,
- generationParameters: {
- ...composerSession.generationParameters,
- size: elements.composerImageSize.value,
- ...(videoTask ? { duration: elements.composerVideoDuration.value } : { quality: elements.composerImageQuality.value })
- }
+ generationParameters
}));
renderComposer();
}
diff --git a/composer-service.js b/composer-service.js
index 2919894..c23099e 100644
--- a/composer-service.js
+++ b/composer-service.js
@@ -142,7 +142,7 @@ export function composerServiceCatalog(aiSettingsValue = {}, visionSettingsValue
videoGeneration: Boolean(xai.mediaConsent && xai.apiKey && xai.textModel && xai.videoModel)
}
];
- for (const providerId of ["gemini", "openrouter", "minimax", "volcengine"]) {
+ for (const providerId of ["kimi", "gemini", "openrouter", "minimax", "volcengine"]) {
const profile = visionSettingsValue?.providerProfiles?.[providerId];
if (!profile) continue;
const models = [...new Set([profile.models?.creativePlanning, profile.models?.imageGeneration, profile.models?.videoGeneration]
@@ -197,28 +197,29 @@ export function composerServiceCapabilities(profileValue, visionSettingsValue =
video: xaiVideoCapability(configured, xai)
};
}
- if (["gemini", "openrouter", "minimax", "volcengine"].includes(profile.serviceId)) {
+ if (["kimi", "gemini", "openrouter", "minimax", "volcengine"].includes(profile.serviceId)) {
const provider = visionSettingsValue?.providerProfiles?.[profile.serviceId];
- const model = profile.model || provider?.models?.videoGeneration;
+ const model = profile.model;
const descriptor = providerModelDescriptor(provider, model);
const configured = Boolean(provider?.consent && provider?.apiKey && model && descriptor?.tasks?.includes("videoGeneration"));
+ const image = ["gemini", "openrouter"].includes(profile.serviceId) ? (() => {
+ const imageModel = profile.model;
+ const imageDescriptor = providerModelDescriptor(provider, imageModel);
+ const references = modelReferenceCapability(provider, imageModel, {
+ supported: imageDescriptor?.inputModalities?.includes("image") === true,
+ maxItems: null
+ });
+ return {
+ generate: Boolean(provider?.consent && provider?.apiKey && imageModel && imageDescriptor?.tasks?.includes("imageGeneration")),
+ references,
+ edit: { whole: imageDescriptor?.inputModalities?.includes("image") === true, local: false },
+ parameters: profile.serviceId === "gemini" ? providerImageParameters(imageDescriptor) : []
+ };
+ })() : null;
return {
serviceId: profile.serviceId,
model,
- image: profile.serviceId === "openrouter" ? (() => {
- const imageModel = provider?.models?.imageGeneration;
- const imageDescriptor = providerModelDescriptor(provider, imageModel);
- const references = modelReferenceCapability(provider, imageModel, {
- supported: imageDescriptor?.inputModalities?.includes("image") === true,
- maxItems: null
- });
- return {
- generate: Boolean(provider?.consent && provider?.apiKey && imageModel && imageDescriptor?.tasks?.includes("imageGeneration")),
- references,
- edit: { whole: imageDescriptor?.inputModalities?.includes("image") === true, local: false },
- parameters: []
- };
- })() : null,
+ image,
video: {
generate: configured,
protocol: provider?.protocol,
@@ -343,7 +344,10 @@ export function normalizeImageGenerationRequest(profileValue, visionSettingsValu
export function composerImageAvailability(profileValue, visionSettingsValue = {}, session = {}) {
if (session?.targetType === "video") return { available: false, message: "视频创作只输出提示词" };
const settings = normalizeVisionSettings(visionSettingsValue);
- const service = composerServiceCatalog({}, visionSettingsValue).find((item) => item.serviceId === normalizeComposerAiProfile(profileValue).serviceId);
+ const profile = normalizeComposerAiProfile(profileValue);
+ const catalog = composerServiceCatalog({}, visionSettingsValue);
+ const service = catalog.find((item) => item.serviceId === profile.serviceId && item.model === profile.model)
+ ?? catalog.find((item) => item.serviceId === profile.serviceId);
if (!service || service.serviceId === "deepseek") return { available: false, message: "当前服务只输出文字提示词" };
if (service.serviceId === "xai") {
if (!service.imageGeneration) return { available: false, message: "xAI 创建图片还缺少 API Key、文字模型或图片模型" };
@@ -359,6 +363,18 @@ export function composerImageAvailability(profileValue, visionSettingsValue = {}
}
return { available: true, message: "由 OpenRouter 独立图片接口生成;不会静默改用其他模型" };
}
+ if (service.serviceId === "gemini") {
+ const capability = composerServiceCapabilities(profileValue, visionSettingsValue).image;
+ if (!capability?.generate) return { available: false, message: "Gemini 生图还缺少已分配的 Nano Banana 模型、API Key 或发送授权" };
+ const count = referenceImageCount(session);
+ if (count && session.imageReferenceMode === "conditioned" && capability.references.supported === false) {
+ return { available: false, message: "所选 Gemini 图片模型未声明参考图输入能力" };
+ }
+ if (session.imageReferenceMode === "conditioned" && Number.isInteger(capability.references.maxItems) && count > capability.references.maxItems) {
+ return { available: false, message: `当前有 ${count} 张参考图,所选 Gemini 模型最多读取 ${capability.references.maxItems} 张,请先减少参考` };
+ }
+ return imageParameterAvailability(profileValue, visionSettingsValue, session, "由 Google Gemini 官方 Interactions 接口直接生成;不会静默改用其他模型");
+ }
if (service.serviceId === "openai") {
const capability = composerServiceCapabilities(profileValue, visionSettingsValue).image;
if (referenceImageCount(session) && session.imageReferenceMode === "conditioned" && capability?.references?.supported === false) {
@@ -405,6 +421,10 @@ export function composerImageEditCapabilities(profileValue, visionSettingsValue
const available = Boolean(settings.consent && settings.openai.apiKey && (profile.model || settings.openai.model));
return { whole: available, local: available };
}
+ if (profile.serviceId === "gemini") {
+ const capability = composerServiceCapabilities(profile, visionSettingsValue).image;
+ return { whole: capability?.generate === true && capability.edit?.whole === true, local: false };
+ }
if (profile.serviceId !== "compatible") return { whole: false, local: false };
const provider = settings.compatible;
const verifiedMicu = serviceLabelForEndpoint(provider.endpoint) === "米醋"
@@ -425,7 +445,9 @@ export async function planComposerTurnWithService(input, settingsValue, options
const profile = normalizeComposerAiProfile(input.session?.aiProfile);
if (profile.serviceId === "deepseek") return planDeepSeekTurn(input, settingsValue.ai, options);
const service = requireVisualService(profile, settingsValue.vision, "规划");
- if (service.planning === false) return planDeepSeekTurn(input, settingsValue.ai, options);
+ if (service.planning === false) {
+ throw new ComposerServiceError(`${service.label} 的所选模型未声明创作规划能力,请重新分配模型`, 422, { retryable: false });
+ }
assertComposerInputBudget(input.session, input.userMessage, input.composerSettings);
const request = plannerRequestPayload(input.session, input.userMessage, input.composerSettings);
const systemInstruction = compileAgentPlanningPrompt({
@@ -843,11 +865,17 @@ async function generateImageTurn(input, service, preparedImages, options) {
if (service.serviceId === "openrouter") {
return generateOpenRouterImageTurn(input, service, preparedImages, referenceMode, options);
}
+ if (service.serviceId === "gemini" && imageEdit?.mode === "local") {
+ throw new ComposerServiceError("Gemini Interactions 当前不支持上传局部遮罩编辑;请改用整图语义修改", 422, { retryable: false });
+ }
const requestState = normalizeImageGenerationRequest(input.session?.generationAiProfile, options.visionSettings ?? {}, input.session?.generationParameters);
if (requestState.issues.length) throw new ComposerServiceError(requestState.issues.join(";"), 422, { retryable: false });
const requestParameters = requestState.parameters;
const baseContent = multimodalContent(input.session, request, preparedImages, service.protocol);
const content = imageEdit ? imageEditContent(baseContent, imageEdit, service.protocol) : baseContent;
+ if (service.imageGeneration.protocol === "gemini_interactions") {
+ return generateGeminiImageTurn(input, service, request, content, referenceMode, imageEdit, requestParameters, preparedImages, options);
+ }
if (service.imageGeneration.protocol === "responses_tool") {
const instructions = [
systemInstruction,
@@ -912,6 +940,102 @@ async function generateImageTurn(input, service, preparedImages, options) {
};
}
+async function generateGeminiImageTurn(input, service, request, conditionedContent, referenceMode, imageEdit, requestParameters, preparedImages, options) {
+ let finalPrompt = String(request.instruction ?? "").trim();
+ let content = conditionedContent;
+ if (!imageEdit && referenceMode !== "conditioned") {
+ const promptResult = await assembleImagePrompt(input, preparedImages, options);
+ finalPrompt = promptResult.finalPrompt;
+ content = [{ type: "text", text: finalPrompt }];
+ }
+ const imageBlocks = content.filter((item) => item.type === "image");
+ const maximum = service.provider
+ ? modelReferenceCapability(service.provider, service.imageGeneration.model, { supported: null, maxItems: null }).maxItems
+ : null;
+ if (Number.isInteger(maximum) && imageBlocks.length > maximum) {
+ throw new ComposerServiceError(`所选 Gemini 模型最多读取 ${maximum} 张参考图,请先减少参考`, 422, {
+ kind: "reference_limit",
+ retryable: false,
+ referenceLimit: { actual: imageBlocks.length, maximum }
+ });
+ }
+ const interactionInput = imageBlocks.length
+ ? content.map((item) => item.type === "image" ? geminiImageInput(item.dataUrl) : { type: "text", text: item.text })
+ : finalPrompt;
+ const responseFormat = { type: "image" };
+ if (requestParameters.aspectRatio) responseFormat.aspect_ratio = requestParameters.aspectRatio;
+ if (requestParameters.imageSize) responseFormat.image_size = requestParameters.imageSize;
+ const body = {
+ model: service.imageGeneration.model,
+ input: interactionInput,
+ response_format: responseFormat
+ };
+ const response = await requestRaw(
+ service.imageGeneration.endpoint,
+ "",
+ body,
+ options,
+ IMAGE_REQUEST_TIMEOUT_MS,
+ "Google Gemini 图片服务",
+ { "x-goog-api-key": service.imageGeneration.apiKey }
+ );
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok) throw responseError("Google Gemini 图片服务", response.status, payload, {
+ secrets: [service.imageGeneration.apiKey]
+ });
+ const parsed = geminiInteractionImages(payload);
+ if (!parsed.images.length) {
+ throw new ComposerServiceError("Google Gemini 图片服务完成请求但没有返回有效图片", 422, { retryable: false });
+ }
+ return {
+ route: "compose",
+ kind: "image",
+ finalPrompt: parsed.text || finalPrompt || "创建图片",
+ images: parsed.images,
+ outputLanguage: request.outputLanguage,
+ usage: normalizeGeminiInteractionsUsage(payload.usage),
+ serviceId: "gemini",
+ model: String(payload.model ?? service.imageGeneration.model),
+ requestModel: service.imageGeneration.model,
+ requestParameters,
+ finishReason: String(payload.status ?? "completed")
+ };
+}
+
+function geminiImageInput(dataUrl) {
+ const match = String(dataUrl ?? "").match(/^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/=]+)$/i);
+ if (!match) throw new ComposerServiceError("Gemini 参考图数据无效,本次没有发送不完整参考", 422, { retryable: false });
+ return { type: "image", mime_type: match[1].toLocaleLowerCase("en-US"), data: match[2] };
+}
+
+function geminiInteractionImages(payload) {
+ const blocks = (Array.isArray(payload?.steps) ? payload.steps : [])
+ .filter((step) => step?.type === "model_output")
+ .flatMap((step) => Array.isArray(step.content) ? step.content : []);
+ if (payload?.output_image && (!payload.output_image.type || payload.output_image.type === "image")) {
+ const outputImage = { type: "image", ...payload.output_image };
+ const alreadyIncluded = blocks.some((block) => block?.type === "image"
+ && block.data === outputImage.data && block.mime_type === outputImage.mime_type);
+ if (!alreadyIncluded) blocks.push(outputImage);
+ }
+ const images = [];
+ const texts = [];
+ for (const block of blocks) {
+ if (block?.type === "text" && String(block.text ?? "").trim()) {
+ texts.push(String(block.text).trim());
+ continue;
+ }
+ if (block?.type !== "image") continue;
+ const encoded = String(block.data ?? "").trim();
+ const mimeType = String(block.mime_type ?? "").trim().toLocaleLowerCase("en-US");
+ if (!encoded || !/^image\/(?:png|jpeg|webp|heic|heif|gif|bmp|tiff)$/.test(mimeType)) continue;
+ try {
+ images.push({ blob: base64Image(encoded, mimeType), mimeType, source: "base64" });
+ } catch {}
+ }
+ return { images, text: texts.join("\n").trim() };
+}
+
async function generateOpenRouterImageTurn(input, service, preparedImages, referenceMode, options) {
if (input.imageEdit?.mode === "local") throw new ComposerServiceError("所选 OpenRouter 模型未声明局部遮罩编辑能力", 422, { retryable: false });
if (referenceMode === "prompt_only") {
@@ -1211,7 +1335,7 @@ async function requestJson(service, body, options = {}, timeoutMs = REQUEST_TIME
return payload;
}
-async function requestRaw(url, apiKey, body, options, timeoutMs, label) {
+async function requestRaw(url, apiKey, body, options, timeoutMs, label, extraHeaders = {}) {
const multipart = typeof FormData !== "undefined" && body instanceof FormData;
if (!multipart) assertComposerRequestBudget(textMessagesForBudget(body));
const controller = new AbortController();
@@ -1219,11 +1343,14 @@ async function requestRaw(url, apiKey, body, options, timeoutMs, label) {
const onAbort = () => controller.abort();
if (options.signal?.aborted) controller.abort();
options.signal?.addEventListener("abort", onAbort, { once: true });
- const timeoutId = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
+ const requestedTimeout = Object.hasOwn(options ?? {}, "timeoutMs") ? options.timeoutMs : timeoutMs;
+ const timeoutId = Number.isFinite(requestedTimeout) && requestedTimeout > 0
+ ? setTimeout(() => { timedOut = true; controller.abort(); }, requestedTimeout)
+ : null;
try {
return await (options.fetchImpl ?? fetch)(url, {
method: "POST",
- headers: { ...(multipart ? {} : { "Content-Type": "application/json" }), ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}) },
+ headers: { ...(multipart ? {} : { "Content-Type": "application/json" }), ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), ...extraHeaders },
body: multipart ? body : JSON.stringify(body),
redirect: "error",
signal: controller.signal
@@ -1233,7 +1360,7 @@ async function requestRaw(url, apiKey, body, options, timeoutMs, label) {
if (error?.name === "AbortError") throw error;
throw new ComposerServiceError(`无法连接 ${label},请检查网络、地址和权限`, 0, { cause: error });
} finally {
- clearTimeout(timeoutId);
+ if (timeoutId !== null) clearTimeout(timeoutId);
options.signal?.removeEventListener("abort", onAbort);
}
}
@@ -1271,17 +1398,23 @@ function requireVisualService(profileValue, visionSettingsValue, action) {
}
};
}
- if (["gemini", "openrouter", "minimax", "volcengine"].includes(profile.serviceId)) {
+ if (["kimi", "gemini", "openrouter", "minimax", "volcengine"].includes(profile.serviceId)) {
const provider = visionSettingsValue?.providerProfiles?.[profile.serviceId];
- const model = profile.model || provider?.models?.videoGeneration;
- if (!provider?.apiKey || !model) throw new ComposerServiceError(`请先完成 ${provider?.label || profile.serviceId} 的 API Key 和视频模型配置`, 422, { retryable: false });
+ const model = profile.model;
+ if (!provider?.apiKey || !model) throw new ComposerServiceError(`请先完成 ${provider?.label || profile.serviceId} 的 API Key 和所选模型配置`, 422, { retryable: false });
if (!provider.consent) throw new ComposerServiceError(`请先确认:主动${action}时会把本轮文字与所选图片发送到 ${provider.label || profile.serviceId}`, 422, { retryable: false });
- const planning = providerModelSupports(provider, provider.models?.creativePlanning, "creativePlanning");
+ const planning = providerModelSupports(provider, model, "creativePlanning");
+ const chatCompatible = ["openrouter", "gemini"].includes(profile.serviceId);
+ const endpoint = profile.serviceId === "openrouter"
+ ? `${String(provider.endpoint).replace(/\/$/, "")}/chat/completions`
+ : profile.serviceId === "gemini"
+ ? `${String(provider.endpoint).replace(/\/$/, "")}/v1beta/openai/chat/completions`
+ : provider.endpoint;
return {
serviceId: profile.serviceId,
label: provider.label || profile.serviceId,
- protocol: profile.serviceId === "openrouter" ? "chat_completions" : provider.protocol,
- endpoint: profile.serviceId === "openrouter" ? `${String(provider.endpoint).replace(/\/$/, "")}/chat/completions` : provider.endpoint,
+ protocol: chatCompatible ? "chat_completions" : provider.protocol,
+ endpoint,
apiKey: provider.apiKey,
model,
planning,
@@ -1290,7 +1423,12 @@ function requireVisualService(profileValue, visionSettingsValue, action) {
imageGeneration: profile.serviceId === "openrouter" ? {
protocol: "openrouter_images",
endpoint: `${String(provider.endpoint).replace(/\/$/, "")}/images`,
- model: provider.models?.imageGeneration
+ model
+ } : profile.serviceId === "gemini" ? {
+ protocol: "gemini_interactions",
+ endpoint: geminiInteractionsEndpoint(provider.endpoint),
+ apiKey: provider.apiKey,
+ model
} : null
};
}
@@ -1420,7 +1558,11 @@ function providerModelDescriptor(profile, modelId) {
}
function providerModelSupports(profile, modelId, taskId) {
- return providerModelDescriptor(profile, modelId)?.tasks?.includes(taskId) === true;
+ const id = String(modelId ?? "").trim();
+ const descriptor = providerModelDescriptor(profile, id);
+ if (descriptor) return descriptor.tasks?.includes(taskId) === true;
+ return profile?.capabilities?.includes(taskId) === true
+ && String(profile?.models?.[taskId] ?? "").trim() === id;
}
function compatibleImageReferenceCapability(visionSettingsValue, modelId) {
@@ -1453,6 +1595,23 @@ function providerVideoParameters(descriptor) {
return parameters;
}
+function providerImageParameters(descriptor) {
+ const parameters = [];
+ const supported = new Set(descriptor?.supportedParameters ?? []);
+ if (supported.has("aspect_ratio") && descriptor?.supportedAspectRatios?.length) {
+ parameters.push(imageParameter("aspectRatio", "画幅比例", descriptor.supportedAspectRatios.map((value) => ({ value, label: value })), descriptor.supportedAspectRatios[0]));
+ }
+ if (supported.has("image_size") && descriptor?.supportedResolutions?.length) {
+ parameters.push(imageParameter("imageSize", "图片尺寸", descriptor.supportedResolutions.map((value) => ({ value, label: value })), descriptor.supportedResolutions[0]));
+ }
+ return parameters;
+}
+
+function geminiInteractionsEndpoint(value) {
+ try { return new URL("/v1beta/interactions", value).href; }
+ catch { throw new ComposerServiceError("Gemini 官方接口地址无效", 422, { retryable: false }); }
+}
+
function imageParameter(key, label, options, defaultValue) {
return {
key,
@@ -1751,6 +1910,16 @@ function normalizeResponsesUsage(value = {}) {
};
}
+function normalizeGeminiInteractionsUsage(value = {}) {
+ return {
+ promptTokens: finite(value.total_input_tokens),
+ completionTokens: finite(value.total_output_tokens),
+ totalTokens: finite(value.total_tokens),
+ cacheHitTokens: finite(value.total_cached_tokens),
+ cacheMissTokens: Math.max(0, finite(value.total_input_tokens) - finite(value.total_cached_tokens))
+ };
+}
+
function normalizeChatUsage(value = {}) {
return {
promptTokens: finite(value.prompt_tokens),
@@ -1787,6 +1956,10 @@ function parseObject(content, message) {
function textMessagesForBudget(body) {
if (Array.isArray(body.messages)) return body.messages.map((item) => ({ content: typeof item.content === "string" ? item.content : JSON.stringify(item.content.filter?.((part) => part.type === "text") ?? []) }));
+ if (typeof body.input === "string") return [{ content: body.input }];
+ if (Array.isArray(body.input) && body.input.some((item) => item?.type === "text" || item?.type === "image")) {
+ return body.input.filter((item) => item?.type === "text").map((item) => ({ content: item.text ?? "" }));
+ }
return [
{ content: body.instructions || "" },
{ content: JSON.stringify((body.input ?? []).map((item) => ({ ...item, content: item.content?.filter?.((part) => part.type === "input_text") }))) }
@@ -1794,7 +1967,7 @@ function textMessagesForBudget(body) {
}
function responseError(label, status, payload, options = {}) {
- const detail = String(payload?.error?.message ?? payload?.message ?? "").trim();
+ const detail = redactSecrets(String(payload?.error?.message ?? payload?.message ?? "").trim(), options.secrets);
const referenceLimit = referenceLimitFromMessage(detail);
const micuRouting = micuImageRoutingError(label, detail, options.credentialHint);
if (micuRouting) {
@@ -1810,6 +1983,13 @@ function responseError(label, status, payload, options = {}) {
} : {});
}
+function redactSecrets(value, secrets = []) {
+ return (Array.isArray(secrets) ? secrets : []).reduce((text, secretValue) => {
+ const secret = String(secretValue ?? "").trim();
+ return secret ? text.split(secret).join("[已隐藏凭据]") : text;
+ }, String(value ?? ""));
+}
+
function micuImageRoutingError(label, detail, keyHint = "") {
if (label !== "米醋" || !/gpt-image-2(?:-pro)?/i.test(detail) || !/(?:无可用渠道|distributor)/i.test(detail)) return "";
const group = detail.match(/分组\s+([^\s]+)\s+下模型/i)?.[1] ?? "";
diff --git a/composer.html b/composer.html
index bcdd26f..fd6fd04 100644
--- a/composer.html
+++ b/composer.html
@@ -78,7 +78,7 @@
<strong id="composer-generation-settings-title" data-i18n="本轮图片参数">本轮图片参数</strong>
<label id="composer-image-size-field" class="composer-option-field"><span data-i18n="画幅与分辨率">画幅与分辨率</span><select id="composer-image-size"></select></label>
<label id="composer-image-quality-field" class="composer-option-field"><span data-i18n="质量">质量</span><select id="composer-image-quality"></select></label>
- <label id="composer-image-reference-mode-field" class="composer-option-field"><span>参考图参与方式</span><select id="composer-image-reference-mode"><option value="conditioned">带原图(默认)</option><option value="prompt_only">只在整理提示词时看图</option><option value="text_only">全程只用分析文字</option></select></label>
+ <label id="composer-image-reference-mode-field" class="composer-option-field"><span data-i18n="参考图参与方式">参考图参与方式</span><select id="composer-image-reference-mode"><option value="conditioned" data-i18n="带原图生成(默认)">带原图生成(默认)</option><option value="prompt_only" data-i18n="先读图整理提示词,生图不垫图">先读图整理提示词,生图不垫图</option><option value="text_only" data-i18n="全程只用案例/分析文字(不读图,最省 token)">全程只用案例/分析文字(不读图,最省 token)</option></select></label>
<label id="composer-video-duration-field" class="composer-option-field" hidden><span data-i18n="时长">时长</span><select id="composer-video-duration"></select></label>
<p id="composer-generation-parameter-note"></p>
</section>
diff --git a/composer.js b/composer.js
index e7af1db..ffcda23 100644
--- a/composer.js
+++ b/composer.js
@@ -25,7 +25,7 @@ import {
export const COMPOSER_METHOD_VERSION = COMPOSER_AGENT_VERSION;
export const COMPOSER_AI_MODELS = Object.freeze(["deepseek-v4-flash", "deepseek-v4-pro"]);
export const COMPOSER_SERVICE_IDS = Object.freeze([
- "deepseek", "openai", "compatible", "xai", "gemini", "openrouter", "minimax", "volcengine"
+ "deepseek", "openai", "compatible", "xai", "kimi", "gemini", "openrouter", "minimax", "volcengine"
]);
export const DEFAULT_COMPOSER_AI_PROFILE = Object.freeze({ serviceId: "deepseek", model: "deepseek-v4-flash", thinking: false });
export const COMPOSER_INPUT_MAX_CHARACTERS = 750_000;
@@ -334,8 +334,14 @@ export function createComposerSession(input = {}) {
export function imageReferenceModeAvailability(referenceSnapshots = []) {
const missingAssetIds = [];
for (const reference of Array.isArray(referenceSnapshots) ? referenceSnapshots : []) {
+ const promptBacked = Boolean(
+ String(reference?.originalText ?? "").trim()
+ || (["prompt", "prompt_vision"].includes(reference?.referenceKind)
+ && String(reference?.referenceText ?? "").trim())
+ );
const assets = new Map((Array.isArray(reference?.assets) ? reference.assets : []).map((item) => [item.assetId, item]));
for (const imageRef of Array.isArray(reference?.imageRefs) ? reference.imageRefs : []) {
+ if (promptBacked) continue;
const assetId = String(imageRef?.visualId ?? "").trim();
const asset = assets.get(assetId);
const fingerprintMatches = Boolean(asset?.imageFingerprint && asset?.analysisImageFingerprint
@@ -361,7 +367,9 @@ export function normalizeGenerationParameters(value = {}, targetType = "image")
}
return {
size: cleanParameter(source.size),
- quality: cleanParameter(source.quality)
+ quality: cleanParameter(source.quality),
+ aspectRatio: cleanParameter(source.aspectRatio),
+ imageSize: cleanParameter(source.imageSize)
};
}
diff --git a/creative-job-runner.js b/creative-job-runner.js
index b2cee35..4bde7eb 100644
--- a/creative-job-runner.js
+++ b/creative-job-runner.js
@@ -22,7 +22,7 @@ import { assertImageDimensions } from "./resource-limits.js";
import { buildSearchIndex } from "./search-index.js";
import { materializeLogicalCases } from "./compound-cases.js";
import { blobToDataUrl, normalizeVisionSettings } from "./vision.js";
-import { normalizeAiServiceProfiles } from "./ai-task-routing.js";
+import { normalizeAiServiceProfiles } from "./ai-service-profiles.js";
export async function runCreativeJob(job, context = {}) {
const signal = context.signal;
diff --git a/creative-skill-service.js b/creative-skill-service.js
index 4522f26..3a52a54 100644
--- a/creative-skill-service.js
+++ b/creative-skill-service.js
@@ -1,5 +1,18 @@
import { COMPOSER_INPUT_MAX_CHARACTERS, createComposerSession, normalizeComposerSettings } from "./composer.js";
import { executeComposerTurnWithService } from "./composer-service.js";
+import { entryMediaAssets } from "./media.js";
+
+export function defaultSkillExtractionInstruction(localeValue = "zh-CN") {
+ return localeValue === "en"
+ ? "Extract only reusable methods that serve the stated goal. Separate transferable rules from source-specific details. Preserve useful variables and decision boundaries. Do not judge completeness, score the user, or summarize unrelated commonalities. Write imperative instructions for another capable creative agent."
+ : "只提取服务于目标的可复用方法,区分可迁移规律与案例专属内容,保留有用变量和判断边界。不要评价完整性,不要给用户打分,也不要总结与目标无关的共同点。用命令式写给另一个有能力的创作 Agent。";
+}
+
+export function defaultSkillVisualInstruction(localeValue = "zh-CN") {
+ return localeValue === "en"
+ ? "Describe reusable visual choices that serve the goal. Distinguish transferable patterns from source-specific details, do not judge completeness, and ignore contact-sheet borders and labels."
+ : "描述服务于目标的可复用视觉选择,区分可迁移规律与案例专属内容,不评价完整性;忽略联系表边框和编号本身。";
+}
export function buildSkillExtractionRequest(input = {}) {
const locale = input.locale === "en" ? "en" : "zh-CN";
@@ -18,18 +31,19 @@ export function buildSkillExtractionRequest(input = {}) {
source.analysis ? `${locale === "en" ? "Existing visual analysis" : "已有画面分析"}:\n${source.analysis}` : ""
].filter(Boolean).join("\n")).join("\n\n");
const visualText = vision.length ? `\n\n${locale === "en" ? "Confirmed visual contact-sheet analyses" : "已确认的视觉联系表分析"}:\n${vision.map((item, index) => `${index + 1}. ${item}`).join("\n")}` : "";
+ const extractionInstruction = multiline(input.instructionOverride) || defaultSkillExtractionInstruction(locale);
if (locale === "en") return [
"Create the executable Markdown body of a portable creative Skill.",
`Extraction goal: ${goal}`,
- "Extract only reusable methods that serve this goal. Separate transferable rules from source-specific details. Preserve useful variables and decision boundaries. Do not judge completeness, do not score the user, and do not summarize unrelated commonalities.",
- "Write imperative instructions for another capable creative agent. Do not include YAML frontmatter, provenance, local identifiers, project names, URLs, or claims about unseen images.",
+ extractionInstruction,
+ "Do not include YAML frontmatter, provenance, local identifiers, project names, URLs, or claims about unseen images.",
sourceText + visualText
].join("\n\n");
return [
"请生成一份可移植创作 Skill 的可执行 Markdown 正文。",
`本次提炼目标:${goal}`,
- "只提取服务于该目标的可复用方法,区分可迁移规律与案例专属内容,保留有用变量和判断边界。不要评价完整性,不要给用户打分,也不要总结与目标无关的共同点。",
- "用命令式写给另一个有能力的创作 Agent。不要输出 YAML frontmatter、来源证据、本地编号、项目名、网址,也不要声称看过未提供的图片。",
+ extractionInstruction,
+ "不要输出 YAML frontmatter、来源证据、本地编号、项目名、网址,也不要声称看过未提供的图片。",
sourceText + visualText
].join("\n\n");
}
@@ -47,7 +61,23 @@ export function skillExtractionWorkload(input = {}) {
textBatchCount: batches.length,
synthesisRequestCount: batches.length > 1 ? 1 : 0,
requestCount: batches.length + (batches.length > 1 ? 1 : 0),
- overSingleRequest: batches.length > 1
+ overSingleRequest: batches.length > 1,
+ tokenEstimate: estimateSkillTokens([
+ clean(input.goal),
+ multiline(input.instructionOverride) || defaultSkillExtractionInstruction(input.locale),
+ ...sources.flatMap((source) => [source.prompt, source.analysis])
+ ].join("\n"))
+ };
+}
+
+export function estimateSkillTokens(value = "") {
+ const text = String(value ?? "");
+ const cjk = (text.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu) ?? []).length;
+ const other = text.replace(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\s]/gu, "").length;
+ return {
+ min: cjk + Math.ceil(other / 4),
+ max: cjk * 2 + Math.ceil(other / 2),
+ kind: "local-range"
};
}
@@ -64,7 +94,7 @@ export async function extractCreativeSkillDraftBatched(input = {}, settingsValue
lastModel = result.model;
usage = addUsage(usage, result.usage);
}
- if (partials.length === 1) return { markdown: partials[0], usage, model: lastModel };
+ if (partials.length === 1) return { ...skillDraftMetadata(partials[0], input.goal), markdown: partials[0], usage, model: lastModel };
options.onProgress?.({ phase: "synthesis", current: 1, total: 1 });
const synthesized = await extractCreativeSkillDraft({
...input,
@@ -96,7 +126,7 @@ export async function extractCreativeSkillDraft(input = {}, settingsValue = {},
}, { ai: settingsValue.ai, vision: settingsValue.vision }, [], options);
const markdown = stripFence(result.text);
if (!markdown) throw new Error("模型没有返回可编辑的 Skill 草稿");
- return { markdown, usage: result.usage, model: result.model };
+ return { ...skillDraftMetadata(markdown, input.goal), markdown, usage: result.usage, model: result.model };
}
export async function analyzeCreativeSkillVisualBatch(input = {}, settingsValue = {}, options = {}) {
@@ -107,9 +137,10 @@ export async function analyzeCreativeSkillVisualBatch(input = {}, settingsValue
const labels = (Array.isArray(input.items) ? input.items : []).map((item) =>
`C${Math.max(1, Number(item.caseNumber) || 1)}.${Math.max(1, Number(item.imageNumber) || 1)}`
).join(", ");
+ const instruction = multiline(input.instructionOverride) || defaultSkillVisualInstruction(locale);
const request = locale === "en"
- ? `Analyze only the visible creative content for this Skill extraction goal: ${goal}. Labels ${labels || "C1.1"} preserve case and image order. Describe reusable visual choices that serve the goal, distinguish transferable patterns from source-specific details, do not judge completeness, and ignore contact-sheet borders and labels.`
- : `只围绕这个 Skill 提炼目标分析可见创作内容:${goal}。标记 ${labels || "C1.1"} 用于保留案例归属和图片顺序。描述服务于目标的可复用视觉选择,区分可迁移规律与案例专属内容,不评价完整性;忽略联系表边框和编号本身。`;
+ ? `Analyze only the visible creative content for this Skill extraction goal: ${goal}. Labels ${labels || "C1.1"} preserve case and image order. ${instruction}`
+ : `只围绕这个 Skill 提炼目标分析可见创作内容:${goal}。标记 ${labels || "C1.1"} 用于保留案例归属和图片顺序。${instruction}`;
const composerSettings = normalizeComposerSettings(settingsValue.composer);
const profile = input.aiProfile;
if (!profile || profile.serviceId === "deepseek") throw new Error(locale === "en" ? "Select a configured vision model" : "请先配置并选择视觉能力模型");
@@ -140,16 +171,56 @@ export async function analyzeCreativeSkillVisualBatch(input = {}, settingsValue
return { description, usage: result.usage, model: result.model };
}
-export function anonymousSkillSources(entriesValue = [], entryIdsValue = []) {
- const selected = new Set((Array.isArray(entryIdsValue) ? entryIdsValue : []).map(String));
- return (Array.isArray(entriesValue) ? entriesValue : []).filter((entry) => selected.has(String(entry?.id ?? ""))).map((entry) => ({
- prompt: multiline(entry?.text),
- analysis: (Array.isArray(entry?.mediaAssets) ? entry.mediaAssets : entry?.visuals ?? [])
- .filter((asset) => asset?.usage !== "poster" && !asset?.visionAnalysis?.invalidated)
- .map((asset) => multiline(asset?.visionAnalysis?.description)).filter(Boolean).join("\n")
+export function anonymousSkillSources(entriesValue = [], selectionsValue = [], options = {}) {
+ const selections = normalizeSourceSelections(selectionsValue);
+ const documents = options.documentTextByAsset instanceof Map ? options.documentTextByAsset : new Map();
+ return (Array.isArray(entriesValue) ? entriesValue : []).flatMap((entry) => {
+ const selection = selections.get(String(entry?.id ?? ""));
+ if (!selection) return [];
+ const selectedAssets = entryMediaAssets(entry).filter((asset) => selection.assetIds === null || selection.assetIds.has(String(asset.id)));
+ const mediaPrompts = new Map((Array.isArray(entry?.mediaPrompts) ? entry.mediaPrompts : [])
+ .map((item) => [String(item?.assetId ?? ""), multiline(item?.text)]));
+ const prompt = [
+ selection.includeEntryText ? multiline(entry?.text) : "",
+ ...selectedAssets.map((asset) => mediaPrompts.get(String(asset.id)) || ""),
+ ...selectedAssets.filter((asset) => asset.kind === "document").map((asset) => multiline(documents.get(String(asset.id))))
+ ].filter(Boolean).join("\n\n");
+ const selectedIds = new Set(selectedAssets.map((asset) => String(asset.id)));
+ const analysis = [
+ ...selectedAssets.filter((asset) => !asset?.visionAnalysis?.invalidated)
+ .map((asset) => multiline(asset?.visionAnalysis?.description)),
+ ...(Array.isArray(entry?.timeNotes) ? entry.timeNotes : [])
+ .filter((note) => selectedIds.has(String(note?.assetId ?? ""))).map((note) => multiline(note?.text)),
+ ...(Array.isArray(entry?.videoAnalyses) ? entry.videoAnalyses : [])
+ .filter((item) => selectedIds.has(String(item?.assetId ?? ""))).map((item) => multiline(item?.description || item?.summary || item?.text))
+ ].filter(Boolean).join("\n");
+ return prompt || analysis ? [{ prompt, analysis }] : [];
+ });
+}
+
+function normalizeSourceSelections(values) {
+ const source = Array.isArray(values) ? values : [];
+ if (source.every((item) => typeof item === "string" || typeof item === "number")) {
+ return new Map(source.map((entryId) => [String(entryId), { includeEntryText: true, assetIds: null }]));
+ }
+ return new Map(source.flatMap((selection) => {
+ const entryId = clean(selection?.entryId);
+ if (!entryId) return [];
+ return [[entryId, {
+ includeEntryText: selection?.includeEntryText !== false,
+ assetIds: new Set((Array.isArray(selection?.assetIds) ? selection.assetIds : []).map(String))
+ }]];
}));
}
+function skillDraftMetadata(markdown, goalValue) {
+ const heading = String(markdown ?? "").match(/^#\s+(.+)$/mu)?.[1]?.trim() || "";
+ return {
+ callName: heading.slice(0, 80),
+ description: clean(goalValue).slice(0, 240)
+ };
+}
+
export function creativeRunEvidenceCandidates(runsValue = [], skillIdValue = "") {
const skillId = clean(skillIdValue);
return (Array.isArray(runsValue) ? runsValue : []).flatMap((run) => {
diff --git a/curated-catalog.js b/curated-catalog.js
index 6bd2b07..6c74308 100644
--- a/curated-catalog.js
+++ b/curated-catalog.js
@@ -4,6 +4,10 @@ import { selectLibraryPackage } from "./library-package.js";
export const CURATED_CATALOG_FORMAT = "prompt-director-curated";
export const CURATED_CATALOG_VERSION = 2;
+export const CURATED_PREVIEW_FORMAT = "prompt-director-curated-preview";
+export const CURATED_PREVIEW_VERSION = 1;
+export const CURATED_METRICS_FORMAT = "prompt-director-curated-metrics";
+export const CURATED_METRICS_VERSION = 1;
const TYPES = new Set(["editorial", "image_prompt", "video_prompt"]);
const COVER_HOSTS = new Set(["wchao6891.github.io"]);
@@ -62,6 +66,79 @@ export function applyCuratedOrigin(entryValue, itemValue, installedAt = new Date
};
}
+export function normalizeCuratedPreview(value, itemValue) {
+ const item = normalizeItem(itemValue);
+ if (value?.format !== CURATED_PREVIEW_FORMAT || value.version !== CURATED_PREVIEW_VERSION || !Array.isArray(value.entries)) {
+ throw new Error("精选预览格式无效");
+ }
+ if (clean(value.catalogId) !== item.id || clean(value.packageId) !== item.packageId || clean(value.packageVersion) !== item.packageVersion) {
+ throw new Error("精选预览与案例包版本不一致");
+ }
+ if (value.entries.length !== item.caseCount) throw new Error("精选预览案例数量与目录不一致");
+ const ids = new Set();
+ const entries = value.entries.map((entry) => {
+ const id = clean(entry?.id);
+ const title = clean(entry?.title);
+ const text = cleanPrompt(entry?.text);
+ const author = clean(entry?.author);
+ const rights = clean(entry?.rights);
+ const mediaKind = ["image", "video"].includes(entry?.mediaKind) ? entry.mediaKind : "";
+ const previewImageUrl = trustedUrl(entry?.previewImageUrl, COVER_HOSTS, "精选预览图片地址不受信任");
+ const sourceUrl = optionalHttpsUrl(entry?.sourceUrl);
+ const hasVideoAsset = Boolean(clean(entry?.videoUrl) || clean(entry?.videoSha256) || clean(entry?.videoMimeType) || Number(entry?.videoBytes) > 0);
+ const videoUrl = hasVideoAsset ? trustedUrl(entry?.videoUrl, DOWNLOAD_HOSTS, "精选视频地址不受信任") : "";
+ const videoSha256 = hasVideoAsset ? String(entry?.videoSha256 ?? "").toLocaleLowerCase("en-US") : "";
+ const videoBytes = hasVideoAsset ? positiveInteger(entry?.videoBytes, "精选视频大小无效") : 0;
+ const videoMimeType = hasVideoAsset ? clean(entry?.videoMimeType) : "";
+ if (!id || !title || !text || !author || !rights || !mediaKind) throw new Error("精选预览案例缺少必填字段");
+ if (hasVideoAsset && (mediaKind !== "video" || !/^[a-f0-9]{64}$/.test(videoSha256) || videoMimeType !== "video/mp4")) {
+ throw new Error("精选视频预览字段无效");
+ }
+ if (ids.has(id)) throw new Error("精选预览包含重复案例");
+ ids.add(id);
+ return {
+ id,
+ title,
+ text,
+ author,
+ rights,
+ sourceUrl,
+ mediaKind,
+ previewImageUrl,
+ ...(hasVideoAsset ? { videoUrl, videoSha256, videoBytes, videoMimeType } : {}),
+ width: positiveInteger(entry?.width),
+ height: positiveInteger(entry?.height)
+ };
+ });
+ return {
+ format: CURATED_PREVIEW_FORMAT,
+ version: CURATED_PREVIEW_VERSION,
+ catalogId: item.id,
+ packageId: item.packageId,
+ packageVersion: item.packageVersion,
+ entries
+ };
+}
+
+export function normalizeCuratedMetrics(value, catalogValue) {
+ const catalog = normalizeCuratedCatalog(catalogValue);
+ if (value?.format !== CURATED_METRICS_FORMAT || value.version !== CURATED_METRICS_VERSION || !value.downloads || Array.isArray(value.downloads)) {
+ throw new Error("精选下载指标格式无效");
+ }
+ const downloads = {};
+ for (const item of catalog.themes) {
+ const count = value.downloads[item.id];
+ if (!Number.isSafeInteger(count) || count < 0) throw new Error("精选下载指标不完整");
+ downloads[item.id] = count;
+ }
+ return {
+ format: CURATED_METRICS_FORMAT,
+ version: CURATED_METRICS_VERSION,
+ updatedAt: validIso(value.updatedAt),
+ downloads
+ };
+}
+
export function curatedSourceKey(entryValue = {}) {
const packageId = clean(entryValue.curatedOrigin?.packageId);
if (!packageId) return "";
@@ -184,6 +261,35 @@ export function validateCuratedPackageContents(itemValue, parsedValue = {}) {
return true;
}
+export function validateCuratedPackageIndex(itemValue, libraryValue = {}, fileNamesValue = []) {
+ const item = normalizeItem(itemValue);
+ const entries = Array.isArray(libraryValue.entries) ? libraryValue.entries : [];
+ if (entries.length !== item.caseCount) throw new Error("精选案例包的案例数量与目录不一致");
+ const fileNames = new Set(fileNamesValue);
+ const assetIds = new Set();
+ const assetPaths = new Set();
+ let imageCount = 0;
+ let videoCount = 0;
+ for (const entry of entries) {
+ for (const asset of Array.isArray(entry?.mediaAssets) ? entry.mediaAssets : []) {
+ if (asset?.storageMode === "reference") continue;
+ const id = clean(asset?.id);
+ const path = clean(asset?.assetPath);
+ if (!id || assetIds.has(id) || !safeCuratedMediaPath(path, asset?.kind) || assetPaths.has(path)) {
+ throw new Error("精选案例包包含无效或重复的媒体索引");
+ }
+ if (!fileNames.has(path)) throw new Error("精选案例包的媒体索引与 ZIP 不一致");
+ assetIds.add(id);
+ assetPaths.add(path);
+ if (asset.kind === "image") imageCount += 1;
+ if (asset.kind === "video") videoCount += 1;
+ }
+ }
+ if (imageCount !== item.imageCount) throw new Error("精选案例包的图片数量与目录不一致");
+ if (videoCount !== item.videoCount) throw new Error("精选案例包的视频数量与目录不一致");
+ return true;
+}
+
export function isTrustedCuratedResponseUrl(value) {
const url = safeHttpsUrl(value);
return Boolean(url && (DOWNLOAD_HOSTS.has(url.hostname) || COVER_HOSTS.has(url.hostname)));
@@ -194,14 +300,16 @@ function normalizeItem(value = {}) {
const title = clean(value.title);
const packageId = clean(value.packageId);
const packageVersion = clean(value.packageVersion);
+ const authorId = safeId(value.authorId);
const type = TYPES.has(value.type) ? value.type : "";
const author = clean(value.author);
const license = clean(value.license);
const updatedAt = validIso(value.updatedAt);
const coverUrl = trustedUrl(value.coverUrl, COVER_HOSTS, "精选封面地址不受信任");
+ const previewUrl = trustedUrl(value.previewUrl, COVER_HOSTS, "精选预览地址不受信任");
const downloadUrl = trustedUrl(value.downloadUrl, DOWNLOAD_HOSTS, "精选下载地址不受信任");
const sha256 = String(value.sha256 ?? "").toLocaleLowerCase("en-US");
- if (!id || !title || !type || !packageId || !packageVersion || !author || !license || !updatedAt ||
+ if (!id || !title || !type || !packageId || !packageVersion || !authorId || !author || !license || !updatedAt ||
!/^[a-f0-9]{64}$/.test(sha256)) {
throw new Error("精选目录条目缺少必填字段或校验值");
}
@@ -211,12 +319,15 @@ function normalizeItem(value = {}) {
type,
packageId,
packageVersion,
+ authorId,
author,
license,
updatedAt,
coverUrl,
+ previewUrl,
downloadUrl,
sha256,
+ archiveBytes: positiveInteger(value.archiveBytes, "精选案例包大小无效"),
caseCount: nonNegativeInteger(value.caseCount),
imageCount: nonNegativeInteger(value.imageCount),
videoCount: nonNegativeInteger(value.videoCount),
@@ -242,6 +353,27 @@ function safeHttpsUrl(value) {
}
}
+function optionalHttpsUrl(value) {
+ if (!clean(value)) return "";
+ const url = safeHttpsUrl(value);
+ if (!url || url.username || url.password) throw new Error("精选案例来源地址无效");
+ return url.href;
+}
+
+function safeCuratedMediaPath(path, kind) {
+ if (!path || path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) return false;
+ if (kind === "image") return /^images\/[A-Za-z0-9._/-]+\.(?:png|jpe?g|webp)$/i.test(path);
+ if (kind === "video") return /^videos\/[A-Za-z0-9._/-]+\.(?:mp4|webm|mov|mkv|avi)$/i.test(path);
+ return false;
+}
+
+function cleanPrompt(value) {
+ return String(value ?? "")
+ .replace(/\r\n?/g, "\n")
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "")
+ .trim();
+}
+
function validIso(value) {
const text = clean(value);
return text && !Number.isNaN(Date.parse(text)) ? new Date(text).toISOString() : "";
@@ -262,8 +394,8 @@ function nonNegativeInteger(value) {
return Math.max(0, Math.floor(Number(value) || 0));
}
-function positiveInteger(value) {
+function positiveInteger(value, message = "精选主题排序无效") {
const number = Math.floor(Number(value) || 0);
- if (number < 1) throw new Error("精选主题排序无效");
+ if (number < 1) throw new Error(message);
return number;
}
diff --git a/curated-config.js b/curated-config.js
index c37471d..5f384b3 100644
--- a/curated-config.js
+++ b/curated-config.js
@@ -1,6 +1,15 @@
export const CURATED_CATALOG_URL =
"https://wchao6891.github.io/PromptDirector-Curated/catalog.json";
+export const CURATED_METRICS_URL =
+ "https://wchao6891.github.io/PromptDirector-Curated/metrics.json";
+
+export const CURATED_PUBLIC_SITE_URL =
+ "https://wchao6891.github.io/PromptDirector-Curated/";
+
+export const CURATED_SUBMISSION_URL =
+ "https://github.com/wchao6891/PromptDirector-Curated/issues/new?template=curated-submission.yml";
+
export const CURATED_PERMISSION_ORIGINS = Object.freeze([
"https://wchao6891.github.io/*",
"https://github.com/*",
diff --git a/curated-download.js b/curated-download.js
index 9f9ef43..f43b2b8 100644
--- a/curated-download.js
+++ b/curated-download.js
@@ -14,6 +14,37 @@ export async function fetchCuratedPackage(url, { fetchImpl = fetch } = {}) {
return fetchImpl(url, PACKAGE_REQUEST_OPTIONS);
}
+export async function readResponseBlobWithProgress(response, { onProgress = () => undefined } = {}) {
+ const contentType = response.headers.get("content-type") || "application/octet-stream";
+ const declaredSize = Number(response.headers.get("content-length"));
+ const total = Number.isSafeInteger(declaredSize) && declaredSize > 0 ? declaredSize : 0;
+ if (!response.body?.getReader) {
+ const blob = await response.blob();
+ onProgress({ loaded: blob.size, total, ratio: total ? Math.min(1, blob.size / total) : null });
+ return blob;
+ }
+
+ const chunks = total ? null : [];
+ const bytes = total ? new Uint8Array(total) : null;
+ const reader = response.body.getReader();
+ let loaded = 0;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (!value?.byteLength) continue;
+ if (total) {
+ if (loaded + value.byteLength > total) throw new Error("精选案例包下载大小与响应不一致");
+ bytes.set(value, loaded);
+ } else {
+ chunks.push(value);
+ }
+ loaded += value.byteLength;
+ onProgress({ loaded, total, ratio: total ? Math.min(1, loaded / total) : null });
+ }
+ if (total && loaded !== total) throw new Error("精选案例包下载不完整");
+ return new Blob(total ? [bytes] : chunks, { type: contentType });
+}
+
function isTransientStatus(status) {
return status === 408 || status === 429 || status >= 500;
}
diff --git a/curated-import.js b/curated-import.js
new file mode 100644
index 0000000..21f738e
--- /dev/null
+++ b/curated-import.js
@@ -0,0 +1,140 @@
+import { curatedSourceKey } from "./curated-catalog.js";
+import { mergeLibraryPackage } from "./library-package.js";
+import { COLLECTION_VISIBILITY, normalizeOrganizerState } from "./organizer.js";
+
+export function mergeCuratedLibraryPackage(currentValue = {}, libraryValue = {}, options = {}) {
+ const packageId = clean(options.packageId);
+ const projectName = clean(options.projectName);
+ const mode = options.mode === "package" ? "package" : "case";
+ if (!packageId) throw new Error("精选案例包缺少稳定编号");
+ if (mode === "package" && !projectName) throw new Error("精选案例包缺少项目名称");
+
+ const current = structuredClone(currentValue);
+ const imported = structuredClone(libraryValue);
+ const sourceEntries = Array.isArray(imported.entries) ? imported.entries : [];
+ if (!sourceEntries.length) throw new Error("精选案例包没有可保存案例");
+
+ const currentBySource = new Map();
+ for (const entry of Array.isArray(current.entries) ? current.entries : []) {
+ const key = curatedSourceKey(entry);
+ if (key && !currentBySource.has(key)) currentBySource.set(key, entry);
+ }
+
+ const originalToAdaptedId = new Map();
+ const sourceEntryIds = new Set();
+ const existingSourceEntryIds = new Set();
+ for (const entry of sourceEntries) {
+ if (clean(entry.curatedOrigin?.packageId) !== packageId) throw new Error("精选案例来源与案例包不一致");
+ const sourceEntryId = clean(entry.curatedOrigin?.sourceEntryId);
+ const key = curatedSourceKey(entry);
+ if (!sourceEntryId || !key || sourceEntryIds.has(sourceEntryId)) throw new Error("精选案例来源编号无效或重复");
+ sourceEntryIds.add(sourceEntryId);
+ const existing = currentBySource.get(key);
+ const originalId = clean(entry.id);
+ const adaptedId = existing?.id || originalId;
+ originalToAdaptedId.set(originalId, adaptedId);
+ entry.id = adaptedId;
+ if (existing) existingSourceEntryIds.add(sourceEntryId);
+ }
+ remapEntryRelationships(imported, originalToAdaptedId);
+ imported.organizerState = { version: 6, collections: [] };
+
+ const result = mergeLibraryPackage(current, imported, {
+ entryIdMap: remapPreferredIds(options.entryIdMap, originalToAdaptedId),
+ compoundIdMap: options.compoundIdMap,
+ visualIdMap: options.visualIdMap,
+ sessionIdMap: options.sessionIdMap,
+ runIdMap: options.runIdMap,
+ preserveLibraryConfiguration: true
+ });
+
+ const entriesBySourceEntryId = {};
+ const entryIds = [];
+ for (const sourceEntryId of sourceEntryIds) {
+ const key = curatedSourceKey({ curatedOrigin: { packageId, sourceEntryId } });
+ if (!key) throw new Error("精选案例来源编号无效");
+ const entry = result.state.entries.find((candidate) => curatedSourceKey(candidate) === key);
+ if (!entry) throw new Error("精选案例没有写入私人案例库");
+ entriesBySourceEntryId[sourceEntryId] = entry.id;
+ entryIds.push(entry.id);
+ }
+
+ let projectId = "";
+ if (mode === "package") {
+ projectId = `curated-project:${safeId(packageId)}`;
+ const organizer = normalizeOrganizerState(result.state.organizerState, result.state.entries.map((entry) => entry.id));
+ const existingProject = organizer.collections.find((collection) => collection.id === projectId);
+ if (existingProject) {
+ existingProject.entryIds = [...new Set([...existingProject.entryIds, ...entryIds])];
+ } else {
+ organizer.collections.push({
+ id: projectId,
+ name: projectName,
+ order: organizer.collections.length,
+ entryIds,
+ visibility: COLLECTION_VISIBILITY.library
+ });
+ }
+ result.state.organizerState = normalizeOrganizerState(organizer, result.state.entries.map((entry) => entry.id));
+ }
+
+ const importedSourceEntryIds = [...sourceEntryIds].filter((id) => !existingSourceEntryIds.has(id));
+ const importedEntryIds = importedSourceEntryIds.map((id) => entriesBySourceEntryId[id]);
+ const importedEntryIdSet = new Set(importedEntryIds);
+ const importedVisualIds = result.state.entries
+ .filter((entry) => importedEntryIdSet.has(entry.id))
+ .flatMap((entry) => (entry.mediaAssets ?? []).filter((asset) => asset.storageMode !== "reference").map((asset) => asset.id));
+
+ return {
+ ...result,
+ entryIdMap: restoreOriginalIdMap(result.entryIdMap, originalToAdaptedId),
+ importedCount: importedSourceEntryIds.length,
+ existingCount: sourceEntryIds.size - importedSourceEntryIds.length,
+ sourceEntryIds: [...sourceEntryIds],
+ importedSourceEntryIds,
+ entriesBySourceEntryId,
+ importedEntryIds,
+ importedVisualIds,
+ projectId
+ };
+}
+
+function remapEntryRelationships(library, idMap) {
+ for (const entry of library.entries ?? []) {
+ if (entry.creationMeta?.sourceEntryIds) {
+ entry.creationMeta.sourceEntryIds = entry.creationMeta.sourceEntryIds.map((id) => idMap.get(id) ?? id);
+ }
+ }
+ for (const item of library.compoundCases ?? []) {
+ item.memberEntryIds = (item.memberEntryIds ?? []).map((id) => idMap.get(id) ?? id);
+ }
+ for (const collection of library.organizerState?.collections ?? []) {
+ collection.entryIds = (collection.entryIds ?? []).map((id) => idMap.get(id) ?? id);
+ }
+}
+
+function remapPreferredIds(value = {}, idMap) {
+ const preferred = {};
+ for (const [sourceId, targetId] of Object.entries(value ?? {})) {
+ preferred[idMap.get(sourceId) ?? sourceId] = targetId;
+ }
+ return preferred;
+}
+
+function restoreOriginalIdMap(value = {}, idMap) {
+ const restored = {};
+ for (const [originalId, adaptedId] of idMap) {
+ if (value[adaptedId]) restored[originalId] = value[adaptedId];
+ }
+ return restored;
+}
+
+function clean(value) {
+ return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
+}
+
+function safeId(value) {
+ const id = clean(value);
+ if (!/^[A-Za-z0-9._-]+$/.test(id) || id === "." || id === "..") throw new Error("精选编号无效");
+ return id;
+}
diff --git a/curated-page.js b/curated-page.js
index 9552262..298f547 100644
--- a/curated-page.js
+++ b/curated-page.js
@@ -2,710 +2,1033 @@ import {
curatedSourceKey,
isTrustedCuratedResponseUrl,
normalizeCuratedCatalog,
- prepareCuratedEntriesPackage,
+ normalizeCuratedMetrics,
+ normalizeCuratedPreview,
prepareCuratedEntryPackage,
+ prepareCuratedEntriesPackage,
prepareCuratedPackageVersion,
- validateCuratedPackageContents,
+ validateCuratedPackageIndex,
verifyCuratedPackageBlob
} from "./curated-catalog.js";
import {
CURATED_CATALOG_URL,
- CURATED_PERMISSION_ORIGINS
+ CURATED_METRICS_URL,
+ CURATED_PUBLIC_SITE_URL
} from "./curated-config.js";
-import { fetchCuratedPackage } from "./curated-download.js";
-import { isComposerEligibleEntry } from "./composer.js";
+import { fetchCuratedPackage, readResponseBlobWithProgress } from "./curated-download.js";
import { initializeUi, t } from "./i18n.js";
import { parseLibraryPackage } from "./library-package.js";
import { deleteMediaBlob, saveMediaBlob } from "./media-store.js";
import { createStableMasonry } from "./stable-masonry.js";
-import { readZipBlob } from "./zip.js";
+import { openZipBlob } from "./zip.js";
const CATALOG_CACHE_KEY = "curatedCatalogCache";
-const PAGE_SIZE = 24;
+const METRICS_CACHE_KEY = "curatedMetricsCache";
+const FOLLOWING_KEY = "curatedFollowingAuthors";
+const CURATED_CASE_PAGE_SIZE = 24;
const elements = Object.fromEntries([
- "active-theme-count", "active-theme-summary", "active-theme-title", "cases-view", "curated-empty", "curated-grid",
- "curated-loading", "curated-status", "detail-backdrop", "detail-close",
- "detail-content", "detail-drawer", "detail-next", "detail-prev", "load-more", "load-sentinel", "retry-catalog",
- "return-label", "return-library", "save-theme", "theme-grid", "theme-save-status", "themes-view"
+ "case-detail-backdrop", "case-detail-close", "case-detail-content", "case-detail-drawer", "case-detail-next", "case-detail-prev",
+ "clear-filters", "curated-app", "curated-search", "curated-status", "curated-status-bar", "curated-toast",
+ "detail-close", "detail-content", "detail-dialog", "filter-button", "filter-count", "filter-popover",
+ "retry-catalog", "return-library", "sort-downloads", "sort-label", "sort-menu"
].map((id) => [camel(id), document.querySelector(`#${id}`)]));
await initializeUi();
-const galleryMasonry = createStableMasonry(elements.curatedGrid);
-const caseImageObserver = new IntersectionObserver((items) => {
- for (const item of items) {
- if (!item.isIntersecting) continue;
- caseImageObserver.unobserve(item.target);
- hydrateCaseImage(item.target);
- }
-}, { rootMargin: "320px" });
-const loadObserver = new IntersectionObserver((items) => {
- if (items.some((item) => item.isIntersecting)) appendNextCases();
-}, { rootMargin: "500px" });
-
-let catalog = null;
-let localEntries = [];
-let activeThemeId = "";
-let activeThemeRecord = null;
-let curatedCases = [];
-let visibleCases = [];
-let renderedCount = 0;
-let currentDetailKey = "";
+
+const state = {
+ catalog: null,
+ metrics: null,
+ previews: new Map(),
+ previewFailures: new Set(),
+ localEntries: [],
+ localStateAvailable: false,
+ following: new Set(),
+ filters: new Set(),
+ query: "",
+ sort: "recommended",
+ selectedId: "",
+ selectedEntryId: ""
+};
+const archivePromises = new Map();
+const packageIndexPromises = new Map();
+const progressListeners = new Map();
+const caseVideoControllers = new Set();
+let toastTimer = 0;
+let searchVersion = 0;
let detailReturnFocus = null;
-let loadingCases = false;
-let savingThemeId = "";
-const themeSaveFailures = new Map();
-const themePackages = new Map();
-const themeCoverUrls = new Map();
-const imageUrls = new Map();
-const mediaUrls = new Map();
-
-elements.retryCatalog.addEventListener("click", () => refreshCatalog(true));
-elements.returnLibrary.addEventListener("click", () => activeThemeId ? backToThemes() : returnToLibrary());
-elements.saveTheme.addEventListener("click", () => saveTheme(activeThemeId, elements.saveTheme));
-elements.loadMore.addEventListener("click", appendNextCases);
-elements.detailBackdrop.addEventListener("click", closeDetail);
+let caseDetailReturnFocus = null;
+let caseMasonry = null;
+let caseLoadObserver = null;
+let renderedCaseCount = 0;
+let caseDetailVideoCleanup = null;
+
+elements.returnLibrary.addEventListener("click", returnToLibrary);
+elements.retryCatalog.addEventListener("click", refreshCatalog);
elements.detailClose.addEventListener("click", closeDetail);
-elements.detailPrev.addEventListener("click", () => moveDetail(-1));
-elements.detailNext.addEventListener("click", () => moveDetail(1));
-document.addEventListener("keydown", (event) => {
- if (!currentDetailKey) return;
- if (event.key === "Escape") closeDetail();
- else if (event.key === "ArrowLeft") moveDetail(-1);
- else if (event.key === "ArrowRight") moveDetail(1);
+elements.detailDialog.addEventListener("click", (event) => {
+ if (event.target === elements.detailDialog) closeDetail();
+});
+elements.caseDetailBackdrop.addEventListener("click", closeCaseDetail);
+elements.caseDetailClose.addEventListener("click", closeCaseDetail);
+elements.caseDetailPrev.addEventListener("click", () => moveCaseDetail(-1));
+elements.caseDetailNext.addEventListener("click", () => moveCaseDetail(1));
+elements.curatedSearch.addEventListener("input", async () => {
+ const version = ++searchVersion;
+ state.query = elements.curatedSearch.value.trim().toLocaleLowerCase();
+ renderGallery();
+ if (!state.query) return;
+ await loadAllPreviews();
+ if (version === searchVersion) renderGallery();
+});
+elements.filterButton.addEventListener("click", () => {
+ elements.filterPopover.hidden = !elements.filterPopover.hidden;
+ elements.filterButton.setAttribute("aria-expanded", String(!elements.filterPopover.hidden));
+});
+elements.filterPopover.addEventListener("change", updateFilters);
+elements.clearFilters.addEventListener("click", () => {
+ elements.filterPopover.querySelectorAll('input[type="checkbox"]').forEach((input) => { input.checked = false; });
+ state.filters.clear();
+ updateFilterCount();
+ renderGallery();
+});
+elements.sortMenu.addEventListener("click", (event) => {
+ const button = event.target.closest("[data-sort]");
+ if (!button || button.disabled) return;
+ state.sort = button.dataset.sort;
+ elements.sortLabel.textContent = button.querySelector("span").textContent;
+ elements.sortMenu.querySelectorAll("[data-sort]").forEach((candidate) => {
+ candidate.setAttribute("aria-current", String(candidate === button));
+ });
+ elements.sortMenu.open = false;
+ renderGallery();
+});
+document.addEventListener("click", (event) => {
+ if (!event.target.closest(".filter-wrap")) {
+ elements.filterPopover.hidden = true;
+ elements.filterButton.setAttribute("aria-expanded", "false");
+ }
+ if (!event.target.closest(".sort-menu")) elements.sortMenu.open = false;
});
-window.addEventListener("unload", () => {
- galleryMasonry.destroy();
- caseImageObserver.disconnect();
- loadObserver.disconnect();
- releaseImageUrls();
- releaseThemeCoverUrls();
+document.addEventListener("keydown", (event) => {
+ if (event.key === "Escape" && state.selectedEntryId) {
+ event.preventDefault();
+ closeCaseDetail();
+ return;
+ }
+ if (event.key === "Escape" && elements.detailDialog.open) {
+ event.preventDefault();
+ closeDetail();
+ return;
+ }
+ if (state.selectedEntryId && !event.target.matches("input, textarea, select")) {
+ if (event.key === "ArrowLeft") moveCaseDetail(-1);
+ if (event.key === "ArrowRight") moveCaseDetail(1);
+ }
+ if ((event.metaKey || event.ctrlKey) && event.key.toLocaleLowerCase() === "k") {
+ event.preventDefault();
+ elements.curatedSearch.focus();
+ }
});
-loadObserver.observe(elements.loadSentinel);
-await loadLocalState();
-await loadCachedCatalog();
-renderThemes();
-if (await hasCatalogPermission()) await refreshCatalog(false);
-else showStatus(t("启用只读目录权限后会自动检查更新;不会上传你的本地案例。"), true, true);
+await loadCachedPublicState();
+if (state.catalog) renderGallery();
+const localStatePromise = loadLocalState().then(() => true).catch(() => false);
+await refreshCatalog();
+if (!await localStatePromise) {
+ showStatus(t("私人案例库暂不可用,精选仍可浏览"), { error: true });
+}
+const requestedId = new URLSearchParams(location.search).get("pack");
+if (requestedId && state.catalog) openDetail(requestedId);
function returnToLibrary() {
location.assign(chrome.runtime.getURL("library.html"));
}
-async function refreshCatalog(requestPermission) {
+async function loadLocalState() {
+ const response = await chrome.runtime.sendMessage({ type: "GET_STATE" });
+ if (!response?.ok) throw new Error(response?.message || "无法读取本地案例库");
+ state.localEntries = response.entries ?? [];
+ state.localStateAvailable = true;
+}
+
+async function loadCachedPublicState() {
+ const stored = await chrome.storage.local.get([CATALOG_CACHE_KEY, METRICS_CACHE_KEY, FOLLOWING_KEY]);
+ state.following = new Set(Array.isArray(stored[FOLLOWING_KEY]) ? stored[FOLLOWING_KEY].filter((id) => typeof id === "string") : []);
+ try {
+ if (stored[CATALOG_CACHE_KEY]) state.catalog = normalizeCuratedCatalog(stored[CATALOG_CACHE_KEY]);
+ } catch {
+ await chrome.storage.local.remove(CATALOG_CACHE_KEY);
+ }
+ try {
+ if (state.catalog && stored[METRICS_CACHE_KEY]) state.metrics = normalizeCuratedMetrics(stored[METRICS_CACHE_KEY], state.catalog);
+ } catch {
+ await chrome.storage.local.remove(METRICS_CACHE_KEY);
+ }
+ updateMetricsUi();
+}
+
+async function refreshCatalog() {
elements.retryCatalog.disabled = true;
- elements.retryCatalog.hidden = true;
try {
- if (requestPermission && !await requestCatalogPermission()) {
- throw new Error(t("未授权访问精选目录,现有本地案例没有改变"));
- }
- if (!await hasCatalogPermission()) throw new Error(t("需要授权只读精选目录后才能联网加载"));
- showStatus(t("正在检查精选目录…"));
- const response = await fetch(CURATED_CATALOG_URL, {
- cache: "no-store",
- credentials: "omit",
- redirect: "error"
- });
+ const response = await fetch(CURATED_CATALOG_URL, { cache: "no-store", credentials: "omit", redirect: "error" });
if (!response.ok) throw new Error(`精选目录返回 HTTP ${response.status}`);
- catalog = normalizeCuratedCatalog(await response.json());
- await chrome.storage.local.set({ [CATALOG_CACHE_KEY]: catalog });
- renderThemes();
- showStatus(`${catalog.themes.length} ${t("期精选主题")}`);
- await loadThemeCovers(catalog.themes);
+ state.catalog = normalizeCuratedCatalog(await response.json());
+ await chrome.storage.local.set({ [CATALOG_CACHE_KEY]: state.catalog });
+ state.previews.clear();
+ state.previewFailures.clear();
+ renderGallery();
+ hideStatus();
+ await refreshMetrics();
} catch (error) {
- showStatus(`${error.message}${catalog ? " · 已保留缓存目录" : ""}`, true, true);
- renderThemes();
+ showStatus(`${friendlyError(error, t("精选目录加载失败"))}${state.catalog ? ` · ${t("目录信息已缓存,可稍后重试")}` : ""}`, { error: true, retry: true });
+ renderGallery();
} finally {
elements.retryCatalog.disabled = false;
}
}
-async function loadCachedCatalog() {
- const stored = await chrome.storage.local.get(CATALOG_CACHE_KEY);
+async function refreshMetrics() {
+ if (!state.catalog) return;
try {
- if (stored[CATALOG_CACHE_KEY]) catalog = normalizeCuratedCatalog(stored[CATALOG_CACHE_KEY]);
+ const response = await fetch(CURATED_METRICS_URL, { cache: "no-store", credentials: "omit", redirect: "error" });
+ if (!response.ok) throw new Error(`精选指标返回 HTTP ${response.status}`);
+ state.metrics = normalizeCuratedMetrics(await response.json(), state.catalog);
+ await chrome.storage.local.set({ [METRICS_CACHE_KEY]: state.metrics });
} catch {
- await chrome.storage.local.remove(CATALOG_CACHE_KEY);
+ if (!state.metrics) await chrome.storage.local.remove(METRICS_CACHE_KEY);
}
+ updateMetricsUi();
+ renderGallery();
}
-async function loadLocalState() {
- const response = await chrome.runtime.sendMessage({ type: "GET_STATE" });
- if (!response?.ok) throw new Error(response?.message || "无法读取本地案例库");
- localEntries = response.entries ?? [];
+function updateMetricsUi() {
+ elements.sortDownloads.disabled = !state.metrics;
+ if (!state.metrics && state.sort === "downloads") {
+ state.sort = "recommended";
+ elements.sortLabel.textContent = t("推荐");
+ }
}
-function renderThemes() {
- showActiveView();
- if (!catalog?.themes?.length) {
- elements.themeGrid.replaceChildren();
+function renderGallery() {
+ if (!state.catalog?.themes?.length) {
+ elements.curatedApp.replaceChildren(element("div", "curated-empty", t("还没有可显示的精选案例")));
return;
}
- elements.themeGrid.replaceChildren(...catalog.themes.map(createThemeCard));
-}
-
-function createThemeCard(theme) {
- const card = document.createElement("article");
- card.className = "theme-card";
- const open = textElement("button", "theme-open", "");
- open.type = "button";
- open.setAttribute("aria-label", t("打开 {title}", { title: theme.title }));
- open.addEventListener("click", () => openTheme(theme.id));
- const cover = document.createElement("span");
- cover.className = "theme-cover";
- const coverUrl = themeCoverUrls.get(theme.id);
- if (coverUrl) {
- const image = document.createElement("img");
- image.src = coverUrl;
- image.alt = `${theme.title} 封面`;
- image.decoding = "async";
- image.loading = "eager";
- cover.append(image);
+ const items = visibleItems();
+ if (!items.length) {
+ elements.curatedApp.replaceChildren(element("div", "curated-empty", t("没有结果")));
+ return;
+ }
+ const grid = element("section", "pack-grid");
+ grid.append(...items.map(createPackCard));
+ elements.curatedApp.replaceChildren(grid);
+}
+
+function visibleItems() {
+ let items = state.catalog.themes.filter((item) => {
+ if (state.filters.has("followed") && !state.following.has(item.authorId)) return false;
+ const typeFilters = [...state.filters].filter((value) => value !== "followed");
+ if (typeFilters.length && !typeFilters.includes(item.type)) return false;
+ return !state.query || searchableText(item).includes(state.query);
+ });
+ if (state.sort === "latest") {
+ items = [...items].sort((left, right) => new Date(right.updatedAt) - new Date(left.updatedAt) || left.order - right.order);
+ } else if (state.sort === "downloads" && state.metrics) {
+ items = [...items].sort((left, right) => state.metrics.downloads[right.id] - state.metrics.downloads[left.id] || left.order - right.order);
} else {
- cover.append(textElement("span", "", t("封面加载中")));
+ items = [...items].sort((left, right) => left.order - right.order);
}
- const copy = document.createElement("span");
- copy.className = "theme-copy";
- copy.append(
- textElement("strong", "", theme.title),
- textElement("span", "", `${theme.caseCount} ${t("个案例")}`),
- textElement("p", "", theme.summary)
- );
- open.append(cover, copy);
- const actions = document.createElement("div");
- actions.className = "theme-card-actions";
- const savedCount = themeSavedCount(theme);
- actions.append(textElement("small", "", `${savedCount}/${theme.caseCount} ${t("已保存")}`));
- const save = textElement("button", "button-secondary", t(savedCount >= theme.caseCount ? "已全部保存" : "全部保存"));
- save.type = "button";
- save.disabled = savingThemeId === theme.id || savedCount >= theme.caseCount;
- save.addEventListener("click", () => saveTheme(theme.id, save));
- actions.append(save);
- card.append(open, actions);
+ return items;
+}
+
+function searchableText(item) {
+ const preview = state.previews.get(item.id);
+ return [item.title, item.author, ...(preview?.entries ?? []).flatMap((entry) => [entry.title, entry.author, entry.text])]
+ .join(" ")
+ .toLocaleLowerCase();
+}
+
+function createPackCard(item) {
+ const card = element("article", "pack-card");
+ card.dataset.packId = item.id;
+ card.tabIndex = 0;
+ card.setAttribute("aria-label", t("打开 {title}", { title: item.title }));
+ const cover = element("span", "pack-cover");
+ const image = element("img");
+ image.src = item.coverUrl;
+ image.alt = "";
+ image.loading = "lazy";
+ cover.append(image);
+ const copy = element("div", "pack-copy");
+ copy.append(element("h2", "", item.title));
+ const meta = element("div", "pack-meta");
+ meta.append(element("span", "", item.author), element("span", "", `${item.caseCount} ${t("个案例")}`));
+ copy.append(meta);
+ card.append(cover, copy);
+ const open = () => openDetail(item.id, card);
+ card.addEventListener("click", open);
+ card.addEventListener("keydown", (event) => {
+ if (!["Enter", " "].includes(event.key)) return;
+ event.preventDefault();
+ open();
+ });
return card;
}
-async function loadThemeCovers(themes) {
- const pending = themes.filter((theme) => !themeCoverUrls.has(theme.id));
- await Promise.allSettled(pending.map(async (theme) => {
- const response = await fetch(theme.coverUrl, { cache: "force-cache", credentials: "omit", redirect: "error" });
- if (!response.ok || !isTrustedCuratedResponseUrl(response.url)) throw new Error("精选主题封面地址无效");
- const blob = await response.blob();
- if (!blob.type.startsWith("image/")) throw new Error("精选主题封面格式无效");
- themeCoverUrls.set(theme.id, URL.createObjectURL(blob));
- }));
- renderThemes();
-}
-
-async function openTheme(themeId) {
- const theme = catalog?.themes.find((item) => item.id === themeId);
- if (!theme) return showStatus("没有找到这期精选主题", true);
- activeThemeId = theme.id;
- elements.activeThemeTitle.textContent = theme.title;
- elements.activeThemeSummary.textContent = theme.summary;
- showActiveView();
- showLoading(true);
+async function openDetail(id, returnFocus = null) {
+ const item = state.catalog?.themes.find((candidate) => candidate.id === id);
+ if (!item) return showToast(t("案例包不存在"));
+ state.selectedId = item.id;
+ if (returnFocus) detailReturnFocus = returnFocus;
+ setDetailUrl(item.id);
+ renderDetail(item, null);
+ document.documentElement.classList.add("detail-open");
+ if (!elements.detailDialog.open) elements.detailDialog.showModal();
+ elements.detailClose.focus({ preventScroll: true });
try {
- activeThemeRecord = await loadThemePackage(theme);
- curatedCases = activeThemeRecord.records;
- showLoading(false);
- renderCases();
- updateThemeSaveUi();
- showStatus("");
+ const preview = await loadPreview(item);
+ if (state.selectedId === item.id) renderDetail(item, preview);
} catch (error) {
- showLoading(false);
- showStatus(error.message, true);
- backToThemes();
+ showToast(friendlyError(error, t("预览加载失败")));
+ if (state.selectedId === item.id) renderDetail(item, null, true);
}
}
-async function loadThemePackage(theme) {
- if (themePackages.has(theme.id)) return themePackages.get(theme.id);
- showStatus(`正在加载 ${theme.title}…`);
- const response = await fetchCuratedPackage(theme.downloadUrl);
- if (!response.ok || !isTrustedCuratedResponseUrl(response.url)) {
- throw new Error(`精选案例包下载失败(HTTP ${response.status})`);
+function closeDetail() {
+ if (state.selectedEntryId) closeCaseDetail({ restoreFocus: false });
+ const returnFocus = detailReturnFocus;
+ const selectedId = state.selectedId;
+ cleanupCaseGallery();
+ state.selectedId = "";
+ detailReturnFocus = null;
+ document.documentElement.classList.remove("detail-open");
+ if (elements.detailDialog.open) elements.detailDialog.close();
+ elements.detailContent.replaceChildren();
+ setDetailUrl("");
+ if (returnFocus?.isConnected) returnFocus.focus();
+ else [...elements.curatedApp.querySelectorAll(".pack-card")].find((card) => card.dataset.packId === selectedId)?.focus();
+}
+
+function setDetailUrl(id) {
+ const url = new URL(location.href);
+ if (id) url.searchParams.set("pack", id);
+ else url.searchParams.delete("pack");
+ history.replaceState(null, "", url);
+}
+
+function renderDetail(item, preview, failed = false) {
+ cleanupCaseGallery();
+ const surface = element("article", "detail-surface");
+ const hero = element("section", "detail-hero");
+ const cover = element("div", "detail-cover");
+ const coverImage = element("img");
+ coverImage.src = item.coverUrl;
+ coverImage.alt = "";
+ cover.append(coverImage);
+ const info = element("div", "detail-info");
+ info.append(element("h1", "", item.title));
+ const meta = element("div", "detail-meta");
+ meta.append(element("span", "", item.author), element("span", "", `${item.caseCount} ${t("个案例")}`), element("span", "", rightsLabel(item.license)));
+ info.append(meta);
+ const actions = element("div", "detail-actions");
+ const download = actionButton("download-action", "save", t("保存整包"));
+ download.addEventListener("click", () => saveEntirePackage(item, download));
+ const following = state.following.has(item.authorId);
+ const follow = actionButton(`button-secondary follow-action${following ? " is-active" : ""}`, following ? "check" : "plus", t(following ? "已关注" : "关注"));
+ follow.addEventListener("click", () => toggleFollow(item, follow));
+ const copyLink = actionButton("button-secondary", "copy", t("复制链接"));
+ copyLink.addEventListener("click", () => copyText(publicPackUrl(item.id), copyLink, t("已复制")));
+ actions.append(download, follow, copyLink);
+ info.append(actions);
+ hero.append(cover, info);
+ surface.append(hero);
+
+ const section = element("section", "case-section");
+ const heading = element("h2", "", t("包内案例"));
+ heading.append(element("span", "", String(item.caseCount)));
+ section.append(heading);
+ if (preview) {
+ const list = element("div", "case-list");
+ const sentinel = element("div", "case-load-sentinel");
+ section.append(list, sentinel);
+ surface.append(section);
+ elements.detailContent.replaceChildren(surface);
+ startCaseGallery(item, preview, list, sentinel);
+ return;
+ }
+ if (failed) {
+ const failure = element("div", "preview-failure");
+ failure.append(element("span", "", t("预览加载失败")));
+ const retry = element("button", "button-secondary", t("重试"));
+ retry.type = "button";
+ retry.addEventListener("click", () => retryPreview(item, retry));
+ failure.append(retry);
+ section.append(failure);
+ } else {
+ const loading = element("div", "case-loading");
+ loading.setAttribute("aria-label", t("正在加载包内案例"));
+ section.append(loading);
}
- const archive = await response.blob();
- await verifyCuratedPackageBlob(archive, theme.sha256);
- const files = await readZipBlob(archive);
- const libraryFile = files.get("library.json");
- if (!libraryFile) throw new Error("精选案例包缺少 library.json");
- const sourceLibrary = JSON.parse(await libraryFile.text());
- const preparedLibrary = prepareCuratedPackageVersion(sourceLibrary, theme);
- const parsed = parseLibraryPackage(preparedLibrary, files);
- validateCuratedPackageContents(theme, parsed);
- const record = {
- theme,
- library: preparedLibrary,
- files,
- records: parsed.entries.map((entry) => {
- const media = primaryMedia(entry);
- const image = media?.kind === "video" ? posterImage(entry, media) : media;
- return {
- key: `${theme.id}:${entry.id}`,
- theme,
- entry,
- media,
- mediaBlob: media ? parsed.assets.get(media.id) ?? null : null,
- image,
- imageBlob: image ? parsed.images.get(image.id) ?? null : null,
- library: preparedLibrary,
- files
- };
- })
+ surface.append(section);
+ elements.detailContent.replaceChildren(surface);
+}
+
+function startCaseGallery(item, preview, list, sentinel) {
+ renderedCaseCount = 0;
+ caseMasonry = createStableMasonry(list, { scrollContainer: elements.detailDialog });
+ const appendNext = () => {
+ const entries = preview.entries.slice(renderedCaseCount, renderedCaseCount + CURATED_CASE_PAGE_SIZE);
+ if (!entries.length) {
+ sentinel.hidden = true;
+ caseLoadObserver?.disconnect();
+ return;
+ }
+ const cards = entries.map((entry) => createCaseCard(item, entry));
+ list.append(...cards);
+ caseMasonry.append(cards);
+ renderedCaseCount += entries.length;
+ sentinel.hidden = renderedCaseCount >= preview.entries.length;
+ if (sentinel.hidden) caseLoadObserver?.disconnect();
};
- themePackages.set(theme.id, record);
- return record;
-}
-
-function backToThemes() {
- closeDetail();
- activeThemeId = "";
- activeThemeRecord = null;
- curatedCases = [];
- visibleCases = [];
- renderedCount = 0;
- galleryMasonry.reset();
- elements.curatedGrid.replaceChildren();
- releaseImageUrls();
- showLoading(false);
- renderThemes();
-}
-
-function renderCases() {
- if (loadingCases) return;
- visibleCases = [...curatedCases];
- elements.activeThemeCount.textContent = `${visibleCases.length} ${t("个精选案例")}`;
- caseImageObserver.disconnect();
- releaseImageUrls();
- galleryMasonry.reset();
- elements.curatedGrid.replaceChildren();
- renderedCount = 0;
- appendNextCases();
- elements.curatedEmpty.hidden = visibleCases.length > 0;
- if (currentDetailKey && !visibleCases.some((record) => record.key === currentDetailKey)) closeDetail();
-}
-
-function appendNextCases() {
- if (!activeThemeId || renderedCount >= visibleCases.length) return updateLoadMore();
- const records = visibleCases.slice(renderedCount, renderedCount + PAGE_SIZE);
- const cards = records.map(createCaseCard);
- elements.curatedGrid.append(...cards);
- galleryMasonry.append(cards);
- renderedCount += records.length;
- updateLoadMore();
-}
-
-function updateLoadMore() {
- const remaining = Math.max(0, visibleCases.length - renderedCount);
- elements.loadMore.hidden = remaining === 0;
- elements.loadMore.textContent = remaining
- ? t("继续加载(剩余 {count})", { count: remaining })
- : t("继续加载");
-}
-
-function createCaseCard(record) {
- const card = document.createElement("article");
- card.className = "case-card";
+ appendNext();
+ if (renderedCaseCount < preview.entries.length) {
+ caseLoadObserver = new IntersectionObserver((records) => {
+ if (records.some((record) => record.isIntersecting)) appendNext();
+ }, { root: elements.detailDialog, rootMargin: "600px 0px" });
+ caseLoadObserver.observe(sentinel);
+ }
+}
+
+function cleanupCaseGallery() {
+ caseLoadObserver?.disconnect();
+ caseLoadObserver = null;
+ caseMasonry?.destroy();
+ caseMasonry = null;
+ for (const controller of caseVideoControllers) controller.destroy();
+ caseVideoControllers.clear();
+ renderedCaseCount = 0;
+}
+
+function createCaseCard(item, entry) {
+ const card = element("article", "case-card");
+ card.dataset.entryId = entry.id;
card.tabIndex = 0;
- card.dataset.entryId = record.entry.id;
- card.setAttribute("aria-label", t("查看案例:{title}", { title: record.entry.title }));
- const open = () => openDetail(record.key, card);
+ card.setAttribute("aria-label", t("查看案例:{title}", { title: entry.title }));
+ const visual = element("div", "case-image-wrap");
+ visual.style.aspectRatio = `${entry.width} / ${entry.height}`;
+ const image = element("img", "case-visual");
+ image.src = entry.previewImageUrl;
+ image.alt = "";
+ image.loading = "lazy";
+ image.decoding = "async";
+ image.width = entry.width;
+ image.height = entry.height;
+ visual.append(image);
+ if (entry.mediaKind === "video") {
+ visual.append(element("span", "case-video-badge", "▶"));
+ if (entry.videoUrl) caseVideoControllers.add(bindRemoteVideoHover(visual, entry));
+ }
+ if (isSaved(item, entry)) card.classList.add("is-saved");
+ card.append(visual);
+ const open = () => openCaseDetail(item, entry, card);
card.addEventListener("click", open);
card.addEventListener("keydown", (event) => {
- if (event.key !== "Enter" && event.key !== " ") return;
+ if (!["Enter", " "].includes(event.key)) return;
event.preventDefault();
open();
});
- const imageWrap = document.createElement("div");
- imageWrap.className = "case-image-wrap case-image-wrap-fixed";
- imageWrap.style.aspectRatio = imageRatio(record.image);
- if (record.imageBlob) {
- const image = document.createElement("img");
- image.className = "case-shot";
- image.alt = `${record.entry.title} 对应画面`;
- image.dataset.recordKey = record.key;
- image.decoding = "async";
- image.loading = "lazy";
- imageWrap.append(image);
- caseImageObserver.observe(image);
- } else {
- imageWrap.append(textElement("span", "case-shot-missing", t("暂无预览图")));
- }
- const saved = textElement("span", "share-check", "✓");
- saved.setAttribute("aria-label", t("已保存"));
- if (isSaved(record)) card.classList.add("curated-saved-card");
- card.append(imageWrap, saved);
return card;
}
-function hydrateCaseImage(image) {
- const record = curatedCases.find((item) => item.key === image.dataset.recordKey);
- if (!record || !image.isConnected) return;
- image.src = recordImageUrl(record);
+function openCaseDetail(item, entry, card) {
+ state.selectedEntryId = entry.id;
+ caseDetailReturnFocus = card ?? caseDetailReturnFocus;
+ elements.caseDetailBackdrop.hidden = false;
+ elements.caseDetailDrawer.classList.add("open");
+ elements.caseDetailDrawer.setAttribute("aria-hidden", "false");
+ setPackageDetailInert(true);
+ renderCaseDetail(item, entry);
+ elements.caseDetailClose.focus({ preventScroll: true });
}
-function openDetail(key, returnFocus = null) {
- currentDetailKey = key;
- if (returnFocus) detailReturnFocus = returnFocus;
- document.documentElement.classList.add("detail-open");
- elements.detailDrawer.classList.add("open");
- elements.detailDrawer.setAttribute("aria-hidden", "false");
- elements.detailBackdrop.hidden = false;
- renderDetail();
- elements.detailClose.focus();
+function closeCaseDetail({ restoreFocus = true } = {}) {
+ const returnFocus = caseDetailReturnFocus;
+ state.selectedEntryId = "";
+ caseDetailReturnFocus = null;
+ elements.caseDetailDrawer.classList.remove("open");
+ elements.caseDetailDrawer.setAttribute("aria-hidden", "true");
+ setPackageDetailInert(false);
+ elements.caseDetailBackdrop.hidden = true;
+ caseDetailVideoCleanup?.();
+ caseDetailVideoCleanup = null;
+ elements.caseDetailContent.replaceChildren();
+ if (restoreFocus && returnFocus?.isConnected) returnFocus.focus({ preventScroll: true });
}
-function closeDetail() {
- const returnFocus = detailReturnFocus;
- currentDetailKey = "";
- detailReturnFocus = null;
- document.documentElement.classList.remove("detail-open");
- elements.detailDrawer.classList.remove("open");
- elements.detailDrawer.setAttribute("aria-hidden", "true");
- elements.detailBackdrop.hidden = true;
- elements.detailContent.replaceChildren();
- returnFocus?.focus();
-}
-
-function moveDetail(offset) {
- const index = visibleCases.findIndex((record) => record.key === currentDetailKey);
- const target = visibleCases[index + offset];
- if (target) openDetail(target.key);
-}
-
-function renderDetail() {
- const record = curatedCases.find((item) => item.key === currentDetailKey);
- if (!record) return closeDetail();
- const visibleIndex = visibleCases.findIndex((item) => item.key === record.key);
- elements.detailPrev.disabled = visibleIndex <= 0;
- elements.detailNext.disabled = visibleIndex < 0 || visibleIndex >= visibleCases.length - 1;
- const content = document.createDocumentFragment();
- const figure = document.createElement("figure");
- figure.className = "detail-figure";
- if (record.media?.kind === "video" && record.mediaBlob) {
- const video = document.createElement("video");
- video.src = recordMediaUrl(record);
- video.controls = true;
- video.playsInline = true;
- video.preload = "metadata";
- if (record.imageBlob) video.poster = recordImageUrl(record);
- figure.append(video);
- } else if (record.imageBlob) {
- const image = document.createElement("img");
- image.src = recordImageUrl(record);
- image.alt = `${record.entry.title} 对应画面`;
- figure.append(image);
+function moveCaseDetail(offset) {
+ const item = selectedItem();
+ const preview = item ? state.previews.get(item.id) : null;
+ if (!item || !preview) return;
+ const index = preview.entries.findIndex((entry) => entry.id === state.selectedEntryId);
+ const entry = preview.entries[index + offset];
+ if (!entry) return;
+ state.selectedEntryId = entry.id;
+ renderCaseDetail(item, entry);
+}
+
+function renderCaseDetail(item, entry) {
+ caseDetailVideoCleanup?.();
+ caseDetailVideoCleanup = null;
+ const preview = state.previews.get(item.id);
+ const index = preview?.entries.findIndex((candidate) => candidate.id === entry.id) ?? -1;
+ elements.caseDetailPrev.disabled = index <= 0;
+ elements.caseDetailNext.disabled = index < 0 || index >= preview.entries.length - 1;
+ const layout = element("article", "case-detail-layout");
+ const figure = element("figure", "case-detail-figure");
+ if (entry.mediaKind === "video" && entry.videoUrl) {
+ const player = createRemoteVideoPlayer(entry);
+ figure.append(player.node);
+ caseDetailVideoCleanup = player.destroy;
} else {
- figure.append(textElement("span", "case-shot-missing", t("暂无预览图")));
+ figure.append(createRemoteImageViewer(entry, entry.previewImageUrl));
+ if (entry.mediaKind === "video") figure.append(element("span", "case-detail-video-label", t("视频暂不可播放")));
}
- content.append(figure);
- const body = document.createElement("div");
- body.className = "detail-body";
- const heading = document.createElement("header");
- heading.className = "detail-heading";
- heading.append(textElement("h2", "", record.entry.title || t("未命名案例")));
+ const body = element("div", "case-detail-body");
+ const heading = element("header", "case-detail-heading");
+ heading.append(element("h2", "", entry.title), element("p", "", entry.author));
body.append(heading);
- const metadata = document.createElement("section");
- metadata.className = "detail-metadata";
- metadata.append(textElement("span", "", sourceRightsLabel(record.entry)));
- body.append(metadata);
- const promptSection = document.createElement("section");
- promptSection.className = "detail-section";
- promptSection.append(
- textElement("h3", "", t("完整提示词")),
- textElement("pre", "detail-prompt", record.entry.text || t("暂无提示词"))
- );
+ const promptSection = element("section", "case-detail-section");
+ promptSection.append(element("h3", "", t("完整提示词")), element("pre", "case-detail-prompt", entry.text));
body.append(promptSection);
- const actions = document.createElement("div");
- actions.className = "detail-actions";
- const copy = textElement("button", "button-secondary", t("复制提示词"));
- copy.type = "button";
- copy.disabled = !record.entry.text;
- copy.addEventListener("click", () => copyPrompt(record.entry.text, copy));
- const save = textElement("button", isSaved(record) ? "saved" : "", isSaved(record) ? t("已保存到我的案例库") : t("保存到我的案例库"));
- save.type = "button";
- save.disabled = isSaved(record);
- save.addEventListener("click", () => saveCuratedCase(record, save));
- const create = textElement("button", "create-action", t("以此创作"));
- create.type = "button";
- const creativeType = record.media?.kind === "video" ? "video" : "image";
- create.disabled = !isComposerEligibleEntry(record.entry, creativeType);
- create.title = create.disabled ? "当前案例缺少可用提示词" : "作为单一参考进入创作台";
- create.addEventListener("click", () => openComposerForRecord(record, create));
- actions.append(copy, save, create);
+ const source = element("div", "case-detail-source");
+ source.append(element("span", "", entry.rights || rightsLabel(item.license)));
+ if (entry.sourceUrl) {
+ const link = element("a", "", t("查看来源"));
+ link.href = entry.sourceUrl;
+ link.target = "_blank";
+ link.rel = "noopener noreferrer";
+ source.append(link);
+ }
+ body.append(source);
+ const actions = element("div", "case-detail-actions");
+ const copy = actionButton("button-secondary", "copy", t("复制提示词"));
+ copy.disabled = !entry.text;
+ copy.addEventListener("click", () => copyCasePrompt(entry, copy));
+ const savedEntry = findSavedEntry(item, entry);
+ const save = actionButton(savedEntry ? "case-save-action is-saved" : "case-save-action", savedEntry ? "check" : "save", t(savedEntry ? "查看已保存" : "保存到案例库"));
+ save.disabled = !state.localStateAvailable;
+ if (!state.localStateAvailable) setButtonLabel(save, t("案例库暂不可用"));
+ save.addEventListener("click", () => savedEntry ? openSavedCase(savedEntry.id) : savePreviewCase(item, entry, save));
+ actions.append(copy, save);
body.append(actions);
- content.append(body);
- elements.detailContent.replaceChildren(content);
+ layout.append(figure, body);
+ elements.caseDetailContent.replaceChildren(layout);
}
-async function saveCuratedCase(record, button, { refreshUi = true } = {}) {
- if (savedEntryForRecord(record)) return true;
- if (button) button.disabled = true;
+async function copyCasePrompt(entry, copy) {
+ await copyText(entry.text, copy, t("已复制"));
+}
+
+async function loadPreview(item) {
+ if (state.previews.has(item.id)) return state.previews.get(item.id);
+ if (state.previewFailures.has(item.id)) throw new Error(t("预览加载失败"));
try {
- showStatus(`${t("正在保存")}:${record.entry.title}…`);
- const selectedLibrary = prepareCuratedEntryPackage(record.library, record.entry.id);
- await importCuratedLibrary(selectedLibrary, record.files);
- await loadLocalState();
- showStatus(`${record.entry.title} · ${t("已保存到我的案例库")}`);
- if (refreshUi) {
- renderCases();
- renderDetail();
- renderThemes();
- }
- return true;
+ const response = await fetch(item.previewUrl, { cache: "no-cache", credentials: "omit", redirect: "error" });
+ if (!response.ok) throw new Error(`精选预览返回 HTTP ${response.status}`);
+ const preview = normalizeCuratedPreview(await response.json(), item);
+ state.previews.set(item.id, preview);
+ return preview;
} catch (error) {
- showStatus(error.message, true);
- if (button?.isConnected) button.disabled = false;
- return false;
+ state.previewFailures.add(item.id);
+ throw error;
}
}
-async function saveTheme(themeId, button) {
- const theme = catalog?.themes.find((item) => item.id === themeId);
- if (!theme || savingThemeId) return;
- savingThemeId = theme.id;
- if (button) button.disabled = true;
- renderThemes();
- let completed = 0;
- let imported = 0;
- let skipped = 0;
+async function loadAllPreviews() {
+ if (!state.catalog) return;
+ await Promise.allSettled(state.catalog.themes.map(loadPreview));
+}
+
+async function retryPreview(item, button) {
+ button.disabled = true;
+ state.previewFailures.delete(item.id);
+ renderDetail(item, null);
try {
- const themeRecord = await loadThemePackage(theme);
- const pendingRecords = themeRecord.records.filter((record) => !savedEntryForRecord(record));
- skipped = themeRecord.records.length - pendingRecords.length;
- completed = skipped;
- const batches = chunk(pendingRecords.map((record) => record.entry.id), PAGE_SIZE);
- updateThemeProgress(completed, theme.caseCount, skipped ? `已跳过 ${skipped} 个已有案例` : "准备保存");
- for (const ids of batches) {
- const selectedLibrary = prepareCuratedEntriesPackage(themeRecord.library, ids);
- const result = await importCuratedLibrary(selectedLibrary, themeRecord.files);
- imported += result.importedCount ?? 0;
- skipped += result.skippedCount ?? 0;
- completed += ids.length;
- await loadLocalState();
- updateThemeProgress(completed, theme.caseCount, `${completed}/${theme.caseCount}`);
- showStatus(`${theme.title} · 已处理 ${completed}/${theme.caseCount}`);
- }
- themeSaveFailures.delete(theme.id);
- showStatus(`${theme.title} · 新增 ${imported} 个,跳过 ${skipped} 个已有案例`);
+ const preview = await loadPreview(item);
+ if (state.selectedId === item.id) renderDetail(item, preview);
} catch (error) {
- themeSaveFailures.set(theme.id, Math.max(1, theme.caseCount - completed));
- showStatus(`${error.message} · 已完成 ${completed}/${theme.caseCount},可重试剩余案例`, true);
+ showToast(friendlyError(error, t("预览加载失败")));
+ if (state.selectedId === item.id) renderDetail(item, null, true);
+ }
+}
+
+async function loadVerifiedArchive(item, onProgress = () => undefined) {
+ const unsubscribe = listenForProgress(item.id, onProgress);
+ try {
+ if (!archivePromises.has(item.id)) {
+ archivePromises.set(item.id, (async () => {
+ emitProgress(item.id, { stage: "downloading", loaded: 0, total: 0, ratio: null });
+ const response = await fetchCuratedPackage(item.downloadUrl);
+ if (!response.ok || !isTrustedCuratedResponseUrl(response.url)) throw new Error(`精选案例包下载失败(HTTP ${response.status})`);
+ const archive = await readResponseBlobWithProgress(response, {
+ onProgress: (progress) => emitProgress(item.id, { stage: "downloading", ...progress })
+ });
+ if (archive.size !== item.archiveBytes) throw new Error("精选案例包下载大小与目录不一致");
+ emitProgress(item.id, { stage: "verifying" });
+ await verifyCuratedPackageBlob(archive, item.sha256);
+ return archive;
+ })().catch((error) => {
+ archivePromises.delete(item.id);
+ throw error;
+ }));
+ }
+ return await archivePromises.get(item.id);
} finally {
- savingThemeId = "";
- if (button?.isConnected) button.disabled = false;
- renderThemes();
- if (activeThemeId === theme.id && themePackages.has(theme.id)) {
- activeThemeRecord = themePackages.get(theme.id);
- curatedCases = activeThemeRecord.records;
- renderCases();
- updateThemeSaveUi();
+ unsubscribe();
+ }
+}
+
+async function loadPackageIndex(item) {
+ if (!packageIndexPromises.has(item.id)) {
+ packageIndexPromises.set(item.id, (async () => {
+ const archive = await loadVerifiedArchive(item);
+ emitProgress(item.id, { stage: "extracting" });
+ const reader = await openZipBlob(archive);
+ const files = await reader.read(["library.json"], {
+ onProgress: ({ completed, total }) => emitProgress(item.id, { stage: "extracting", completed, total })
+ });
+ const libraryFile = files.get("library.json");
+ if (!libraryFile) throw new Error("精选案例包缺少 library.json");
+ const sourceLibrary = JSON.parse(await libraryFile.text());
+ const library = prepareCuratedPackageVersion(sourceLibrary, item);
+ validateCuratedPackageIndex(item, library, reader.names);
+ return { library, reader };
+ })().catch((error) => {
+ packageIndexPromises.delete(item.id);
+ throw error;
+ }));
+ }
+ return packageIndexPromises.get(item.id);
+}
+
+async function savePreviewCase(item, previewEntry, button) {
+ const existing = findSavedEntry(item, previewEntry);
+ if (existing) return openSavedCase(existing.id);
+ button.disabled = true;
+ setProgressButton(button, { stage: "downloading", loaded: 0, total: 0, ratio: null });
+ try {
+ const result = await saveCuratedSelection(item, [previewEntry.id], {
+ mode: "case",
+ onProgress: (progress) => setProgressButton(button, progress)
+ });
+ await loadLocalState();
+ const entryId = result.entriesBySourceEntryId?.[previewEntry.id];
+ if (!entryId || result.importedCount + result.existingCount !== 1) throw new Error("精选案例没有写入私人案例库");
+ setProgressButton(button, { stage: result.importedCount === 1 ? "saved" : "existing" });
+ markSavedCard(previewEntry.id);
+ setTimeout(() => openSavedCase(entryId), 280);
+ } catch (error) {
+ setProgressButton(button, { stage: "failed" });
+ showToast(friendlyError(error, t("精选案例保存失败")));
+ if (button.isConnected) button.disabled = false;
+ }
+}
+
+async function saveEntirePackage(item, button) {
+ if (!await confirmPackSave(item)) return;
+ button.disabled = true;
+ setProgressButton(button, { stage: "downloading", loaded: 0, total: item.archiveBytes, ratio: 0 });
+ try {
+ const result = await saveCuratedSelection(item, null, {
+ mode: "package",
+ onProgress: (progress) => setProgressButton(button, progress)
+ });
+ await loadLocalState();
+ if (!result.projectId || result.importedCount + result.existingCount !== item.caseCount) {
+ throw new Error("精选案例包没有完整写入私人案例库");
}
+ setProgressButton(button, { stage: "saved" });
+ setTimeout(() => openSavedProject(result.projectId), 280);
+ } catch (error) {
+ setProgressButton(button, { stage: "failed" });
+ showToast(friendlyError(error, t("精选案例保存失败")));
+ if (button.isConnected) button.disabled = false;
}
}
-async function importCuratedLibrary(library, files) {
- const parsed = parseLibraryPackage(library, files);
- const preview = await chrome.runtime.sendMessage({
- type: "PREVIEW_LIBRARY_IMPORT",
- library,
- preserveLibraryConfiguration: true
- });
- if (!preview?.ok) throw new Error(preview?.message || "无法检查精选案例");
+async function saveCuratedSelection(item, sourceEntryIds, { mode, onProgress }) {
+ const unsubscribe = listenForProgress(item.id, onProgress);
const storedAssetIds = [];
- let applied = false;
try {
- for (const entry of parsed.entries) {
- if (!preview.entryIdMap?.[entry.id]) continue;
- for (const asset of entry.mediaAssets) {
+ const { library, reader } = await loadPackageIndex(item);
+ const requested = sourceEntryIds
+ ? library.entries.filter((entry) => sourceEntryIds.includes(entry.curatedOrigin?.sourceEntryId))
+ : library.entries;
+ if (requested.length !== (sourceEntryIds?.length ?? item.caseCount)) throw new Error("精选案例包缺少请求的案例");
+ const selectedLibrary = prepareCuratedEntriesPackage(library, requested.map((entry) => entry.id));
+ const preview = await chrome.runtime.sendMessage({
+ type: "PREVIEW_CURATED_IMPORT",
+ library: selectedLibrary,
+ packageId: item.packageId,
+ projectName: item.title,
+ mode
+ });
+ if (!preview?.ok) throw new Error(preview?.message || "无法检查精选案例");
+ const newSources = new Set(preview.importedSourceEntryIds ?? []);
+ const newEntries = selectedLibrary.entries.filter((entry) => newSources.has(entry.curatedOrigin?.sourceEntryId));
+ const totalAssets = newEntries.reduce((sum, entry) => sum + entry.mediaAssets.filter((asset) => asset.storageMode !== "reference").length, 0);
+ let completedAssets = 0;
+ for (const entry of newEntries) {
+ const singleLibrary = prepareCuratedEntryPackage(selectedLibrary, entry.id);
+ const mediaPaths = entry.mediaAssets.filter((asset) => asset.storageMode !== "reference").map((asset) => asset.assetPath);
+ const files = await reader.read(mediaPaths, {
+ onProgress: ({ completed }) => emitProgress(item.id, { stage: "extracting", completed: completedAssets + completed, total: totalAssets })
+ });
+ const parsed = parseLibraryPackage(singleLibrary, files);
+ for (const asset of parsed.entries.flatMap((parsedEntry) => parsedEntry.mediaAssets)) {
+ if (asset.storageMode === "reference") continue;
const targetId = preview.visualIdMap?.[asset.id] ?? asset.id;
const blob = parsed.assets.get(asset.id);
if (!blob) throw new Error("精选案例媒体缺失");
await saveMediaBlob(targetId, blob);
storedAssetIds.push(targetId);
+ completedAssets += 1;
+ emitProgress(item.id, { stage: "saving", completed: completedAssets, total: totalAssets });
}
}
+ if (mode === "package") emitProgress(item.id, { stage: "creating-project" });
const result = await chrome.runtime.sendMessage({
- type: "APPLY_LIBRARY_IMPORT",
- library,
+ type: "APPLY_CURATED_IMPORT",
+ library: selectedLibrary,
+ packageId: item.packageId,
+ projectName: item.title,
+ mode,
entryIdMap: preview.entryIdMap,
visualIdMap: preview.visualIdMap,
compoundIdMap: preview.compoundIdMap,
sessionIdMap: preview.sessionIdMap,
- runIdMap: preview.runIdMap,
- preserveLibraryConfiguration: true
+ runIdMap: preview.runIdMap
});
if (!result?.ok) throw new Error(result?.message || "精选案例保存失败");
- applied = true;
- return { ...preview, ...result };
+ const retained = new Set(result.importedVisualIds ?? []);
+ await Promise.allSettled(storedAssetIds.filter((id) => !retained.has(id)).map((id) => deleteMediaBlob(id)));
+ return result;
} catch (error) {
- if (!applied) await Promise.allSettled(storedAssetIds.map((id) => deleteMediaBlob(id)));
+ await Promise.allSettled(storedAssetIds.map((id) => deleteMediaBlob(id)));
throw error;
- }
-}
-
-async function openComposerForRecord(record, button) {
- const creativeType = record.media?.kind === "video" ? "video" : "image";
- if (!isComposerEligibleEntry(record.entry, creativeType)) {
- return showStatus("当前案例缺少可作为参考的提示词", true);
- }
- button.disabled = true;
- try {
- if (!savedEntryForRecord(record) && !await saveCuratedCase(record, button, { refreshUi: false })) return;
- const savedEntry = savedEntryForRecord(record);
- if (!savedEntry) throw new Error("案例保存后未能在本地案例库中找到,请重试");
- const url = new URL(chrome.runtime.getURL("composer.html"));
- url.searchParams.set("references", savedEntry.id);
- url.searchParams.set("type", creativeType);
- location.assign(url.href);
- } catch (error) {
- showStatus(error.message || "无法打开创作台", true);
} finally {
- if (button.isConnected) button.disabled = false;
+ unsubscribe();
}
}
-function updateThemeSaveUi() {
- const theme = catalog?.themes.find((item) => item.id === activeThemeId);
- if (!theme) return;
- const saved = themeSavedCount(theme);
- const failed = themeSaveFailures.get(theme.id) ?? 0;
- elements.saveTheme.textContent = savingThemeId === theme.id
- ? `保存中 ${saved}/${theme.caseCount}`
- : failed
- ? `重试失败 ${failed}`
- : t(saved >= theme.caseCount ? "已全部保存" : "全部保存");
- elements.saveTheme.disabled = savingThemeId === theme.id || saved >= theme.caseCount;
- elements.themeSaveStatus.textContent = `${saved}/${theme.caseCount} 已保存`;
+function openSavedCase(entryId) {
+ const url = new URL(chrome.runtime.getURL("library.html"));
+ url.searchParams.set("case", entryId);
+ url.searchParams.set("source", "curated");
+ location.assign(url.href);
}
-function updateThemeProgress(value, max, label) {
- if (!activeThemeId) return;
- if (savingThemeId === activeThemeId) elements.saveTheme.textContent = `保存中 ${Math.min(value, max)}/${max}`;
- elements.themeSaveStatus.textContent = label;
+function openSavedProject(projectId) {
+ const url = new URL(chrome.runtime.getURL("library.html"));
+ url.searchParams.set("project", projectId);
+ url.searchParams.set("source", "curated");
+ location.assign(url.href);
}
-function themeSavedCount(theme) {
- const loaded = themePackages.get(theme.id);
- if (loaded) return loaded.records.filter((record) => savedEntryForRecord(record)).length;
- const identities = new Set(localEntries
- .filter((entry) => entry.curatedOrigin?.packageId === theme.packageId)
- .map(curatedSourceKey)
- .filter(Boolean));
- return Math.min(theme.caseCount, identities.size);
+function confirmPackSave(item) {
+ const dialog = document.querySelector("#pack-save-dialog");
+ dialog.querySelector("h2").textContent = item.title;
+ dialog.querySelector(".pack-save-meta").textContent = `${item.caseCount} ${t("个案例")} · ${formatBytes(item.archiveBytes)}`;
+ dialog.querySelector(".pack-save-confirm").textContent = t("保存整包");
+ dialog.querySelector(".pack-save-cancel").textContent = t("取消");
+ return new Promise((resolve) => {
+ const finish = (value) => {
+ dialog.close();
+ resolve(value);
+ };
+ dialog.querySelector(".pack-save-confirm").onclick = () => finish(true);
+ dialog.querySelector(".pack-save-cancel").onclick = () => finish(false);
+ dialog.oncancel = (event) => { event.preventDefault(); finish(false); };
+ dialog.showModal();
+ });
}
-function recordImageUrl(record) {
- if (!record.imageBlob) return "";
- if (!imageUrls.has(record.entry.id)) imageUrls.set(record.entry.id, URL.createObjectURL(record.imageBlob));
- return imageUrls.get(record.entry.id);
+function listenForProgress(id, listener) {
+ if (!progressListeners.has(id)) progressListeners.set(id, new Set());
+ progressListeners.get(id).add(listener);
+ return () => {
+ const listeners = progressListeners.get(id);
+ listeners?.delete(listener);
+ if (!listeners?.size) progressListeners.delete(id);
+ };
}
-function recordMediaUrl(record) {
- if (!record.mediaBlob) return "";
- if (!mediaUrls.has(record.entry.id)) mediaUrls.set(record.entry.id, URL.createObjectURL(record.mediaBlob));
- return mediaUrls.get(record.entry.id);
+function emitProgress(id, progress) {
+ progressListeners.get(id)?.forEach((listener) => listener(progress));
}
-async function copyPrompt(text, button) {
- try {
- await navigator.clipboard.writeText(text);
- button.textContent = t("已复制");
- setTimeout(() => {
- if (button.isConnected) button.textContent = t("复制提示词");
- }, 1200);
- } catch {
- showStatus(t("浏览器未允许复制,请选中文本后复制"), true);
+function setProgressButton(button, progress) {
+ if (!button?.isConnected) return;
+ button.classList.toggle("is-progressing", ["downloading", "verifying", "extracting", "saving", "creating-project"].includes(progress.stage));
+ button.style.setProperty("--progress", progress.ratio == null ? "0" : String(progress.ratio));
+ const labels = {
+ verifying: t("校验中"),
+ extracting: progress.total ? `${t("解包中")} ${progress.completed}/${progress.total}` : t("解包中"),
+ saving: progress.total ? `${t("写入案例库")} ${progress.completed}/${progress.total}` : t("写入案例库"),
+ "creating-project": t("正在创建项目"),
+ saved: t("已保存"),
+ existing: t("案例已存在"),
+ failed: t("重试")
+ };
+ if (progress.stage === "downloading") {
+ setButtonLabel(button, progress.total
+ ? `${t("下载中")} ${Math.round((progress.ratio ?? 0) * 100)}%`
+ : `${t("下载中")} ${formatBytes(progress.loaded)}`);
+ } else {
+ setButtonLabel(button, labels[progress.stage] || t("处理中"));
}
}
-function isSaved(record) {
- return Boolean(savedEntryForRecord(record));
+function setButtonLabel(button, label) {
+ const labelElement = button.querySelector("span");
+ if (labelElement) labelElement.textContent = label;
+}
+
+function formatBytes(bytes = 0) {
+ if (!bytes) return "0 MB";
+ return `${(bytes / 1024 / 1024).toFixed(bytes >= 10 * 1024 * 1024 ? 1 : 2)} MB`;
}
-function savedEntryForRecord(record) {
- const sourceKey = curatedSourceKey(record?.entry);
- if (!sourceKey) return localEntries.find((entry) => entry.id === record?.entry?.id) ?? null;
- return localEntries.find((entry) => curatedSourceKey(entry) === sourceKey) ?? null;
+function markSavedCard(entryId) {
+ elements.detailContent.querySelector(`.case-card[data-entry-id="${CSS.escape(entryId)}"]`)?.classList.add("is-saved");
}
-function primaryMedia(entry) {
- const content = (entry.mediaAssets ?? []).filter((asset) => asset.usage !== "poster");
- return content.find((asset) => asset.id === entry.primaryMediaId) ?? content[0] ?? null;
+function isSaved(item, previewEntry) {
+ return Boolean(findSavedEntry(item, previewEntry));
+}
+
+function findSavedEntry(item, previewEntry) {
+ const key = curatedSourceKey({
+ curatedOrigin: { packageId: item.packageId, sourceEntryId: previewEntry.id }
+ });
+ return state.localEntries.find((entry) => curatedSourceKey(entry) === key) ?? null;
}
-function posterImage(entry, media) {
- const images = (entry.mediaAssets ?? []).filter((asset) => asset.kind === "image");
- return images.find((asset) => asset.id === media?.posterAssetId)
- ?? images.find((asset) => asset.usage === "poster")
- ?? null;
+function bindRemoteVideoHover(container, entry) {
+ let video = null;
+ const canPlay = () => document.documentElement.dataset.motion !== "reduced"
+ && globalThis.matchMedia?.("(hover: hover) and (pointer: fine)")?.matches;
+ const destroy = () => {
+ if (!video) return;
+ video.pause();
+ video.removeAttribute("src");
+ video.load();
+ video.remove();
+ video = null;
+ container.classList.remove("is-video-playing", "is-video-loading");
+ };
+ const start = async () => {
+ if (!canPlay() || video) return;
+ container.classList.add("is-video-loading");
+ video = document.createElement("video");
+ video.className = "case-video-preview";
+ video.muted = true;
+ video.loop = true;
+ video.playsInline = true;
+ video.preload = "metadata";
+ video.poster = entry.previewImageUrl;
+ video.src = entry.videoUrl;
+ video.setAttribute("aria-hidden", "true");
+ video.addEventListener("playing", () => {
+ container.classList.remove("is-video-loading");
+ container.classList.add("is-video-playing");
+ }, { once: true });
+ video.addEventListener("error", () => {
+ destroy();
+ container.classList.add("is-video-preview-unavailable");
+ }, { once: true });
+ container.append(video);
+ await video.play().catch(() => destroy());
+ };
+ container.addEventListener("pointerenter", start);
+ container.addEventListener("pointerleave", destroy);
+ return {
+ destroy() {
+ container.removeEventListener("pointerenter", start);
+ container.removeEventListener("pointerleave", destroy);
+ destroy();
+ }
+ };
}
-function imageRatio(image) {
- const width = Number(image?.width);
- const height = Number(image?.height);
- return width > 0 && height > 0 ? `${width} / ${height}` : "4 / 3";
+function createRemoteVideoPlayer(entry) {
+ const video = document.createElement("video");
+ video.className = "case-detail-video";
+ video.controls = true;
+ video.preload = "metadata";
+ video.autoplay = false;
+ video.playsInline = true;
+ video.poster = entry.previewImageUrl;
+ video.src = entry.videoUrl;
+ video.style.aspectRatio = `${entry.width} / ${entry.height}`;
+ const failure = element("div", "case-video-error");
+ failure.hidden = true;
+ failure.append(element("span", "", t("视频加载失败")));
+ const retry = element("button", "button-secondary", t("重试"));
+ retry.type = "button";
+ retry.addEventListener("click", () => {
+ failure.hidden = true;
+ video.src = entry.videoUrl;
+ video.load();
+ });
+ failure.append(retry);
+ video.addEventListener("error", () => { failure.hidden = false; });
+ const wrap = element("div", "case-detail-video-wrap");
+ wrap.append(video, failure);
+ return {
+ node: wrap,
+ destroy() {
+ video.pause();
+ video.removeAttribute("src");
+ video.load();
+ }
+ };
}
-function sourceRightsLabel(entry) {
- return String(entry.metadataLabels?.[0] ?? "").trim() || t("权利归原作者");
+function createRemoteImageViewer(entry, url) {
+ const image = element("img");
+ image.alt = entry.title;
+ image.width = entry.width;
+ image.height = entry.height;
+ const failure = element("div", "case-video-error");
+ failure.hidden = true;
+ failure.append(element("span", "", t("图片加载失败")));
+ const retry = element("button", "button-secondary", t("重试"));
+ retry.type = "button";
+ retry.addEventListener("click", () => {
+ failure.hidden = true;
+ image.removeAttribute("src");
+ requestAnimationFrame(() => { image.src = url; });
+ });
+ failure.append(retry);
+ image.addEventListener("error", () => { failure.hidden = false; });
+ image.src = url;
+ const fragment = document.createDocumentFragment();
+ fragment.append(image, failure);
+ return fragment;
}
-function showActiveView() {
- elements.themesView.hidden = Boolean(activeThemeId);
- elements.casesView.hidden = !activeThemeId;
- elements.returnLabel.textContent = t(activeThemeId ? "返回主题" : "返回我的案例库");
+function setPackageDetailInert(inert) {
+ elements.detailContent.inert = inert;
+ elements.detailClose.inert = inert;
}
-function showLoading(active) {
- loadingCases = active;
- elements.curatedLoading.hidden = !active;
- if (active) {
- elements.themesView.hidden = true;
- elements.casesView.hidden = true;
- } else {
- showActiveView();
+async function toggleFollow(item, button) {
+ if (state.following.has(item.authorId)) state.following.delete(item.authorId);
+ else state.following.add(item.authorId);
+ await chrome.storage.local.set({ [FOLLOWING_KEY]: [...state.following] });
+ updateFilters();
+ const following = state.following.has(item.authorId);
+ button?.classList.toggle("is-active", following);
+ if (button) {
+ setButtonLabel(button, t(following ? "已关注" : "关注"));
+ button.querySelector("use")?.setAttribute("href", `assets/ui-icons.svg#icon-${following ? "check" : "plus"}`);
}
}
-function releaseImageUrls() {
- for (const url of imageUrls.values()) URL.revokeObjectURL(url);
- imageUrls.clear();
- for (const url of mediaUrls.values()) URL.revokeObjectURL(url);
- mediaUrls.clear();
+function updateFilters() {
+ state.filters = new Set([...elements.filterPopover.querySelectorAll('input[type="checkbox"]:checked')].map((input) => input.value));
+ updateFilterCount();
+ renderGallery();
}
-function releaseThemeCoverUrls() {
- for (const url of themeCoverUrls.values()) URL.revokeObjectURL(url);
- themeCoverUrls.clear();
+function updateFilterCount() {
+ elements.filterCount.textContent = state.filters.size ? ` ${state.filters.size}` : "";
}
-async function hasCatalogPermission() {
- return chrome.permissions.contains({ origins: CURATED_PERMISSION_ORIGINS });
+function selectedItem() {
+ return state.catalog?.themes.find((item) => item.id === state.selectedId) ?? null;
}
-async function requestCatalogPermission() {
- if (await hasCatalogPermission()) return true;
- return chrome.permissions.request({ origins: CURATED_PERMISSION_ORIGINS });
+function publicPackUrl(id) {
+ const url = new URL(CURATED_PUBLIC_SITE_URL);
+ url.searchParams.set("pack", id);
+ return url.href;
}
-function showStatus(message, error = false, retry = false) {
+function rightsLabel(license = "") {
+ if (license.includes("PromptDirector 原创")) return t("PromptDirector 原创");
+ if (license.includes("权利归原作者")) return t("权利归原作者");
+ return license || t("权利未标注");
+}
+
+async function copyText(value, button, successLabel) {
+ const originalLabel = button?.querySelector("span")?.textContent ?? "";
+ try {
+ await navigator.clipboard.writeText(value);
+ if (button) {
+ setButtonLabel(button, successLabel);
+ button.classList.add("is-success");
+ setTimeout(() => {
+ if (!button.isConnected) return;
+ setButtonLabel(button, originalLabel);
+ button.classList.remove("is-success");
+ }, 1600);
+ }
+ } catch {
+ showToast(t("浏览器未允许复制,请选中文本后复制"));
+ }
+}
+
+function friendlyError(error, fallback) {
+ const message = String(error?.message || "");
+ if (/failed to fetch|networkerror|load failed/i.test(message)) return t("无法下载案例包,请检查网络后重试");
+ return message || fallback;
+}
+
+function showStatus(message, { error = false, retry = false } = {}) {
elements.curatedStatus.textContent = message;
- elements.curatedStatus.classList.toggle("error", error);
+ elements.curatedStatusBar.hidden = false;
+ elements.curatedStatusBar.classList.toggle("error", error);
elements.retryCatalog.hidden = !retry;
}
-function textElement(tagName, className, text) {
- const element = document.createElement(tagName);
- if (className) element.className = className;
- element.textContent = text;
- return element;
+function hideStatus() {
+ elements.curatedStatusBar.hidden = true;
+ elements.curatedStatus.textContent = "";
+ elements.retryCatalog.hidden = true;
+}
+
+function showToast(message) {
+ clearTimeout(toastTimer);
+ elements.curatedToast.textContent = message;
+ elements.curatedToast.hidden = false;
+ toastTimer = setTimeout(() => { elements.curatedToast.hidden = true; }, 2400);
+}
+
+function actionButton(className, iconName, label) {
+ const button = element("button", className);
+ button.type = "button";
+ button.append(createIcon(iconName), element("span", "", label));
+ return button;
+}
+
+function createIcon(name) {
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
+ svg.setAttribute("class", "ui-icon");
+ svg.setAttribute("viewBox", "0 0 24 24");
+ svg.setAttribute("aria-hidden", "true");
+ const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
+ use.setAttribute("href", `assets/ui-icons.svg#icon-${name}`);
+ svg.append(use);
+ return svg;
}
-function chunk(values, size) {
- return Array.from({ length: Math.ceil(values.length / size) }, (_, index) => values.slice(index * size, (index + 1) * size));
+function element(tagName, className = "", text = "") {
+ const value = document.createElement(tagName);
+ if (className) value.className = className;
+ if (text) value.textContent = text;
+ return value;
}
function camel(value) {
diff --git a/curated-submission.js b/curated-submission.js
new file mode 100644
index 0000000..662506c
--- /dev/null
+++ b/curated-submission.js
@@ -0,0 +1,166 @@
+import { selectLibraryPackage, selectProjectPackage } from "./library-package.js";
+import { normalizeEntryMedia } from "./media.js";
+
+export const CURATED_SUBMISSION_FORMAT = "prompt-director-curated-submission";
+export const CURATED_SUBMISSION_VERSION = 1;
+export const CURATED_SUBMISSION_PART_FORMAT = "prompt-director-curated-submission-part";
+export const CURATED_SUBMISSION_PART_VERSION = 1;
+export const CURATED_SUBMISSION_MAX_FILE_BYTES = 24 * 1024 * 1024;
+export const CURATED_SUBMISSION_PART_OVERHEAD_BYTES = 16 * 1024;
+export const CURATED_SUBMISSION_PART_PAYLOAD_BYTES = CURATED_SUBMISSION_MAX_FILE_BYTES - CURATED_SUBMISSION_PART_OVERHEAD_BYTES;
+
+export function prepareCuratedSubmissionState(stateValue = {}, selection = {}) {
+ const selected = selection.collectionId
+ ? selectProjectPackage(stateValue, selection.collectionId)
+ : selectLibraryPackage(stateValue, selection.entryIds);
+ const entries = selected.entries.map(sanitizeCuratedSubmissionEntry);
+ const requiredTypes = new Set(entries.map((entry) => entry.classification.pathIds[0]));
+ const taxonomy = structuredClone(stateValue.taxonomy ?? {});
+ taxonomy.nodes = (taxonomy.nodes ?? []).filter((node) => requiredTypes.has(node?.id));
+ if (taxonomy.nodes.length !== requiredTypes.size) throw new Error("投稿案例缺少图片或视频类型信息");
+ const project = selection.collectionId
+ ? selected.organizerState?.collections?.[0]
+ : null;
+ return {
+ title: clean(project?.name) || "精选投稿",
+ entries,
+ state: {
+ entries,
+ settings: { libraryTitle: clean(project?.name) || "精选投稿", outputPath: "PromptDirector-投稿.zip" },
+ taxonomy,
+ facetCatalog: { version: 2, revision: 1, facets: [], nodes: [] },
+ classificationRules: [],
+ organizerState: { version: 4, collections: [], projectMethods: {} },
+ compoundCases: []
+ }
+ };
+}
+
+export function sanitizeCuratedSubmissionEntry(entryValue = {}) {
+ const entry = normalizeEntryMedia(entryValue);
+ const contentAssets = entry.mediaAssets.filter((asset) => asset.usage !== "poster");
+ if (contentAssets.length !== 1 || !["image", "video"].includes(contentAssets[0]?.kind)) {
+ throw new Error(`“${clean(entry.title) || "未命名案例"}”投稿时必须只包含一个图片或视频主体`);
+ }
+ const primary = contentAssets[0];
+ if (primary.storageMode !== "managed") throw new Error(`“${clean(entry.title) || "未命名案例"}”需要先把媒体保存到本地再投稿`);
+ const posters = entry.mediaAssets.filter((asset) => asset.usage === "poster");
+ if (primary.kind === "image" && posters.length) throw new Error(`“${clean(entry.title) || "未命名案例"}”包含多余封面`);
+ if (primary.kind === "video" && (posters.length !== 1 || primary.posterAssetId !== posters[0].id)) {
+ throw new Error(`“${clean(entry.title) || "未命名案例"}”的视频缺少唯一封面`);
+ }
+ const text = cleanPrompt(entry.text);
+ if (!text) throw new Error(`“${clean(entry.title) || "未命名案例"}”缺少可公开的提示词`);
+ const sourceUrl = firstHttpsUrl([entry.url, ...(entry.sourcePages ?? []).map((page) => page?.url)]);
+ const sourceTitle = clean(entry.sourcePages?.find((page) => firstHttpsUrl([page?.url]) === sourceUrl)?.title);
+ const allowedIds = new Set([primary.id, ...posters.map((asset) => asset.id)]);
+ const mediaAssets = entry.mediaAssets
+ .filter((asset) => allowedIds.has(asset.id))
+ .map(sanitizeMediaAsset);
+ return {
+ id: clean(entry.id),
+ title: clean(entry.title) || "未命名案例",
+ text,
+ savedAt: validIso(entry.savedAt),
+ schemaVersion: Number.isSafeInteger(entry.schemaVersion) ? entry.schemaVersion : undefined,
+ classification: {
+ pathIds: [primary.kind === "video" ? "content:prompt:video" : "content:prompt:image"],
+ status: "confirmed",
+ source: "manual"
+ },
+ facetAssignments: [],
+ customLabels: [],
+ metadataLabels: (entry.metadataLabels ?? []).map(clean).filter((label) => /^(?:作者|权利)[::]/u.test(label)),
+ url: sourceUrl,
+ sourcePages: sourceUrl ? [{ title: sourceTitle || clean(entry.title), url: sourceUrl }] : [],
+ mediaAssets,
+ primaryMediaId: primary.id,
+ timeNotes: []
+ };
+}
+
+export function submissionManifest({ submissionId, payloadBytes, caseCount, mediaCount, createdAt = new Date().toISOString() }) {
+ return {
+ format: CURATED_SUBMISSION_FORMAT,
+ version: CURATED_SUBMISSION_VERSION,
+ submissionId: sha256(submissionId),
+ payloadBytes: positiveInteger(payloadBytes),
+ caseCount: positiveInteger(caseCount),
+ mediaCount: positiveInteger(mediaCount),
+ createdAt: validIso(createdAt)
+ };
+}
+
+export function submissionPartManifest({ submissionId, archiveSha256, archiveBytes, partIndex, partCount, payloadSha256, payloadBytes }) {
+ return {
+ format: CURATED_SUBMISSION_PART_FORMAT,
+ version: CURATED_SUBMISSION_PART_VERSION,
+ submissionId: sha256(submissionId),
+ archiveSha256: sha256(archiveSha256),
+ archiveBytes: positiveInteger(archiveBytes),
+ partIndex: positiveInteger(partIndex),
+ partCount: positiveInteger(partCount),
+ payloadSha256: sha256(payloadSha256),
+ payloadBytes: positiveInteger(payloadBytes)
+ };
+}
+
+function sanitizeMediaAsset(asset) {
+ const sourceUrl = firstHttpsUrl([asset.sourceUrl]);
+ return {
+ id: clean(asset.id),
+ kind: asset.kind,
+ usage: asset.usage === "poster" ? "poster" : "content",
+ storageMode: "managed",
+ sourceUrl,
+ sourceTitle: clean(asset.sourceTitle),
+ capturedAt: validIso(asset.capturedAt),
+ mimeType: clean(asset.mimeType),
+ width: positiveInteger(asset.width),
+ height: positiveInteger(asset.height),
+ ...(asset.durationMs ? { durationMs: positiveInteger(asset.durationMs) } : {}),
+ ...(asset.byteSize ? { byteSize: positiveInteger(asset.byteSize) } : {}),
+ ...(clean(asset.posterAssetId) ? { posterAssetId: clean(asset.posterAssetId) } : {}),
+ ...(clean(asset.derivedFromAssetId) ? { derivedFromAssetId: clean(asset.derivedFromAssetId) } : {}),
+ reviewStatus: "unverified"
+ };
+}
+
+function firstHttpsUrl(values) {
+ for (const value of values) {
+ try {
+ const url = new URL(String(value ?? ""));
+ if (url.protocol === "https:" && !url.username && !url.password) return url.href;
+ } catch {
+ }
+ }
+ return "";
+}
+
+function cleanPrompt(value) {
+ return String(value ?? "")
+ .replace(/\r\n?/g, "\n")
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "")
+ .trim();
+}
+
+function clean(value) {
+ return String(value ?? "").trim();
+}
+
+function positiveInteger(value) {
+ const number = Number(value);
+ if (!Number.isSafeInteger(number) || number < 1) throw new Error("投稿包包含无效数值");
+ return number;
+}
+
+function sha256(value) {
+ const normalized = clean(value).toLocaleLowerCase("en-US");
+ if (!/^[a-f0-9]{64}$/.test(normalized)) throw new Error("投稿包摘要无效");
+ return normalized;
+}
+
+function validIso(value) {
+ const text = clean(value);
+ return text && Number.isFinite(Date.parse(text)) ? new Date(text).toISOString() : new Date().toISOString();
+}
diff --git a/curated.css b/curated.css
index 3a9ef9c..6b3408a 100644
--- a/curated.css
+++ b/curated.css
@@ -1,130 +1,182 @@
:root {
- --visual-wall-gap: 2px;
- --visual-card-radius: 2px;
+ --curated-max-width: 1500px;
+ --curated-gap: 8px;
+ --curated-radius: var(--ui-container-radius);
}
html.detail-open, html.detail-open body { overflow: hidden; }
body { min-width: 320px; }
+.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
-.curated-header { position: sticky; z-index: 10; top: 0; display: grid; min-height: 58px; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 12px; border-bottom: 1px solid var(--line); padding: 9px max(12px, calc((100vw - 1500px) / 2)); background: var(--bar); }
-.page-back-action { display: inline-flex; align-items: center; gap: 7px; }
-.page-back-action .ui-icon { width: 15px; height: 15px; }
-.curated-header h1 { margin: 0; font-size: 17px; letter-spacing: 0; }
-main { width: min(1500px, calc(100vw - 12px)); margin: 12px auto 48px; }
-.curated-status-row { display: flex; min-height: 30px; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 10px; }
-.curated-status { min-height: 20px; margin: 0; color: var(--muted); }
-.curated-status.error { color: var(--danger); }
-.curated-status-row button { min-height: 30px; padding: 5px 9px; font-size: 11px; }
+.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-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); }
+.curated-search input { min-width: 0; min-height: 34px; border: 0; padding: 0; outline: 0; background: transparent; box-shadow: none; }
+.curated-header-actions { display: flex; align-items: center; gap: 7px; }
+.curated-header-actions button { min-height: 34px; }
+.tool-button, .page-back-action { display: inline-flex; align-items: center; gap: 7px; }
+.tool-button .ui-icon, .page-back-action .ui-icon { width: 15px; height: 15px; }
+.filter-wrap, .sort-menu { position: relative; }
+.menu-panel { position: absolute; z-index: 30; top: calc(100% + 7px); right: 0; display: grid; border: 1px solid var(--ui-border-strong); border-radius: var(--curated-radius); padding: 5px; background: var(--ui-surface); box-shadow: var(--ui-shadow); }
+.menu-panel[hidden] { display: none; }
+.filter-panel { width: 210px; gap: 4px; padding: 9px; }
+.filter-panel strong { padding: 2px 3px 5px; font-size: var(--ui-meta-size); }
+.filter-panel label { display: flex; min-height: 32px; align-items: center; gap: 8px; font-size: var(--ui-button-size); }
+.filter-panel input { width: 15px; min-height: 15px; accent-color: var(--ui-accent); }
+.filter-panel button { margin-top: 4px; }
+.sort-menu > summary { display: flex; min-width: 76px; min-height: 34px; align-items: center; justify-content: space-between; gap: 8px; padding: 7px 9px; cursor: pointer; font-size: var(--ui-button-size); font-weight: 750; list-style: none; }
+.sort-menu > summary::-webkit-details-marker { display: none; }
+.sort-menu > summary .ui-icon { width: 14px; height: 14px; transition: transform var(--ui-motion-fast) ease; }
+.sort-menu[open] > summary .ui-icon { transform: rotate(180deg); }
+.sort-panel { width: 110px; gap: 2px; }
+.sort-panel button { display: flex; min-height: 32px; align-items: center; justify-content: space-between; border: 0; padding: 5px 9px; color: var(--ui-text); background: transparent; text-align: left; }
+.sort-panel button:hover:not(:disabled), .sort-panel button[aria-current="true"] { background: var(--ui-hover); }
+.sort-panel .sort-check { display: none; width: 14px; height: 14px; }
+.sort-panel button[aria-current="true"] .sort-check { display: block; }
-.themes-heading { margin: 8px 0 14px; }
-.themes-heading h2 { margin: 0; font-size: 22px; }
-.themes-heading p { margin: 4px 0 0; color: var(--muted); }
-.theme-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
-.theme-card { min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 6px; background: var(--card); }
-.theme-open { display: block; width: 100%; min-height: 0; padding: 0; color: var(--ink); background: transparent; text-align: left; white-space: normal; }
-.theme-open:hover:not(:disabled) { color: var(--ink); background: transparent; }
-.theme-cover { display: grid; width: 100%; aspect-ratio: 4 / 5; overflow: hidden; place-items: center; color: var(--muted); background: #111419; }
-.theme-cover img { display: block; width: 100%; height: 100%; object-fit: cover; }
-.theme-copy { display: grid; gap: 5px; padding: 11px 11px 8px; }
-.theme-copy strong { font-size: 14px; line-height: 1.35; }
-.theme-copy span { color: var(--muted); font-size: 11px; }
-.theme-copy p { display: -webkit-box; min-height: 34px; overflow: hidden; margin: 0; color: var(--muted); font-size: 11px; line-height: 1.5; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
-.theme-card-actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; border-top: 1px solid var(--line); padding: 8px 10px; }
-.theme-card-actions small { color: var(--muted); }
-.theme-card-actions button { min-height: var(--ui-compact-height); padding: 5px 9px; font-size: 11px; }
+.curated-status-bar { position: sticky; z-index: 15; top: 58px; display: flex; min-height: 38px; align-items: center; justify-content: space-between; gap: 12px; border-bottom: 1px solid var(--ui-border); padding: 5px max(12px, calc((100vw - var(--curated-max-width)) / 2)); color: var(--ui-muted); background: var(--ui-raised); font-size: var(--ui-meta-size); }
+.curated-status-bar[hidden] { display: none; }
+.curated-status-bar.error { color: var(--danger); }
+.curated-status-bar button { min-height: 28px; padding: 4px 8px; }
+.curated-app { width: calc(100% - 12px); max-width: var(--curated-max-width); min-height: calc(100dvh - 58px); margin: 8px auto 48px; }
+.pack-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: var(--curated-gap); }
+.pack-card { min-width: 0; overflow: hidden; border: 1px solid var(--ui-border); border-radius: var(--curated-radius); background: var(--ui-surface); cursor: pointer; }
+.pack-card:hover { border-color: var(--ui-border-strong); box-shadow: 0 8px 20px color-mix(in srgb, var(--ui-text) 10%, transparent); }
+.pack-card:focus-visible { outline: 2px solid var(--ui-focus); outline-offset: 2px; }
+.pack-cover { display: block; width: 100%; aspect-ratio: 4 / 5; overflow: hidden; background: var(--viewer-bg); }
+.pack-cover img { display: block; width: 100%; height: 100%; object-fit: cover; }
+.pack-copy { display: grid; gap: 6px; padding: 9px 10px 10px; }
+.pack-copy h2 { overflow: hidden; margin: 0; font-size: 14px; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
+.pack-meta { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 8px; color: var(--ui-muted); font-size: var(--ui-meta-size); }
+.pack-meta span:first-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.pack-meta span:last-child { flex: none; }
+.curated-loading { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: var(--curated-gap); }
+.curated-loading span { aspect-ratio: 4 / 5.55; border-radius: var(--curated-radius); background: var(--ui-raised); }
+.curated-empty { display: grid; min-height: 55dvh; place-items: center; color: var(--ui-muted); font-size: var(--ui-meta-size); }
-.theme-toolbar { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 14px; border-bottom: 1px solid var(--line); padding: 2px 0 12px; }
-.theme-toolbar-copy { min-width: 0; }
-.theme-toolbar-copy h2 { margin: 0; font-size: 20px; }
-.theme-toolbar-copy p { margin: 3px 0 0; overflow: hidden; color: var(--muted); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
-.theme-save-actions { display: flex; min-width: 220px; align-items: center; justify-content: flex-end; gap: 10px; }
-.theme-save-summary { display: grid; min-width: 96px; justify-items: end; gap: 2px; }
-.theme-save-actions strong { color: var(--muted); font-size: 11px; }
-.theme-save-actions small { min-height: 14px; color: var(--muted); font-size: 10px; }
+.detail-dialog { width: 100%; max-width: none; height: 100dvh; max-height: none; margin: 0; border: 0; border-radius: 0; padding: 0; color: var(--ui-text); background: var(--ui-page); }
+.detail-dialog::backdrop { background: rgba(4, 6, 9, .84); }
+.detail-dialog:focus { outline: 0; }
+.detail-close { position: fixed; z-index: 50; top: 11px; right: 12px; color: var(--ui-text); background: var(--ui-surface); }
+.detail-surface { min-height: 100dvh; padding-bottom: 40px; }
+.detail-hero { display: grid; height: min(70dvh, 680px); min-height: 460px; grid-template-columns: minmax(0, 1fr) clamp(360px, 31vw, 450px); border-bottom: 1px solid var(--ui-border); background: var(--ui-surface); }
+.detail-cover { min-height: 380px; overflow: hidden; background: var(--viewer-bg); }
+.detail-cover img { display: block; width: 100%; height: 100%; object-fit: cover; }
+.detail-info { display: grid; align-content: center; gap: 16px; padding: 42px 24px 34px; }
+.detail-info h1 { display: -webkit-box; overflow: hidden; margin: 0; font-size: clamp(24px, 3vw, 40px); line-height: 1.12; letter-spacing: -.035em; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
+.detail-meta { display: flex; min-width: 0; overflow: hidden; color: var(--ui-muted); font-size: var(--ui-meta-size); white-space: nowrap; }
+.detail-meta span { display: inline-flex; align-items: center; white-space: nowrap; }
+.detail-meta span:first-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
+.detail-meta span + span { border-left: 1px solid var(--ui-border-strong); margin-left: 10px; padding-left: 10px; }
+.detail-actions { display: flex; align-items: center; gap: 7px; }
+.detail-actions button { display: inline-flex; align-items: center; gap: 6px; }
+.detail-actions .ui-icon { width: 15px; height: 15px; }
+.download-action { color: var(--ui-accent-contrast); background: var(--ui-accent); }
+.download-action .ui-icon { width: 16px; height: 16px; }
+.follow-action.is-active { color: var(--ui-accent); border-color: var(--ui-border-strong); }
+.case-section { width: calc(100% - 16px); max-width: var(--curated-max-width); margin: 18px auto 0; }
+.case-section > h2 { display: flex; align-items: baseline; gap: 7px; margin: 0 2px 9px; font-size: var(--ui-section-title-size); }
+.case-section > h2 span { color: var(--ui-muted); font-size: var(--ui-meta-size); font-weight: 500; }
+.case-list { position: relative; width: 100%; overflow-anchor: none; --masonry-card-min-width: 270px; --masonry-gap: var(--curated-gap); }
+.case-card { position: absolute; display: block; min-width: 0; margin: 0; overflow: hidden; border: 0; border-radius: var(--curated-radius); background: var(--ui-surface); cursor: pointer; }
+.case-card:hover { box-shadow: 0 8px 20px color-mix(in srgb, var(--ui-text) 10%, transparent); }
+.case-card:focus-visible { outline: 2px solid var(--ui-focus); outline-offset: 2px; }
+.case-image-wrap { position: relative; width: 100%; min-height: 110px; overflow: hidden; background: var(--viewer-bg); }
+.case-visual { display: block; width: 100%; height: 100%; object-fit: cover; background: var(--viewer-bg); }
+.case-video-preview { position: absolute; z-index: 1; inset: 0; width: 100%; height: 100%; object-fit: cover; pointer-events: none; }
+.case-image-wrap.is-video-playing .case-video-badge { opacity: 0; }
+.case-video-badge { position: absolute; right: 8px; bottom: 8px; display: grid; width: 28px; height: 28px; place-items: center; border: 1px solid rgba(255, 255, 255, .25); border-radius: 50%; color: white; background: rgba(5, 7, 11, .7); font-size: 10px; }
+.case-card.is-saved::after { content: "✓"; position: absolute; z-index: 2; top: 8px; right: 8px; display: grid; width: 24px; height: 24px; place-items: center; border-radius: 50%; color: var(--ui-accent-contrast); background: var(--ui-accent); font-size: 12px; font-weight: 800; }
+.case-load-sentinel { height: 2px; }
+.case-loading { min-height: 160px; border: 1px solid var(--ui-border); border-radius: var(--curated-radius); background: var(--ui-raised); }
+.preview-failure { display: flex; min-height: 160px; align-items: center; justify-content: center; gap: 10px; border: 1px solid var(--ui-border); border-radius: var(--curated-radius); color: var(--ui-muted); background: var(--ui-raised); font-size: var(--ui-meta-size); }
+.preview-failure button { min-height: 30px; }
+.curated-toast { position: fixed; z-index: 90; right: 18px; bottom: 18px; max-width: min(360px, calc(100vw - 36px)); border: 1px solid var(--ui-border-strong); border-radius: var(--curated-radius); padding: 9px 12px; color: var(--ui-text); background: var(--ui-surface); box-shadow: var(--ui-shadow); font-size: var(--ui-meta-size); font-weight: 650; }
-.curated-grid { position: relative; width: 100%; overflow-anchor: none; --masonry-card-min-width: 220px; --masonry-gap: var(--visual-wall-gap); }
-.case-card { position: absolute; display: block; margin: 0; overflow: hidden; border: 0; border-radius: var(--visual-card-radius); color: var(--ink); background: #111419; cursor: pointer; }
-.case-card:hover { box-shadow: 0 8px 24px color-mix(in srgb, var(--ink) 15%, transparent); }
-.case-card:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
-.case-image-wrap { position: relative; min-height: 100px; overflow: hidden; background: #111419; }
-.case-shot { display: block; width: 100%; height: auto; background: #111419; }
-.case-image-wrap-fixed .case-shot { height: 100%; object-fit: cover; }
-.case-shot-missing { display: grid; min-height: 170px; place-items: center; padding: 22px; color: var(--muted); background: var(--raised); font-size: 11px; text-align: center; }
-.share-check { position: absolute; z-index: 2; top: 7px; right: 7px; display: none; width: 24px; height: 24px; place-items: center; color: var(--button-ink); border: 2px solid white; border-radius: 50%; background: var(--accent); }
-.curated-saved-card .share-check { display: grid; }
-.load-sentinel { height: 1px; }
-.load-more { display: block; margin: 12px auto 0; }
+.case-detail-backdrop { position: fixed; z-index: 70; inset: 0; background: rgba(0, 0, 0, .76); }
+.case-detail-backdrop[hidden] { display: none; }
+.case-detail-drawer { position: fixed; z-index: 71; inset: 0; width: 100vw; height: 100dvh; overflow: hidden; visibility: hidden; background: var(--viewer-bg); opacity: 0; pointer-events: none; transform: scale(.992); }
+.case-detail-drawer.open { visibility: visible; opacity: 1; pointer-events: auto; transform: scale(1); }
+.case-detail-toolbar { position: fixed; z-index: 73; top: 12px; right: 12px; display: flex; gap: 6px; }
+.case-detail-toolbar .icon-button { color: var(--ui-text); border-color: var(--ui-border); background: color-mix(in srgb, var(--ui-surface) 88%, transparent); box-shadow: var(--ui-shadow); }
+.case-detail-content { width: 100%; height: 100%; overflow: auto; }
+.case-detail-layout { display: grid; min-height: 100dvh; grid-template-columns: minmax(0, 1fr) clamp(380px, 34vw, 480px); }
+.case-detail-figure { position: relative; display: grid; min-width: 0; min-height: 100dvh; margin: 0; place-items: center; overflow: hidden; background: var(--viewer-bg); }
+.case-detail-figure img { display: block; width: auto; height: auto; max-width: 100%; max-height: 100dvh; object-fit: contain; }
+.case-detail-video-wrap { position: relative; display: block; width: 100%; height: 100dvh; }
+.case-detail-video { display: block; width: 100%; height: 100%; object-fit: contain; background: var(--viewer-bg); }
+.case-video-error { position: absolute; inset: auto 14px 14px; display: flex; align-items: center; justify-content: center; gap: 8px; border: 1px solid rgba(255,255,255,.2); border-radius: var(--curated-radius); padding: 7px 9px; color: rgba(255,255,255,.9); background: rgba(5,7,11,.78); font-size: var(--ui-meta-size); }
+.case-video-error[hidden] { display: none; }
+.case-video-error button { min-height: 28px; }
+.case-detail-video-label { position: absolute; right: 14px; bottom: 14px; border-radius: var(--curated-radius); padding: 6px 9px; color: rgba(255,255,255,.86); background: rgba(5,7,11,.72); font-size: var(--ui-meta-size); }
+.case-detail-body { display: grid; min-width: 0; min-height: 100dvh; align-content: start; grid-template-rows: auto minmax(0, 1fr) auto auto; border-left: 1px solid var(--ui-border); background: var(--ui-surface); }
+.case-detail-heading { padding: 68px 22px 17px; border-bottom: 1px solid var(--ui-border); }
+.case-detail-heading h2 { margin: 0; font-size: 18px; line-height: 1.35; }
+.case-detail-heading p { margin: 6px 0 0; color: var(--ui-muted); font-size: var(--ui-meta-size); }
+.case-detail-section { min-height: 0; padding: 18px 22px; }
+.case-detail-section h3 { margin: 0 0 10px; font-size: var(--ui-meta-size); }
+.case-detail-prompt { max-height: calc(100dvh - 300px); overflow: auto; margin: 0; border-radius: var(--curated-radius); padding: 13px; color: var(--prompt-ink); background: var(--prompt-bg); font: 12px/1.7 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
+.case-detail-source { display: flex; align-items: center; justify-content: space-between; gap: 12px; border-top: 1px solid var(--ui-border); padding: 12px 22px; color: var(--ui-muted); font-size: var(--ui-meta-size); }
+.case-detail-source a { color: var(--ui-text); font-weight: 700; text-decoration: none; }
+.case-detail-actions { position: sticky; bottom: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 7px; border-top: 1px solid var(--ui-border); padding: 12px 22px 16px; background: var(--ui-surface); }
+.case-detail-actions button { position: relative; display: inline-flex; min-width: 0; align-items: center; justify-content: center; gap: 6px; overflow: hidden; }
+.case-detail-actions .ui-icon { width: 15px; height: 15px; }
+.case-save-action { color: var(--ui-accent-contrast); background: var(--ui-accent); }
+.case-save-action.is-saved, .case-detail-actions .is-success { color: var(--ui-accent); border-color: var(--ui-border-strong); background: var(--ui-raised); }
+.is-progressing::after { content: ""; position: absolute; right: 0; bottom: 0; left: 0; height: 2px; background: linear-gradient(90deg, var(--ui-accent) calc(var(--progress) * 100%), transparent 0); }
+.is-progressing[style*="--progress: 0"]::after { width: 38%; background: var(--ui-accent); animation: curated-progress 1.1s ease-in-out infinite alternate; }
-.curated-loading { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; }
-.curated-loading div { min-height: 230px; border-radius: 4px; background: var(--raised); }
-.curated-loading div:nth-child(2n) { min-height: 300px; }
-.curated-loading div:nth-child(3n) { min-height: 190px; }
-.curated-empty { border: 1px dashed var(--line); border-radius: 6px; padding: 40px 20px; color: var(--muted); text-align: center; }
-.curated-empty strong { color: var(--ink); font-size: 15px; }
-.curated-empty p { margin: 5px 0 0; }
+.pack-save-dialog { width: min(420px, calc(100vw - 28px)); border: 1px solid var(--ui-border-strong); border-radius: var(--curated-radius); padding: 20px; color: var(--ui-text); background: var(--ui-surface); box-shadow: var(--ui-shadow); }
+.pack-save-dialog::backdrop { background: rgba(4,6,9,.76); }
+.pack-save-dialog h2 { overflow: hidden; margin: 0; font-size: 18px; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
+.pack-save-meta { margin: 8px 0 18px; color: var(--ui-muted); font-size: var(--ui-meta-size); }
+.pack-save-actions { display: flex; justify-content: flex-end; gap: 7px; }
-.detail-backdrop { position: fixed; z-index: 38; inset: 0; background: rgba(4, 6, 9, 0.84); }
-.detail-drawer { --detail-panel-width: clamp(360px, 31vw, 450px); position: fixed; z-index: 40; inset: 0; display: flex; width: 100vw; height: 100dvh; overflow: hidden; visibility: hidden; flex-direction: column; background: var(--viewer-bg); pointer-events: none; opacity: 0; transform: scale(0.99); transition: opacity 140ms ease, transform 140ms ease; }
-.detail-drawer.open { visibility: visible; pointer-events: auto; opacity: 1; transform: scale(1); }
-.detail-toolbar { position: absolute; z-index: 3; inset: 0 0 auto; height: 0; pointer-events: none; }
-.detail-toolbar .icon-button { color: var(--ink); border-color: var(--line); background: var(--card); pointer-events: auto; }
-.detail-toolbar > div { position: absolute; top: 50dvh; left: 0; display: flex; width: calc(100vw - var(--detail-panel-width)); justify-content: space-between; padding: 0 12px; transform: translateY(-50%); pointer-events: none; }
-.detail-toolbar > div .icon-button { color: var(--viewer-ink); border-color: rgba(255, 255, 255, 0.22); background: var(--viewer-control); }
-.detail-toolbar > .icon-button { position: absolute; top: 12px; right: 12px; }
-.detail-content { display: grid; min-height: 0; overflow: hidden; flex: 1 1 auto; grid-template-columns: minmax(0, 1fr) var(--detail-panel-width); }
-.detail-figure { display: grid; min-width: 0; height: 100dvh; margin: 0; padding: 42px; place-items: center; background: var(--viewer-bg); }
-.detail-figure img,
-.detail-figure video { display: block; width: auto; max-width: 100%; height: auto; max-height: calc(100dvh - 84px); object-fit: contain; }
-.detail-body { display: grid; min-height: 0; align-content: start; gap: 16px; overflow: auto; border-left: 1px solid var(--line); padding: 62px 20px 26px; background: var(--card); }
-.detail-heading h2 { margin: 0; font-size: 20px; line-height: 1.3; }
-.detail-metadata { color: var(--muted); font-size: 11px; }
-.detail-metadata span { overflow-wrap: anywhere; }
-.detail-section { display: grid; gap: 8px; }
-.detail-section h3 { margin: 0; font-size: 12px; }
-.detail-prompt { margin: 0; border: 1px solid var(--line); border-radius: 6px; padding: 12px; color: var(--ink); background: var(--raised); font: 12px/1.65 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
-.detail-actions { position: sticky; bottom: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 7px; margin: 0 -20px -26px; border-top: 1px solid var(--line); padding: 12px 20px 15px; background: var(--card); }
-.detail-actions .create-action { grid-column: 1 / -1; }
-.detail-actions .saved { color: var(--accent-ink); border: 1px solid var(--line); background: var(--card); }
+@keyframes curated-progress { from { transform: translateX(-90%); } to { transform: translateX(260%); } }
-@media (max-width: 900px) {
- .theme-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
- .curated-loading { grid-template-columns: repeat(3, minmax(0, 1fr)); }
- .detail-drawer { --detail-panel-width: clamp(320px, 38vw, 390px); }
+@media (max-width: 1050px) {
+ .pack-grid, .curated-loading { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+ .case-list { --masonry-card-min-width: 220px; }
}
-@media (max-width: 700px) {
- .curated-header { min-height: 54px; gap: 7px; padding: 8px 10px; }
- .curated-header h1 { font-size: 15px; }
- .curated-header button { padding-inline: 8px; }
- main { width: min(100% - 8px, 1500px); margin-top: 8px; }
- .theme-grid { gap: 6px; }
- .theme-copy { padding: 9px 9px 7px; }
- .theme-card-actions { align-items: stretch; flex-direction: column; }
- .theme-card-actions button { width: 100%; }
- .theme-toolbar { grid-template-columns: minmax(0, 1fr); gap: 8px; }
- .theme-save-actions { width: 100%; min-width: 0; justify-content: space-between; }
- .theme-save-summary { justify-items: start; }
- .curated-grid { --masonry-card-min-width: 145px; --masonry-gap: var(--visual-wall-gap); }
- .curated-loading { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 5px; }
- .detail-drawer { transform: translateY(10px); }
- .detail-drawer.open { transform: translateY(0); }
- .detail-toolbar > div { top: 29dvh; width: 100vw; padding: 0 8px; }
- .detail-toolbar > .icon-button { color: var(--viewer-ink); border-color: rgba(255, 255, 255, 0.22); background: var(--viewer-control); }
- .detail-content { display: block; overflow: auto; background: var(--card); }
- .detail-figure { height: 58dvh; padding: 42px 12px 14px; }
- .detail-figure img,
- .detail-figure video { max-height: calc(58dvh - 56px); }
- .detail-body { min-height: 42dvh; overflow: visible; border-top: 1px solid var(--line); border-left: 0; padding: 20px 14px 24px; }
- .detail-actions { margin: 0 -14px -24px; padding: 11px 14px 14px; }
+@media (max-width: 760px) {
+ .curated-header { grid-template-columns: auto 1fr; padding: 8px 10px; }
+ .curated-header-actions { justify-self: end; }
+ .curated-search { grid-column: 1 / -1; grid-row: 2; }
+ .page-back-action span { display: none; }
+ .curated-app { width: min(100% - 8px, var(--curated-max-width)); }
+ .pack-grid, .curated-loading { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }
+ .case-list { --masonry-card-min-width: 155px; --masonry-gap: 6px; }
+ .detail-hero { height: auto; min-height: 0; grid-template-columns: 1fr; }
+ .detail-cover { min-height: 46dvh; max-height: 56dvh; }
+ .detail-info { padding: 24px 14px; }
+ .detail-info h1 { font-size: 24px; }
+ .case-section { width: calc(100vw - 16px); }
+ .case-detail-layout { grid-template-columns: 1fr; }
+ .case-detail-figure { min-height: 54dvh; }
+ .case-detail-figure img { max-height: 54dvh; }
+ .case-detail-video-wrap { height: 54dvh; }
+ .case-detail-body { min-height: 46dvh; border-top: 1px solid var(--ui-border); border-left: 0; }
+ .case-detail-heading { padding: 18px 14px 14px; }
+ .case-detail-section { padding: 16px 14px; }
+ .case-detail-prompt { max-height: none; }
+ .case-detail-source { padding: 12px 14px; }
+ .case-detail-actions { padding: 10px 14px 14px; }
}
-@media (prefers-reduced-motion: reduce) {
- .detail-drawer { transition: none; }
+@media (max-width: 460px) {
+ .tool-button > span:not(#filter-count) { display: none; }
+ .detail-info { gap: 12px; }
+ .detail-actions { flex-wrap: wrap; }
+ .case-detail-toolbar { top: 8px; right: 8px; }
}
@media (prefers-reduced-motion: no-preference) {
- button,
- input,
- .theme-card,
- .case-card { transition: color 140ms ease, background-color 140ms ease, border-color 140ms ease, box-shadow 140ms ease, transform 120ms ease; }
+ button, input, summary, .pack-card, .case-card, .case-detail-drawer { transition: color 140ms ease, background-color 140ms ease, border-color 140ms ease, box-shadow 140ms ease, transform 120ms ease, opacity 140ms ease; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .is-progressing[style*="--progress: 0"]::after { width: 100%; opacity: .55; animation: none; }
}
diff --git a/curated.html b/curated.html
index 21c26d7..b1bb883 100644
--- a/curated.html
+++ b/curated.html
@@ -11,57 +11,66 @@
<body>
<header class="curated-header">
<h1 data-i18n="精选案例">精选案例</h1>
- <button id="return-library" class="button-secondary page-back-action" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-arrow-left"></use></svg><span id="return-label">返回我的案例库</span></button>
- </header>
- <main>
- <div class="curated-status-row">
- <p id="curated-status" class="curated-status" role="status" aria-live="polite"></p>
- <button id="retry-catalog" class="button-secondary" type="button" hidden data-i18n="重试">重试</button>
- </div>
-
- <section id="themes-view" class="themes-view">
- <header class="themes-heading">
- <h2 data-i18n="按期浏览">按期浏览</h2>
- <p data-i18n="选择一期主题,再浏览或保存其中的案例。">选择一期主题,再浏览或保存其中的案例。</p>
- </header>
- <section id="theme-grid" class="theme-grid" aria-live="polite"></section>
- </section>
-
- <section id="cases-view" class="cases-view" hidden>
- <header class="theme-toolbar">
- <div class="theme-toolbar-copy">
- <h2 id="active-theme-title"></h2>
- <p id="active-theme-summary"></p>
+ <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>
+ <input id="curated-search" type="search" autocomplete="off" placeholder="搜索创作包或包内案例" data-i18n-placeholder="搜索创作包或包内案例" />
+ </label>
+ <div class="curated-header-actions">
+ <div class="filter-wrap">
+ <button id="filter-button" class="button-secondary tool-button" type="button" aria-expanded="false"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-sliders-horizontal"></use></svg><span data-i18n="筛选">筛选</span><span id="filter-count"></span></button>
+ <div id="filter-popover" class="menu-panel filter-panel" hidden>
+ <strong data-i18n="内容类型">内容类型</strong>
+ <label><input type="checkbox" value="image_prompt" /><span data-i18n="图片案例">图片案例</span></label>
+ <label><input type="checkbox" value="video_prompt" /><span data-i18n="视频案例">视频案例</span></label>
+ <label><input type="checkbox" value="followed" /><span data-i18n="已关注">已关注</span></label>
+ <button id="clear-filters" type="button" data-i18n="清除筛选">清除筛选</button>
</div>
- <div class="theme-save-actions">
- <span class="theme-save-summary"><strong id="active-theme-count"></strong><small id="theme-save-status"></small></span>
- <button id="save-theme" type="button" data-i18n="全部保存">全部保存</button>
+ </div>
+ <details id="sort-menu" class="sort-menu">
+ <summary class="button-secondary"><span id="sort-label" data-i18n="推荐">推荐</span><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-chevron-down"></use></svg></summary>
+ <div class="menu-panel sort-panel">
+ <button type="button" data-sort="recommended" aria-current="true"><span data-i18n="推荐">推荐</span><svg class="ui-icon sort-check" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-check"></use></svg></button>
+ <button type="button" data-sort="latest" aria-current="false"><span data-i18n="最新">最新</span><svg class="ui-icon sort-check" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-check"></use></svg></button>
+ <button id="sort-downloads" type="button" data-sort="downloads" aria-current="false" disabled><span data-i18n="下载">下载</span><svg class="ui-icon sort-check" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-check"></use></svg></button>
</div>
- </header>
- <section id="curated-grid" class="curated-grid" aria-live="polite"></section>
- <div id="load-sentinel" class="load-sentinel" aria-hidden="true"></div>
- <button id="load-more" class="button-secondary load-more" type="button" hidden data-i18n="继续加载">继续加载</button>
- <section id="curated-empty" class="curated-empty" hidden>
- <strong data-i18n="还没有可显示的精选案例">还没有可显示的精选案例</strong>
- <p data-i18n="联网检查目录,或稍后再试。已缓存的目录在离线时仍可查看。">联网检查目录,或稍后再试。已缓存的目录在离线时仍可查看。</p>
- </section>
- </section>
+ </details>
+ <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>
- <section id="curated-loading" class="curated-loading" aria-label="正在加载精选案例" data-i18n-aria-label="正在加载精选案例" hidden>
- <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
+ <div id="curated-status-bar" class="curated-status-bar" hidden>
+ <span id="curated-status" role="status" aria-live="polite"></span>
+ <button id="retry-catalog" class="button-secondary" type="button" data-i18n="重试">重试</button>
+ </div>
+ <main id="curated-app" class="curated-app" aria-live="polite">
+ <section class="curated-loading" aria-label="正在加载精选案例" data-i18n-aria-label="正在加载精选案例">
+ <span></span><span></span><span></span><span></span>
</section>
</main>
- <div id="detail-backdrop" class="detail-backdrop" hidden></div>
- <aside id="detail-drawer" class="detail-drawer" role="dialog" aria-modal="true" aria-label="精选案例详情" data-i18n-aria-label="精选案例详情" aria-hidden="true">
- <div class="detail-toolbar">
- <div>
- <button id="detail-prev" 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-chevron-left"></use></svg></button>
- <button id="detail-next" 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-chevron-right"></use></svg></button>
- </div>
- <button id="detail-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>
+
+ <dialog id="detail-dialog" class="detail-dialog" aria-label="精选案例详情" data-i18n-aria-label="精选案例详情">
+ <button id="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="detail-content"></div>
+ <div id="case-detail-backdrop" class="case-detail-backdrop" hidden></div>
+ <aside id="case-detail-drawer" class="case-detail-drawer" role="dialog" aria-modal="true" aria-hidden="true" aria-label="案例详情" data-i18n-aria-label="案例详情">
+ <nav class="case-detail-toolbar" aria-label="案例切换" data-i18n-aria-label="案例切换">
+ <button id="case-detail-prev" class="icon-button" 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-chevron-left"></use></svg></button>
+ <button id="case-detail-next" class="icon-button" 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-chevron-right"></use></svg></button>
+ <button id="case-detail-close" class="icon-button" 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>
+ </nav>
+ <div id="case-detail-content" class="case-detail-content"></div>
+ </aside>
+ </dialog>
+ <dialog id="pack-save-dialog" class="pack-save-dialog" aria-label="保存整包" data-i18n-aria-label="保存整包">
+ <h2></h2>
+ <p class="pack-save-meta"></p>
+ <div class="pack-save-actions">
+ <button class="pack-save-cancel button-secondary" type="button" data-i18n="取消">取消</button>
+ <button class="pack-save-confirm" type="button" data-i18n="保存整包">保存整包</button>
</div>
- <div id="detail-content" class="detail-content"></div>
- </aside>
+ </dialog>
+ <div id="curated-toast" class="curated-toast" role="status" hidden></div>
<script type="module" src="curated-page.js"></script>
</body>
</html>
diff --git a/deepseek.js b/deepseek.js
index 309836a..9b0ccbb 100644
--- a/deepseek.js
+++ b/deepseek.js
@@ -52,12 +52,11 @@ export function deepSeekErrorDetails(error) {
}
export function normalizeAiSettings(value = {}) {
- const legacyModel = String(value.model ?? "").trim();
return {
activeProvider: value.activeProvider === "compatible" ? "compatible" : "deepseek",
apiKey: String(value.apiKey ?? "").trim(),
consent: value.consent === true,
- analysisModel: String(value.analysisModel ?? "").trim() || legacyModel || DEFAULT_ANALYSIS_MODEL,
+ analysisModel: String(value.analysisModel ?? "").trim() || DEFAULT_ANALYSIS_MODEL,
analysisInstructionsByLocale: normalizeAnalysisInstructions(value.analysisInstructionsByLocale),
compatible: {
endpoint: String(value.compatible?.endpoint ?? "").trim(),
@@ -77,7 +76,7 @@ export function mergeAiSettings(currentValue = {}, incomingValue = {}) {
const credentialReset = Boolean(current.compatible.apiKey && currentOrigin && nextOrigin !== currentOrigin && !incomingCompatibleKey);
const settings = normalizeAiSettings({
activeProvider: incoming.activeProvider ?? current.activeProvider,
- analysisModel: incoming.analysisModel ?? incoming.model ?? current.analysisModel,
+ analysisModel: incoming.analysisModel ?? current.analysisModel,
apiKey: String(incoming.apiKey ?? "").trim() || current.apiKey,
consent: incoming.consent === true,
analysisInstructionsByLocale: {
@@ -430,12 +429,14 @@ async function streamAgentText({ settings, profile, systemInstruction, execution
}, profile);
assertComposerRequestBudget(body.messages);
const controller = new AbortController();
- const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : DEFAULT_COMPOSER_STREAM_TIMEOUT_MS;
+ const timeoutMs = options.timeoutMs === null
+ ? null
+ : Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : DEFAULT_COMPOSER_STREAM_TIMEOUT_MS;
let timedOut = false;
const onAbort = () => controller.abort();
if (options.signal?.aborted) controller.abort();
options.signal?.addEventListener("abort", onAbort, { once: true });
- const timeoutId = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
+ const timeoutId = timeoutMs === null ? null : setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
try {
const response = await fetchDeepSeekStream(body, settings, options.fetchImpl ?? fetch, controller.signal);
const result = await readDeepSeekSse(response, options.onDelta);
@@ -445,7 +446,7 @@ async function streamAgentText({ settings, profile, systemInstruction, execution
if (timedOut) throw new DeepSeekApiError("DeepSeek 流式输出超时,本次结果未保存", 408);
throw error;
} finally {
- clearTimeout(timeoutId);
+ if (timeoutId !== null) clearTimeout(timeoutId);
options.signal?.removeEventListener("abort", onAbort);
}
}
diff --git a/i18n.js b/i18n.js
index dca26c5..0ae539a 100644
--- a/i18n.js
+++ b/i18n.js
@@ -31,10 +31,50 @@ const EN = Object.freeze({
"搜索案例": "Search cases",
"搜索提示词或标题": "Search prompts or titles",
"项目只帮助选材,保存后的 Skill 不属于任何项目。": "Projects only help select sources. Saved Skills do not belong to a project.",
+ "清空全部案例": "Clear all cases",
+ "已选 {count} 个案例": "{count} cases selected",
+ "{assets} 项素材 · {texts} 份案例文字": "{assets} assets · {texts} case texts",
+ "尚未选择案例": "No cases selected",
+ "选择案例后,可点击“内容”精确调整图片、视频、文档和文字。": "Select a case, then open Content to precisely adjust images, videos, documents, and text.",
+ "图片 {images} · 视频 {videos} · 文档 {documents} · 案例文字 {texts}": "Images {images} · Videos {videos} · Documents {documents} · Case text {texts}",
+ "点击内容可精确调整": "Open Content for precise selection",
+ "加载更多案例": "Load more cases",
+ "加载更多案例(已显示 {shown}/{total})": "Load more cases ({shown}/{total} shown)",
+ "{count} 项内容": "{count} items",
+ "查看内容": "View content",
+ "已选 {selected}/{total}": "{selected}/{total} selected",
+ "{count} 图": "{count} images",
+ "{count} 视频": "{count} videos",
+ "{count} 文档": "{count} documents",
+ "案例文字": "Case text",
+ "无可用内容": "No usable content",
+ "精确选择 {title} 的内容": "Precisely select content from {title}",
"来源": "Sources",
"案例组合": "Case selection",
"说明提炼目标": "Describe the extraction goal",
"说清楚你想从这些案例中学什么,例如只提炼色彩组织、构图逻辑、角色塑造或动作设计。": "Describe exactly what you want to learn from these cases, such as color organization, composition logic, character design, or action design.",
+ "例如:只提炼这些案例的人物构图与动作节奏": "For example: extract only the character composition and action rhythm",
+ "分析所选图片": "Analyze selected images",
+ "当前没有选择可分析的图片": "No analyzable images are selected",
+ "尚未配置可用的图片分析模型": "No usable image-analysis model is configured",
+ "张图片": "images",
+ "运行设置": "Run settings",
+ "文字提炼模型": "Text extraction model",
+ "图片分析模型": "Image analysis model",
+ "本次提炼指令": "Extraction instruction for this run",
+ "本次视觉分析指令": "Visual-analysis instruction for this run",
+ "恢复默认指令": "Restore default instructions",
+ "查看并编辑 SKILL.md": "View and edit SKILL.md",
+ "运行记录": "Run log",
+ "精确选择": "Precise selection",
+ "全选可用内容": "Select all usable content",
+ "清空本案例": "Clear this case",
+ "应用选择": "Apply selection",
+ "包含案例文字": "Include case text",
+ "图片": "Image",
+ "文档": "Document",
+ "视频": "Video",
+ "本地素材": "Local asset",
"文字提炼": "Text extraction",
"使用原提示词和已有画面分析": "Use original prompts and existing visual analyses",
"增加视觉分析": "Add visual analysis",
@@ -62,6 +102,7 @@ const EN = Object.freeze({
"当前 v{version}": "Current v{version}",
"未命名案例": "Untitled case",
"{service} · {images} 张内容图 · {batches} 个视觉批次 · 预计 {requests} 次付费请求。联系表仅在本轮内存中生成,不会保存。": "{service} · {images} content images · {batches} visual batches · approximately {requests} paid requests. Contact sheets exist only in memory for this run and are not saved.",
+ "{service} · {images} 张内容图 · {batches} 个视觉批次 · 预计 {requests} 次付费请求。": "{service} · {images} content images · {batches} visual batches · approximately {requests} paid requests.",
"尚未配置可用的视觉模型 · {images} 张内容图 · {batches} 个视觉批次。请先在资料库设置中完成视觉服务配置。": "No usable vision model is configured · {images} content images · {batches} visual batches. Configure a vision service in library settings first.",
"请先选择至少一个来源案例": "Select at least one source case",
"请先选择至少一项案例或人工判断证据": "Select at least one case or human judgment",
@@ -74,9 +115,33 @@ const EN = Object.freeze({
"已取消视觉分析,没有发送图片": "Visual analysis canceled. No images were sent.",
"正在分析视觉批次 {current}/{total}…": "Analyzing visual batch {current}/{total}...",
"视觉批次失败": "Visual batch failed",
+ "图片批次 {current}/{total} 完成 · {model}": "Image batch {current}/{total} completed · {model}",
+ "图片批次 {current}/{total} 失败:{message}": "Image batch {current}/{total} failed: {message}",
+ "{success} 个视觉批次成功,{failures} 个失败。可只重试失败批次。": "{success} visual batches succeeded and {failures} failed. Retry only the failed batches.",
"{success} 个视觉批次成功,{failures} 个失败。可只重试失败批次,或切回文字提炼。": "{success} visual batches succeeded and {failures} failed. Retry only the failed batches or switch to text extraction.",
"正在围绕你的目标提炼可复用方法…": "Extracting a reusable method around your goal...",
"草稿已生成 · {model}": "Draft generated · {model}",
+ "文字提炼完成 · {model}": "Text extraction completed · {model}",
+ "案例与证据:{cases} 项\n文字量:{characters} 字符 · 约 {tokenMin}–{tokenMax} tokens\n文字批次:{textBatches} · 图片:{images} 张 · 视觉批次:{visualBatches}\n预计请求:{requests} 次\n文字模型:{service}\n图片模型:{visionService}\n\n不会抽样、截断、自动换模型或自动重试。": "Cases and evidence: {cases}\nText: {characters} characters · about {tokenMin}–{tokenMax} tokens\nText batches: {textBatches} · Images: {images} · Visual batches: {visualBatches}\nEstimated requests: {requests}\nText model: {service}\nImage model: {visionService}\n\nNo sampling, truncation, automatic model switching, or automatic retry.",
+ "不发送图片": "No images sent",
+ "正在准备发送内容": "Preparing content to send",
+ "发送范围已确认": "Sending scope confirmed",
+ "已取消,没有发送内容": "Canceled. Nothing was sent.",
+ "正在分析图片 {current}/{total}": "Analyzing image batch {current}/{total}",
+ "正在接收图片分析结果": "Receiving image-analysis results",
+ "正在接收 Skill 草稿": "Receiving the Skill draft",
+ "正在汇总全部批次": "Merging all batches",
+ "正在提炼文字 {current}/{total}": "Extracting text batch {current}/{total}",
+ "服务响应较慢,仍在等待;你可以继续等待或停止": "The service is responding slowly. You can keep waiting or stop.",
+ "服务响应较慢,未自动中止": "The response is slow; the request was not stopped automatically",
+ "准备": "Prepare",
+ "图片分析": "Image analysis",
+ "文字提炼": "Text extraction",
+ "完成": "Complete",
+ "图片输入:已声明支持": "Image input: declared supported",
+ "图片输入:明确不支持": "Image input: explicitly unsupported",
+ "图片输入:能力来源未知,运行前仍按任务配置校验": "Image input: capability source unknown; task configuration is still checked before running",
+ "发送范围:{cases} 个匿名案例 · {assets} 项素材 · {images} 张图片\n模型:{textModel}{visionModel}\n地址:{textEndpoint}{visionEndpoint}\n{capability}\n只发送明确选择的文字、已有分析和图片;标题、网址、本地编号与未选内容不会发送。": "Sending scope: {cases} anonymous cases · {assets} assets · {images} images\nModels: {textModel}{visionModel}\nEndpoints: {textEndpoint}{visionEndpoint}\n{capability}\nOnly explicitly selected text, existing analyses, and images are sent. Titles, URLs, local IDs, and unselected content are excluded.",
"调用名、说明和 SKILL.md 正文都需要填写": "Call name, description, and SKILL.md body are required",
"匿名来源 {index} 参与了本次方法提炼。": "Anonymous source {index} informed this method extraction.",
"匿名案例来源 {index} 参与了本次方法提炼。": "Anonymous case source {index} informed this method extraction.",
@@ -112,21 +177,70 @@ const EN = Object.freeze({
"框选区域太小,请重新拖动 · Esc 取消": "The selection is too small. Drag again · Esc to cancel",
"点击选择图片,可多选 · Esc 取消": "Click images to select one or more · Esc to cancel",
"已选 {count} 张": "{count} selected",
+ "预览不可用": "Preview unavailable",
"选择图片": "Select image",
"打开灵感库": "Open library",
"框选": "Select area",
"智能选图": "Select visuals",
- "提取文字": "Extract text",
+ "提取文字/图片": "Extract text/image",
+ "+ 提取文字/图片": "+ Extract text/image",
"框选截图": "Select screenshot area",
"加入素材": "Add visuals",
"取消": "Cancel",
"已识别 {count} 项 · 已确认 {selected} 项内容": "{count} items found · {selected} components selected",
+ "已识别 {count} 个主体方案 · 已确认 {selected} 个": "{count} subject options found · {selected} confirmed",
"正在扫描已加载内容;可随时停止,结束后会恢复原滚动位置。": "Scanning loaded content. You can stop at any time; the original scroll position will be restored.",
+ "先查看并修正网页区域,再确认一个创作主体。确认后会按原始顺序保存完整文章和相关资源。": "Inspect and correct the page region, then confirm one creative subject. The complete article and related resources will be saved in source order.",
+ "查看网页区域": "Inspect page region",
+ "创作章节": "Creative sections",
+ "{count} 个高价值章节": "{count} high-value sections",
+ "章节 {count}": "Section {count}",
+ "可能遗漏({count})": "Possible omissions ({count})",
+ "确认这个主体": "Confirm this subject",
+ "已确认这个主体": "Subject confirmed",
+ "移除此案例": "Remove this case",
+ "媒体 {current} / {count}": "Media {current} / {count}",
+ "保存案例 · 含 {count} 项媒体": "Save case · {count} media items",
+ "保存 {cases} 个案例 · 含 {media} 项媒体": "Save {cases} cases · {media} media items",
+ "只保存 {count} 个正文案例": "Save text only for {count} cases",
+ "只保存正文": "Save text only",
+ "保存时将确认 {count} 项媒体": "Saving will confirm {count} media items",
+ "未识别到媒体,可返回网页补选": "No media found. Return to the page to add any missing items.",
+ "可能遗漏媒体({count})": "Possibly missing media ({count})",
+ "请先查看并确认一个代表案例,再开始列表采集": "Inspect and confirm one representative case before starting list capture.",
+ "请输入 1 到 {count} 之间的目标案例数": "Enter a target between 1 and {count} cases.",
+ "目标 {target} 个,实际识别 {actual} 个。{reason}": "Target: {target}. Found: {actual}. {reason}",
+ "已达到目标数量。": "Target reached.",
+ "列表没有新增案例,已按实际数量结束。": "No new cases were found; capture ended with the actual count.",
+ "没有可继续的列表页,已按实际数量结束。": "No next list page was available; capture ended with the actual count.",
+ "列表结构发生变化,已停止。": "The list structure changed, so capture stopped.",
+ "列表翻页失败,已按当前结果结束。": "List pagination failed; capture ended with the current results.",
+ "采集已由用户停止。": "Capture was stopped by the user.",
+ "已按当前列表可识别结果结束。": "Capture ended with the results recognized from the current list.",
"扫描不会自动保存。请确认正文、图片或视频,未勾选的内容不会进入案例库。": "Scanning never saves automatically. Confirm the text, images, or videos you want; unchecked content will not enter the library.",
"正文": "Text",
+ "原网页选区": "Page selection",
+ "智能正文": "Reader article",
+ "结构化正文": "Structured article",
+ "页面正文": "Page text",
+ "正文分段": "Article sections",
+ "{count} 段 · 可逐段确认": "{count} sections · review individually",
+ "第 {count} 段": "Section {count}",
"{count} 字": "{count} characters",
"视频引用": "Video reference",
"可见媒体": "Visible media",
+ "候选 {count}px": "{count}px candidate",
+ "候选 {count}x": "{count}x candidate",
+ "picture 响应图": "Responsive picture source",
+ "延迟加载原图": "Deferred original",
+ "srcset 响应图": "Responsive srcset source",
+ "站点原图": "Site original",
+ "结构化原图": "Structured original",
+ "页面当前图": "Current page image",
+ "页面可见画面": "Visible page pixels",
+ "CSS 背景图": "CSS background image",
+ "公开原图失败时,将使用当前网页已有登录状态读取所选图片;不会读取或保存登录信息。": "If public originals fail, the selected images will be read through the current page session. Sign-in information is never read or saved.",
+ "公开原图失败时,只会使用当前网页已有登录状态读取已确认主体内的相关媒体;不会读取或保存登录信息。": "If public originals fail, only related media inside the confirmed subject may be read through the current page session. Sign-in information is never read or saved.",
"正在停止整页扫描": "Stopping full-page scan",
"文章": "Article",
"作品": "Work",
@@ -278,8 +392,65 @@ const EN = Object.freeze({
"每次分析一张图片;失败项需手动重试。": "Images are analyzed one at a time. Retry failed items manually.",
"取消任务": "Cancel task",
"分享项目": "Share project",
+ "导出分享包": "Export share pack",
+ "投稿到精选": "Submit to curated",
+ "我确认素材将公开上传到 GitHub 审核队列": "I understand these files will be uploaded publicly to the GitHub review queue",
+ "显示投稿文件": "Show submission files",
+ "打开投稿表单": "Open submission form",
+ "正在生成投稿包": "Preparing submission",
+ "无法生成精选投稿包": "Could not prepare the curated submission",
+ "投稿包已生成": "Submission prepared",
+ "投稿包已生成,共 {count} 个分卷": "Submission prepared in {count} parts",
+ "{count} 个案例": "{count} cases",
+ "请先选择要分享的案例": "Select cases to share first",
"当前图片完成后取消,不会再发送下一张": "The task will stop after the current image. No further image will be sent.",
"精选案例": "Curated cases",
+ "搜索创作包或包内案例": "Search packs or cases",
+ "筛选": "Filter",
+ "清除筛选": "Clear filters",
+ "已关注": "Following",
+ "最新": "Latest",
+ "下载": "Downloads",
+ "下载包": "Download pack",
+ "保存整包": "Save full pack",
+ "关注": "Follow",
+ "已取消关注": "Unfollowed",
+ "复制链接": "Copy link",
+ "已复制链接": "Link copied",
+ "包内案例": "Cases",
+ "正在加载包内案例": "Loading cases",
+ "没有结果": "No results",
+ "案例包不存在": "Pack not found",
+ "预览加载失败": "Preview unavailable",
+ "保存案例": "Save case",
+ "精选案例保存失败": "Could not save this case",
+ "下载中": "Downloading",
+ "校验中": "Verifying",
+ "解包中": "Opening pack",
+ "写入案例库": "Saving to library",
+ "正在创建项目": "Creating project",
+ "保存文件中": "Saving file",
+ "处理中": "Working",
+ "下载完成": "Download complete",
+ "下载失败": "Download failed",
+ "保存到案例库": "Save to library",
+ "查看已保存": "View saved case",
+ "案例已存在": "Case already saved",
+ "查看来源": "View source",
+ "视频封面": "Video cover",
+ "视频暂不可播放": "Video unavailable",
+ "视频加载失败": "Video could not be loaded",
+ "图片加载失败": "Image could not be loaded",
+ "案例库暂不可用": "Library unavailable",
+ "私人案例库暂不可用,精选仍可浏览": "The private library is unavailable. Curated cases remain available to browse",
+ "案例切换": "Case navigation",
+ "上一个案例": "Previous case",
+ "下一个案例": "Next case",
+ "关闭案例详情": "Close case details",
+ "精选目录加载失败": "Could not load curated catalog",
+ "无法下载案例包,请检查网络后重试": "Could not download the pack. Check your connection and retry",
+ "PromptDirector 原创": "PromptDirector original",
+ "权利未标注": "Rights not specified",
"按期浏览": "Browse by edition",
"选择一期主题,再浏览或保存其中的案例。": "Choose an edition to browse or save its cases.",
"返回主题": "Back to editions",
@@ -523,8 +694,15 @@ const EN = Object.freeze({
"本轮图片参数": "Image parameters for this run",
"本轮视频参数": "Video parameters for this run",
"画幅与分辨率": "Aspect ratio and resolution",
+ "画幅比例": "Aspect ratio",
+ "图片尺寸": "Image size",
+ "由服务决定": "Decided by the service",
"时长": "Duration",
"质量": "Quality",
+ "参考图参与方式": "How reference images are used",
+ "带原图生成(默认)": "Generate with original images (default)",
+ "先读图整理提示词,生图不垫图": "Analyze images for the prompt, then generate without image conditioning",
+ "全程只用案例/分析文字(不读图,最省 token)": "Use case prompts or analysis text only (no image reading, lowest token use)",
"方形 · 1024×1024": "Square · 1024×1024",
"横向 · 1536×1024": "Landscape · 1536×1024",
"纵向 · 1024×1536": "Portrait · 1024×1536",
@@ -1112,6 +1290,101 @@ const EN = Object.freeze({
"批量分析已停止": "Batch analysis stopped",
"分析结果提交失败": "The analysis result could not be saved",
"分析失败": "Analysis failed",
+ "AI 任务配置": "AI task configuration",
+ "已连接 {count} 个服务;文字、图片、视频与生成任务各自明确分配,不会静默切换。": "{count} services connected. Text, image, video, and generation tasks are assigned explicitly and never switched silently.",
+ "尚未连接 AI 服务;本地资料整理仍可使用。": "No AI service connected. Local library organization remains available.",
+ "各任务默认模型": "Default model for each task",
+ "连接 AI 服务": "Connect AI service",
+ "分析规则与创作方法(高级)": "Analysis rules and creation methods (Advanced)",
+ "只管理分析规则和创作方法;服务连接与模型分配均在上方完成。": "Manage only analysis rules and creation methods here. Connect services and assign models above.",
+ "保存分析规则": "Save analysis rules",
+ "图片视觉分析规则": "Image-analysis rules",
+ "这里只管理图片分析规则;服务连接与默认模型在上方配置。": "Manage only image-analysis rules here. Configure the service connection and default model above.",
+ "规则保存在本机,只在对应任务运行时使用。": "Rules are stored locally and used only when the corresponding task runs.",
+ "分析规则已保存": "Analysis rules saved",
+ "分析规则保存失败": "Analysis rules could not be saved",
+ "官方服务": "Official services",
+ "聚合平台": "Aggregators",
+ "自定义兼容服务": "Custom compatible services",
+ "自定义兼容服务(文字)": "Custom compatible service (Text)",
+ "自定义兼容服务(图片与生成)": "Custom compatible service (Images and generation)",
+ "火山引擎": "Volcengine",
+ "Skill 提炼": "Skill extraction",
+ "创作规划": "Creative planning",
+ "视频分析": "Video analysis",
+ "图片生成": "Image generation",
+ "视频生成": "Video generation",
+ "配置": "Configure",
+ "编辑配置": "Edit configuration",
+ "刷新模型": "Refresh models",
+ "更换": "Change",
+ "尚未分配": "Not assigned",
+ "模型未填写": "Model not specified",
+ "已分配服务不存在": "The assigned service no longer exists",
+ "已连接": "Connected",
+ "尚未连接": "Not connected",
+ "API Key 已保存,尚未确认发送授权": "API key saved; sending permission not yet confirmed",
+ "模型目录未读取": "Model catalog not loaded",
+ "模型目录读取失败:{error};保留 {count} 个模型{unavailable}": "Model catalog load failed: {error}; keeping {count} models{unavailable}",
+ ",其中 {count} 个下架或当前不可用": ", including {count} retired or currently unavailable",
+ "模型目录已读取 · {count} 个模型 · 尚未执行模型调用验证{unavailable}": "Model catalog loaded · {count} models · model execution not yet verified{unavailable}",
+ " · {count} 个下架或当前不可用": " · {count} retired or currently unavailable",
+ "(已下架或当前不可用)": " (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.",
+ "这里设置全局默认;创作台中的本轮切换不会改动此处。": "Set the global default here. Switching a model for one Composer run does not change this setting.",
+ "模型": "Model",
+ "保存任务默认": "Save task default",
+ "请选择或填写模型": "Select or enter a model",
+ "任务默认保存失败": "The task default could not be saved",
+ "{task}默认模型已保存": "Default model saved for {task}",
+ "编辑服务": "Edit service",
+ "图片分析 API Key": "Image-analysis API key",
+ "图片分析 API Key(米醋 vip_2,只用于看图)": "Image-analysis API key (Micu vip_2; vision only)",
+ "图片生成 API Key(米醋 vip_2_image,需单独创建)": "Image-generation API key (create a separate Micu vip_2_image key)",
+ "图片生成 API Key(可与分析 Key 不同)": "Image-generation API key (may differ from the analysis key)",
+ "已保存;留空保持不变": "Saved; leave blank to keep it unchanged",
+ "粘贴服务商提供的 API Key": "Paste the API key from the service provider",
+ "这把 Key 只用于图片分析,不会发送给最终生图接口。": "This key is used only for image analysis and is never sent to the final image-generation endpoint.",
+ "已保存{hint};留空保持不变": "Saved{hint}; leave blank to keep it unchanged",
+ "(尾号 {hint})": " (ending in {hint})",
+ "粘贴米醋 vip_2_image 分组 Key": "Paste the Micu vip_2_image group key",
+ "留空则复用上方 API Key": "Leave blank to reuse the API key above",
+ "留空会保留已保存的生图 Key。模型目录可见不等于已获得 Image2 生图分组授权,最终以米醋生成接口返回为准。": "Leaving this blank keeps the saved generation key. Catalog visibility does not prove Image2 generation-group access; the Micu generation endpoint is authoritative.",
+ "图片分析接口(高级)": "Image-analysis endpoint (Advanced)",
+ "接口地址(高级)": "Endpoint URL (Advanced)",
+ "兼容协议(高级)": "Compatible protocol (Advanced)",
+ "服务原生协议": "Service-native protocol",
+ "{task}模型(高级)": "{task} model (Advanced)",
+ "图片生成协议(高级)": "Image-generation protocol (Advanced)",
+ "不启用图片生成": "Disable image generation",
+ "OpenAI Responses 生图工具": "OpenAI Responses image-generation tool",
+ "图片生成接口(高级)": "Image-generation endpoint (Advanced)",
+ "多图参考 / 编辑接口(高级)": "Multi-image reference / edit endpoint (Advanced)",
+ "此服务支持的图片尺寸(能力声明,不是本轮输出值)": "Supported image sizes (capability declaration, not this run's output)",
+ "此服务支持的质量选项(能力声明,不是本轮输出值)": "Supported quality options (capability declaration, not this run's output)",
+ "我确认:主动使用 {provider} 时发送本次任务所需内容": "I confirm that content required for this task is sent when I explicitly use {provider}",
+ "官方服务通常只需填写 API Key。账号专属模型与兼容服务连接参数位于高级连接。": "Official services usually require only an API key. Account-specific models and compatible-service connection settings are under Advanced connection.",
+ "保存配置": "Save configuration",
+ "高级连接": "Advanced connection",
+ "仅在接口地址、协议或模型发生变化时修改": "Change these only when the endpoint, protocol, or model changes",
+ "填入米醋个人中转预设": "Fill Micu personal relay preset",
+ "米醋 gpt-image-2 需要单独的 vip_2_image 分组 Key,不能复用上方文字 / 分析 Key": "Micu gpt-image-2 requires a separate vip_2_image group key; the text / analysis key above cannot be reused",
+ "没有获得新增 AI 服务的访问权限,设置未保存": "Permission to access the AI service was not granted. Settings were not saved.",
+ "米醋图片生成 Key 的模型目录检查失败": "The Micu image-generation key failed the model-catalog check",
+ "AI 服务配置保存失败": "The AI service configuration could not be saved",
+ "配置已保存": "Configuration saved",
+ "模型目录中可见 {model};这只证明目录可见,不代表米醋已授权该 Key 进入生图分组": "{model} is visible in the model catalog. This proves catalog visibility only; it does not prove that Micu authorized this key for the image-generation group.",
+ "{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)",
+ "请先保存该厂商的 API Key": "Save this provider's API key first",
+ "正在读取…": "Loading…",
+ "目录服务暂时不可用": "The catalog service is temporarily unavailable",
"无法应用分析结果": "The analysis result could not be applied",
"无法生成重分析预览": "Could not create the reanalysis preview"
});
@@ -1189,6 +1462,8 @@ export function translateUiMessage(value) {
[/^已拆分为 (\d+) 个独立案例$/, "Split into $1 separate cases"],
[/^(\d+) 条案例 \/ (\d+) 张截图$/, "$1 cases / $2 screenshots"],
[/^选择案例:(.+)$/, "Select case: $1"],
+ [/^还有 (\d+) 张参考图既没有案例提示词,也没有有效分析文字,暂时必须带原图$/, "$1 reference images have neither a case prompt nor valid analysis text, so their originals are still required"],
+ [/^还有 (\d+) 张参考图既没有案例提示词,也没有有效分析文字,不能关闭原图$/, "$1 reference images have neither a case prompt nor valid analysis text, so original images cannot be disabled"],
[/^查看案例:(.+)$/, "View case: $1"],
[/^(.+) 对应画面$/, "Visual for $1"],
[/^(.+) 完整截图$/, "Full screenshot for $1"],
diff --git a/library-model.js b/library-model.js
index 39431d2..14d8e83 100644
--- a/library-model.js
+++ b/library-model.js
@@ -91,13 +91,33 @@ export function entrySourceMetadataRows(entry = {}, sourceLabel = "来源") {
const descriptors = [];
const fields = [];
const seen = new Set();
+ const english = sourceLabel === "Source";
+ const labels = english
+ ? { provider: "Provider", itemId: "Work ID", author: "Author", handle: "Account", publishedAt: "Published", model: "Model", dimensions: "Dimensions", favorites: "Favorites", likes: "Likes", uses: "Uses", views: "Views", shares: "Shares" }
+ : { provider: "来源", itemId: "作品 ID", author: "作者", handle: "账号", publishedAt: "发布时间", model: "模型", dimensions: "尺寸", favorites: "收藏", likes: "点赞", uses: "使用", views: "浏览", shares: "分享" };
+ const addField = (label, value) => {
+ const text = String(value ?? "").trim();
+ const key = `${label}\n${text}`;
+ if (!label || !text || seen.has(key)) return;
+ seen.add(key);
+ fields.push({ label, value: text });
+ };
+ const sourceFacts = entry.sourceFacts && typeof entry.sourceFacts === "object" ? entry.sourceFacts : {};
+ for (const name of ["provider", "itemId", "author", "handle", "publishedAt", "model", "dimensions"]) {
+ addField(labels[name], sourceFacts[name]);
+ }
+ for (const [name, amount] of Object.entries(sourceFacts.engagement || {})) {
+ if (Number.isFinite(Number(amount)) && Number(amount) >= 0) addField(labels[name] || name, String(amount));
+ }
for (const value of entry.metadataLabels ?? []) {
const text = String(value ?? "").trim();
- if (!text || seen.has(text)) continue;
- seen.add(text);
+ if (!text) continue;
const match = text.match(/^([^::]{1,24})[::]\s*(.+)$/);
- if (match) fields.push({ label: match[1].trim(), value: match[2].trim() });
- else descriptors.push(text);
+ if (match) addField(match[1].trim(), match[2].trim());
+ else if (!seen.has(text)) {
+ seen.add(text);
+ descriptors.push(text);
+ }
}
return [
...(descriptors.length ? [{ label: sourceLabel, value: descriptors.join(" · ") }] : []),
@@ -123,8 +143,20 @@ export function entrySearchText(entry, catalogValue, nodeByIdValue) {
const node = nodeById.get(item.nodeId);
return node ? [node.name, ...node.aliases] : [];
});
+ const sourceFacts = entry.sourceFacts && typeof entry.sourceFacts === "object" ? entry.sourceFacts : {};
+ const sourceFactValues = [
+ sourceFacts.provider,
+ sourceFacts.itemId,
+ sourceFacts.author,
+ sourceFacts.handle,
+ sourceFacts.publishedAt,
+ sourceFacts.model,
+ sourceFacts.dimensions,
+ ...Object.entries(sourceFacts.engagement || {}).flatMap(([key, value]) => [key, value])
+ ];
return [
entry.title, entry.text, entry.url, ...tags, ...(entry.customLabels ?? []), ...(entry.metadataLabels ?? []),
+ ...sourceFactValues,
...visualDescriptions(entry),
...(entry.negativeTerms ?? []), ...(entry.legacyFacetCandidates ?? []),
...(entry.timeNotes ?? []).map((note) => note.text),
diff --git a/library-package.js b/library-package.js
index df4209a..f1dfe9e 100644
--- a/library-package.js
+++ b/library-package.js
@@ -12,6 +12,7 @@ import { expandLogicalCaseIds, normalizeCompoundCases } from "./compound-cases.j
import { isFixedTagTree, migrateLegacyFacetState } from "./tag-taxonomy.js";
import { migrateLibraryState } from "./migration.js";
import { LIBRARY_PACKAGE_FORMAT, isSupportedLibraryPackageVersion } from "./library-package-format.js";
+import { remapArticleDocumentAssets } from "./article-document.js";
export function parseLibraryPackage(value, files = new Map(), limitsValue = {}) {
const limits = portableLibraryLimits(limitsValue);
@@ -355,6 +356,7 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
return { ...visual, id: targetVisualId };
});
entry.primaryMediaId = visualIdMap[entry.primaryMediaId] ?? entry.primaryMediaId;
+ entry.articleDocument = remapArticleDocumentAssets(entry.articleDocument, visualIdMap);
entry.mediaAssets = entry.mediaAssets.map((asset) => ({
...asset,
...(asset.posterAssetId ? { posterAssetId: visualIdMap[asset.posterAssetId] ?? asset.posterAssetId } : {}),
diff --git a/library.css b/library.css
index d65325e..0d7d286 100644
--- a/library.css
+++ b/library.css
@@ -105,6 +105,16 @@ body[data-library-state="ready"] > .library-loading { display: none; }
box-shadow: var(--shadow);
}
.data-safety-dialog::backdrop { background: rgba(0, 0, 0, 0.62); }
+.share-dialog { width: min(460px, calc(100vw - 28px)); }
+.share-dialog-body { display: grid; gap: 14px; }
+.share-dialog-meta { margin: 0; color: var(--muted); font-size: var(--ui-meta-size); }
+.share-dialog-options { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
+.share-dialog-options button { display: inline-flex; min-width: 0; align-items: center; justify-content: center; gap: 7px; }
+.share-dialog-options .ui-icon { width: 16px; height: 16px; }
+.share-dialog-disclosure { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: var(--ui-meta-size); }
+.share-dialog-disclosure input { width: 16px; height: 16px; accent-color: var(--ui-accent); }
+.share-dialog-result { display: grid; gap: 10px; border-top: 1px solid var(--line); padding-top: 14px; }
+.share-dialog-result > div { display: flex; gap: 8px; }
.data-safety-header { display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--line); padding: 16px 18px; }
.data-safety-header h2 { margin: 2px 0 0; font-size: 18px; }
.data-safety-body { display: grid; gap: 12px; padding: 18px; }
@@ -282,9 +292,6 @@ button[aria-busy="true"] { cursor: progress; }
.gallery-heading strong { color: var(--ink); }
.project-selection-actions { display: flex; flex: 1 1 auto; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 7px; }
.project-selection-count { margin-right: auto; color: var(--muted); font-size: 11px; font-weight: 700; }
-#feedback { position: fixed; z-index: 90; right: 18px; bottom: 18px; max-width: min(360px, calc(100vw - 36px)); margin: 0; border: 1px solid var(--selection-edge); border-radius: 9px; padding: 9px 12px; color: var(--ink); background: var(--card); box-shadow: var(--shadow); font-size: 12px; pointer-events: none; }
-#feedback:empty { display: none; }
-#feedback.error { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 36%, var(--line)); }
.masonry { position: relative; width: 100%; overflow-anchor: none; --masonry-card-min-width: 270px; --masonry-gap: var(--visual-wall-gap); }
.case-card { position: absolute; display: block; margin: 0; overflow: hidden; color: var(--ink); border: 0; border-radius: var(--visual-card-radius); background: var(--card); cursor: pointer; }
.case-card:hover { box-shadow: 0 8px 20px color-mix(in srgb, var(--ink) 10%, transparent); }
@@ -664,7 +671,7 @@ button[aria-busy="true"] { cursor: progress; }
.analysis-settings-subgroup { display: grid; gap: 10px; border: 1px solid var(--line); border-radius: 14px; padding: 14px; background: var(--subtle-card); }
.section-heading-tight { padding: 0; }
.compatibility-settings-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
-.vision-compatible-help { grid-column: 1 / -1; display: flex; align-items: center; gap: 10px; color: var(--muted); font-size: 11px; font-weight: 700; }
+.vision-compatible-help { grid-column: 1 / -1; display: flex; flex-wrap: wrap; align-items: center; gap: 10px; min-width: 0; color: var(--muted); font-size: 11px; font-weight: 700; }
.vision-compatible-help button { flex: none; }
.analysis-settings-form .ai-consent { display: grid; grid-template-columns: auto 1fr; }
.task-option { display: grid; grid-template-columns: auto 1fr; align-items: start; gap: 10px; border: 1px solid var(--line); border-radius: 7px; padding: 10px 12px; color: var(--ink); background: var(--subtle-card); }
@@ -854,6 +861,37 @@ button[aria-busy="true"] { cursor: progress; }
.pdf-page-viewport canvas { display: block; max-width: none; margin: 0 auto; background: #fff; box-shadow: 0 8px 24px rgba(0,0,0,.24); }
.document-text-reader { width: 100%; border: 1px solid var(--line); border-radius: 10px; padding: 18px; background: var(--raised); }
.document-text-reader pre { margin: 12px 0 0; overflow: auto; color: var(--ink); font: inherit; font-size: 13px; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; }
+.article-document-reader { display: grid; gap: 16px; padding: 22px; border-bottom: 1px solid var(--line); background: var(--card); }
+.article-document-reader h1, .article-document-reader h2, .article-document-reader h3, .article-document-reader h4, .article-document-reader h5, .article-document-reader h6 { margin: 12px 0 0; color: var(--ink); line-height: 1.35; }
+.article-document-reader p, .article-document-reader blockquote, .article-document-reader pre { margin: 0; color: var(--ink); font-size: 14px; line-height: 1.8; white-space: pre-wrap; overflow-wrap: anywhere; }
+.article-document-reader blockquote { border-left: 3px solid var(--line-strong); padding-left: 14px; color: var(--muted); }
+.article-document-reader pre { overflow: auto; border-radius: 8px; padding: 12px; background: var(--raised); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
+.article-document-media { display: grid; gap: 7px; margin: 0; }
+.article-document-image { display: block; max-width: 100%; max-height: 78dvh; margin: 0 auto; border-radius: 8px; object-fit: contain; cursor: zoom-in; }
+.article-document-media figcaption { color: var(--muted); font-size: 11px; line-height: 1.5; }
+.article-document-video .detail-video-wrap, .article-document-video .detail-video { width: 100%; }
+.article-document-resource { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; border: 1px solid var(--line); border-radius: 8px; padding: 12px; background: var(--raised); }
+.article-document-resource-type { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 7px; color: var(--accent); background: var(--accent-soft); font-size: 10px; font-weight: 850; }
+.article-document-resource small { grid-column: 2 / -1; color: var(--muted); }
+.article-media-library { padding: 16px 22px; border-bottom: 1px solid var(--line); }
+.article-media-library > summary { cursor: pointer; font-size: 12px; font-weight: 800; }
+.article-media-library > .detail-visual-gallery { margin-top: 12px; }
+.captured-post-view { display: grid; gap: 14px; padding: 20px 22px; border-bottom: 1px solid var(--line); background: var(--card); }
+.captured-post-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
+.captured-post-heading h3 { margin: 0; }
+.captured-post-heading small { color: var(--muted); }
+.captured-post-text { margin: 0; color: var(--ink); font-size: 15px; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; }
+.captured-post-editor { min-height: 180px; line-height: 1.7; }
+.captured-post-actions { display: flex; flex-wrap: wrap; gap: 8px; }
+.captured-post-media { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
+.compact-captured-media { display: grid; min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 9px; background: var(--raised); }
+.compact-captured-media > img { display: block; width: 100%; max-height: 420px; object-fit: contain; cursor: zoom-in; }
+.compact-media-link { position: relative; display: grid; min-height: 116px; place-items: center; overflow: hidden; padding: 14px; color: var(--ink); text-align: center; text-decoration: none; }
+.compact-media-link img { position: absolute; width: 100%; height: 100%; object-fit: cover; inset: 0; }
+.compact-media-link img + strong { position: relative; z-index: 1; border-radius: 999px; padding: 8px 12px; color: #fff; background: rgba(0, 0, 0, .72); }
+.unplaced-media-section { display: grid; gap: 10px; }
+.unplaced-media-section h3, .unplaced-media-section p { margin: 0; }
+.unplaced-media-shelf { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 8px; }
.markdown-reader { color: var(--ink); font-size: 13px; line-height: 1.75; overflow-wrap: anywhere; }
.markdown-reader > :first-child { margin-top: 12px; }
.markdown-reader h1, .markdown-reader h2, .markdown-reader h3, .markdown-reader h4, .markdown-reader h5, .markdown-reader h6 { margin: 1.35em 0 .55em; line-height: 1.3; }
diff --git a/library.html b/library.html
index 737adef..70030f0 100644
--- a/library.html
+++ b/library.html
@@ -97,7 +97,7 @@
<button id="project-selection-save" type="button" data-i18n="保存项目案例">保存项目案例</button>
</div>
</div>
- <p id="feedback" role="status"></p>
+ <p id="feedback" class="ui-feedback-toast" role="status" aria-live="polite"></p>
<section id="case-list" class="masonry" aria-live="polite"></section>
<div id="load-sentinel" class="load-sentinel" aria-hidden="true"></div>
<button id="load-more" class="button-secondary load-more" type="button" hidden></button>
@@ -121,6 +121,25 @@
<div><strong>松开以检查本机资料</strong><span>导入前可确认项目、重复项和画面分析</span></div>
</div>
+ <dialog id="share-dialog" class="data-safety-dialog share-dialog" aria-labelledby="share-dialog-title">
+ <header class="data-safety-header">
+ <div><p class="eyebrow">SHARE CASES</p><h2 id="share-dialog-title" data-i18n="分享案例">分享案例</h2></div>
+ <button id="share-dialog-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>
+ <div class="data-safety-body share-dialog-body">
+ <p id="share-dialog-meta" class="share-dialog-meta"></p>
+ <div id="share-dialog-options" class="share-dialog-options">
+ <button id="share-dialog-export" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-download"></use></svg><span data-i18n="导出分享包">导出分享包</span></button>
+ <button id="share-dialog-submit" type="button" disabled><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-upload"></use></svg><span data-i18n="投稿到精选">投稿到精选</span></button>
+ </div>
+ <label class="share-dialog-disclosure"><input id="share-dialog-disclosure" type="checkbox" /><span data-i18n="我确认素材将公开上传到 GitHub 审核队列">我确认素材将公开上传到 GitHub 审核队列</span></label>
+ <section id="share-dialog-result" class="share-dialog-result" hidden>
+ <strong id="share-dialog-result-text"></strong>
+ <div><button id="share-dialog-show-files" class="button-secondary" type="button" data-i18n="显示投稿文件">显示投稿文件</button><button id="share-dialog-open-form" type="button" data-i18n="打开投稿表单">打开投稿表单</button></div>
+ </section>
+ </div>
+ </dialog>
+
<dialog id="import-dialog" class="data-safety-dialog import-dialog" aria-labelledby="import-dialog-title">
<header class="data-safety-header">
<div><p class="eyebrow">LOCAL IMPORT</p><h2 id="import-dialog-title">确认导入</h2></div>
@@ -275,15 +294,15 @@
</section>
<section id="settings-ai-panel" class="settings-panel settings-ai-panel" data-settings-panel="ai" hidden>
<section class="ai-routing-card">
- <div class="ai-routing-heading"><h3>AI 任务配置</h3><p id="ai-routing-summary">先按任务选择默认服务;API Key 只需在连接服务时填写一次。</p></div>
+ <div class="ai-routing-heading"><h3 data-i18n="AI 任务配置">AI 任务配置</h3><p id="ai-routing-summary">先按任务选择默认服务;API Key 只需在连接服务时填写一次。</p></div>
<div class="ai-routing-regions">
- <section class="ai-task-region"><h4>各任务默认模型</h4><div id="ai-assignment-list" class="ai-assignment-list"></div></section>
- <section><h4>已连接服务</h4><div id="ai-provider-list" class="ai-provider-list"></div></section>
+ <section class="ai-task-region"><h4 data-i18n="各任务默认模型">各任务默认模型</h4><div id="ai-assignment-list" class="ai-assignment-list"></div></section>
+ <section><h4 data-i18n="AI 服务">AI 服务</h4><div id="ai-provider-list" class="ai-provider-list"></div></section>
</div>
- <button id="open-ai-routing" type="button">添加 AI 服务</button>
+ <button id="open-ai-routing" type="button" data-i18n="连接 AI 服务">连接 AI 服务</button>
</section>
<details class="ai-advanced-settings">
- <summary><strong>分析规则与高级连接</strong><span>用于调整分析规则、本机模型或第三方兼容接口</span></summary>
+ <summary><strong data-i18n="分析规则与创作方法(高级)">分析规则与创作方法(高级)</strong><span data-i18n="只管理分析规则和创作方法;服务连接与模型分配均在上方完成。">只管理分析规则和创作方法;服务连接与模型分配均在上方完成。</span></summary>
<div class="ai-advanced-settings-body">
<div class="analysis-kind-tabs" role="tablist" aria-label="分析类型" data-i18n-aria-label="分析类型">
<button type="button" data-analysis-kind="text" aria-selected="true" data-i18n="文字标签">文字标签</button>
@@ -300,18 +319,8 @@
</section>
<div class="analysis-rule-actions"><button id="restore-analysis-default" class="button-secondary" type="button" data-i18n="恢复默认">恢复默认</button></div>
<div class="analysis-protocol"><strong data-i18n="固定输入与输出协议">固定输入与输出协议</strong><p id="analysis-protocol"></p></div>
- <label><span>AI 服务</span><select id="text-ai-provider"><option value="deepseek">DeepSeek API</option><option value="compatible">OpenAI-compatible / 本机</option></select></label>
- <div class="analysis-model-fields">
- <label class="text-deepseek-field">API Key<input id="deepseek-api-key" type="password" autocomplete="off" placeholder="已配置时可留空" data-i18n-placeholder="已配置时可留空" /></label>
- <label class="text-deepseek-field"><span data-i18n="批量分析模型">批量分析模型</span><input id="deepseek-analysis-model" value="deepseek-v4-flash" /></label>
- <label class="text-compatible-field" hidden><span>兼容接口</span><input id="text-compatible-endpoint" type="url" placeholder="http://localhost:1234/v1/chat/completions" /></label>
- <label class="text-compatible-field" hidden><span>模型</span><input id="text-compatible-model" list="vision-compatible-models" /></label>
- <label class="text-compatible-field" hidden><span>API Key(本机可留空)</span><input id="text-compatible-api-key" type="password" autocomplete="off" /></label>
- </div>
- <div class="analysis-rule-actions text-compatible-field" hidden><button id="text-local-preset" class="button-secondary" type="button">LM Studio 本机模式</button><button id="test-text-ai-service" class="button-secondary" type="button">测试并读取模型</button></div>
- <label class="ai-consent"><input id="deepseek-consent" type="checkbox" /><span>我了解:只有主动分析或创作时,所选案例文字才会发送到当前选择的 AI 服务。</span></label>
<label class="ai-consent"><input id="show-analysis-diagnostics" type="checkbox" /><span data-i18n="显示故障诊断(仅排查问题时开启)">显示故障诊断(仅排查问题时开启)</span></label>
- <div class="analysis-settings-actions"><button type="submit" data-i18n="保存分析设置">保存分析设置</button><button id="clear-api-key" class="button-secondary" type="button" data-i18n="清除本地 API Key">清除本地 API Key</button></div>
+ <div class="analysis-settings-actions"><button type="submit" data-i18n="保存分析规则">保存分析规则</button></div>
<p id="ai-settings-status"></p>
</form>
<form id="composer-settings-form" class="analysis-settings-form" data-analysis-kind-panel="composer" hidden>
@@ -342,7 +351,7 @@
</details>
</form>
<form id="vision-settings-form" class="analysis-settings-form" data-analysis-kind-panel="vision" hidden>
- <div class="section-heading"><div><h3 data-i18n="图片视觉分析">图片视觉分析</h3><p data-i18n="可以主动分析单张图片,也可以在导入后自动分析全部内容图。">可以主动分析单张图片,也可以在导入后自动分析全部内容图。</p></div></div>
+ <div class="section-heading"><div><h3 data-i18n="图片视觉分析规则">图片视觉分析规则</h3><p data-i18n="这里只管理图片分析规则;服务连接与默认模型在上方配置。">这里只管理图片分析规则;服务连接与默认模型在上方配置。</p></div></div>
<section data-analysis-locale-panel="zh-CN">
<label><span data-i18n="中文图片分析规则">中文图片分析规则</span><textarea id="vision-instructions-zh" rows="10"></textarea></label>
</section>
@@ -351,31 +360,7 @@
</section>
<div class="analysis-rule-actions"><button id="restore-vision-default" class="button-secondary" type="button" data-i18n="恢复默认">恢复默认</button></div>
<div class="analysis-protocol"><strong data-i18n="固定输入与输出协议">固定输入与输出协议</strong><p id="vision-protocol"></p></div>
- <label><span data-i18n="图片分析服务">图片分析服务</span><select id="vision-provider"><option value="openai">OpenAI</option><option value="compatible" data-i18n="兼容接口">兼容接口</option></select></label>
- <div id="vision-openai-fields" class="analysis-model-fields">
- <label>OpenAI API Key<input id="vision-openai-api-key" type="password" autocomplete="off" placeholder="已配置时可留空" data-i18n-placeholder="已配置时可留空" /></label>
- <label><span data-i18n="图片分析模型">图片分析模型</span><input id="vision-openai-model" value="gpt-5-mini" /></label>
- <label><span data-i18n="视频生成模型">视频生成模型</span><input id="vision-openai-video-model" placeholder="按账号已开通模型填写" data-i18n-placeholder="按账号已开通模型填写" /></label>
- <label><span data-i18n="视频尺寸选项">视频尺寸选项</span><input id="vision-openai-video-sizes" placeholder="用逗号分隔服务支持值" data-i18n-placeholder="用逗号分隔服务支持值" /></label>
- <label><span data-i18n="视频时长选项">视频时长选项</span><input id="vision-openai-video-durations" placeholder="用逗号分隔服务支持值" data-i18n-placeholder="用逗号分隔服务支持值" /></label>
- </div>
- <div id="vision-compatible-fields" class="analysis-settings-group" hidden>
- <div class="analysis-settings-subgroup">
- <div class="section-heading section-heading-tight"><div><h3 data-i18n="分析能力">分析能力</h3><p data-i18n="只配置看图分析与多模态输入所需连接。">只配置看图分析与多模态输入所需连接。</p></div></div>
- <div class="compatibility-settings-grid">
- <label><span data-i18n="兼容协议">兼容协议</span><select id="vision-compatible-protocol"><option value="responses">OpenAI Responses</option><option value="chat_completions">Chat Completions</option></select></label>
- <label><span>兼容接口地址(本机可用 HTTP)</span><input id="vision-compatible-endpoint" type="url" placeholder="https://www.micuapi.ai/v1/responses" /></label>
- <label>API Key<input id="vision-compatible-api-key" type="password" autocomplete="off" placeholder="已配置时可留空" data-i18n-placeholder="已配置时可留空" /></label>
- <label><span data-i18n="图片分析模型">图片分析模型</span><input id="vision-compatible-model" list="vision-compatible-models" /><datalist id="vision-compatible-models"></datalist></label>
- </div>
- <p id="vision-compatible-target" class="field-note"></p>
- <div class="vision-compatible-help"><button id="vision-local-preset" class="button-secondary" type="button">LM Studio 本机模式</button><button id="test-vision-service" class="button-secondary" type="button">测试连接并读取模型</button><button id="vision-micu-preset" class="button-secondary" type="button" data-i18n="填入米醋设置">填入米醋设置</button><span>本机服务不要求 Key;远程和局域网服务应配置认证。</span></div>
- </div>
- </div>
- <label class="ai-consent"><input id="vision-consent" type="checkbox" /><span>我了解:主动分析时发送当前内容图;多模态创作时发送本轮手选内容图、对应原提示词和创作要求。</span></label>
- <label class="ai-consent"><input id="vision-auto-analyze-imports" type="checkbox" /><span data-i18n="导入案例或加入新图片后,自动分析全部尚未分析的内容图(会产生服务费用)。">导入案例或加入新图片后,自动分析全部尚未分析的内容图(会产生服务费用)。</span></label>
- <p class="privacy-note" data-i18n="OpenAI API 数据默认不用于训练,除非用户主动选择共享;滥用监控日志可能保留最多 30 天,图片会执行安全扫描。兼容服务的数据处理规则由对应服务商决定。">OpenAI API 数据默认不用于训练,除非用户主动选择共享;滥用监控日志可能保留最多 30 天,图片会执行安全扫描。兼容服务的数据处理规则由对应服务商决定。</p>
- <div class="analysis-settings-actions"><button type="submit" data-i18n="保存图片分析设置">保存图片分析设置</button><button id="clear-vision-api-key" class="button-secondary" type="button" data-i18n="清除所选 API Key">清除所选 API Key</button></div>
+ <div class="analysis-settings-actions"><button type="submit" data-i18n="保存分析规则">保存分析规则</button></div>
<p id="vision-settings-status"></p>
</form>
</div>
diff --git a/library.js b/library.js
index d6e3ce7..faf8862 100644
--- a/library.js
+++ b/library.js
@@ -44,8 +44,7 @@ import {
analyzeTextDetailedWithDeepSeek,
isRetryableDeepSeekError,
normalizeAiSettings,
- organizeDetailTagsWithDeepSeek,
- permissionPatternForAiSettings
+ organizeDetailTagsWithDeepSeek
} from "./deepseek.js";
import { runAnalysisClaimsIndependently } from "./analysis-runner.js";
import {
@@ -68,11 +67,10 @@ import {
import { createStableMasonry } from "./stable-masonry.js";
import {
DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE,
- DEFAULT_VISION_MODEL,
- MICU_DEFAULT_CHAT_MODEL,
+ MICU_IMAGE_EDITS_ENDPOINT,
+ MICU_IMAGE_GENERATIONS_ENDPOINT,
MICU_RESPONSES_ENDPOINT,
normalizeVisionSettings,
- permissionPatternsForVisionSettings,
blobToDataUrl,
visionProtocolDescription
} from "./vision.js";
@@ -104,7 +102,6 @@ import { bindVideoHoverPreview } from "./video-hover-preview.js";
import { CONTENT_ROLES, CONTENT_TYPE_VISIBILITY, contentRoleForEntry } from "./taxonomy.js";
import { createUiIcon } from "./ui-icons.js";
import { confirmAppAction, promptAppText, showAppDialog } from "./ui-dialogs.js";
-import { normalizeAiTaskRoutes } from "./ai-task-routing.js";
import {
AI_ASSIGNMENT_TASKS,
availableAiProvidersForTask
@@ -130,6 +127,7 @@ import {
parseLibraryReturnSnapshot,
serializeLibraryReturnSnapshot
} from "./navigation-state.js";
+import { CURATED_SUBMISSION_URL } from "./curated-config.js";
const uiPreferences = await initializeUi();
bindUiPreferenceReload();
@@ -138,26 +136,25 @@ const libraryWindowId = (await chrome.windows.getCurrent()).id;
const elements = Object.fromEntries([
"about-version", "active-filter-badge", "add-folder", "add-media", "add-video-reference", "ai-settings-form", "ai-settings-status", "ai-routing-summary", "ai-provider-list", "ai-assignment-list", "open-ai-routing", "analysis-instructions-en", "analysis-instructions-zh", "analysis-protocol", "apply-reanalyze", "case-list", "cancel-library-maintenance",
- "clear-api-key", "clear-filters", "content-filters", "content-type-count", "content-type-name", "content-type-replacement", "content-type-replacement-field", "content-type-role", "content-type-role-help",
+ "clear-filters", "content-filters", "content-type-count", "content-type-name", "content-type-replacement", "content-type-replacement-field", "content-type-role", "content-type-role-help",
"content-type-list", "content-type-editor", "content-type-editor-title", "content-type-delete-transfer", "content-type-delete-message",
"add-content-type", "cancel-content-type-edit", "cancel-delete-content-type", "confirm-delete-content-type", "save-content-type",
"collection-filters", "create-collection",
"analysis-batch-summary", "analysis-diagnostics", "analysis-diagnostic-events", "analysis-progress", "analysis-progress-bar", "analysis-runtime-version", "apply-staged-analysis-rebuild", "batch-status-badge", "cancel-analysis-batch", "composer-agent-instruction", "composer-method-default-text", "composer-method-migration", "composer-method-version", "composer-settings-form", "composer-settings-status", "composer-task-key", "composer-task-method", "copy-analysis-diagnostics", "restore-composer-agent", "restore-composer-task", "save-composer-agent",
"creative-experiment-auto-analyze", "creative-experiment-enabled", "creative-experiment-status", "save-creative-experiment",
"creative-experiment-file", "export-creative-experiments", "import-creative-experiments",
- "create-node-form", "deepseek-analysis-model", "deepseek-api-key", "deepseek-consent", "delete-content-type", "detail-close", "detail-content", "detail-drawer", "detail-navigation", "detail-next",
+ "create-node-form", "delete-content-type", "detail-close", "detail-content", "detail-drawer", "detail-navigation", "detail-next",
"detail-prev", "drawer-backdrop", "drawer-toolbar", "empty-filter", "empty-library", "empty-state",
"facet-filters", "feedback", "filter-sidebar", "gallery-heading", "legacy-candidates", "library-summary",
"image-lightbox", "image-lightbox-close", "image-lightbox-image", "library-title", "load-more", "load-sentinel", "manage-facets", "manager-close", "manager-dialog", "manager-feedback",
"manager-pending", "manager-content-types", "manager-vocabulary", "new-node-aliases",
"new-node-name", "new-node-parent", "pending-count", "pending-filter",
- "add-quick-note", "organize-detail-tags", "organize-detail-status", "pause-analysis-batch", "pause-library-maintenance", "preview-analysis-batch", "preview-analysis-reanalyze", "preview-reanalyze", "reanalyze-preview", "result-count", "resume-analysis-batch", "resume-library-maintenance", "retry-analysis-failures", "retry-library-maintenance", "start-analysis-reanalyze", "text-ai-provider", "text-compatible-endpoint", "text-compatible-model", "text-compatible-api-key", "text-local-preset", "test-text-ai-service",
+ "add-quick-note", "organize-detail-tags", "organize-detail-status", "pause-analysis-batch", "pause-library-maintenance", "preview-analysis-batch", "preview-analysis-reanalyze", "preview-reanalyze", "reanalyze-preview", "result-count", "resume-analysis-batch", "resume-library-maintenance", "retry-analysis-failures", "retry-library-maintenance", "start-analysis-reanalyze",
"project-selection-actions", "project-selection-cancel", "project-selection-clear", "project-selection-count", "project-selection-save", "project-selection-select-all", "project-selection-select-filtered", "project-selection-title", "restore-analysis-default", "search-input", "selection-hint", "share-bar", "share-cancel", "share-count", "share-export", "start-analysis-batch", "start-compose", "toggle-filters", "undo-analysis-batch", "undo-facet", "vocabulary-facet", "workspace-library",
+ "share-dialog", "share-dialog-close", "share-dialog-title", "share-dialog-meta", "share-dialog-options", "share-dialog-export", "share-dialog-submit", "share-dialog-disclosure", "share-dialog-result", "share-dialog-result-text", "share-dialog-show-files", "share-dialog-open-form",
"add-menu", "export-path-setting", "media-file", "media-folder", "library-name-setting", "save-library-settings", "select-cases", "selection-add-project", "selection-new-project", "selection-combine", "selection-analyze", "selection-project-target", "open-settings", "settings-dialog", "settings-close",
"project-section", "selection-simple-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree", "maintenance-progress", "maintenance-progress-bar",
- "vision-auto-analyze-imports", "vision-compatible-api-key", "vision-compatible-endpoint", "vision-compatible-fields", "vision-compatible-model", "vision-compatible-protocol", "vision-compatible-target", "vision-consent",
- "vision-instructions-en", "vision-instructions-zh", "vision-openai-api-key", "vision-openai-fields", "vision-openai-model", "vision-openai-video-model", "vision-openai-video-sizes", "vision-openai-video-durations", "vision-provider",
- "vision-protocol", "vision-settings-form", "vision-settings-status", "vision-micu-preset", "vision-local-preset", "test-vision-service", "vision-compatible-models", "restore-vision-default", "clear-vision-api-key",
+ "vision-instructions-en", "vision-instructions-zh", "vision-protocol", "vision-settings-form", "vision-settings-status", "restore-vision-default",
"open-curated", "open-skills", "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",
"vision-batch-dialog", "vision-batch-close", "vision-batch-summary", "vision-batch-service", "vision-batch-all-images", "vision-batch-reanalyze",
@@ -214,12 +211,10 @@ let organizerState = { collections: [] };
let aiSettings = { configured: false, consent: false, analysisModel: "deepseek-v4-flash" };
let visionSettings = normalizeVisionSettings();
let aiServiceProfiles = { gemini: { configured: false, model: "" }, xai: { configured: false, textModel: "", imageModel: "", videoModel: "" } };
-let aiTaskRoutes = normalizeAiTaskRoutes();
let aiProviderRegistry = { version: 1, providers: {} };
let aiTaskAssignments = {};
let aiModelCatalogRefreshStarted = false;
let creativeExperimentSettings = { enabled: false, autoAnalyze: false };
-let privateVisionEndpoint = "";
let visionUndoEntryIds = new Set();
let visibleEntries = [];
let renderedCount = 0;
@@ -246,6 +241,8 @@ let activeVideoAnalysisUi = null;
let selectionMode = "";
let projectSelectionId = "";
const selectedCaseIds = new Set();
+let shareDialogContext = null;
+let submissionDownloadIds = [];
let analysisBatchJob = null;
let visionBatchJob = null;
let canUndoAnalysisBatch = false;
@@ -287,6 +284,8 @@ let activeImportJob = null;
let latestImportJob = null;
let importPollTimer = 0;
let importDragDepth = 0;
+let externalLibraryRefreshTimer = 0;
+let externalLibraryRefreshPending = false;
const mobileLayout = matchMedia("(max-width: 640px)");
if (mobileLayout.matches) workspace.classList.add("filters-collapsed");
@@ -314,6 +313,17 @@ window.addEventListener("scroll", () => {
scheduleLoadCheck();
scheduleVisibleMediaHydration();
}, { passive: true });
+chrome.storage.onChanged.addListener((changes, areaName) => {
+ if (areaName !== "local" || !["entries", "organizerState", "compoundCases"].some((key) => changes[key])) return;
+ externalLibraryRefreshPending = true;
+ scheduleExternalLibraryRefresh();
+});
+document.addEventListener("visibilitychange", () => {
+ if (!document.hidden && externalLibraryRefreshPending) scheduleExternalLibraryRefresh();
+});
+window.addEventListener("focus", () => {
+ if (externalLibraryRefreshPending) scheduleExternalLibraryRefresh();
+});
bindEvents();
renderAnalysisDiagnostics();
@@ -323,6 +333,7 @@ elements.uiMotion.value = uiPreferences.motion;
elements.showAnalysisDiagnostics.checked = uiPreferences.analysisDiagnostics;
elements.aboutVersion.textContent = `PromptDirector ${chrome.runtime.getManifest().version}`;
await refreshLibrary();
+await openRequestedLibraryTarget();
await resumeImportJob();
openRequestedSettings();
@@ -336,6 +347,16 @@ window.addEventListener("unload", () => {
for (const url of [...thumbnailUrls.values(), ...originalUrls.values(), ...documentPreviewUrls.values()]) URL.revokeObjectURL(url);
});
+function scheduleExternalLibraryRefresh() {
+ if (document.hidden || externalLibraryRefreshTimer) return;
+ externalLibraryRefreshTimer = window.setTimeout(async () => {
+ externalLibraryRefreshTimer = 0;
+ if (!externalLibraryRefreshPending) return;
+ externalLibraryRefreshPending = false;
+ await refreshLibrary();
+ }, 80);
+}
+
async function previewDeepSeekAnalysisBatch(mode = "incremental") {
const button = mode === "rebuild" ? elements.previewAnalysisReanalyze : elements.previewAnalysisBatch;
button.disabled = true;
@@ -536,6 +557,17 @@ function bindEvents() {
elements.startCompose.addEventListener("click", openComposerPage);
elements.shareCancel.addEventListener("click", exitSelectionMode);
elements.shareExport.addEventListener("click", completeSelection);
+ elements.shareDialogClose.addEventListener("click", closeShareDialog);
+ elements.shareDialog.addEventListener("click", (event) => {
+ if (event.target === elements.shareDialog) closeShareDialog();
+ });
+ elements.shareDialogDisclosure.addEventListener("change", () => {
+ elements.shareDialogSubmit.disabled = !elements.shareDialogDisclosure.checked;
+ });
+ elements.shareDialogExport.addEventListener("click", exportFromShareDialog);
+ elements.shareDialogSubmit.addEventListener("click", submitFromShareDialog);
+ elements.shareDialogShowFiles.addEventListener("click", showSubmissionFiles);
+ elements.shareDialogOpenForm.addEventListener("click", () => chrome.tabs.create({ url: CURATED_SUBMISSION_URL, active: true }));
elements.selectionCombine.addEventListener("click", saveCompoundSelection);
elements.selectionAddProject.addEventListener("click", addSelectionToProject);
elements.selectionNewProject.addEventListener("click", createProjectFromSelection);
@@ -628,73 +660,21 @@ function bindEvents() {
elements.resumeLibraryMaintenance.addEventListener("click", () => updateLibraryMaintenance("RESUME_LIBRARY_MAINTENANCE"));
elements.retryLibraryMaintenance.addEventListener("click", () => updateLibraryMaintenance("RETRY_LIBRARY_MAINTENANCE"));
elements.cancelLibraryMaintenance.addEventListener("click", () => updateLibraryMaintenance("CANCEL_LIBRARY_MAINTENANCE"));
- elements.aiSettingsForm.addEventListener("submit", async (event) => {
- event.preventDefault();
- const settingsValue = currentTextAiFormValue();
- try {
- const permission = permissionPatternForAiSettings(settingsValue);
- if (!await chrome.permissions.request({ origins: [permission] })) throw new Error("没有获得所选 AI 服务的访问权限");
- } catch (error) {
- return showFeedback(error.message, true);
- }
- await perform(elements.aiSettingsForm.querySelector("button"), {
- type: "UPDATE_AI_TEXT_PROVIDER",
- settings: settingsValue
- });
- elements.deepseekApiKey.value = "";
- elements.textCompatibleApiKey.value = "";
- });
+ elements.aiSettingsForm.addEventListener("submit", saveAiRulePreferences);
elements.openAiRouting.addEventListener("click", () => openAiProviderDialog());
- elements.textAiProvider.addEventListener("change", renderTextAiProviderFields);
- elements.textLocalPreset.addEventListener("click", () => {
- elements.textAiProvider.value = "compatible";
- elements.textCompatibleEndpoint.value = "http://localhost:1234/v1/chat/completions";
- elements.textCompatibleModel.value = "";
- renderTextAiProviderFields();
- });
- elements.testTextAiService.addEventListener("click", testTextAiService);
elements.restoreAnalysisDefault.addEventListener("click", () => {
const target = activeAnalysisLocale === "en" ? elements.analysisInstructionsEn : elements.analysisInstructionsZh;
target.value = DEFAULT_ANALYSIS_INSTRUCTIONS_BY_LOCALE[activeAnalysisLocale];
target.focus();
- showFeedback("已恢复编辑框默认内容,点击保存后生效");
+ showFeedback(t("已恢复编辑框默认内容,点击保存后生效"));
});
- elements.clearApiKey.addEventListener("click", () => perform(elements.clearApiKey, {
- type: "UPDATE_AI_TEXT_PROVIDER",
- settings: {
- ...currentTextAiFormValue(),
- clearApiKey: elements.textAiProvider.value === "compatible" ? "compatible" : "deepseek"
- }
- }));
- elements.visionProvider.addEventListener("change", renderVisionProviderFields);
- elements.visionCompatibleProtocol.addEventListener("change", renderVisionCompatibleEndpointHint);
- elements.visionCompatibleEndpoint.addEventListener("input", renderVisionCompatibleEndpointHint);
- elements.visionMicuPreset.addEventListener("click", () => {
- elements.visionProvider.value = "compatible";
- elements.visionCompatibleProtocol.value = "responses";
- elements.visionCompatibleEndpoint.value = MICU_RESPONSES_ENDPOINT;
- elements.visionCompatibleModel.value ||= MICU_DEFAULT_CHAT_MODEL;
- renderVisionProviderFields();
- renderVisionCompatibleEndpointHint();
- elements.visionCompatibleApiKey.focus();
- });
- elements.visionLocalPreset.addEventListener("click", () => {
- elements.visionProvider.value = "compatible";
- elements.visionCompatibleProtocol.value = "chat_completions";
- elements.visionCompatibleEndpoint.value = "http://localhost:1234/v1/chat/completions";
- elements.visionCompatibleModel.value = "";
- renderVisionProviderFields();
- elements.testVisionService.focus();
- });
- elements.testVisionService.addEventListener("click", testCompatibleVisionService);
- elements.visionSettingsForm.addEventListener("submit", saveVisionSettings);
+ elements.visionSettingsForm.addEventListener("submit", saveAiRulePreferences);
elements.restoreVisionDefault.addEventListener("click", () => {
const target = activeAnalysisLocale === "en" ? elements.visionInstructionsEn : elements.visionInstructionsZh;
target.value = DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE[activeAnalysisLocale];
target.focus();
- showFeedback("已恢复编辑框默认内容,点击保存后生效");
+ showFeedback(t("已恢复编辑框默认内容,点击保存后生效"));
});
- elements.clearVisionApiKey.addEventListener("click", clearSelectedVisionApiKey);
elements.previewAnalysisBatch.addEventListener("click", () => previewDeepSeekAnalysisBatch("incremental"));
elements.previewAnalysisReanalyze.addEventListener("click", () => previewDeepSeekAnalysisBatch("rebuild"));
elements.organizeDetailTags.addEventListener("click", organizeDetailTags);
@@ -787,7 +767,6 @@ async function refreshLibrary() {
aiSettings = response.aiSettings ?? aiSettings;
visionSettings = response.visionSettings ?? visionSettings;
aiServiceProfiles = response.aiServiceProfiles ?? aiServiceProfiles;
- aiTaskRoutes = normalizeAiTaskRoutes(response.aiTaskRoutes);
aiProviderRegistry = response.aiProviderRegistry ?? aiProviderRegistry;
aiTaskAssignments = response.aiTaskAssignments ?? aiTaskAssignments;
if (!aiModelCatalogRefreshStarted) {
@@ -833,11 +812,6 @@ async function refreshLibrary() {
updateCachedDocumentCards();
if (elements.searchInput.value.trim()) scheduleSearchRender();
}).catch(() => undefined);
- void chrome.runtime.sendMessage({ type: "GET_COMPOSER_AI_RUNTIME" }).then((response) => {
- if (!response?.ok) return;
- const privateSettings = normalizeVisionSettings(response.visionSettings);
- privateVisionEndpoint = privateSettings.compatible.endpoint;
- }).catch(() => undefined);
if (elements.managerDialog.open) renderManager();
if (elements.settingsDialog.open && activeSettingsTab === "tasks") renderBatchManager();
if (currentDetailId && logicalCases.some((entry) => entry.id === currentDetailId) && !promptEditState?.dirty) renderDetail();
@@ -1576,7 +1550,7 @@ function isVisionSelectableEntry(entry) {
}
function completeSelection() {
- return exportSharedCases();
+ return openShareDialog({ entryIds: [...selectedCaseIds], title: t("分享案例") });
}
async function addSelectionToProject() {
@@ -1695,36 +1669,88 @@ async function saveProjectSelection() {
}
}
-async function exportSharedCases() {
- elements.shareExport.disabled = true;
+async function shareProjectCollection(collection) {
+ const memberIds = new Set(collection.entryIds);
+ const count = entries.filter((entry) => memberIds.has(entry.id)).length;
+ openShareDialog({ collectionId: collection.id, title: collection.name, count });
+}
+
+function openShareDialog({ entryIds = [], collectionId = "", title = "", count = 0 } = {}) {
+ const selectedCount = count || entryIds.length;
+ if (!selectedCount) return showFeedback(t("请先选择要分享的案例"), true);
+ shareDialogContext = { entryIds, collectionId, title, count: selectedCount };
+ submissionDownloadIds = [];
+ elements.shareDialogTitle.textContent = title || t("分享案例");
+ elements.shareDialogMeta.textContent = t("{count} 个案例", { count: selectedCount });
+ elements.shareDialogDisclosure.checked = false;
+ elements.shareDialogSubmit.disabled = true;
+ elements.shareDialogExport.disabled = false;
+ elements.shareDialogResult.hidden = true;
+ elements.shareDialogOptions.hidden = false;
+ elements.shareDialog.showModal();
+ elements.shareDialogExport.focus();
+}
+
+function closeShareDialog() {
+ if (elements.shareDialog.open) elements.shareDialog.close();
+ shareDialogContext = null;
+ submissionDownloadIds = [];
+}
+
+async function exportFromShareDialog() {
+ if (!shareDialogContext) return;
+ elements.shareDialogExport.disabled = true;
try {
- const response = await chrome.runtime.sendMessage({ type: "EXPORT_ARCHIVE", entryIds: [...selectedCaseIds] });
- if (!response?.ok) throw new Error(response?.message || "无法导出分享包");
+ const message = shareDialogContext.collectionId
+ ? { type: "EXPORT_PROJECT", collectionId: shareDialogContext.collectionId }
+ : { type: "EXPORT_ARCHIVE", entryIds: shareDialogContext.entryIds };
+ const response = await chrome.runtime.sendMessage(message);
+ if (!response?.ok) throw new Error(response?.message || t("无法导出分享包"));
showFeedback(response.message);
- exitSelectionMode();
+ const selected = Boolean(shareDialogContext.entryIds.length);
+ closeShareDialog();
+ if (selected) exitSelectionMode();
} catch (error) {
- showFeedback(error.message, true);
- elements.shareExport.disabled = !selectedCaseIds.size;
+ showFeedback(error.message || t("无法导出分享包"), true);
+ elements.shareDialogExport.disabled = false;
}
}
-async function shareProjectCollection(collection) {
- const memberIds = new Set(collection.entryIds);
- const projectEntries = entries.filter((entry) => memberIds.has(entry.id));
- const imageCount = projectEntries.reduce((sum, entry) => sum + entryMediaAssets(entry).filter((asset) => asset.kind === "image" && asset.usage !== "poster").length, 0);
- const summary = currentLocale() === "en"
- ? `Export project “${collection.name}” with ${projectEntries.length} cases and ${imageCount} images?`
- : `导出项目“${collection.name}”?将包含 ${projectEntries.length} 个案例和 ${imageCount} 张图片。`;
- if (!await confirmAppAction({ title: t("导出项目?"), description: summary, confirmLabel: t("导出") })) return;
+async function submitFromShareDialog() {
+ if (!shareDialogContext || !elements.shareDialogDisclosure.checked) return;
+ elements.shareDialogSubmit.disabled = true;
+ elements.shareDialogExport.disabled = true;
+ const label = elements.shareDialogSubmit.querySelector("span");
+ const original = label.textContent;
+ label.textContent = t("正在生成投稿包");
try {
- const response = await chrome.runtime.sendMessage({ type: "EXPORT_PROJECT", collectionId: collection.id });
- if (!response?.ok) throw new Error(response?.message || "项目分享失败");
- showFeedback(response.message);
+ const response = await chrome.runtime.sendMessage({
+ type: "EXPORT_CURATED_SUBMISSION",
+ entryIds: shareDialogContext.entryIds,
+ collectionId: shareDialogContext.collectionId
+ });
+ if (!response?.ok) throw new Error(response?.message || t("无法生成精选投稿包"));
+ submissionDownloadIds = response.downloadIds ?? [];
+ elements.shareDialogResultText.textContent = response.partCount > 1
+ ? t("投稿包已生成,共 {count} 个分卷", { count: response.partCount })
+ : t("投稿包已生成");
+ elements.shareDialogResult.hidden = false;
+ elements.shareDialogOptions.hidden = true;
} catch (error) {
- showFeedback(error.message, true);
+ showFeedback(error.message || t("无法生成精选投稿包"), true);
+ elements.shareDialogSubmit.disabled = false;
+ elements.shareDialogExport.disabled = false;
+ } finally {
+ label.textContent = original;
}
}
+async function showSubmissionFiles() {
+ const downloadId = submissionDownloadIds.at(-1);
+ if (!Number.isInteger(downloadId)) return;
+ await chrome.downloads.show(downloadId);
+}
+
async function openComposerPage(collectionId = "") {
try {
const url = new URL(chrome.runtime.getURL("composer.html"));
@@ -1797,6 +1823,30 @@ function openRequestedSettings() {
history.replaceState(null, "", "library.html");
}
+async function openRequestedLibraryTarget() {
+ const params = new URLSearchParams(location.search);
+ const caseId = params.get("case") || "";
+ const projectId = params.get("project") || "";
+ if (!caseId && !projectId) return;
+ try { sessionStorage.removeItem(LIBRARY_RETURN_STORAGE_KEY); } catch {}
+ selectedContentId = "";
+ selectedFacets.clear();
+ elements.pendingFilter.checked = false;
+ elements.searchInput.value = "";
+ libraryReturnScrollY = null;
+ if (caseId && logicalCases.some((entry) => entry.id === caseId)) {
+ selectedCollectionId = "";
+ renderGallery();
+ await openDetail(caseId);
+ } else if (projectId && organizerState.collections.some((collection) => collection.id === projectId)) {
+ selectedCollectionId = projectId;
+ renderGallery();
+ } else {
+ showFeedback(caseId ? "保存的案例不存在" : "保存的项目不存在", true);
+ }
+ history.replaceState(null, "", "library.html");
+}
+
async function openVisionBatchConfirmation() {
if (!selectedCaseIds.size) return showFeedback("请先选择至少一个带图片的案例", true);
elements.visionBatchFeedback.textContent = "";
@@ -2784,8 +2834,10 @@ async function renderDetail() {
const content = document.createDocumentFragment();
const body = el("div", "detail-body");
const hasPrimaryMedia = entryHasMedia(entry);
- const usesStageNavigation = entryHasMedia(entry, "image") || entryHasMedia(entry, "video");
- elements.detailContent.classList.toggle("has-primary-media", hasPrimaryMedia);
+ const capturedPost = isCapturedPost(entry);
+ const hasArticleDocument = !capturedPost && Boolean(entry.articleDocument?.blocks?.length);
+ const usesStageNavigation = !capturedPost && !hasArticleDocument && (entryHasMedia(entry, "image") || entryHasMedia(entry, "video"));
+ elements.detailContent.classList.toggle("has-primary-media", hasPrimaryMedia && !hasArticleDocument && !capturedPost);
elements.detailContent.classList.toggle("is-compound-detail", Boolean(entry.compoundCase));
elements.drawerToolbar.classList.toggle("has-document-navigation", Boolean(entry.compoundCase) || !usesStageNavigation);
if (entry.compoundCase) {
@@ -2799,11 +2851,18 @@ async function renderDetail() {
const primary = el("div", "detail-primary");
if (usesStageNavigation) primary.append(elements.detailNavigation);
else elements.drawerToolbar.prepend(elements.detailNavigation);
- if (hasPrimaryMedia) primary.append(await createDetailMediaGallery(entry, { immersive: true }));
- else if (!entry.text?.trim()) primary.append(textEl("div", "detail-placeholder", "这条案例还没有内容"));
+ if (hasPrimaryMedia && !hasArticleDocument && !capturedPost) primary.append(await createDetailMediaGallery(entry, { immersive: true }));
+ else if (!entry.text?.trim() && !capturedPost) primary.append(textEl("div", "detail-placeholder", "这条案例还没有内容"));
body.append(createDetailHeader(entry));
+ if (capturedPost) {
+ body.append(await createCapturedPostView(entry));
+ } else if (hasArticleDocument) {
+ body.append(await createArticleDocumentReader(entry));
+ const unplacedMedia = await createUnplacedMediaShelf(entry);
+ if (unplacedMedia) body.append(unplacedMedia);
+ }
if (isEntryPending(entry)) body.append(createPendingReviewPanel(entry));
- const prompt = createPromptSection(entry);
+ const prompt = capturedPost ? null : createPromptSection(entry);
if (prompt) body.append(prompt);
const visionDescription = createVisionDescription(entry);
if (visionDescription) body.append(visionDescription);
@@ -3016,6 +3075,197 @@ function createCompoundOrganizer(entry) {
return details;
}
+function isCapturedPost(entry) {
+ return entry?.sourceFacts?.pageType === "post";
+}
+
+function articleReferencedAssetIds(entry) {
+ return new Set((entry?.articleDocument?.blocks || []).flatMap((block) => block.assetId ? [block.assetId] : []));
+}
+
+async function createCapturedPostView(entryValue) {
+ const entry = normalizeEntryMedia(entryValue);
+ const section = el("section", "captured-post-view");
+ const heading = el("div", "captured-post-heading");
+ const facts = [
+ entry.sourceFacts?.author,
+ entry.sourceFacts?.handle ? `@${entry.sourceFacts.handle}` : "",
+ entry.sourceFacts?.publishedAt ? formatDate(entry.sourceFacts.publishedAt) : ""
+ ].filter(Boolean).join(" · ");
+ heading.append(textEl("h3", "", "帖子文字"), rawTextEl("small", "", facts));
+ section.append(heading);
+ if (promptEditState?.entryId === entry.id && !promptEditState.assetId) {
+ const textarea = document.createElement("textarea");
+ textarea.className = "captured-post-editor";
+ textarea.value = promptEditState.draftText;
+ textarea.setAttribute("aria-label", "编辑帖子文字");
+ textarea.addEventListener("input", () => {
+ promptEditState.draftText = textarea.value;
+ promptEditState.dirty = textarea.value !== promptEditState.originalText;
+ });
+ const actions = el("div", "captured-post-actions");
+ const save = textEl("button", "", "保存文字");
+ const cancel = textEl("button", "button-secondary", "取消");
+ save.addEventListener("click", async () => {
+ save.disabled = true;
+ try {
+ const response = await chrome.runtime.sendMessage({
+ type: "UPDATE_ENTRY_TEXT",
+ entryId: entry.id,
+ text: textarea.value,
+ textRevision: entryTextRevision(entry)
+ });
+ if (!response?.ok) throw new Error(response?.message || "帖子文字保存失败");
+ promptEditState = null;
+ showFeedback(response.message);
+ await refreshLibrary();
+ } catch (error) {
+ showFeedback(error.message || "帖子文字保存失败", true);
+ save.disabled = false;
+ }
+ });
+ cancel.addEventListener("click", () => {
+ promptEditState = null;
+ renderDetail();
+ });
+ actions.append(save, cancel);
+ section.append(textarea, actions);
+ queueMicrotask(() => textarea.focus());
+ } else {
+ section.append(rawTextEl("p", "captured-post-text", entry.text || "这条帖子没有可显示的文字"));
+ const actions = el("div", "captured-post-actions");
+ const copy = textEl("button", "button-secondary", "复制文字");
+ const edit = textEl("button", "button-secondary", "编辑文字");
+ copy.disabled = !entry.text;
+ copy.addEventListener("click", () => copyTextWithFeedback(copy, entry.text, "帖子文字已复制", "浏览器未允许复制,请选中文字后复制"));
+ edit.addEventListener("click", () => {
+ promptEditState = { entryId: entry.id, assetId: "", originalText: entry.text || "", draftText: entry.text || "", dirty: false };
+ renderDetail();
+ });
+ actions.append(copy, edit);
+ section.append(actions);
+ }
+ const media = entry.mediaAssets.filter((asset) => asset.usage !== "poster");
+ if (media.length) {
+ const grid = el("div", "captured-post-media");
+ for (const asset of media) grid.append(await createCompactCapturedMedia(entry, asset, { post: true }));
+ section.append(grid);
+ }
+ return section;
+}
+
+async function createUnplacedMediaShelf(entryValue) {
+ const entry = normalizeEntryMedia(entryValue);
+ const referenced = articleReferencedAssetIds(entry);
+ const media = entry.mediaAssets.filter((asset) => asset.usage !== "poster" && !referenced.has(asset.id));
+ if (!media.length) return null;
+ const section = el("section", "detail-section unplaced-media-section");
+ section.append(textEl("h3", "", "未定位媒体"), textEl("p", "detail-helper", "这些媒体由你明确保存,但无法确认它们在原文中的位置。"));
+ const shelf = el("div", "unplaced-media-shelf");
+ for (const asset of media) shelf.append(await createCompactCapturedMedia(entry, asset));
+ section.append(shelf);
+ return section;
+}
+
+async function createCompactCapturedMedia(entry, asset, { post = false } = {}) {
+ const card = el("article", `compact-captured-media compact-captured-${asset.kind}`);
+ if (asset.kind === "image" && asset.storageMode === "managed") {
+ const image = document.createElement("img");
+ image.src = await originalScreenshotUrl(asset.id);
+ image.alt = asset.sourceTitle || entry.title;
+ image.loading = "lazy";
+ image.addEventListener("click", () => openImageLightbox(image, entry));
+ card.append(image);
+ } else if (asset.kind === "video") {
+ const poster = posterAssetForVideo(entry, asset);
+ const posterBlob = poster ? await getMediaBlob(poster.id) : null;
+ const link = el("a", "compact-media-link");
+ link.href = (post ? entry.url : "") || asset.reference?.url || asset.sourceUrl || entry.url || "#";
+ link.target = "_blank";
+ link.rel = "noopener noreferrer";
+ if (posterBlob) {
+ const image = document.createElement("img");
+ image.src = rememberDetailBlobUrl(posterBlob);
+ image.alt = `${entry.title} 视频封面`;
+ link.append(image);
+ }
+ link.append(rawTextEl("strong", "", post ? "打开原帖观看视频" : "打开视频来源"));
+ card.append(link);
+ } else {
+ const link = rawTextEl("a", "compact-media-link compact-document-link", asset.sourceTitle || "打开文档来源");
+ link.href = asset.sourceUrl || entry.url || "#";
+ link.target = "_blank";
+ link.rel = "noopener noreferrer";
+ card.append(link);
+ }
+ return card;
+}
+
+async function createArticleDocumentReader(entryValue) {
+ const entry = normalizeEntryMedia(entryValue);
+ const reader = el("article", "article-document-reader");
+ const assets = new Map(entry.mediaAssets.map((asset) => [asset.id, asset]));
+ for (const block of entry.articleDocument?.blocks || []) {
+ if (block.kind === "heading") {
+ reader.append(rawTextEl(`h${Math.min(6, Math.max(1, Number(block.level) || 2))}`, "", block.text));
+ continue;
+ }
+ if (["paragraph", "list", "quote", "code", "table"].includes(block.kind)) {
+ const tagName = block.kind === "quote" ? "blockquote" : block.kind === "code" || block.kind === "table" ? "pre" : "p";
+ const text = block.kind === "list" ? block.text.split("\n").map((item) => `• ${item}`).join("\n") : block.text;
+ reader.append(rawTextEl(tagName, block.kind === "table" ? "article-table-text" : "", text));
+ continue;
+ }
+ const asset = block.assetId ? assets.get(block.assetId) : null;
+ if (block.kind === "image") {
+ const figure = el("figure", "article-document-media");
+ if (asset?.kind === "image" && asset.storageMode === "managed") {
+ const image = document.createElement("img");
+ image.className = "article-document-image";
+ image.alt = block.label || entry.title;
+ image.src = await originalScreenshotUrl(asset.id);
+ image.loading = "lazy";
+ image.addEventListener("click", () => openImageLightbox(image, entry));
+ figure.append(image);
+ } else figure.append(articleSourceLink(block.sourceUrl, block.label || "打开原图"));
+ if (block.label) figure.append(rawTextEl("figcaption", "", block.label));
+ reader.append(figure);
+ continue;
+ }
+ if (block.kind === "video") {
+ const figure = el("figure", "article-document-media article-document-video");
+ if (asset?.kind === "video" && asset.storageMode !== "reference") figure.append(await createMediaViewer(asset, "", entry));
+ else if (asset?.kind === "video") figure.append(await createCompactCapturedMedia(entry, asset));
+ else figure.append(articleSourceLink(block.sourceUrl, block.label || "打开视频来源"));
+ if (block.label) figure.append(rawTextEl("figcaption", "", block.label));
+ reader.append(figure);
+ continue;
+ }
+ if (["document", "link"].includes(block.kind)) {
+ const card = el("div", "article-document-resource");
+ card.append(
+ rawTextEl("span", "article-document-resource-type", block.kind === "document" ? "DOC" : "LINK"),
+ rawTextEl("strong", "", block.label || asset?.sourceTitle || "文章资源")
+ );
+ const sourceUrl = block.sourceUrl || asset?.sourceUrl || "";
+ if (sourceUrl) card.append(articleSourceLink(sourceUrl, asset ? "打开来源" : "打开链接"));
+ if (asset?.kind === "document" && asset.storageMode === "managed") card.append(rawTextEl("small", "", "本地副本已保存在案例媒体中"));
+ reader.append(card);
+ }
+ }
+ return reader;
+}
+
+function articleSourceLink(urlValue, label) {
+ const url = String(urlValue || "");
+ if (!url) return rawTextEl("span", "detail-placeholder", "来源暂时不可用");
+ const link = rawTextEl("a", "button-secondary media-open-link", label);
+ link.href = url;
+ link.target = "_blank";
+ link.rel = "noopener noreferrer";
+ return link;
+}
+
async function createDetailMediaGallery(entryValue, { immersive = false } = {}) {
const normalizedEntry = normalizeEntryMedia(entryValue);
const entry = { ...normalizedEntry, mediaAssets: normalizedEntry.mediaAssets.filter((asset) => asset.usage !== "poster") };
@@ -3032,6 +3282,8 @@ async function createDetailMediaGallery(entryValue, { immersive = false } = {})
let activeIndex = Math.max(0, entry.mediaAssets.findIndex((asset) => asset.id === (activeDetailMediaIdByEntry.get(entry.id) || entry.primaryMediaId)));
let renderToken = 0;
let activeController = null;
+ let lockedImageStageHeight = 0;
+ let lockedImageStageWidth = 0;
const resizeObserver = new ResizeObserver(() => {
const asset = entry.mediaAssets[activeIndex];
const image = stage.querySelector(".detail-image");
@@ -3063,7 +3315,26 @@ async function createDetailMediaGallery(entryValue, { immersive = false } = {})
stage.style.height = `${availableHeight}px`;
return;
}
- stage.style.height = `${Math.min(galleryWidth * dimensions.height / dimensions.width, availableHeight)}px`;
+ if (lockedImageStageWidth && Math.abs(lockedImageStageWidth - galleryWidth) > 1) lockedImageStageHeight = 0;
+ lockedImageStageWidth = galleryWidth;
+ if (!lockedImageStageHeight) lockedImageStageHeight = Math.min(galleryWidth * dimensions.height / dimensions.width, availableHeight);
+ stage.style.height = `${lockedImageStageHeight}px`;
+ }
+
+ function captureDetailScrollAnchor(anchor) {
+ return anchor ? {
+ anchor,
+ top: anchor.getBoundingClientRect().top,
+ scrollTop: elements.detailContent.scrollTop
+ } : null;
+ }
+
+ function restoreDetailScrollAnchor(snapshot) {
+ if (!snapshot?.anchor?.isConnected) return;
+ const delta = snapshot.anchor.getBoundingClientRect().top - snapshot.top;
+ elements.detailContent.scrollTop = snapshot.scrollTop + delta;
+ snapshot.scrollTop = elements.detailContent.scrollTop;
+ snapshot.top = snapshot.anchor.getBoundingClientRect().top;
}
async function renderActive() {
@@ -3155,11 +3426,14 @@ async function createDetailMediaGallery(entryValue, { immersive = false } = {})
}
button.addEventListener("click", async () => {
const railScrollLeft = rail.scrollLeft;
+ const preservedAnchor = captureDetailScrollAnchor(button);
activeIndex = index;
activeDetailMediaIdByEntry.set(entry.id, asset.id);
await renderActive();
rail.scrollLeft = railScrollLeft;
button.focus({ preventScroll: true });
+ restoreDetailScrollAnchor(preservedAnchor);
+ requestAnimationFrame(() => restoreDetailScrollAnchor(preservedAnchor));
});
rail.append(button);
}
@@ -5583,42 +5857,14 @@ function renderBatchManager() {
function renderAnalysisSettings() {
analysisKindTabs.forEach((button) => button.setAttribute("aria-selected", String(button.dataset.analysisKind === activeAnalysisKind)));
analysisKindPanels.forEach((panel) => { panel.hidden = panel.dataset.analysisKindPanel !== activeAnalysisKind; });
- elements.deepseekAnalysisModel.value = aiSettings.analysisModel || "deepseek-v4-flash";
- elements.textAiProvider.value = aiSettings.activeProvider || "deepseek";
- elements.textCompatibleEndpoint.value = aiSettings.compatible?.endpoint || "";
- elements.textCompatibleModel.value = aiSettings.compatible?.model || "";
- elements.deepseekConsent.checked = Boolean(aiSettings.consent);
elements.showAnalysisDiagnostics.checked = uiPreferences.analysisDiagnostics;
elements.analysisInstructionsZh.value = aiSettings.analysisInstructionsByLocale?.["zh-CN"] || DEFAULT_ANALYSIS_INSTRUCTIONS_BY_LOCALE["zh-CN"];
elements.analysisInstructionsEn.value = aiSettings.analysisInstructionsByLocale?.en || DEFAULT_ANALYSIS_INSTRUCTIONS_BY_LOCALE.en;
- elements.aiSettingsStatus.textContent = aiSettings.configured
- ? aiSettings.consent
- ? t("API Key 已配置。只在你主动分析或生成时发送实际使用的案例文字。")
- : t("API Key 已配置;勾选文字发送说明后才能开始分析或创作。")
- : t("尚未配置 API Key;本地结构提取和色卡仍可使用。");
- renderTextAiProviderFields();
- elements.visionProvider.value = visionSettings.activeProvider || "openai";
- elements.visionOpenaiModel.value = visionSettings.openai?.model || DEFAULT_VISION_MODEL;
- elements.visionOpenaiVideoModel.value = visionSettings.openai?.videoGeneration?.model || "";
- elements.visionOpenaiVideoSizes.value = (visionSettings.openai?.videoGeneration?.sizes ?? []).join(", ");
- elements.visionOpenaiVideoDurations.value = (visionSettings.openai?.videoGeneration?.durations ?? []).join(", ");
- elements.visionCompatibleEndpoint.value = privateVisionEndpoint;
- elements.visionCompatibleProtocol.value = visionSettings.compatible?.protocol || "chat_completions";
- elements.visionCompatibleModel.value = visionSettings.compatible?.model || "";
- elements.visionConsent.checked = Boolean(visionSettings.consent);
- elements.visionAutoAnalyzeImports.checked = Boolean(visionSettings.autoAnalyzeImports);
+ elements.aiSettingsStatus.textContent = t("规则保存在本机,只在对应任务运行时使用。");
elements.visionInstructionsZh.value = visionSettings.instructionsByLocale?.["zh-CN"] || DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE["zh-CN"];
elements.visionInstructionsEn.value = visionSettings.instructionsByLocale?.en || DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE.en;
- const activeVisionProvider = visionSettings.activeProvider === "compatible" ? visionSettings.compatible : visionSettings.openai;
- elements.visionSettingsStatus.textContent = activeVisionProvider?.configured
- ? (visionSettings.consent
- ? visionSettings.autoAnalyzeImports
- ? t("服务已配置。新导入案例的全部内容图会在后台自动分析。")
- : t("服务已配置。只在你主动点击分析画面时发送当前截图。")
- : t("服务已配置;确认截图发送说明后才能分析画面。"))
- : t("所选图片服务尚未完成连接配置。");
+ elements.visionSettingsStatus.textContent = t("规则保存在本机,只在对应任务运行时使用。");
renderComposerMethodSettings();
- renderVisionProviderFields();
renderAnalysisLocale();
renderAiRoutingSummary();
}
@@ -5626,71 +5872,114 @@ function renderAnalysisSettings() {
function renderAiRoutingSummary() {
if (!elements.aiRoutingSummary) return;
const profiles = Object.values(aiProviderRegistry.providers ?? {});
- const connected = profiles.filter((profile) => profile.configured);
+ const connected = profiles.filter(providerConnectionReady);
elements.aiRoutingSummary.textContent = connected.length
- ? `已连接 ${connected.length} 个服务;文字、图片、视频与生成任务各自明确分配,不会静默切换。`
- : "尚未连接 AI 服务;本地资料整理仍可使用。";
- elements.aiProviderList?.replaceChildren(...(connected.length
- ? connected.map((profile) => {
+ ? t("已连接 {count} 个服务;文字、图片、视频与生成任务各自明确分配,不会静默切换。", { count: connected.length })
+ : t("尚未连接 AI 服务;本地资料整理仍可使用。");
+ const categoryLabels = { official: "官方服务", aggregator: "聚合平台", custom: "自定义兼容服务" };
+ const providerGroups = Object.entries(categoryLabels).flatMap(([category, label]) => {
+ const members = profiles.filter((profile) => profile.category === category);
+ if (!members.length) return [];
+ const group = el("section", "ai-provider-group");
+ group.dataset.providerCategory = category;
+ group.append(rawTextEl("h5", "", t(label)), ...members.map((profile) => {
const row = el("div", "ai-provider-row");
- const discoveredAt = profile.discovery?.discoveredAt
- ? ` · ${profile.discoveredModels?.length || 0} 个模型 · ${profile.discovery.source || "厂商目录"} · ${new Date(profile.discovery.discoveredAt).toLocaleString()}`
- : " · 模型目录未读取";
- const status = profile.configured ? `已连接${discoveredAt}` : "尚未连接";
- const configure = textEl("button", "button-secondary", profile.credentialConfigured ? "编辑配置" : "填写 API Key");
+ row.dataset.providerId = profile.id;
+ const status = `${providerConnectionLabel(profile)} · ${providerCatalogLabel(profile)}`;
+ const configure = textEl("button", "button-secondary", t(profile.credentialConfigured ? "编辑配置" : "配置"));
configure.type = "button";
configure.addEventListener("click", () => openAiProviderDialog(profile.id));
- const refresh = textEl("button", "button-secondary", "刷新模型");
+ const refresh = textEl("button", "button-secondary", t("刷新模型"));
refresh.type = "button";
refresh.disabled = !profile.credentialConfigured;
refresh.addEventListener("click", () => refreshAiProviderModels(profile.id, refresh));
- row.append(rawTextEl("strong", "", profile.label), textEl("span", "", status), configure, refresh);
+ row.append(rawTextEl("strong", "", providerDisplayLabel(profile)), textEl("span", "", status), configure, refresh);
return row;
- })
- : [textEl("p", "ai-routing-empty", "尚未连接服务;点击下方按钮添加")]
- ));
+ }));
+ return [group];
+ });
+ elements.aiProviderList?.replaceChildren(...providerGroups);
elements.aiAssignmentList?.replaceChildren(...AI_ASSIGNMENT_TASKS.map((task) => {
const assignment = aiTaskAssignments[task.id] ?? {};
const profile = aiProviderRegistry.providers?.[assignment.providerId];
const row = el("div", "ai-assignment-row");
- const change = textEl("button", "button-secondary", profile?.configured ? "更换" : "配置");
+ const modelState = assignedModelState(profile, assignment.model);
+ const change = textEl("button", "button-secondary", t(assignment.providerId ? "更换" : "配置"));
change.type = "button";
change.addEventListener("click", () => openAiTaskAssignmentDialog(task.id));
row.append(
- rawTextEl("strong", "", task.label),
- rawTextEl("span", "", profile ? `${profile.label} · ${assignment.model || "模型未填写"}` : "尚未分配"),
+ rawTextEl("strong", "", t(task.label)),
+ rawTextEl("span", "", !assignment.providerId
+ ? t("尚未分配")
+ : profile ? `${providerDisplayLabel(profile)} · ${assignment.model || t("模型未填写")}${modelState}` : t("已分配服务不存在")),
change
);
return row;
}));
}
+function providerConnectionReady(profile = {}) {
+ return profile.credentialConfigured === true && profile.consent === true;
+}
+
+function providerConnectionLabel(profile = {}) {
+ if (!profile.credentialConfigured) return t("尚未连接");
+ if (!profile.consent) return t("API Key 已保存,尚未确认发送授权");
+ return t("已连接");
+}
+
+function providerCatalogLabel(profile = {}) {
+ const models = profile.discoveredModels ?? [];
+ const unavailable = models.filter((model) => model.status === "unavailable").length;
+ if (profile.discovery?.error) {
+ return t("模型目录读取失败:{error};保留 {count} 个模型{unavailable}", {
+ error: translateUiMessage(profile.discovery.error),
+ count: models.length,
+ unavailable: unavailable ? t(",其中 {count} 个下架或当前不可用", { count: unavailable }) : ""
+ });
+ }
+ if (!profile.discovery?.discoveredAt) return t("模型目录未读取");
+ return t("模型目录已读取 · {count} 个模型 · 尚未执行模型调用验证{unavailable}", {
+ count: models.length,
+ unavailable: unavailable ? t(" · {count} 个下架或当前不可用", { count: unavailable }) : ""
+ });
+}
+
+function assignedModelState(profile, modelValue) {
+ const model = String(modelValue ?? "").trim();
+ if (!profile || !model) return "";
+ const discovered = (profile.discoveredModels ?? []).find((item) => item.id === model);
+ if (discovered?.status === "unavailable") return t("(已下架或当前不可用)");
+ if (profile.discovery?.discoveredAt && !discovered) return t("(当前目录不可用)");
+ return "";
+}
+
async function openAiTaskAssignmentDialog(taskId) {
const task = AI_ASSIGNMENT_TASKS.find((item) => item.id === taskId);
if (!task) return;
const current = aiTaskAssignments[taskId] ?? {};
const capable = Object.values(aiProviderRegistry.providers ?? {}).filter((profile) =>
- profile.capabilities?.includes(taskId) && profile.credentialConfigured
+ providerConnectionReady(profile) && taskModelOptions(profile, taskId).length
);
if (!capable.length) {
- showFeedback(`请先添加一个支持“${task.label}”的 AI 服务`, true);
+ showFeedback(t("尚无已连接且模型目录明确支持“{task}”的服务,请先连接服务并刷新模型", { task: t(task.label) }), true);
return openAiProviderDialog();
}
const selectedProviderId = capable.some((profile) => profile.id === current.providerId)
? current.providerId : capable[0].id;
- const modelOptions = (providerId, selected = "") => discoveredModelOptions(
- aiProviderRegistry.providers?.[providerId], taskId, selected || aiProviderRegistry.providers?.[providerId]?.models?.[taskId]
- );
- const initialModels = modelOptions(selectedProviderId, current.model);
+ const modelOptions = (providerId) => taskModelOptions(aiProviderRegistry.providers?.[providerId], taskId);
+ const initialModels = modelOptions(selectedProviderId);
const result = await showAppDialog({
- title: task.label,
- description: "这里设置全局默认;创作台中的本轮切换不会改动此处。",
+ title: t(task.label),
+ description: t("这里设置全局默认;创作台中的本轮切换不会改动此处。"),
fields: [
- { id: "providerId", label: "AI 服务", type: "select", value: selectedProviderId, options: capable.map((profile) => ({ value: profile.id, label: profile.label })) },
- { id: "model", label: "模型", type: initialModels.length ? "select" : "text", value: current.model || capable[0]?.models?.[taskId] || "", options: initialModels }
+ { id: "providerId", label: t("AI 服务"), type: "select", value: selectedProviderId, options: capable.map((profile) => ({ value: profile.id, label: providerDisplayLabel(profile) })) },
+ { id: "model", label: t("模型"), type: "select", value: initialModels.some((item) => item.value === current.model) ? current.model : initialModels[0]?.value || "", options: initialModels }
],
- confirmLabel: "保存任务默认",
- onReady: ({ controls }) => {
+ confirmLabel: t("保存任务默认"),
+ cancelLabel: t("取消"),
+ onReady: ({ dialog, controls }) => {
+ localizeAiDialogClose(dialog);
const provider = controls.get("providerId");
const model = controls.get("model");
provider?.addEventListener("change", () => {
@@ -5703,21 +5992,21 @@ async function openAiTaskAssignmentDialog(taskId) {
return option;
}));
}
- model.value = options[0]?.value || aiProviderRegistry.providers?.[provider.value]?.models?.[taskId] || "";
+ model.value = options[0]?.value || "";
});
},
onSubmit: async (values) => {
- if (!String(values.model ?? "").trim()) throw new Error("请选择或填写模型");
+ if (!String(values.model ?? "").trim()) throw new Error(t("请选择或填写模型"));
const response = await chrome.runtime.sendMessage({
type: "UPDATE_AI_PROVIDER_CONFIGURATION",
assignments: { ...aiTaskAssignments, [taskId]: { providerId: values.providerId, model: values.model } }
});
- if (!response?.ok) throw new Error(response?.message || "任务默认保存失败");
+ if (!response?.ok) throw new Error(translateUiMessage(response?.message) || t("任务默认保存失败"));
applyAiConfigurationResponse(response);
return response;
}
});
- if (result) showFeedback(`${task.label}默认模型已保存`);
+ if (result) showFeedback(t("{task}默认模型已保存", { task: t(task.label) }));
}
async function openAiProviderDialog(initialProviderId = "") {
@@ -5728,10 +6017,13 @@ async function openAiProviderDialog(initialProviderId = "") {
const keyFor = (providerId) => providerId.replaceAll("-", "_");
const fields = [{
id: "providerEditor",
- label: "编辑服务",
+ label: t("编辑服务"),
type: "select",
value: firstProviderId,
- options: profiles.map((profile) => ({ value: profile.id, label: profile.label }))
+ options: profiles.map((profile) => ({
+ value: profile.id,
+ label: `${providerCategoryLabel(profile.category)} · ${providerDisplayLabel(profile)}`
+ }))
}];
for (const profile of profiles) {
const key = keyFor(profile.id);
@@ -5740,76 +6032,82 @@ async function openAiProviderDialog(initialProviderId = "") {
fields.push({
id: `provider_${key}_apiKey`,
label: micuImageService
- ? "图片分析 API Key(米醋 vip_2,只用于看图)"
- : profile.id === "custom-media" ? "图片分析 API Key" : "API Key",
+ ? t("图片分析 API Key(米醋 vip_2,只用于看图)")
+ : profile.id === "custom-media" ? t("图片分析 API Key") : "API Key",
type: "secret",
autocomplete: "off",
- placeholder: profile.credentialConfigured ? "已保存;留空保持不变" : "粘贴服务商提供的 API Key",
- help: micuImageService ? "这把 Key 只用于图片分析,不会发送给最终生图接口。" : ""
+ placeholder: profile.credentialConfigured ? t("已保存;留空保持不变") : t("粘贴服务商提供的 API Key"),
+ help: micuImageService ? t("这把 Key 只用于图片分析,不会发送给最终生图接口。") : ""
});
if (profile.id === "custom-media") fields.push({
id: `provider_${key}_imageApiKey`,
label: micuImageService
- ? "图片生成 API Key(米醋 vip_2_image,需单独创建)"
- : "图片生成 API Key(可与分析 Key 不同)",
+ ? t("图片生成 API Key(米醋 vip_2_image,需单独创建)")
+ : t("图片生成 API Key(可与分析 Key 不同)"),
type: "secret",
autocomplete: "off",
placeholder: profile.imageGeneration?.credentialConfigured
- ? `已保存${profile.imageGeneration.credentialHint ? `(尾号 ${profile.imageGeneration.credentialHint})` : ""};留空保持不变`
- : micuImageService ? "粘贴米醋 vip_2_image 分组 Key" : "留空则复用上方 API Key",
- help: micuImageService ? "留空会保留已保存的生图 Key。模型目录可见不等于已获得 Image2 生图分组授权,最终以米醋生成接口返回为准。" : ""
+ ? t("已保存{hint};留空保持不变", { hint: profile.imageGeneration.credentialHint ? t("(尾号 {hint})", { hint: profile.imageGeneration.credentialHint }) : "" })
+ : micuImageService ? t("粘贴米醋 vip_2_image 分组 Key") : t("留空则复用上方 API Key"),
+ help: micuImageService ? t("留空会保留已保存的生图 Key。模型目录可见不等于已获得 Image2 生图分组授权,最终以米醋生成接口返回为准。") : ""
});
if (custom) fields.push(
- { id: `provider_${key}_endpoint`, label: profile.id === "custom-media" ? "图片分析接口(高级)" : "接口地址(高级)", type: "url", value: profile.endpoint },
- { id: `provider_${key}_protocol`, label: "兼容协议(高级)", type: "select", value: profile.protocol, options: [
- { value: "native", label: "服务原生协议" },
+ { id: `provider_${key}_endpoint`, label: t(profile.id === "custom-media" ? "图片分析接口(高级)" : "接口地址(高级)"), type: "url", value: profile.endpoint, advanced: true },
+ { id: `provider_${key}_protocol`, label: t("兼容协议(高级)"), type: "select", value: profile.protocol, advanced: true, options: [
+ { value: "native", label: t("服务原生协议") },
{ value: "responses", label: "OpenAI Responses" },
{ value: "chat_completions", label: "OpenAI Chat Completions" }
] }
);
- if (custom) fields.push(...profile.capabilities.map((taskId) => ({
+ fields.push(...profile.capabilities.map((taskId) => {
+ const catalogRequired = profile.catalogRequiredTasks?.includes(taskId) === true;
+ const options = discoveredModelOptions(profile, taskId, catalogRequired ? "" : profile.models?.[taskId]);
+ return {
id: `provider_${key}_model_${taskId}`,
- label: `${AI_ASSIGNMENT_TASKS.find((task) => task.id === taskId)?.label || taskId}模型(高级)`,
- type: discoveredModelOptions(profile, taskId, profile.models?.[taskId]).length ? "select" : "text",
- value: profile.models?.[taskId] || "",
- options: discoveredModelOptions(profile, taskId, profile.models?.[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] : "",
+ options,
+ advanced: true
+ };
+ }));
if (profile.id === "custom-media") fields.push(
- { id: `provider_${key}_imageProtocol`, label: "图片生成协议(高级)", type: "select", value: profile.imageGeneration?.protocol || "none", options: [
- { value: "none", label: "不启用图片生成" },
- { value: "responses_tool", label: "OpenAI Responses 生图工具" },
+ { id: `provider_${key}_imageProtocol`, label: t("图片生成协议(高级)"), type: "select", value: profile.imageGeneration?.protocol || "none", advanced: true, options: [
+ { value: "none", label: t("不启用图片生成") },
+ { value: "responses_tool", label: t("OpenAI Responses 生图工具") },
{ value: "images_generations", label: "Images Generations / Edits" }
] },
- { id: `provider_${key}_imageEndpoint`, label: "图片生成接口(高级)", type: "url", value: profile.imageGeneration?.endpoint || "" },
- { id: `provider_${key}_imageEditsEndpoint`, label: "多图参考 / 编辑接口(高级)", type: "url", value: profile.imageGeneration?.editsEndpoint || "" },
- { id: `provider_${key}_imageSizes`, label: "此服务支持的图片尺寸(能力声明,不是本轮输出值)", type: "text", value: (profile.imageGeneration?.sizes ?? []).join(", ") },
- { id: `provider_${key}_imageQualities`, label: "此服务支持的质量选项(能力声明,不是本轮输出值)", type: "text", value: (profile.imageGeneration?.qualities ?? []).join(", ") }
+ { id: `provider_${key}_imageEndpoint`, label: t("图片生成接口(高级)"), type: "url", value: profile.imageGeneration?.endpoint || "", advanced: true },
+ { id: `provider_${key}_imageEditsEndpoint`, label: t("多图参考 / 编辑接口(高级)"), type: "url", value: profile.imageGeneration?.editsEndpoint || "", advanced: true },
+ { id: `provider_${key}_imageSizes`, label: t("此服务支持的图片尺寸(能力声明,不是本轮输出值)"), type: "text", value: (profile.imageGeneration?.sizes ?? []).join(", "), advanced: true },
+ { id: `provider_${key}_imageQualities`, label: t("此服务支持的质量选项(能力声明,不是本轮输出值)"), type: "text", value: (profile.imageGeneration?.qualities ?? []).join(", "), advanced: true }
);
- fields.push({ id: `provider_${key}_consent`, label: `我确认:主动使用 ${profile.label} 时发送本次任务所需内容`, type: "checkbox", value: profile.consent === true });
- }
- const advancedFieldIds = new Set(fields.flatMap((field) => (
- String(field.label ?? "").includes("(高级)")
- || /_image(?:Sizes|Qualities)$/.test(field.id)
- ? [field.id]
- : []
- )));
+ fields.push({ id: `provider_${key}_consent`, label: t("我确认:主动使用 {provider} 时发送本次任务所需内容", { provider: providerDisplayLabel(profile) }), type: "checkbox", value: profile.consent === true });
+ }
+ const advancedFieldIds = new Set(fields.flatMap((field) => field.advanced === true ? [field.id] : []));
const result = await showAppDialog({
- title: "连接 AI 服务",
- description: "官方服务通常只需填写 API Key。接口、协议和手填模型仅用于第三方兼容服务。",
+ title: t("连接 AI 服务"),
+ description: t("官方服务通常只需填写 API Key。账号专属模型与兼容服务连接参数位于高级连接。"),
fields,
- confirmLabel: "保存配置",
- pendingLabel: "正在保存…",
+ confirmLabel: t("保存配置"),
+ cancelLabel: t("取消"),
+ pendingLabel: t("正在保存…"),
renderBody: ({ body }) => {
const details = document.createElement("details");
details.className = "ai-advanced-settings app-dialog-advanced-settings";
const summary = document.createElement("summary");
const title = document.createElement("strong");
- title.textContent = "高级连接";
+ title.textContent = t("高级连接");
const description = document.createElement("span");
- description.textContent = "仅在接口地址、协议或模型发生变化时修改";
+ description.textContent = t("仅在接口地址、协议或模型发生变化时修改");
summary.append(title, description);
const advancedBody = document.createElement("div");
advancedBody.className = "ai-advanced-settings-body";
+ const micuPreset = textEl("button", "button-secondary", t("填入米醋个人中转预设"));
+ micuPreset.type = "button";
+ micuPreset.dataset.providerPreset = "micu-personal";
+ micuPreset.hidden = true;
+ advancedBody.append(micuPreset);
for (const fieldId of advancedFieldIds) {
const wrapper = body.querySelector(`[data-field-id="${fieldId}"]`);
if (wrapper) advancedBody.append(wrapper);
@@ -5818,8 +6116,19 @@ async function openAiProviderDialog(initialProviderId = "") {
body.append(details);
},
onReady: ({ dialog, controls }) => {
+ localizeAiDialogClose(dialog);
const editor = controls.get("providerEditor");
const advanced = dialog.querySelector(".app-dialog-advanced-settings");
+ 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;
+ controls.get(`${prefix}apiKey`).focus();
+ });
const syncProviderFields = () => {
for (const profile of profiles) {
const prefix = `provider_${keyFor(profile.id)}_`;
@@ -5827,6 +6136,7 @@ async function openAiProviderDialog(initialProviderId = "") {
if (id.startsWith(prefix)) input.parentElement.hidden = profile.id !== editor.value;
}
}
+ if (micuPreset) micuPreset.hidden = editor.value !== "custom-media";
advanced.hidden = ![...advanced.querySelectorAll("[data-field-id]")].some((wrapper) => !wrapper.hidden);
};
editor.addEventListener("change", syncProviderFields);
@@ -5839,9 +6149,10 @@ async function openAiProviderDialog(initialProviderId = "") {
const key = keyFor(profile.id);
const apiKey = values[`provider_${key}_apiKey`];
const endpoint = profile.id.startsWith("custom") ? values[`provider_${key}_endpoint`] : profile.endpoint;
- const models = profile.id.startsWith("custom")
- ? Object.fromEntries(profile.capabilities.map((taskId) => [taskId, values[`provider_${key}_model_${taskId}`]]))
- : profile.models;
+ const models = Object.fromEntries(profile.capabilities.flatMap((taskId) => {
+ const model = String(values[`provider_${key}_model_${taskId}`] ?? "").trim();
+ return model ? [[taskId, model]] : [];
+ }));
const imageGeneration = profile.id === "custom-media" ? {
protocol: values[`provider_${key}_imageProtocol`],
endpoint: values[`provider_${key}_imageEndpoint`],
@@ -5854,7 +6165,7 @@ async function openAiProviderDialog(initialProviderId = "") {
let imageCredentialVerification = null;
if (imageGeneration && providerUsesMicuImageGroup({ ...profile, imageGeneration })
&& !imageGeneration.apiKey && !profile.imageGeneration?.credentialConfigured) {
- throw new Error("米醋 gpt-image-2 需要单独的 vip_2_image 分组 Key,不能复用上方文字 / 分析 Key");
+ throw new Error(t("米醋 gpt-image-2 需要单独的 vip_2_image 分组 Key,不能复用上方文字 / 分析 Key"));
}
registryUpdate.providers[profile.id] = {
endpoint,
@@ -5871,7 +6182,7 @@ async function openAiProviderDialog(initialProviderId = "") {
if (imageGeneration?.editsEndpoint && (imageGeneration.apiKey || profile.imageGeneration?.credentialConfigured || apiKey || profile.credentialConfigured)) {
origins.add(permissionPatternForProvider(imageGeneration.editsEndpoint));
}
- if (origins.size && !await chrome.permissions.request({ origins: [...origins] })) throw new Error("没有获得新增 AI 服务的访问权限,设置未保存");
+ if (origins.size && !await chrome.permissions.request({ origins: [...origins] })) throw new Error(t("没有获得新增 AI 服务的访问权限,设置未保存"));
if (imageGeneration && providerUsesMicuImageGroup({ ...profile, imageGeneration })
&& (imageGeneration.apiKey || profile.imageGeneration?.credentialConfigured)) {
imageCredentialVerification = await chrome.runtime.sendMessage({
@@ -5881,18 +6192,18 @@ async function openAiProviderDialog(initialProviderId = "") {
apiKey: imageGeneration.apiKey,
model: imageGeneration.model
});
- if (!imageCredentialVerification?.ok) throw new Error(imageCredentialVerification?.message || "米醋图片生成 Key 的模型目录检查失败");
+ if (!imageCredentialVerification?.ok) throw new Error(translateUiMessage(imageCredentialVerification?.message) || t("米醋图片生成 Key 的模型目录检查失败"));
}
const response = await chrome.runtime.sendMessage({
type: "UPDATE_AI_PROVIDER_CONFIGURATION",
registry: registryUpdate,
assignments: aiTaskAssignments
});
- if (!response?.ok) throw new Error(response?.message || "AI 服务配置保存失败");
+ if (!response?.ok) throw new Error(translateUiMessage(response?.message) || t("AI 服务配置保存失败"));
applyAiConfigurationResponse(response);
const savedMessage = imageCredentialVerification?.message
- ? `${response.message || "配置已保存"};${imageCredentialVerification.message}`
- : response.message || "配置已保存";
+ ? `${t("配置已保存")};${t("模型目录中可见 {model};这只证明目录可见,不代表米醋已授权该 Key 进入生图分组", { model: imageGeneration.model })}`
+ : t("配置已保存");
if (!(apiKey || profile.credentialConfigured)) return { ...response, message: savedMessage };
try {
const discovery = await chrome.runtime.sendMessage({
@@ -5900,14 +6211,14 @@ async function openAiProviderDialog(initialProviderId = "") {
providerId: profile.id,
force: true
});
- if (!discovery?.ok) throw new Error(discovery?.message || "模型目录读取失败");
+ if (!discovery?.ok) throw new Error(translateUiMessage(discovery?.message) || t("模型目录读取失败"));
applyAiConfigurationResponse(discovery);
- return { ...discovery, message: `${savedMessage};${discovery.message || "模型已读取"}` };
+ return { ...discovery, message: `${savedMessage};${t("{provider} 已发现 {count} 个模型", { provider: providerDisplayLabel(profile), count: discovery.aiProviderRegistry?.providers?.[profile.id]?.discoveredModels?.length || 0 })}` };
} catch (error) {
return {
...response,
- message: `${savedMessage};模型目录暂时读取失败,可稍后手动刷新`,
- discoveryWarning: error.message || "模型目录读取失败"
+ message: `${savedMessage};${t("模型目录暂时读取失败,可稍后手动刷新")}`,
+ discoveryWarning: translateUiMessage(error.message) || t("模型目录读取失败")
};
}
}
@@ -5918,6 +6229,24 @@ async function openAiProviderDialog(initialProviderId = "") {
}
}
+function providerCategoryLabel(category) {
+ return t({ official: "官方服务", aggregator: "聚合平台", custom: "自定义兼容服务" }[category] || "自定义兼容服务");
+}
+
+function localizeAiDialogClose(dialog) {
+ const close = dialog.querySelector(".app-dialog-close");
+ close?.setAttribute("aria-label", t("关闭"));
+ if (close) close.title = t("关闭");
+}
+
+function providerDisplayLabel(profile = {}) {
+ return t(profile.label || "自定义兼容服务");
+}
+
+function taskDisplayLabel(taskId) {
+ return t(AI_ASSIGNMENT_TASKS.find((task) => task.id === taskId)?.label || taskId);
+}
+
function providerUsesMicuImageGroup(profile = {}) {
if (profile.imageGeneration?.protocol !== "images_generations") return false;
try {
@@ -5938,7 +6267,6 @@ function applyAiConfigurationResponse(response) {
aiSettings = response.aiSettings;
visionSettings = response.visionSettings;
aiServiceProfiles = response.aiServiceProfiles;
- aiTaskRoutes = normalizeAiTaskRoutes(response.aiTaskRoutes);
renderAiRoutingSummary();
}
@@ -5947,15 +6275,21 @@ function discoveredModelOptions(profile, taskId, selectedValue = "") {
.filter((model) => model.status !== "unavailable" && model.tasks?.includes(taskId))
.map((model) => ({
value: model.id,
- label: `${model.name || model.id} · ${model.confidence === "declared" ? "厂商声明" : model.confidence === "protocol_inferred" ? "协议确认" : "待验证"}${modelPriceLabel(model.pricing)}`
+ label: `${model.name || model.id} · ${t(model.confidence === "declared" ? "厂商声明" : model.confidence === "protocol_inferred" ? "协议确认" : "待验证")}${modelPriceLabel(model.pricing)}`
}));
const selected = String(selectedValue ?? "").trim();
if (selected && !options.some((option) => option.value === selected)) {
- options.unshift({ value: selected, label: `${selected}(当前配置)` });
+ options.unshift({ value: selected, label: t("{model}(手动声明,未验证)", { model: selected }) });
}
return options;
}
+function taskModelOptions(profile, taskId) {
+ if (!profile?.capabilities?.includes(taskId)) return [];
+ const manualModel = profile.catalogRequiredTasks?.includes(taskId) ? "" : profile.models?.[taskId] || "";
+ return discoveredModelOptions(profile, taskId, manualModel);
+}
+
function modelPriceLabel(pricing) {
if (!pricing || typeof pricing !== "object") return "";
const first = Object.entries(pricing).find(([, value]) => typeof value === "string" || typeof value === "number");
@@ -5964,19 +6298,22 @@ function modelPriceLabel(pricing) {
async function refreshAiProviderModels(providerId, button) {
const profile = aiProviderRegistry.providers?.[providerId];
- if (!profile?.credentialConfigured) return showFeedback("请先保存该厂商的 API Key");
+ if (!profile?.credentialConfigured) return showFeedback(t("请先保存该厂商的 API Key"));
button.disabled = true;
const oldText = button.textContent;
- button.textContent = "正在读取…";
+ button.textContent = t("正在读取…");
try {
const response = await chrome.runtime.sendMessage({ type: "DISCOVER_AI_PROVIDER_MODELS", providerId, force: true });
- if (!response?.ok) throw new Error(response?.message || "模型目录读取失败");
+ if (!response?.ok) throw new Error(translateUiMessage(response?.message) || t("模型目录读取失败"));
aiProviderRegistry = response.aiProviderRegistry;
aiTaskAssignments = response.aiTaskAssignments;
renderAiRoutingSummary();
- showFeedback(response.message);
+ showFeedback(t("{provider} 已发现 {count} 个模型", {
+ provider: providerDisplayLabel(profile),
+ count: response.aiProviderRegistry?.providers?.[providerId]?.discoveredModels?.length || 0
+ }));
} catch (error) {
- showFeedback(error.message || "模型目录读取失败");
+ showFeedback(translateUiMessage(error.message) || t("模型目录读取失败"));
} finally {
if (button.isConnected) {
button.disabled = false;
@@ -6111,187 +6448,38 @@ async function saveCreativeExperimentSettings() {
}
}
-function renderVisionProviderFields() {
- const compatible = elements.visionProvider.value === "compatible";
- elements.visionOpenaiFields.hidden = compatible;
- elements.visionCompatibleFields.hidden = !compatible;
- renderVisionCompatibleEndpointHint();
-}
-
-function renderTextAiProviderFields() {
- const compatible = elements.textAiProvider.value === "compatible";
- document.querySelectorAll(".text-deepseek-field").forEach((field) => { field.hidden = compatible; });
- document.querySelectorAll(".text-compatible-field").forEach((field) => { field.hidden = !compatible; });
-}
-
-function currentTextAiFormValue() {
- return {
- activeProvider: elements.textAiProvider.value,
- apiKey: elements.deepseekApiKey.value,
- consent: elements.deepseekConsent.checked,
- analysisModel: elements.deepseekAnalysisModel.value,
- analysisInstructionsByLocale: {
- "zh-CN": elements.analysisInstructionsZh.value,
- en: elements.analysisInstructionsEn.value
- },
- compatible: {
- endpoint: elements.textCompatibleEndpoint.value,
- model: elements.textCompatibleModel.value,
- apiKey: elements.textCompatibleApiKey.value
- }
- };
-}
-
-async function testTextAiService() {
- const button = elements.testTextAiService;
- button.disabled = true;
- try {
- const settings = currentTextAiFormValue();
- const permission = permissionPatternForAiSettings(settings);
- if (!await chrome.permissions.request({ origins: [permission] })) throw new Error("没有获得该服务地址的访问权限");
- const response = await chrome.runtime.sendMessage({ type: "PROBE_VISION_MODELS", settings: settings.compatible });
- if (!response?.ok) throw new Error(response?.message || "服务连接失败");
- elements.visionCompatibleModels.replaceChildren(...response.models.map((model) => {
- const option = document.createElement("option");
- option.value = model;
- return option;
- }));
- if (!response.models.includes(elements.textCompatibleModel.value)) elements.textCompatibleModel.value = response.models[0];
- showFeedback(`${response.message};已选择 ${elements.textCompatibleModel.value}`);
- } catch (error) {
- showFeedback(error.message, true);
- } finally {
- button.disabled = false;
- }
-}
-
-function renderVisionCompatibleEndpointHint() {
- elements.visionCompatibleEndpoint.placeholder = elements.visionCompatibleProtocol.value === "responses"
- ? "https://www.micuapi.ai/v1/responses"
- : "http://localhost:1234/v1/chat/completions";
- const origin = compatibleEndpointOrigin(elements.visionCompatibleEndpoint.value);
- if (!origin) {
- elements.visionCompatibleTarget.textContent = t("填写 HTTPS 地址,或使用 localhost 本机服务。");
- return;
- }
- const changed = Boolean(
- visionSettings.compatible?.configured &&
- visionSettings.compatible?.targetOrigin &&
- origin !== visionSettings.compatible.targetOrigin
- );
- elements.visionCompatibleTarget.textContent = changed
- ? (currentLocale() === "en"
- ? `Target: ${origin}. The domain changed; re-enter this service's API key before saving.`
- : `Key 接收域名:${origin}。域名已变化,保存时必须重新填写新服务的 Key。`)
- : (currentLocale() === "en" ? `API key target: ${origin}` : `Key 接收域名:${origin}`);
-}
-
-function compatibleEndpointOrigin(value) {
- try {
- const url = new URL(String(value ?? "").trim());
- const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname.toLocaleLowerCase("en-US"));
- return url.protocol === "https:" || url.protocol === "http:" && loopback ? url.origin : "";
- } catch {
- return "";
- }
-}
-
-async function testCompatibleVisionService() {
- const button = elements.testVisionService;
- button.disabled = true;
- try {
- const form = currentVisionFormValue();
- const permissions = permissionPatternsForVisionSettings(normalizeVisionSettings({ ...form, activeProvider: "compatible" }));
- if (!await chrome.permissions.request({ origins: permissions })) throw new Error("没有获得该服务地址的访问权限");
- const response = await chrome.runtime.sendMessage({ type: "PROBE_VISION_MODELS", settings: form.compatible });
- if (!response?.ok) throw new Error(response?.message || "服务连接失败");
- elements.visionCompatibleModels.replaceChildren(...response.models.map((model) => {
- const option = document.createElement("option");
- option.value = model;
- return option;
- }));
- if (!response.models.includes(elements.visionCompatibleModel.value)) elements.visionCompatibleModel.value = response.models[0];
- showFeedback(`${response.message};已选择 ${elements.visionCompatibleModel.value}`);
- } catch (error) {
- showFeedback(error.message, true);
- } finally {
- button.disabled = false;
- }
-}
-
-async function saveVisionSettings(event) {
+async function saveAiRulePreferences(event) {
event.preventDefault();
- const button = event.submitter ?? elements.visionSettingsForm.querySelector("button[type='submit']");
- button.disabled = true;
- try {
- const settingsValue = currentVisionFormValue();
- if (settingsValue.activeProvider === "compatible" && !settingsValue.compatible.model.trim()) {
- throw new Error("请填写兼容服务的图片分析模型");
- }
- const permissions = permissionPatternsForVisionSettings(normalizeVisionSettings(settingsValue));
- if (!await chrome.permissions.request({ origins: permissions })) {
- throw new Error("未获得所选图片服务的访问权限,设置没有保存");
- }
- const response = await chrome.runtime.sendMessage({ type: "UPDATE_AI_VISION_PROVIDER", settings: settingsValue });
- if (!response?.ok) throw new Error(response?.message || "图片视觉设置保存失败");
- elements.visionOpenaiApiKey.value = "";
- elements.visionCompatibleApiKey.value = "";
- showFeedback(response.message);
- await refreshLibrary();
- } catch (error) {
- showFeedback(error.message, true);
- } finally {
- button.disabled = false;
- }
-}
-
-async function clearSelectedVisionApiKey() {
- const button = elements.clearVisionApiKey;
+ const button = event.submitter ?? event.currentTarget.querySelector("button[type='submit']");
button.disabled = true;
try {
const response = await chrome.runtime.sendMessage({
- type: "UPDATE_AI_VISION_PROVIDER",
- settings: { ...currentVisionFormValue(), clearApiKey: elements.visionProvider.value }
+ type: "UPDATE_AI_PROVIDER_CONFIGURATION",
+ preferences: {
+ textInstructionsByLocale: {
+ "zh-CN": elements.analysisInstructionsZh.value,
+ en: elements.analysisInstructionsEn.value
+ },
+ visionInstructionsByLocale: {
+ "zh-CN": elements.visionInstructionsZh.value,
+ en: elements.visionInstructionsEn.value
+ },
+ autoAnalyzeImports: visionSettings.autoAnalyzeImports === true
+ }
});
- if (!response?.ok) throw new Error(response?.message || "无法清除 API Key");
- elements.visionOpenaiApiKey.value = "";
- elements.visionCompatibleApiKey.value = "";
- showFeedback(response.message);
- await refreshLibrary();
+ if (!response?.ok) throw new Error(response?.message || t("分析规则保存失败"));
+ applyAiConfigurationResponse(response);
+ const message = t("分析规则已保存");
+ elements.aiSettingsStatus.textContent = message;
+ elements.visionSettingsStatus.textContent = message;
+ showFeedback(message);
} catch (error) {
- showFeedback(error.message, true);
+ showFeedback(translateUiMessage(error.message), true);
} finally {
button.disabled = false;
}
}
-function currentVisionFormValue() {
- return {
- activeProvider: elements.visionProvider.value,
- consent: elements.visionConsent.checked,
- autoAnalyzeImports: elements.visionAutoAnalyzeImports.checked,
- instructionsByLocale: {
- "zh-CN": elements.visionInstructionsZh.value,
- en: elements.visionInstructionsEn.value
- },
- openai: {
- apiKey: elements.visionOpenaiApiKey.value,
- model: elements.visionOpenaiModel.value,
- videoGeneration: {
- model: elements.visionOpenaiVideoModel.value,
- sizes: elements.visionOpenaiVideoSizes.value,
- durations: elements.visionOpenaiVideoDurations.value
- }
- },
- compatible: {
- protocol: elements.visionCompatibleProtocol.value,
- endpoint: elements.visionCompatibleEndpoint.value,
- apiKey: elements.visionCompatibleApiKey.value,
- model: elements.visionCompatibleModel.value
- }
- };
-}
-
async function startDeepSeekAnalysisBatch() {
const mode = analysisBatchPreview?.mode === "rebuild" ? "rebuild" : "incremental";
const button = mode === "rebuild" ? elements.startAnalysisReanalyze : elements.startAnalysisBatch;
diff --git a/local-media.js b/local-media.js
index 9fb9ea1..98a1d6e 100644
--- a/local-media.js
+++ b/local-media.js
@@ -1,5 +1,5 @@
import { readImageDimensions as readStoredImageDimensions } from "./image-metadata.js";
-import { assertImageDimensions } from "./resource-limits.js";
+import { PORTABLE_LIBRARY_LIMITS, assertImageDimensions, formatBytes } from "./resource-limits.js";
import { assertStorageCapacity, validateMediaBlob } from "./media-store.js";
import { ingestLocalDocument } from "./document-ingestion.js";
@@ -53,6 +53,9 @@ export function normalizeLocalRelativePath(value, fallbackName = "") {
export async function prepareLocalMedia(file, assetId, options = {}) {
const format = detectLocalMediaFile(file, { allowVideo: options.allowVideo !== false });
+ if (format.kind === "image" && file.size > PORTABLE_LIBRARY_LIMITS.maxImageBytes) {
+ throw new Error(`图片超过 ${formatBytes(PORTABLE_LIBRARY_LIMITS.maxImageBytes)} 上限`);
+ }
const id = clean(assetId);
if (!id) throw new Error("媒体缺少有效编号");
const blob = file.type === format.mimeType ? file : file.slice(0, file.size, format.mimeType);
diff --git a/manifest.json b/manifest.json
index 963bb70..20beb57 100644
--- a/manifest.json
+++ b/manifest.json
@@ -2,7 +2,7 @@
"manifest_version": 3,
"name": "__MSG_extensionName__",
"short_name": "__MSG_extensionShortName__",
- "version": "1.18.4",
+ "version": "1.18.5",
"homepage_url": "https://github.com/wchao6891/PromptDirector",
"default_locale": "zh_CN",
"minimum_chrome_version": "116",
@@ -25,7 +25,11 @@
"unlimitedStorage"
],
"host_permissions": [
- "https://api.deepseek.com/*"
+ "https://api.deepseek.com/*",
+ "https://wchao6891.github.io/*",
+ "https://github.com/*",
+ "https://objects.githubusercontent.com/*",
+ "https://release-assets.githubusercontent.com/*"
],
"optional_host_permissions": [
"<all_urls>"
@@ -49,7 +53,7 @@
"default_path": "collector.html"
},
"content_security_policy": {
- "extension_pages": "script-src 'self'; object-src 'self'; img-src 'self' data: blob: https:; media-src 'self' blob:; frame-src blob: https://player.vimeo.com https://www.youtube-nocookie.com https://player.bilibili.com https://www.douyin.com https://open.douyin.com https://platform.twitter.com;"
+ "extension_pages": "script-src 'self'; object-src 'self'; img-src 'self' data: blob: https:; media-src 'self' blob: https://github.com https://objects.githubusercontent.com https://release-assets.githubusercontent.com; frame-src blob: https://player.vimeo.com https://www.youtube-nocookie.com https://player.bilibili.com https://www.douyin.com https://open.douyin.com https://platform.twitter.com;"
},
"commands": {
"save-selection": {
diff --git a/media.js b/media.js
index c08054b..029242c 100644
--- a/media.js
+++ b/media.js
@@ -1,4 +1,6 @@
-const IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp"]);
+import { normalizeArticleDocument, removeArticleDocumentAsset } from "./article-document.js";
+
+const IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif", "image/avif"]);
const VIDEO_MIME_TYPES = new Set([
"video/mp4", "video/webm", "video/quicktime", "video/x-matroska", "video/x-msvideo"
]);
@@ -42,6 +44,8 @@ export function normalizeMediaAsset(value = {}) {
storageMode,
sourceUrl,
sourceTitle: clean(value.sourceTitle),
+ sourceAuthor: clean(value.sourceAuthor),
+ originalWorkUrl: safeHttpUrl(value.originalWorkUrl),
capturedAt,
...(mimeTypeForKind(kind, mimeType) ? { mimeType } : {}),
...(width ? { width } : {}),
@@ -95,6 +99,9 @@ export function normalizeEntryMedia(entryValue = {}) {
const requestedPrimary = clean(entry.primaryMediaId || entry.primaryVisualId);
entry.mediaAssets = mediaAssets;
entry.primaryMediaId = contentAssets.some((item) => item.id === requestedPrimary) ? requestedPrimary : contentAssets[0]?.id || "";
+ const articleDocument = normalizeArticleDocument(entry.articleDocument);
+ if (articleDocument) entry.articleDocument = articleDocument;
+ else delete entry.articleDocument;
entry.timeNotes = normalizeTimeNotes(entry.timeNotes, ids);
entry.mediaPrompts = normalizeMediaPrompts(entry.mediaPrompts, ids);
entry.visualSetAnalyses = normalizeVersionedAnalyses(entry.visualSetAnalyses, "visual-set");
@@ -176,6 +183,8 @@ export function removeEntryMedia(entryValue, assetId) {
entry.timeNotes = entry.timeNotes.filter((item) => item.assetId !== id);
entry.mediaPrompts = entry.mediaPrompts.filter((item) => !removedIds.has(item.assetId));
entry.videoAnalyses = entry.videoAnalyses.filter((item) => !removedIds.has(item.assetId));
+ for (const removedId of removedIds) entry.articleDocument = removeArticleDocumentAsset(entry.articleDocument, removedId);
+ if (!entry.articleDocument) delete entry.articleDocument;
if (entry.primaryMediaId === id) entry.primaryMediaId = entry.mediaAssets.find((item) => item.usage !== "poster")?.id || "";
return entry;
}
@@ -261,7 +270,7 @@ export function mediaDescriptions(entryValue = {}) {
export function mediaKindFromFile(file) {
const mimeType = clean(file?.type).toLocaleLowerCase("en-US");
const name = clean(file?.name).toLocaleLowerCase("en-US");
- if (mimeType.startsWith("image/") || /\.(?:png|jpe?g|webp)$/.test(name)) return "image";
+ if (mimeType.startsWith("image/") || /\.(?:avif|gif|png|jpe?g|webp)$/.test(name)) return "image";
if (mimeType.startsWith("video/") || /\.(?:mp4|webm|mov|mkv|avi)$/.test(name)) return "video";
if (DOCUMENT_MIME_TYPES.has(mimeType) || /\.(?:pdf|md|markdown|txt|html?|rtf)$/.test(name)) return "document";
return "";
diff --git a/migration.js b/migration.js
index 8de99bb..824721a 100644
--- a/migration.js
+++ b/migration.js
@@ -240,8 +240,10 @@ function normalizeCuratedOrigin(value) {
const normalized = Object.fromEntries(required.map((key) => [key, String(value[key] ?? "").trim()]));
if (required.some((key) => !normalized[key])) return undefined;
const installedAt = String(value.installedAt ?? "").trim();
+ const sourceEntryId = String(value.sourceEntryId ?? "").trim();
return {
...normalized,
+ ...(sourceEntryId ? { sourceEntryId } : {}),
...(installedAt && !Number.isNaN(Date.parse(installedAt))
? { installedAt: new Date(installedAt).toISOString() }
: {})
diff --git a/offscreen.js b/offscreen.js
index d5c65cd..5d0c91d 100644
--- a/offscreen.js
+++ b/offscreen.js
@@ -8,6 +8,13 @@ import {
renderMarkdown
} from "./lib.js";
import { createZipBlob } from "./zip.js";
+import { sha256Hex } from "./sync-crypto.js";
+import {
+ CURATED_SUBMISSION_MAX_FILE_BYTES,
+ CURATED_SUBMISSION_PART_PAYLOAD_BYTES,
+ submissionManifest,
+ submissionPartManifest
+} from "./curated-submission.js";
import { PALETTE_VERSION, extractPalette } from "./palette.js";
import {
SHARE_PREVIEW_FOUNDATION_FILENAME,
@@ -42,8 +49,12 @@ async function handleMessage(message) {
return cropScreenshot(message);
case "CROP_AND_STORE_SCREENSHOTS":
return cropScreenshots(message);
+ case "CROP_PAGE_CAPTURE_PREVIEWS":
+ return cropPageCapturePreviews(message);
case "CREATE_ARCHIVE_URL":
return createArchiveUrl(message);
+ case "CREATE_CURATED_SUBMISSION_URLS":
+ return createCuratedSubmissionUrls(message);
case "CREATE_CREATIVE_EXPERIMENT_ARCHIVE_URL":
return createCreativeExperimentArchiveUrl(message);
case "ANALYZE_STORED_SCREENSHOT":
@@ -232,6 +243,44 @@ async function cropScreenshots({ entryIds, dataUrl, selections }) {
}
}
+async function cropPageCapturePreviews({ dataUrl, selections, maxDataUrlCharacters }) {
+ const values = Array.isArray(selections) ? selections : [];
+ if (!values.length) return { ok: true, dataUrls: [] };
+ const image = await loadImage(dataUrl);
+ const limit = Number.isSafeInteger(Number(maxDataUrlCharacters)) && Number(maxDataUrlCharacters) > 0
+ ? Number(maxDataUrlCharacters)
+ : 1;
+ return {
+ ok: true,
+ dataUrls: values.map((selection) => cropLoadedScreenshotDataUrl(image, selection, limit))
+ };
+}
+
+function cropLoadedScreenshotDataUrl(image, selection, maxCharacters) {
+ const geometry = calculateCropGeometry({
+ imageWidth: image.naturalWidth,
+ imageHeight: image.naturalHeight,
+ viewportWidth: selection.viewportWidth,
+ viewportHeight: selection.viewportHeight,
+ rect: selection.rect
+ });
+ let width = geometry.outputWidth;
+ let height = geometry.outputHeight;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext("2d", { alpha: false });
+ if (!context) return "";
+ context.drawImage(image, geometry.sourceX, geometry.sourceY, geometry.sourceWidth, geometry.sourceHeight, 0, 0, width, height);
+ const dataUrl = canvas.toDataURL(SCREENSHOT_SETTINGS.mimeType, SCREENSHOT_SETTINGS.quality);
+ if (dataUrl.length <= maxCharacters) return dataUrl;
+ width = Math.max(1, Math.floor(width * 0.7));
+ height = Math.max(1, Math.floor(height * 0.7));
+ }
+ return "";
+}
+
async function cropLoadedScreenshot(image, entryId, selection) {
const geometry = calculateCropGeometry({
imageWidth: image.naturalWidth,
@@ -390,6 +439,106 @@ async function createArchiveUrl({
return { ok: true, url, imageCount, fileCount: files.length, byteSize: archive.size };
}
+async function createCuratedSubmissionUrls({
+ entries, settings, taxonomy, facetCatalog, classificationRules, organizerState, compoundCases
+}) {
+ const files = [];
+ const resolvedEntries = [];
+ let mediaCount = 0;
+ for (const entry of Array.isArray(entries) ? entries : []) {
+ const normalized = normalizeEntryMedia(entry);
+ const mediaAssets = [];
+ for (const asset of normalized.mediaAssets) {
+ if (asset.storageMode !== "managed") throw new Error(`“${entry.title || "未命名案例"}”包含未保存到本地的媒体`);
+ const blob = await getMediaBlob(asset.id);
+ if (!blob) throw new Error(`“${entry.title || "未命名案例"}”的媒体文件缺失`);
+ const assetPath = `${mediaDirectory(asset.kind)}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${mediaExtension(blob.type, asset.kind)}`;
+ files.push({ name: assetPath, data: blob });
+ mediaAssets.push({ ...asset, assetPath, byteSize: blob.size, mimeType: blob.type || asset.mimeType });
+ mediaCount += 1;
+ }
+ resolvedEntries.push({ ...normalized, mediaAssets });
+ }
+ files.unshift({
+ name: "library.json",
+ data: renderLibraryJson(
+ resolvedEntries,
+ settings,
+ taxonomy,
+ facetCatalog,
+ classificationRules,
+ organizerState,
+ null,
+ compoundCases
+ )
+ });
+ const payload = await createZipBlob(files);
+ const submissionId = await sha256Hex(payload);
+ const manifest = submissionManifest({
+ submissionId,
+ payloadBytes: payload.size,
+ caseCount: resolvedEntries.length,
+ mediaCount
+ });
+ const submissionArchive = await createZipBlob([
+ { name: "submission.json", data: `${JSON.stringify(manifest, null, 2)}\n` },
+ { name: "payload.zip", data: payload }
+ ]);
+ const archiveSha256 = await sha256Hex(submissionArchive);
+ const outputBlobs = submissionArchive.size <= CURATED_SUBMISSION_MAX_FILE_BYTES
+ ? [submissionArchive]
+ : await splitCuratedSubmissionArchive(submissionArchive, { submissionId, archiveSha256 });
+ const shortId = submissionId.slice(0, 12);
+ const outputs = outputBlobs.map((blob, index) => {
+ const url = URL.createObjectURL(blob);
+ blobUrls.add(url);
+ const split = outputBlobs.length > 1;
+ return {
+ url,
+ byteSize: blob.size,
+ filename: split
+ ? `PromptDirector-投稿-${shortId}-${String(index + 1).padStart(2, "0")}-of-${String(outputBlobs.length).padStart(2, "0")}.zip`
+ : `PromptDirector-投稿-${shortId}.zip`
+ };
+ });
+ return {
+ ok: true,
+ submissionId,
+ caseCount: resolvedEntries.length,
+ mediaCount,
+ payloadBytes: payload.size,
+ archiveBytes: submissionArchive.size,
+ partCount: outputs.length,
+ outputs
+ };
+}
+
+async function splitCuratedSubmissionArchive(archive, { submissionId, archiveSha256 }) {
+ const bytes = new Uint8Array(await archive.arrayBuffer());
+ const partCount = Math.ceil(bytes.byteLength / CURATED_SUBMISSION_PART_PAYLOAD_BYTES);
+ const parts = [];
+ for (let index = 0; index < partCount; index += 1) {
+ const start = index * CURATED_SUBMISSION_PART_PAYLOAD_BYTES;
+ const payload = bytes.slice(start, Math.min(bytes.byteLength, start + CURATED_SUBMISSION_PART_PAYLOAD_BYTES));
+ const manifest = submissionPartManifest({
+ submissionId,
+ archiveSha256,
+ archiveBytes: bytes.byteLength,
+ partIndex: index + 1,
+ partCount,
+ payloadSha256: await sha256Hex(payload),
+ payloadBytes: payload.byteLength
+ });
+ const part = await createZipBlob([
+ { name: "part.json", data: `${JSON.stringify(manifest, null, 2)}\n` },
+ { name: "payload.bin", data: payload }
+ ]);
+ if (part.size > CURATED_SUBMISSION_MAX_FILE_BYTES) throw new Error("投稿分卷超过 GitHub 上传上限");
+ parts.push(part);
+ }
+ return parts;
+}
+
async function packagedRuntimeAsset(path) {
const response = await fetch(chrome.runtime.getURL(path));
if (!response.ok) throw new Error(`分享页运行资源缺失:${path}`);
diff --git a/package-lock.json b/package-lock.json
index bd005c7..0ff40f0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "prompt-case-collector",
- "version": "1.18.4",
+ "version": "1.18.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.18.4",
+ "version": "1.18.5",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
diff --git a/package.json b/package.json
index 4a6dcca..daaf22d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.18.4",
+ "version": "1.18.5",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
diff --git a/page-capture-adapter-registry.js b/page-capture-adapter-registry.js
new file mode 100644
index 0000000..d631997
--- /dev/null
+++ b/page-capture-adapter-registry.js
@@ -0,0 +1,164 @@
+const GENERIC_CARD_SELECTORS = Object.freeze(["main article", "[role=main] article"]);
+const EMPTY_FIELDS = Object.freeze({});
+
+export const GENERIC_PAGE_CAPTURE_ADAPTER = Object.freeze({
+ id: "generic",
+ label: "通用网页",
+ support: "generic",
+ hosts: Object.freeze([]),
+ cardSelectors: GENERIC_CARD_SELECTORS,
+ fields: EMPTY_FIELDS,
+ trustedMediaHosts: Object.freeze([])
+});
+
+export const PAGE_CAPTURE_ADAPTERS = Object.freeze([
+ adapter("jimeng", "即梦", ["jimeng.jianying.com"], "verified-deep", ["[data-testid*=work]", "[class*=masonry] > *"], {
+ title: ["[class*=title]"], author: ["[class*=author]"], model: ["[class*=model]"]
+ }, ["byteimg.com"]),
+ adapter("liblibai", "LiblibAI", ["liblib.art", "liblib.ai"], "verified-deep", ["[class*=work-card]", "[class*=waterfall] > *"], {}, ["liblib.cloud"]),
+ adapter("higgsfield", "Higgsfield", ["higgsfield.ai"], "verified-declarative", ["[data-testid*=creation]", "[class*=feed] > article"], {}, ["higgsfield.ai", "higgs.ai", "d2ol7oe51mr4n9.cloudfront.net", "du4zrvwy3vtek.cloudfront.net", "d8j0ntlcm91z4.cloudfront.net"]),
+ adapter("krea", "Krea", ["krea.ai"], "verified-declarative", ["a[href^='/feed/']", "[data-testid*=generation]", "[class*=gallery] > *"], {}, ["krea.ai"]),
+ adapter("tapnow", "TapNow", ["tapnow.ai"], "generic", ["[data-testid*=work]", "[class*=gallery] > *"]),
+
+ adapter("pinterest", "Pinterest", ["pinterest.com", "pin.it"], "verified-deep", ["[data-test-id=pin]", "[data-grid-item]"], {}, ["i.pinimg.com"]),
+ adapter("behance", "Behance", ["behance.net"], "verified-declarative", ["[data-project-id]", "main article"], {}, ["mir-s3-cdn-cf.behance.net"]),
+ adapter("dribbble", "Dribbble", ["dribbble.com"], "generic", ["[data-thumbnail-id]", "main article"]),
+ adapter("artstation", "ArtStation", ["artstation.com"], "generic", [".project", "[data-test=project-card]"]),
+ adapter("deviantart", "DeviantArt", ["deviantart.com"], "generic", ["main article", "[data-hook=deviation_link]"]),
+ adapter("designspiration", "Designspiration", ["designspiration.com"], "generic", ["main article", "[data-testid*=save]"]),
+ adapter("huaban", "花瓣", ["huaban.com"], "generic", ["[data-id][data-type=pin]", "main article"]),
+ adapter("zcool", "站酷", ["zcool.com.cn"], "generic", ["main article", "[class*=work-card]"]),
+ adapter("500px", "500px", ["500px.com"], "generic", ["main article", "[data-testid*=photo]"]),
+ adapter("flickr", "Flickr", ["flickr.com", "flic.kr"], "generic", ["main article", "[class*=photo-list-photo]"]),
+ adapter("pexels", "Pexels", ["pexels.com"], "generic", ["main article", "[data-testid*=media-grid]"]),
+
+ adapter("instagram", "Instagram", ["instagram.com"], "generic", ["main article", "article"]),
+ adapter("x", "X", ["x.com", "twitter.com"], "generic", ["article[data-testid=tweet]"], {
+ author: ["[data-testid=User-Name] a[href^='/'] span:first-child", "[data-testid=User-Name]"], handle: ["[data-testid=User-Name] a[href^='/']"],
+ canonicalUrl: ["a[href*='/status/']"], publishedAt: ["time"], likes: ["[data-testid=like]"], reposts: ["[data-testid=retweet]"]
+ }),
+ adapter("reddit", "Reddit", ["reddit.com", "redd.it"], "generic", ["shreddit-post", "article"], {
+ title: ["[slot=title]", "h1,h2,h3"], author: ["[slot=authorName]", "[class*=author]"], publishedAt: ["time"]
+ }),
+ adapter("imgur", "Imgur", ["imgur.com"], "generic", ["main article", "[class*=Gallery-Content]"]),
+ adapter("weibo", "微博", ["weibo.com", "weibo.cn"], "generic", ["article", "[class*=Feed_wrap]"]),
+ adapter("jike", "即刻", ["okjike.com"], "generic", ["main article", "[data-testid*=post]"]),
+ adapter("qzone", "QQ 空间相册", ["qzone.qq.com", "photo.qq.com"], "generic", ["main article", "[class*=photo]"]),
+ adapter("douban", "豆瓣相册", ["douban.com"], "generic", ["main article", ".photo_wrap", ".photolst li"]),
+ adapter("poco", "POCO", ["poco.cn"], "generic", ["main article", "[class*=work]"]),
+
+ adapter("wechat", "微信公众号", ["mp.weixin.qq.com"], "verified-declarative", ["#js_content"], {
+ title: ["#activity-name"], author: ["#js_name"], publishedAt: ["#publish_time", "em#publish_time"]
+ }, ["qpic.cn", "qlogo.cn"]),
+ adapter("medium", "Medium", ["medium.com"], "generic", ["main article", "article"]),
+
+ adapter("jd", "京东", ["jd.com"], "generic", ["main", "[class*=product-intro]"]),
+ adapter("taobao", "淘宝", ["taobao.com"], "generic", ["main", "[class*=Item]"]),
+ adapter("tmall", "天猫", ["tmall.com"], "generic", ["main", "[class*=Item]"]),
+ adapter("1688", "1688", ["1688.com"], "generic", ["main", "[class*=offer]"]),
+ adapter("mogujie", "蘑菇街", ["mogujie.com"], "generic", ["main", "[class*=detail]"]),
+
+ adapter("architectural-digest", "Architectural Digest", ["architecturaldigest.com"], "generic", ["main article", "article"]),
+ adapter("archiproducts", "Archiproducts", ["archiproducts.com"], "generic", ["main article", "main"]),
+ adapter("houzz", "Houzz", ["houzz.com"], "generic", ["main article", "main"]),
+ adapter("house-beautiful", "House Beautiful", ["housebeautiful.com"], "generic", ["main article", "article"]),
+ adapter("officesnapshots", "OfficeSnapshots", ["officesnapshots.com"], "generic", ["main article", "article"]),
+ adapter("archilovers", "Archilovers", ["archilovers.com"], "generic", ["main article", "main"]),
+ adapter("archdaily", "ArchDaily", ["archdaily.com"], "generic", ["main article", "article"]),
+ adapter("archdaily-cn", "ArchDaily 中文", ["archdaily.cn"], "generic", ["main article", "article"]),
+ adapter("dezeen", "Dezeen", ["dezeen.com"], "generic", ["main article", "article"]),
+ adapter("interior-design", "Interior Design", ["interiordesign.net"], "generic", ["main article", "article"]),
+
+ adapter("youtube", "YouTube", ["youtube.com", "youtu.be"], "generic", ["ytd-rich-item-renderer", "ytd-video-renderer"], {
+ title: ["#video-title"], author: ["#channel-name"], views: ["#metadata-line span"]
+ }),
+ adapter("bilibili", "哔哩哔哩", ["bilibili.com", "b23.tv"], "generic", [".bili-video-card", ".video-card"]),
+ adapter("steam", "Steam", ["steampowered.com", "steamcommunity.com"], "generic", [".apphub_Card", ".search_result_row", ".workshopItem"])
+]);
+
+export const PAGE_CAPTURE_PLATFORM_ADAPTERS = Object.freeze([
+ platformAdapter("wordpress", "WordPress", { generator: ["\\bwordpress\\b"], links: ["/wp-(?:content|includes)/"] }),
+ platformAdapter("wix", "Wix", { generator: ["\\bwix\\b"], applicationName: ["\\bwix\\b"], scripts: ["(?:parastorage|wixstatic|wix-thunderbolt)"], links: ["(?:parastorage|wixstatic|wix-thunderbolt)"] }),
+ platformAdapter("squarespace", "Squarespace", { generator: ["\\bsquarespace\\b"], applicationName: ["\\bsquarespace\\b"], scripts: ["squarespace(?:\\.com|-cdn)"], links: ["squarespace(?:\\.com|-cdn)"] }),
+ platformAdapter("medium", "Medium", { generator: ["\\bmedium\\b"], applicationName: ["\\bmedium\\b"], links: ["medium\\.com"] })
+]);
+
+export function resolvePageCaptureAdapter(value, signalsValue = {}, adapters = PAGE_CAPTURE_ADAPTERS) {
+ const host = hostname(value);
+ const direct = adapters.find((item) => item.hosts.some((suffix) => host === suffix || host.endsWith(`.${suffix}`)));
+ if (direct) return direct;
+ const signals = normalizeSignals(signalsValue);
+ return PAGE_CAPTURE_PLATFORM_ADAPTERS.find((item) => matchesPlatformSignals(item, signals)) || GENERIC_PAGE_CAPTURE_ADAPTER;
+}
+
+export function pageCaptureSupportMatrix() {
+ return [...PAGE_CAPTURE_ADAPTERS, ...PAGE_CAPTURE_PLATFORM_ADAPTERS].map(({ id, label, hosts = [], support }) => ({
+ id, label, hosts: [...hosts], support
+ }));
+}
+
+function adapter(id, label, hosts, support, cardSelectors, fields = EMPTY_FIELDS, trustedMediaHosts = []) {
+ return Object.freeze({
+ id,
+ label,
+ support,
+ pageType: defaultPageType(id),
+ hosts: Object.freeze([...hosts]),
+ cardSelectors: Object.freeze([...cardSelectors]),
+ fields: Object.freeze({ ...fields }),
+ trustedMediaHosts: Object.freeze([...trustedMediaHosts])
+ });
+}
+
+function platformAdapter(id, label, signalPatterns) {
+ return Object.freeze({
+ id,
+ label,
+ support: "generic",
+ pageType: id === "medium" ? "article" : "generic",
+ hosts: Object.freeze([]),
+ cardSelectors: GENERIC_CARD_SELECTORS,
+ fields: EMPTY_FIELDS,
+ trustedMediaHosts: Object.freeze([]),
+ signalPatterns: Object.freeze(Object.fromEntries(Object.entries(signalPatterns).map(([key, values]) => [key, Object.freeze([...values])])))
+ });
+}
+
+function defaultPageType(id) {
+ if (["youtube", "bilibili"].includes(id)) return "video";
+ if (["x", "reddit", "instagram", "weibo", "jike"].includes(id)) return "post";
+ if (["wechat", "medium", "architectural-digest", "house-beautiful", "officesnapshots", "archdaily", "archdaily-cn", "dezeen", "interior-design"].includes(id)) return "article";
+ return "artwork";
+}
+
+function matchesPlatformSignals(adapterValue, signals) {
+ return Object.entries(adapterValue.signalPatterns || {}).some(([key, patterns]) => {
+ const values = Array.isArray(signals[key]) ? signals[key] : [signals[key]];
+ return patterns.some((pattern) => values.some((value) => {
+ try { return new RegExp(pattern, "iu").test(value); } catch { return false; }
+ }));
+ });
+}
+
+function normalizeSignals(value = {}) {
+ const metas = value?.metas && typeof value.metas === "object" ? value.metas : {};
+ return {
+ generator: clean(metas.generator || value.generator),
+ applicationName: clean(metas.applicationName || value.applicationName),
+ scripts: stringList(value.scripts),
+ links: stringList(value.links)
+ };
+}
+
+function stringList(value) {
+ return (Array.isArray(value) ? value : []).map(clean).filter(Boolean);
+}
+
+function hostname(value) {
+ try { return new URL(String(value ?? "")).hostname.toLocaleLowerCase("en-US"); }
+ catch { return clean(value).toLocaleLowerCase("en-US"); }
+}
+
+function clean(value) {
+ return String(value ?? "").trim();
+}
diff --git a/page-capture-site-adapters.js b/page-capture-site-adapters.js
new file mode 100644
index 0000000..3775db1
--- /dev/null
+++ b/page-capture-site-adapters.js
@@ -0,0 +1,1187 @@
+const JIMENG_HOST = "jimeng.jianying.com";
+const JIMENG_DETAIL_PATH = "/ai-tool/work-detail/";
+const JIMENG_OBSERVER_KEY = "__PROMPTDIRECTOR_JIMENG_CAPTURE__";
+const JIMENG_IMAGE_HOST_PATTERN = /^p\d+-(?:dreamina|artist)(?:-safe)?-sign\.byteimg\.com$/u;
+
+export function installPageCaptureSiteObserver(options = {}) {
+ const clean = (value) => String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
+ if (clean(globalThis.location?.hostname).toLocaleLowerCase("en-US") !== "jimeng.jianying.com") return null;
+ const stateKey = "__PROMPTDIRECTOR_JIMENG_CAPTURE__";
+ const maxItems = Number(options.maxCandidates);
+ const maxMedia = Number(options.maxMedia);
+ if (!Number.isSafeInteger(maxItems) || maxItems <= 0 || !Number.isSafeInteger(maxMedia) || maxMedia <= 0) {
+ return { installed: false, reason: "invalid-resource-limits" };
+ }
+ const existing = globalThis[stateKey];
+ if (existing?.version === 1) {
+ existing.maxItems = maxItems;
+ existing.maxMedia = maxMedia;
+ return { installed: true, itemCount: Array.isArray(existing.items) ? existing.items.length : 0 };
+ }
+
+ const state = {
+ version: 1,
+ maxItems,
+ maxMedia,
+ items: [],
+ modelNames: {},
+ updatedAt: ""
+ };
+ Object.defineProperty(globalThis, stateKey, { value: state, configurable: true });
+
+ const safeText = (value, limit = 10000) => clean(value).slice(0, limit);
+ const safeInteger = (value) => Number.isSafeInteger(Number(value)) ? Number(value) : 0;
+ const modelKey = (content) => {
+ try {
+ const draft = JSON.parse(String(content || "{}"));
+ return safeText(draft?.component_list?.[0]?.abilities?.generate?.core_param?.model, 200);
+ } catch {
+ return "";
+ }
+ };
+ const safeImage = (value) => ({
+ image_url: safeText(value?.image_url, 5000),
+ width: safeInteger(value?.width),
+ height: safeInteger(value?.height),
+ format: safeText(value?.format, 20)
+ });
+ const sanitizeItem = (item) => {
+ const id = safeText(item?.common_attr?.id, 64);
+ if (!/^\d{8,32}$/u.test(id)) return null;
+ return {
+ extra: { template_type: safeText(item?.extra?.template_type, 40) },
+ common_attr: {
+ id,
+ title: safeText(item?.common_attr?.title, 500),
+ description: safeText(item?.common_attr?.description),
+ create_time: safeInteger(item?.common_attr?.create_time)
+ },
+ author: {
+ name: safeText(item?.author?.name, 300),
+ uid: safeText(item?.author?.uid, 200)
+ },
+ aigc_image_params: {
+ text2image_params: { prompt: safeText(item?.aigc_image_params?.text2image_params?.prompt, 30000) }
+ },
+ model_key: safeText(item?.model_key, 200) || modelKey(item?.aigc_draft?.content),
+ statistic: {
+ favorite_num: safeInteger(item?.statistic?.favorite_num),
+ usage_num: safeInteger(item?.statistic?.usage_num)
+ },
+ image: {
+ large_images: (Array.isArray(item?.image?.large_images) ? item.image.large_images : [])
+ .slice(0, state.maxMedia)
+ .map(safeImage)
+ }
+ };
+ };
+ const ingestModels = (value) => {
+ for (const model of value?.data?.model_list || []) {
+ const key = safeText(model?.model_req_key, 200);
+ const name = safeText(model?.model_name, 300);
+ if (key && name) state.modelNames[key] = name;
+ }
+ };
+ const ingest = (payload) => {
+ const items = Array.isArray(payload?.data?.item_list) ? payload.data.item_list : [];
+ const byId = new Map(state.items.map((item) => [item.common_attr.id, item]));
+ for (const value of items) {
+ const item = sanitizeItem(value);
+ if (item) byId.set(item.common_attr.id, item);
+ }
+ state.items = [...byId.values()].slice(-state.maxItems);
+ state.updatedAt = new Date().toISOString();
+ };
+ const isFeedUrl = (value) => {
+ try {
+ const url = new URL(String(value || ""), globalThis.location?.href);
+ return url.hostname === "jimeng.jianying.com" && ["/mweb/v1/get_explore", "/mweb/v1/feed"].includes(url.pathname);
+ } catch {
+ return false;
+ }
+ };
+
+ ingest(globalThis.__get_explore_result);
+ ingestModels(globalThis.__image_generate_model_config__);
+
+ if (typeof globalThis.fetch === "function") {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async function promptDirectorObservedFetch(...args) {
+ const response = await originalFetch.apply(this, args);
+ const requestUrl = typeof args[0] === "string" || args[0] instanceof URL ? args[0] : args[0]?.url;
+ if (response?.ok && isFeedUrl(requestUrl || response.url)) {
+ response.clone().json().then(ingest).catch(() => undefined);
+ }
+ return response;
+ };
+ }
+
+ const Xhr = globalThis.XMLHttpRequest;
+ if (typeof Xhr === "function") {
+ const originalOpen = Xhr.prototype.open;
+ const originalSend = Xhr.prototype.send;
+ Xhr.prototype.open = function promptDirectorObservedOpen(method, url, ...rest) {
+ this.__promptDirectorJimengFeed = isFeedUrl(url);
+ return originalOpen.call(this, method, url, ...rest);
+ };
+ Xhr.prototype.send = function promptDirectorObservedSend(...args) {
+ if (this.__promptDirectorJimengFeed) {
+ this.addEventListener("loadend", () => {
+ if (this.status < 200 || this.status >= 300 || typeof this.responseText !== "string") return;
+ try { ingest(JSON.parse(this.responseText)); } catch { }
+ }, { once: true });
+ }
+ return originalSend.apply(this, args);
+ };
+ }
+
+ let checks = 0;
+ const timer = globalThis.setInterval?.(() => {
+ checks += 1;
+ ingest(globalThis.__get_explore_result);
+ ingestModels(globalThis.__image_generate_model_config__);
+ if (checks >= 40 || state.items.length) globalThis.clearInterval?.(timer);
+ }, 250);
+ return { installed: true, itemCount: state.items.length };
+}
+
+export function collectPageCaptureSitePayload(options = {}) {
+ const clean = (value) => String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
+ const maxMedia = Number.isSafeInteger(Number(options.maxMedia)) && Number(options.maxMedia) > 0 ? Number(options.maxMedia) : 0;
+ const maxNodes = Number.isSafeInteger(Number(options.maxCandidates)) && Number(options.maxCandidates) > 0 ? Number(options.maxCandidates) : 0;
+ const maxTextCharacters = Number.isSafeInteger(Number(options.maxTextCharacters)) && Number(options.maxTextCharacters) > 0 ? Number(options.maxTextCharacters) : 0;
+ const host = clean(globalThis.location?.hostname).toLocaleLowerCase("en-US");
+ if ((host === "liblib.art" || host.endsWith(".liblib.art") || host === "liblib.ai" || host.endsWith(".liblib.ai"))
+ && clean(globalThis.location?.pathname).startsWith("/imageinfo/")) {
+ try {
+ const nextData = JSON.parse(String(globalThis.document?.querySelector?.("#__NEXT_DATA__")?.textContent || "null"));
+ const pageProps = nextData?.props?.pageProps;
+ const data = pageProps?.data;
+ if (!data || typeof data !== "object") return { adapter: "liblibai", status: "partial" };
+ const rawImages = Array.isArray(data.images)
+ ? data.images
+ : (Array.isArray(data.imagesV2) ? data.imagesV2.flatMap((items) => Array.isArray(items) ? items : []) : []);
+ const images = rawImages.slice(0, maxMedia).map((image) => ({
+ id: Number(image?.id) || 0,
+ uuid: clean(image?.uuid),
+ originalImageUrl: clean(image?.originalImageUrl || image?.previewUrl),
+ imageUrl: clean(image?.imageUrl || image?.watermarkImageUrl),
+ width: Number(image?.width) || 0,
+ height: Number(image?.height) || 0,
+ generateInfo: {
+ prompt: String(image?.generateInfo?.prompt || "").slice(0, maxTextCharacters),
+ negativePrompt: String(image?.generateInfo?.negativePrompt || "").slice(0, maxTextCharacters)
+ },
+ models: (Array.isArray(image?.models) ? image.models : []).slice(0, maxMedia).map((model) => ({
+ modelName: clean(model?.modelName),
+ versionName: clean(model?.versionName),
+ modelType: Number(model?.modelType) || 0
+ }))
+ }));
+ return {
+ adapter: "liblibai",
+ canonicalUrl: clean(globalThis.location?.href),
+ data: {
+ uuid: clean(data.uuid),
+ title: clean(data.title),
+ createTime: clean(data.createTime),
+ counter: {
+ likeCount: Number(data?.counter?.likeCount) || 0,
+ commentCount: Number(data?.counter?.commentCount) || 0,
+ hitCount: Number(data?.counter?.hitCount) || 0
+ },
+ images
+ },
+ author: {
+ nickname: clean(pageProps?.authorInfo?.userDetail?.nickname),
+ uuid: clean(pageProps?.authorInfo?.userDetail?.uuid)
+ },
+ status: images.length ? "complete" : "partial"
+ };
+ } catch {
+ return { adapter: "liblibai", status: "partial" };
+ }
+ }
+ if (host === "krea.ai" || host.endsWith(".krea.ai")) {
+ const compactImageObject = (value) => ({
+ "@type": clean(value?.["@type"]),
+ name: clean(value?.name),
+ url: clean(value?.url),
+ contentUrl: clean(value?.contentUrl),
+ thumbnailUrl: clean(value?.thumbnailUrl),
+ datePublished: clean(value?.datePublished),
+ width: Number(value?.width?.value || value?.width) || 0,
+ height: Number(value?.height?.value || value?.height) || 0
+ });
+ const jsonLd = [];
+ for (const script of [...(globalThis.document?.querySelectorAll?.('script[type="application/ld+json"]') || [])].slice(0, maxNodes)) {
+ try {
+ const parsed = JSON.parse(String(script.textContent || "null"));
+ const values = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.["@graph"]) ? parsed["@graph"] : [parsed];
+ for (const value of values) {
+ const type = Array.isArray(value?.["@type"]) ? value["@type"] : [value?.["@type"]];
+ if (type.includes("ImageObject") && jsonLd.length < maxNodes) jsonLd.push(compactImageObject(value));
+ }
+ } catch {
+ }
+ }
+ const path = clean(globalThis.location?.pathname);
+ const uuidPattern = /[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/iu;
+ const detailId = path.match(uuidPattern)?.[0]?.toLocaleLowerCase("en-US") || "";
+ if (detailId) {
+ return {
+ adapter: "krea",
+ pageKind: "detail",
+ canonicalUrl: clean(globalThis.location?.href),
+ prompt: String(globalThis.document?.querySelector?.("article h1")?.textContent || "").slice(0, maxTextCharacters).trim(),
+ jsonLd,
+ status: jsonLd.length ? "complete" : "partial"
+ };
+ }
+ const items = [];
+ const seen = new Set();
+ for (const link of [...(globalThis.document?.querySelectorAll?.('a[href^="/feed/"],a[href^="https://www.krea.ai/feed/"]') || [])].slice(0, maxNodes * 2)) {
+ const href = clean(link.href || link.getAttribute?.("href"));
+ let canonicalUrl = "";
+ try { canonicalUrl = new URL(href, globalThis.location?.href).href; } catch { continue; }
+ const itemId = canonicalUrl.match(uuidPattern)?.[0]?.toLocaleLowerCase("en-US") || "";
+ if (!itemId || seen.has(itemId)) continue;
+ const imageNode = link.querySelector?.('[style*="background"]');
+ const styleText = clean(imageNode?.style?.backgroundImage || imageNode?.getAttribute?.("style"));
+ const imageUrls = styleText.match(/https:\/\/[^\s"')]+/gu) || [];
+ const observedImage = imageUrls.find((url) => url.includes("-1024.webp")) || imageUrls[0] || "";
+ let observedHost = "";
+ try { observedHost = new URL(observedImage).hostname; } catch { }
+ const imageUrl = observedImage.includes(itemId) && (observedHost === "krea.ai" || observedHost.endsWith(".krea.ai"))
+ ? `https://gen.krea.ai/images/${itemId}.png`
+ : observedImage;
+ if (!imageUrl) continue;
+ const slug = new URL(canonicalUrl).pathname.split("/").filter(Boolean).at(-1) || "";
+ seen.add(itemId);
+ items.push({
+ itemId,
+ canonicalUrl,
+ title: clean(slug.replace(new RegExp(`-${itemId}$`, "iu"), "").replace(/-/gu, " ")),
+ imageUrl
+ });
+ if (items.length >= maxNodes) break;
+ }
+ return { adapter: "krea", pageKind: "feed", canonicalUrl: clean(globalThis.location?.href), items, status: items.length ? "complete" : "partial" };
+ }
+ if (host === "higgsfield.ai" || host.endsWith(".higgsfield.ai")) {
+ const compactPerson = (value) => value && typeof value === "object" ? {
+ "@type": clean(value["@type"]),
+ name: clean(value.name),
+ alternateName: clean(value.alternateName),
+ identifier: clean(value.identifier)
+ } : null;
+ const compactImage = (value) => {
+ if (typeof value === "string") return clean(value);
+ if (!value || typeof value !== "object") return "";
+ return {
+ url: clean(value.url),
+ contentUrl: clean(value.contentUrl),
+ thumbnailUrl: clean(value.thumbnailUrl),
+ width: Number(value.width?.value || value.width) || 0,
+ height: Number(value.height?.value || value.height) || 0
+ };
+ };
+ const compactStatistics = (value) => (Array.isArray(value) ? value : value ? [value] : []).slice(0, maxMedia).map((item) => ({
+ interactionType: { "@type": clean(item?.interactionType?.["@type"] || item?.interactionType) },
+ userInteractionCount: Number(item?.userInteractionCount) || 0
+ }));
+ const compactCreativeWork = (value) => ({
+ "@type": clean(value?.["@type"]),
+ name: clean(value?.name),
+ description: String(value?.description || "").slice(0, maxTextCharacters).trim(),
+ url: clean(value?.url),
+ identifier: clean(value?.identifier),
+ author: compactPerson(value?.author || value?.creator),
+ datePublished: clean(value?.datePublished || value?.dateCreated || value?.uploadDate),
+ image: (Array.isArray(value?.image) ? value.image : value?.image ? [value.image] : []).slice(0, maxMedia).map(compactImage).filter(Boolean),
+ thumbnailUrl: clean(value?.thumbnailUrl),
+ interactionStatistic: compactStatistics(value?.interactionStatistic)
+ });
+ const jsonLd = [];
+ for (const script of [...(globalThis.document?.querySelectorAll?.('script[type="application/ld+json"]') || [])].slice(0, maxNodes)) {
+ try {
+ const parsed = JSON.parse(String(script.textContent || "null"));
+ const values = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.["@graph"]) ? parsed["@graph"] : [parsed];
+ for (const value of values) {
+ const types = Array.isArray(value?.["@type"]) ? value["@type"] : [value?.["@type"]];
+ if (types.includes("CreativeWork") && jsonLd.length < maxNodes) jsonLd.push(compactCreativeWork(value));
+ if (types.includes("ItemList") && jsonLd.length < maxNodes) {
+ jsonLd.push({
+ "@type": "ItemList",
+ itemListElement: (Array.isArray(value?.itemListElement) ? value.itemListElement : []).slice(0, maxNodes).flatMap((entry, index) => {
+ const item = entry?.item || entry;
+ const itemTypes = Array.isArray(item?.["@type"]) ? item["@type"] : [item?.["@type"]];
+ return itemTypes.includes("CreativeWork") ? [{ position: Number(entry?.position) || index + 1, item: compactCreativeWork(item) }] : [];
+ })
+ });
+ }
+ }
+ } catch {
+ }
+ }
+ const detail = /^\/@[^/]+\/projects\/[^/]+/u.test(clean(globalThis.location?.pathname));
+ const brief = detail
+ ? String(globalThis.document?.querySelector?.('[aria-label^="Project brief:"]')?.innerText || "").slice(0, maxTextCharacters).trim()
+ : "";
+ return {
+ adapter: "higgsfield",
+ pageKind: detail ? "detail" : "feed",
+ canonicalUrl: clean(globalThis.location?.href),
+ brief,
+ jsonLd,
+ status: jsonLd.length ? "complete" : "partial"
+ };
+ }
+ if ((host === "pinterest.com" || host.endsWith(".pinterest.com")) && /^\/pin\/(?:[^/]*--)?\d+\/?$/u.test(clean(globalThis.location?.pathname))) {
+ const parseRelayResponse = (source) => {
+ const text = String(source || "");
+ const marker = "window.__PWS_RELAY_REGISTER_COMPLETED_REQUEST__";
+ const markerIndex = text.indexOf(marker);
+ if (markerIndex < 0 || text.length > maxTextCharacters) return null;
+ const separator = text.indexOf(", {", markerIndex + marker.length);
+ if (separator < 0) return null;
+ const start = text.indexOf("{", separator);
+ let depth = 0;
+ let quote = "";
+ let escaped = false;
+ for (let index = start; index < text.length; index += 1) {
+ const character = text[index];
+ if (quote) {
+ if (escaped) escaped = false;
+ else if (character === "\\") escaped = true;
+ else if (character === quote) quote = "";
+ continue;
+ }
+ if (character === '"') {
+ quote = character;
+ continue;
+ }
+ if (character === "{") depth += 1;
+ if (character === "}") depth -= 1;
+ if (depth === 0) {
+ try { return JSON.parse(text.slice(start, index + 1)); } catch { return null; }
+ }
+ }
+ return null;
+ };
+ let rawPin = null;
+ for (const script of [...(globalThis.document?.scripts || [])]) {
+ const text = String(script?.textContent || "");
+ if (!text.includes("v3GetPinQueryv2")) continue;
+ rawPin = parseRelayResponse(text)?.data?.v3GetPinQueryv2?.data || null;
+ if (rawPin) break;
+ }
+ if (!rawPin || typeof rawPin !== "object") return { adapter: "pinterest", pageKind: "detail", status: "partial" };
+ const image = (value) => ({
+ url: clean(value?.url),
+ width: Number(value?.width) || 0,
+ height: Number(value?.height) || 0
+ });
+ const creator = rawPin.nativeCreator || rawPin.closeupAttribution || rawPin.pinner || {};
+ const repins = Number(globalThis.document?.querySelector?.('meta[property="pinterestapp:repins"],meta[name="pinterestapp:repins"]')?.content);
+ return {
+ adapter: "pinterest",
+ pageKind: "detail",
+ canonicalUrl: clean(globalThis.location?.href),
+ pin: {
+ entityId: clean(rawPin.entityId),
+ title: clean(rawPin.gridTitle || rawPin.seoTitle),
+ description: String(rawPin.gridDescription || rawPin.description || "").slice(0, maxTextCharacters).trim(),
+ createdAt: clean(rawPin.createdAt),
+ author: {
+ fullName: clean(creator.fullName || creator.name || creator.firstName),
+ username: clean(creator.username)
+ },
+ ...(Number.isSafeInteger(repins) && repins >= 0 ? { repins } : {}),
+ images: {
+ original: image(rawPin.images_orig || (rawPin.embed?.src ? { url: rawPin.embed.src } : null)),
+ large: image(rawPin.images_1200x || rawPin.images_736x),
+ display: image(rawPin.images_736x || rawPin.images_564x)
+ }
+ },
+ status: "complete"
+ };
+ }
+ if ((host === "behance.net" || host.endsWith(".behance.net")) && /^\/gallery\/\d+\//u.test(clean(globalThis.location?.pathname))) {
+ const jsonLd = [];
+ for (const script of [...(globalThis.document?.querySelectorAll?.('script[type="application/ld+json"]') || [])].slice(0, maxNodes)) {
+ try {
+ const parsed = JSON.parse(String(script.textContent || "null"));
+ const values = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.["@graph"]) ? parsed["@graph"] : [parsed];
+ for (const value of values) {
+ const types = Array.isArray(value?.["@type"]) ? value["@type"] : [value?.["@type"]];
+ if (!types.includes("VisualArtwork") || jsonLd.length >= maxNodes) continue;
+ jsonLd.push({
+ "@type": "VisualArtwork",
+ name: clean(value?.name),
+ description: String(value?.description || "").slice(0, maxTextCharacters).trim(),
+ url: clean(value?.url),
+ identifier: clean(value?.identifier),
+ image: clean(typeof value?.image === "string" ? value.image : value?.image?.contentUrl || value?.image?.url),
+ creator: (Array.isArray(value?.creator) ? value.creator : value?.creator ? [value.creator] : []).slice(0, maxMedia).map((creator) => ({
+ "@type": clean(creator?.["@type"]),
+ identifier: clean(creator?.identifier),
+ name: clean(creator?.name),
+ url: clean(creator?.url)
+ })),
+ interactionStatistic: (Array.isArray(value?.interactionStatistic) ? value.interactionStatistic : value?.interactionStatistic ? [value.interactionStatistic] : []).slice(0, maxMedia).map((item) => ({
+ interactionType: clean(item?.interactionType?.["@type"] || item?.interactionType),
+ userInteractionCount: Number(item?.userInteractionCount) || 0
+ }))
+ });
+ }
+ } catch {
+ }
+ }
+ return {
+ adapter: "behance",
+ pageKind: "detail",
+ canonicalUrl: clean(globalThis.location?.href),
+ publishedAt: clean(globalThis.document?.querySelector?.("time[datetime]")?.dateTime || globalThis.document?.querySelector?.("time[datetime]")?.getAttribute?.("datetime")),
+ jsonLd,
+ status: jsonLd.length ? "complete" : "partial"
+ };
+ }
+ if (host === "mp.weixin.qq.com") {
+ const content = globalThis.document?.querySelector?.("#js_content");
+ if (!content) return { adapter: "wechat", status: "partial" };
+ const images = [...(content.querySelectorAll?.("img") || [])].slice(0, maxMedia).flatMap((image) => {
+ const url = clean(image.getAttribute?.("data-src") || image.currentSrc || image.src);
+ if (!url) return [];
+ const width = Number(image.getAttribute?.("data-w") || image.naturalWidth || image.width) || 0;
+ const naturalHeight = Number(image.naturalHeight || image.height) || 0;
+ const ratio = Number(image.getAttribute?.("data-ratio")) || 0;
+ return [{ url, width, height: naturalHeight || (width && ratio ? Math.round(width * ratio) : 0), alt: clean(image.alt) }];
+ });
+ return {
+ adapter: "wechat",
+ canonicalUrl: clean(globalThis.location?.href),
+ title: clean(globalThis.document.querySelector?.("#activity-name")?.textContent),
+ author: clean(globalThis.document.querySelector?.("#js_name")?.textContent),
+ publishedAt: clean(globalThis.document.querySelector?.("#publish_time")?.getAttribute?.("datetime") || globalThis.document.querySelector?.("#publish_time")?.textContent),
+ contentText: String(content.innerText || "").replace(/\r\n?/g, "\n").trim().slice(0, maxTextCharacters),
+ images,
+ status: "complete"
+ };
+ }
+ if (host !== "jimeng.jianying.com") return null;
+
+ const path = clean(globalThis.location?.pathname);
+ const rawLastPart = path.split("/").filter(Boolean).at(-1) || "";
+ const workId = /^\d{8,32}$/u.test(rawLastPart) ? rawLastPart : "";
+ const pageKind = workId ? "detail" : path.startsWith("/ai-tool/home") ? "feed" : "unknown";
+ const parseAssignedJson = (source, marker) => {
+ const text = String(source || "");
+ const markerIndex = text.indexOf(marker);
+ if (markerIndex < 0) return null;
+ let start = markerIndex + marker.length;
+ while (/\s/u.test(text[start] || "")) start += 1;
+ const opening = text[start];
+ const closing = opening === "{" ? "}" : opening === "[" ? "]" : "";
+ if (!closing) return null;
+ let depth = 0;
+ let quote = "";
+ let escaped = false;
+ for (let index = start; index < text.length; index += 1) {
+ const character = text[index];
+ if (quote) {
+ if (escaped) escaped = false;
+ else if (character === "\\") escaped = true;
+ else if (character === quote) quote = "";
+ continue;
+ }
+ if (character === '"' || character === "'") {
+ quote = character;
+ continue;
+ }
+ if (character === opening) depth += 1;
+ if (character === closing) depth -= 1;
+ if (depth === 0) {
+ try { return JSON.parse(text.slice(start, index + 1)); }
+ catch { return null; }
+ }
+ }
+ return null;
+ };
+ const scripts = [...(globalThis.document?.scripts || [])];
+ const assigned = (marker) => {
+ for (const script of scripts) {
+ const parsed = parseAssignedJson(script?.textContent, marker);
+ if (parsed) return parsed;
+ }
+ return null;
+ };
+ const explore = globalThis.__get_explore_result || assigned("window.__get_explore_result=");
+ const modelConfig = globalThis.__image_generate_model_config__
+ || assigned("window.__image_generate_model_config__=");
+ const observer = globalThis.__PROMPTDIRECTOR_JIMENG_CAPTURE__;
+ const observedItems = Array.isArray(observer?.items) ? observer.items : [];
+ const initialItems = Array.isArray(explore?.data?.item_list) ? explore.data.item_list : [];
+ const byId = new Map();
+ for (const item of [...initialItems, ...observedItems]) {
+ const id = clean(item?.common_attr?.id);
+ if (/^\d{8,32}$/u.test(id)) byId.set(id, item);
+ }
+
+ const detailFromDom = () => {
+ if (!workId || !globalThis.document?.body) return null;
+ const bodyText = String(globalThis.document.body.innerText || "").replace(/\r\n?/g, "\n");
+ const lines = bodyText.split("\n").map((line) => line.replace(/\s+/g, " ").trim()).filter(Boolean);
+ const dateIndex = lines.findIndex((line) => /20\d{2}[-/.]\d{1,2}[-/.]\d{1,2}/u.test(line));
+ const excludedAuthor = /^(?:\+?\s*关注|更多|图片提示词|内容由\s*AI\s*生成|做同款|用作参考图|发现|技能|短片|活动)$/u;
+ let author = "";
+ let authorIndex = -1;
+ for (let index = dateIndex - 1; index >= Math.max(0, dateIndex - 8); index -= 1) {
+ const candidate = lines[index];
+ if (candidate.length <= 80 && !excludedAuthor.test(candidate) && !/^\d+$/u.test(candidate)) {
+ author = candidate;
+ authorIndex = index;
+ break;
+ }
+ }
+ const favoriteLine = authorIndex >= 0 && dateIndex > authorIndex
+ ? lines.slice(authorIndex + 1, dateIndex).find((line) => /^\d+(?:\.\d+)?\s*(?:万|w|k)?$/iu.test(line)) || ""
+ : "";
+ const favoriteMatch = favoriteLine.match(/^(\d+(?:\.\d+)?)\s*(万|w|k)?$/iu);
+ const favoriteUnit = favoriteMatch?.[2]?.toLocaleLowerCase("en-US") || "";
+ const favoriteMultiplier = ["万", "w"].includes(favoriteUnit)
+ ? 10000
+ : favoriteUnit === "k" ? 1000 : 1;
+ const favoriteCount = favoriteMatch ? Math.round(Number(favoriteMatch[1]) * favoriteMultiplier) : 0;
+ const promptStart = lines.findIndex((line) => line === "图片提示词" || line.endsWith("图片提示词"));
+ const promptLines = [];
+ for (let index = promptStart + 1; promptStart >= 0 && index < lines.length; index += 1) {
+ if (/^图片\s*\d+(?:\.\d+)?(?:\s+(?:Lite|Pro))?(?:\s*[||]|$)/iu.test(lines[index]) || /^(?:做同款|用作参考图)$/u.test(lines[index])) break;
+ promptLines.push(lines[index]);
+ }
+ const modelLine = lines.find((line) => /^图片\s*\d+(?:\.\d+)?(?:\s+(?:Lite|Pro))?(?:\s*[||]|$)/iu.test(line)) || "";
+ const modelMatch = modelLine.match(/(?:图片\s*)?(\d+(?:\.\d+)?(?:\s+(?:Lite|Pro))?)/iu);
+ const dateMatch = dateIndex >= 0 ? lines[dateIndex].match(/20\d{2}[-/.]\d{1,2}[-/.]\d{1,2}/u) : null;
+ const createTime = dateMatch ? Math.floor(Date.parse(dateMatch[0].replace(/[/.]/g, "-")) / 1000) : 0;
+ const images = [];
+ for (const image of globalThis.document.querySelectorAll?.("img") || []) {
+ const url = clean(image.currentSrc || image.src);
+ const width = Number(image.naturalWidth || image.width) || 0;
+ const height = Number(image.naturalHeight || image.height) || 0;
+ if (/^https:\/\/p\d+-(?:dreamina|artist)(?:-safe)?-sign\.byteimg\.com\//u.test(url) && width >= 256 && height >= 256) {
+ images.push({ image_url: url, width, height });
+ }
+ }
+ if (!author && !promptLines.length && !modelMatch) return null;
+ return {
+ common_attr: { id: workId, create_time: createTime },
+ author: { name: author },
+ aigc_image_params: { text2image_params: { prompt: promptLines.join("\n") } },
+ model_key: clean(modelMatch?.[1]),
+ statistic: { favorite_num: favoriteCount },
+ image: { large_images: images }
+ };
+ };
+
+ if (pageKind === "detail" && !byId.has(workId)) {
+ const domItem = detailFromDom();
+ if (domItem) byId.set(workId, domItem);
+ }
+ const items = pageKind === "detail"
+ ? [...byId.values()].filter((item) => clean(item?.common_attr?.id) === workId)
+ : [...byId.values()];
+ const names = {
+ ...(observer?.modelNames && typeof observer.modelNames === "object" ? observer.modelNames : {}),
+ ...Object.fromEntries((modelConfig?.data?.model_list || [])
+ .map((model) => [clean(model?.model_req_key), clean(model?.model_name)])
+ .filter(([key, name]) => key && name))
+ };
+ return {
+ adapter: "jimeng",
+ pageKind,
+ workId,
+ items,
+ ...(items.length === 1 ? { item: items[0] } : {}),
+ modelNames: names,
+ status: items.length ? "complete" : "partial"
+ };
+}
+
+export function normalizePageCaptureSitePayload(value, canonicalUrlValue = "") {
+ if (value?.adapter === "liblibai") return normalizeStructuredFeedMedia(normalizeLiblibPayload(value, canonicalUrlValue));
+ if (value?.adapter === "krea") return normalizeStructuredFeedMedia(normalizeKreaPayload(value, canonicalUrlValue));
+ if (value?.adapter === "higgsfield") return normalizeStructuredFeedMedia(normalizeHiggsfieldPayload(value, canonicalUrlValue));
+ if (value?.adapter === "behance") return normalizeStructuredFeedMedia(normalizeBehancePayload(value, canonicalUrlValue));
+ if (value?.adapter === "pinterest") return normalizeStructuredFeedMedia(normalizePinterestPayload(value, canonicalUrlValue));
+ if (value?.adapter === "wechat") return normalizeStructuredFeedMedia(normalizeWechatPayload(value, canonicalUrlValue));
+ if (value?.adapter !== "jimeng") return null;
+ const pageKind = ["feed", "detail"].includes(value?.pageKind) ? value.pageKind : "detail";
+ const rawItems = Array.isArray(value?.items) ? value.items : value?.item ? [value.item] : [];
+ const seen = new Set();
+ const candidates = rawItems.flatMap((item) => {
+ const candidate = normalizeJimengItem(item, value?.modelNames);
+ if (!candidate || seen.has(candidate.sourceFacts.itemId)) return [];
+ seen.add(candidate.sourceFacts.itemId);
+ return [candidate];
+ });
+ const canonicalUrl = safeHttpUrl(canonicalUrlValue);
+ if (!candidates.length) {
+ return {
+ adapter: "jimeng",
+ pageKind,
+ canonicalUrl,
+ completeness: "partial",
+ sourceFacts: { provider: "jimeng", pageType: pageKind === "feed" ? "feed" : "artwork", itemId: "", status: "partial" },
+ media: [],
+ candidates: []
+ };
+ }
+ if (pageKind === "feed") {
+ return normalizeStructuredFeedMedia({
+ adapter: "jimeng",
+ pageKind,
+ canonicalUrl,
+ completeness: candidates.every((item) => item.completeness === "complete") ? "complete" : "partial",
+ candidates
+ });
+ }
+ const exact = candidates.find((candidate) => candidate.sourceFacts.itemId === clean(value?.workId)) || candidates[0];
+ return { ...exact, pageKind, candidates: [exact] };
+}
+
+function normalizeStructuredFeedMedia(payload) {
+ if (payload?.pageKind !== "feed" || !Array.isArray(payload.candidates)) return payload;
+ return {
+ ...payload,
+ candidates: payload.candidates.map((candidate) => ({
+ ...candidate,
+ media: Array.isArray(candidate?.media)
+ ? candidate.media.map((item) => ({ ...item, placement: "inline" }))
+ : []
+ }))
+ };
+}
+
+export function isTrustedPageCaptureMediaUrl(adapterId, value) {
+ try {
+ const url = new URL(String(value || ""));
+ if (url.protocol !== "https:") return false;
+ if (adapterId === "jimeng") return JIMENG_IMAGE_HOST_PATTERN.test(url.hostname);
+ if (adapterId === "liblibai") return url.hostname === "liblib.cloud" || url.hostname.endsWith(".liblib.cloud");
+ if (adapterId === "krea") return url.hostname === "krea.ai" || url.hostname.endsWith(".krea.ai");
+ if (adapterId === "higgsfield") return url.hostname === "higgsfield.ai"
+ || url.hostname.endsWith(".higgsfield.ai")
+ || url.hostname === "higgs.ai"
+ || url.hostname.endsWith(".higgs.ai")
+ || ["d2ol7oe51mr4n9.cloudfront.net", "du4zrvwy3vtek.cloudfront.net", "d8j0ntlcm91z4.cloudfront.net"].includes(url.hostname);
+ if (adapterId === "behance") return url.hostname === "mir-s3-cdn-cf.behance.net";
+ if (adapterId === "pinterest") return url.hostname === "i.pinimg.com";
+ if (adapterId === "wechat") return url.hostname === "qpic.cn" || url.hostname.endsWith(".qpic.cn");
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function normalizeKreaPayload(value, canonicalUrlValue) {
+ const canonicalUrl = safeHttpUrl(value?.canonicalUrl || canonicalUrlValue);
+ if (!canonicalUrl) return null;
+ const canonicalHost = new URL(canonicalUrl).hostname;
+ if (!(canonicalHost === "krea.ai" || canonicalHost.endsWith(".krea.ai"))) return null;
+ const pageKind = value?.pageKind === "feed" ? "feed" : "detail";
+ if (pageKind === "feed") {
+ const seen = new Set();
+ const candidates = (Array.isArray(value?.items) ? value.items : []).flatMap((item) => {
+ const candidate = normalizeKreaItem(item);
+ const itemId = candidate?.sourceFacts?.itemId;
+ if (!candidate || seen.has(itemId)) return [];
+ seen.add(itemId);
+ return [candidate];
+ });
+ return {
+ adapter: "krea",
+ pageKind,
+ canonicalUrl,
+ completeness: candidates.length && candidates.every((candidate) => candidate.completeness === "complete") ? "complete" : "partial",
+ candidates
+ };
+ }
+ const jsonLd = (Array.isArray(value?.jsonLd) ? value.jsonLd : []).find((node) => {
+ const types = Array.isArray(node?.["@type"]) ? node["@type"] : [node?.["@type"]];
+ return types.includes("ImageObject");
+ }) || {};
+ return normalizeKreaItem({
+ itemId: kreaItemId(canonicalUrl) || kreaItemId(jsonLd.contentUrl),
+ canonicalUrl,
+ title: jsonLd.name,
+ prompt: value?.prompt,
+ imageUrl: jsonLd.contentUrl || jsonLd.url || jsonLd.thumbnailUrl,
+ publishedAt: jsonLd.datePublished,
+ width: jsonLd.width,
+ height: jsonLd.height
+ });
+}
+
+function normalizeKreaItem(value) {
+ const canonicalUrl = safeHttpUrl(value?.canonicalUrl);
+ if (!canonicalUrl) return null;
+ const canonicalHost = new URL(canonicalUrl).hostname;
+ if (!(canonicalHost === "krea.ai" || canonicalHost.endsWith(".krea.ai"))) return null;
+ const itemId = clean(value?.itemId) || kreaItemId(canonicalUrl) || kreaItemId(value?.imageUrl);
+ if (!itemId) return null;
+ const url = safeTrustedMediaUrl("krea", value?.imageUrl);
+ const width = positiveInteger(value?.width);
+ const height = positiveInteger(value?.height);
+ const prompt = cleanMultiline(value?.prompt);
+ const media = url ? [{
+ id: `krea:${itemId}:1`, kind: "image", url, width, height,
+ sourceKind: "site-original", captureMethod: "source",
+ variants: [{ url, sourceKind: "site-original", width, height }]
+ }] : [];
+ const complete = Boolean(prompt && media.length);
+ return {
+ id: `krea:${itemId}`,
+ adapter: "krea",
+ pageType: "artwork",
+ canonicalUrl,
+ title: clean(value?.title) || (prompt ? prompt.slice(0, 160) : `Krea ${itemId.slice(0, 8)}`),
+ contentText: prompt,
+ media,
+ completeness: complete ? "complete" : "partial",
+ extraction: { scope: "document", method: "structured", textBlockCount: prompt ? 1 : 0 },
+ sourceFacts: {
+ provider: "krea", pageType: "artwork", itemId,
+ publishedAt: validIso(value?.publishedAt),
+ dimensions: width && height ? `${width}×${height}` : "",
+ engagement: {}, extractionMethod: "structured",
+ status: complete ? "complete" : "partial"
+ }
+ };
+}
+
+function kreaItemId(value) {
+ return clean(value).match(/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/iu)?.[0]?.toLocaleLowerCase("en-US") || "";
+}
+
+function normalizeHiggsfieldPayload(value, canonicalUrlValue) {
+ const canonicalUrl = safeHttpUrl(value?.canonicalUrl || canonicalUrlValue);
+ if (!canonicalUrl) return null;
+ const canonicalHost = new URL(canonicalUrl).hostname;
+ if (!(canonicalHost === "higgsfield.ai" || canonicalHost.endsWith(".higgsfield.ai"))) return null;
+ const nodes = Array.isArray(value?.jsonLd) ? value.jsonLd : [];
+ const pageKind = value?.pageKind === "feed" ? "feed" : "detail";
+ if (pageKind === "feed") {
+ const works = nodes.flatMap((node) => {
+ const types = Array.isArray(node?.["@type"]) ? node["@type"] : [node?.["@type"]];
+ if (types.includes("CreativeWork")) return [node];
+ if (!types.includes("ItemList")) return [];
+ return (Array.isArray(node?.itemListElement) ? node.itemListElement : []).map((entry) => entry?.item || entry).filter(Boolean);
+ });
+ const seen = new Set();
+ const candidates = works.flatMap((work) => {
+ const candidate = normalizeHiggsfieldWork(work, "");
+ const itemId = candidate?.sourceFacts?.itemId;
+ if (!candidate || seen.has(itemId)) return [];
+ seen.add(itemId);
+ return [candidate];
+ });
+ return {
+ adapter: "higgsfield",
+ pageKind,
+ canonicalUrl,
+ completeness: candidates.length && candidates.every((candidate) => candidate.completeness === "complete") ? "complete" : "partial",
+ candidates
+ };
+ }
+ const work = nodes.find((node) => {
+ const types = Array.isArray(node?.["@type"]) ? node["@type"] : [node?.["@type"]];
+ return types.includes("CreativeWork") && (!safeHttpUrl(node?.url) || safeHttpUrl(node?.url) === canonicalUrl);
+ }) || nodes.find((node) => {
+ const types = Array.isArray(node?.["@type"]) ? node["@type"] : [node?.["@type"]];
+ return types.includes("CreativeWork");
+ });
+ if (!work) return null;
+ const candidate = normalizeHiggsfieldWork({ ...work, url: safeHttpUrl(work?.url) || canonicalUrl }, value?.brief);
+ return candidate ? { ...candidate, pageKind, candidates: [candidate] } : null;
+}
+
+function normalizeHiggsfieldWork(value, briefValue) {
+ const canonicalUrl = safeHttpUrl(value?.url);
+ if (!canonicalUrl) return null;
+ const host = new URL(canonicalUrl).hostname;
+ if (!(host === "higgsfield.ai" || host.endsWith(".higgsfield.ai"))) return null;
+ const pathParts = new URL(canonicalUrl).pathname.split("/").filter(Boolean);
+ const handlePart = pathParts.find((part) => part.startsWith("@")) || "";
+ const projectIndex = pathParts.indexOf("projects");
+ const projectSlug = projectIndex >= 0 ? clean(pathParts[projectIndex + 1]) : "";
+ const author = clean(value?.author?.name || value?.creator?.name);
+ const handle = clean(value?.author?.alternateName || value?.creator?.alternateName || handlePart).replace(/^@/u, "");
+ const itemId = [handle, projectSlug].filter(Boolean).join("/") || clean(value?.identifier) || stableTextHash(canonicalUrl);
+ const imageValues = Array.isArray(value?.image) ? value.image : value?.image ? [value.image] : [];
+ const imageValue = imageValues.find((item) => typeof item === "string" ? item : item?.contentUrl || item?.url || item?.thumbnailUrl);
+ const imageUrlValue = typeof imageValue === "string" ? imageValue : imageValue?.contentUrl || imageValue?.url || imageValue?.thumbnailUrl;
+ const url = safeTrustedMediaUrl("higgsfield", imageUrlValue || value?.thumbnailUrl);
+ const width = positiveInteger(typeof imageValue === "object" ? imageValue?.width : 0);
+ const height = positiveInteger(typeof imageValue === "object" ? imageValue?.height : 0);
+ const contentText = cleanMultiline(briefValue) || cleanMultiline(value?.description);
+ const media = url ? [{
+ id: `higgsfield:${stableTextHash(itemId)}:1`, kind: "image", url, width, height,
+ sourceKind: "site-original", captureMethod: "source",
+ variants: [{ url, sourceKind: "site-original", width, height }]
+ }] : [];
+ const engagement = Object.fromEntries([
+ ["likes", interactionCount(value?.interactionStatistic, "LikeAction")],
+ ["comments", interactionCount(value?.interactionStatistic, "CommentAction")],
+ ["views", interactionCount(value?.interactionStatistic, "ViewAction")]
+ ].filter(([, count]) => count !== null));
+ const title = clean(value?.name);
+ const complete = Boolean(title && author && contentText && media.length);
+ return {
+ id: `higgsfield:${stableTextHash(itemId)}`,
+ adapter: "higgsfield",
+ pageType: "artwork",
+ canonicalUrl,
+ title: title || author || `Higgsfield ${projectSlug || itemId}`,
+ contentText,
+ media,
+ completeness: complete ? "complete" : "partial",
+ extraction: { scope: "document", method: "structured", textBlockCount: contentText ? 1 : 0 },
+ sourceFacts: {
+ provider: "higgsfield", pageType: "artwork", itemId, author, handle,
+ publishedAt: validIso(value?.datePublished || value?.dateCreated || value?.uploadDate),
+ dimensions: width && height ? `${width}×${height}` : "",
+ engagement, extractionMethod: "structured",
+ status: complete ? "complete" : "partial"
+ }
+ };
+}
+
+function normalizeBehancePayload(value, canonicalUrlValue) {
+ const canonicalUrl = safeHttpUrl(value?.canonicalUrl || canonicalUrlValue);
+ if (!canonicalUrl) return null;
+ const host = new URL(canonicalUrl).hostname;
+ if (!(host === "behance.net" || host.endsWith(".behance.net"))) return null;
+ const artwork = (Array.isArray(value?.jsonLd) ? value.jsonLd : []).find((node) => {
+ const types = Array.isArray(node?.["@type"]) ? node["@type"] : [node?.["@type"]];
+ return types.includes("VisualArtwork");
+ });
+ if (!artwork) return null;
+ const pathId = new URL(canonicalUrl).pathname.match(/^\/gallery\/(\d+)\//u)?.[1] || "";
+ const itemId = clean(artwork.identifier) || pathId;
+ if (!itemId) return null;
+ const creators = (Array.isArray(artwork?.creator) ? artwork.creator : artwork?.creator ? [artwork.creator] : []).filter(Boolean);
+ const author = creators.map((creator) => clean(creator?.name)).filter(Boolean).join(", ");
+ let handle = "";
+ try { handle = new URL(creators[0]?.url || "").pathname.split("/").filter(Boolean).at(-1) || ""; } catch { }
+ const imageUrl = safeTrustedMediaUrl("behance", typeof artwork?.image === "string" ? artwork.image : artwork?.image?.contentUrl || artwork?.image?.url);
+ const contentText = cleanMultiline(artwork?.description);
+ const media = imageUrl ? [{
+ id: `behance:${itemId}:cover`, kind: "image", url: imageUrl,
+ sourceKind: "structured", captureMethod: "source",
+ variants: [{ url: imageUrl, sourceKind: "structured" }]
+ }] : [];
+ const engagement = Object.fromEntries([
+ ["likes", interactionCount(artwork?.interactionStatistic, "LikeAction")],
+ ["views", interactionCount(artwork?.interactionStatistic, "WatchAction")]
+ ].filter(([, count]) => count !== null));
+ const title = clean(artwork?.name);
+ const complete = Boolean(title && author && contentText && media.length);
+ const candidate = {
+ id: `behance:${itemId}`,
+ adapter: "behance",
+ pageType: "artwork",
+ canonicalUrl,
+ title: title || author || `Behance ${itemId}`,
+ contentText,
+ media,
+ completeness: complete ? "complete" : "partial",
+ extraction: { scope: "document", method: "structured", textBlockCount: contentText ? 1 : 0 },
+ sourceFacts: {
+ provider: "behance", pageType: "artwork", itemId, author, handle,
+ publishedAt: validIso(value?.publishedAt), engagement,
+ extractionMethod: "structured", status: complete ? "complete" : "partial"
+ }
+ };
+ return { ...candidate, pageKind: "detail", candidates: [candidate] };
+}
+
+function normalizePinterestPayload(value, canonicalUrlValue) {
+ const canonicalUrl = safeHttpUrl(value?.canonicalUrl || canonicalUrlValue);
+ if (!canonicalUrl) return null;
+ const host = new URL(canonicalUrl).hostname;
+ if (!(host === "pinterest.com" || host.endsWith(".pinterest.com"))) return null;
+ const pin = value?.pin && typeof value.pin === "object" ? value.pin : {};
+ const pathId = new URL(canonicalUrl).pathname.match(/(?:--)?(\d+)\/?$/u)?.[1] || "";
+ const itemId = clean(pin.entityId) || pathId;
+ if (!/^\d+$/u.test(itemId)) return null;
+ const author = clean(pin?.author?.fullName) || clean(pin?.author?.username);
+ const handle = clean(pin?.author?.username);
+ const variants = [
+ [pin?.images?.original, "site-original"],
+ [pin?.images?.large, "responsive"],
+ [pin?.images?.display, "current"]
+ ].flatMap(([image, sourceKind]) => {
+ const url = safeTrustedMediaUrl("pinterest", image?.url);
+ if (!url) return [];
+ return [{ url, sourceKind, width: positiveInteger(image?.width), height: positiveInteger(image?.height) }];
+ }).filter((variant, index, items) => items.findIndex((candidate) => candidate.url === variant.url) === index);
+ const first = variants[0];
+ const contentText = cleanMultiline(pin.description);
+ const media = first ? [{
+ id: `pinterest:${itemId}:1`, kind: "image", url: first.url,
+ width: first.width, height: first.height, sourceKind: first.sourceKind,
+ captureMethod: "source", variants
+ }] : [];
+ const engagement = Number.isSafeInteger(Number(pin.repins)) && Number(pin.repins) >= 0 ? { repins: Number(pin.repins) } : {};
+ const title = clean(pin.title);
+ const complete = Boolean(title && author && contentText && media.length);
+ const candidate = {
+ id: `pinterest:${itemId}`,
+ adapter: "pinterest",
+ pageType: "artwork",
+ canonicalUrl,
+ title: title || author || `Pinterest ${itemId}`,
+ contentText,
+ media,
+ completeness: complete ? "complete" : "partial",
+ extraction: { scope: "document", method: "structured", textBlockCount: contentText ? 1 : 0 },
+ sourceFacts: {
+ provider: "pinterest", pageType: "artwork", itemId, author, handle,
+ publishedAt: validIso(pin.createdAt), engagement,
+ extractionMethod: "structured", status: complete ? "complete" : "partial"
+ }
+ };
+ return { ...candidate, pageKind: "detail", candidates: [candidate] };
+}
+
+function normalizeLiblibPayload(value, canonicalUrlValue) {
+ const canonicalUrl = safeHttpUrl(value?.canonicalUrl || canonicalUrlValue);
+ if (!canonicalUrl) return null;
+ const canonicalHost = new URL(canonicalUrl).hostname;
+ if (!["liblib.art", "liblib.ai"].some((host) => canonicalHost === host || canonicalHost.endsWith(`.${host}`))) return null;
+ const data = value?.data && typeof value.data === "object" ? value.data : {};
+ const itemId = clean(data.uuid) || new URL(canonicalUrl).pathname.split("/").filter(Boolean).at(-1) || "";
+ const author = clean(value?.author?.nickname);
+ const handle = clean(value?.author?.uuid);
+ const images = Array.isArray(data.images) ? data.images : [];
+ const media = images.flatMap((image, index) => {
+ const originalUrl = safeTrustedMediaUrl("liblibai", image?.originalImageUrl || image?.previewUrl);
+ const displayUrl = safeTrustedMediaUrl("liblibai", image?.imageUrl || image?.watermarkImageUrl);
+ const url = originalUrl || displayUrl;
+ if (!url) return [];
+ const width = positiveInteger(image?.width);
+ const height = positiveInteger(image?.height);
+ const variants = [
+ originalUrl ? { url: originalUrl, sourceKind: "site-original", width, height } : null,
+ displayUrl && displayUrl !== originalUrl ? { url: displayUrl, sourceKind: "current", width, height } : null
+ ].filter(Boolean);
+ return [{
+ id: `liblibai:${itemId}:${clean(image?.uuid || image?.id) || index + 1}`,
+ kind: "image",
+ url,
+ width,
+ height,
+ sourceKind: originalUrl ? "site-original" : "current",
+ captureMethod: "source",
+ variants
+ }];
+ });
+ const promptText = cleanMultiline(images.map((image) => image?.generateInfo?.prompt).find(clean));
+ const model = [...new Set(images.flatMap((image) => Array.isArray(image?.models) ? image.models : []).map((entry) => (
+ [clean(entry?.modelName), clean(entry?.versionName)].filter(Boolean).join(" ")
+ )).filter(Boolean))].join(" · ");
+ const engagement = Object.fromEntries([
+ ["likes", data?.counter?.likeCount],
+ ["comments", data?.counter?.commentCount],
+ ["views", data?.counter?.hitCount]
+ ].flatMap(([name, amount]) => Number.isSafeInteger(Number(amount)) && Number(amount) >= 0 ? [[name, Number(amount)]] : []));
+ const complete = Boolean(promptText && author && media.length);
+ return {
+ id: `liblibai:${itemId}`,
+ adapter: "liblibai",
+ pageType: "artwork",
+ canonicalUrl,
+ title: clean(data.title) || author || "LiblibAI 作品",
+ contentText: promptText,
+ media,
+ completeness: complete ? "complete" : "partial",
+ extraction: { scope: "document", method: "structured", textBlockCount: promptText ? 1 : 0 },
+ sourceFacts: {
+ provider: "liblibai", pageType: "artwork", itemId, author, handle,
+ publishedAt: validIso(data.createTime), model,
+ dimensions: media[0]?.width && media[0]?.height ? `${media[0].width}×${media[0].height}` : "",
+ engagement, extractionMethod: "structured",
+ status: complete ? "complete" : "partial"
+ }
+ };
+}
+
+function normalizeWechatPayload(value, canonicalUrlValue) {
+ const canonicalUrl = safeHttpUrl(value?.canonicalUrl || canonicalUrlValue);
+ if (!canonicalUrl || new URL(canonicalUrl).hostname !== "mp.weixin.qq.com") return null;
+ const title = clean(value?.title);
+ const author = clean(value?.author);
+ const contentText = cleanMultiline(value?.contentText);
+ const media = (Array.isArray(value?.images) ? value.images : []).flatMap((image, index) => {
+ const url = safeTrustedMediaUrl("wechat", image?.url);
+ if (!url) return [];
+ const width = positiveInteger(image?.width);
+ const height = positiveInteger(image?.height);
+ return [{
+ id: `wechat:${index + 1}:${stableTextHash(url)}`, kind: "image", url, width, height,
+ alt: clean(image?.alt), sourceKind: "site-original", captureMethod: "source",
+ variants: [{ url, sourceKind: "site-original", width, height }]
+ }];
+ });
+ const complete = Boolean(title && author && contentText);
+ return {
+ id: `wechat:${stableTextHash(canonicalUrl)}`,
+ adapter: "wechat",
+ pageType: "article",
+ canonicalUrl,
+ title: title || author || "微信公众号文章",
+ contentText,
+ media,
+ completeness: complete ? "complete" : "partial",
+ extraction: { scope: "document", method: "structured", textBlockCount: contentText ? 1 : 0 },
+ sourceFacts: {
+ provider: "wechat", pageType: "article", itemId: stableTextHash(canonicalUrl), author,
+ publishedAt: validIso(value?.publishedAt), extractionMethod: "structured",
+ status: complete ? "complete" : "partial"
+ }
+ };
+}
+
+function interactionCount(value, action) {
+ const items = Array.isArray(value) ? value : value ? [value] : [];
+ const item = items.find((candidate) => clean(candidate?.interactionType?.["@type"] || candidate?.interactionType).split(/[\/#]/u).at(-1) === action);
+ const number = Number(item?.userInteractionCount);
+ return Number.isSafeInteger(number) && number >= 0 ? number : null;
+}
+
+function safeTrustedMediaUrl(adapterId, value) {
+ const url = safeHttpUrl(value);
+ return url && isTrustedPageCaptureMediaUrl(adapterId, url) ? url : "";
+}
+
+function validIso(value) {
+ const timestamp = Date.parse(clean(value));
+ return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : "";
+}
+
+function stableTextHash(value) {
+ let hash = 2166136261;
+ for (const character of String(value)) hash = Math.imul(hash ^ character.charCodeAt(0), 16777619);
+ return (hash >>> 0).toString(36);
+}
+
+function normalizeJimengItem(item, modelNamesValue = {}) {
+ const workId = clean(item?.common_attr?.id);
+ if (!/^\d{8,32}$/u.test(workId)) return null;
+ const prompt = cleanMultiline(item?.aigc_image_params?.text2image_params?.prompt);
+ const images = Array.isArray(item?.image?.large_images) ? item.image.large_images : [];
+ const modelKey = clean(item?.model_key) || jimengDraftModel(item?.aigc_draft?.content);
+ const model = clean(modelNamesValue?.[modelKey]) || modelKey;
+ const author = clean(item?.author?.name);
+ const publishedAt = epochSecondsToIso(item?.common_attr?.create_time);
+ const canonicalUrl = `https://${JIMENG_HOST}${JIMENG_DETAIL_PATH}${workId}`;
+ const media = images.flatMap((image, index) => {
+ const url = safeJimengImageUrl(image?.image_url);
+ if (!url) return [];
+ const width = positiveInteger(image?.width);
+ const height = positiveInteger(image?.height);
+ return [{
+ id: `jimeng:${workId}:${index + 1}`,
+ kind: "image",
+ url,
+ width,
+ height,
+ sourceKind: "site-original",
+ captureMethod: "source",
+ variants: [{ url, sourceKind: "site-original", width, height }]
+ }];
+ });
+ if (!prompt && !author && !media.length) return null;
+ const title = clean(item?.common_attr?.title);
+ const dateLabel = publishedAt.slice(0, 10);
+ const displayTitle = title || [author, dateLabel].filter(Boolean).join(" · ") || author || `即梦作品 ${workId.slice(-6)}`;
+ const complete = Boolean(prompt && author && media.length);
+ return {
+ id: `jimeng:${workId}`,
+ adapter: "jimeng",
+ pageType: "artwork",
+ canonicalUrl,
+ title: displayTitle,
+ displayTitle,
+ contentText: prompt,
+ media,
+ completeness: complete ? "complete" : "partial",
+ extraction: { scope: "document", method: "structured", textBlockCount: prompt ? 1 : 0 },
+ sourceFacts: {
+ provider: "jimeng",
+ pageType: "artwork",
+ itemId: workId,
+ author,
+ handle: clean(item?.author?.uid),
+ publishedAt,
+ model,
+ dimensions: media[0]?.width && media[0]?.height ? `${media[0].width}×${media[0].height}` : "",
+ engagement: {
+ favorites: nonNegativeInteger(item?.statistic?.favorite_num),
+ uses: nonNegativeInteger(item?.statistic?.usage_num)
+ },
+ extractionMethod: "structured",
+ status: complete ? "complete" : "partial"
+ }
+ };
+}
+
+function jimengDraftModel(content) {
+ try {
+ const draft = JSON.parse(String(content || "{}"));
+ return clean(draft?.component_list?.[0]?.abilities?.generate?.core_param?.model);
+ } catch {
+ return "";
+ }
+}
+
+function safeJimengImageUrl(value) {
+ try {
+ const url = new URL(String(value || ""));
+ return url.protocol === "https:" && JIMENG_IMAGE_HOST_PATTERN.test(url.hostname) ? url.href : "";
+ } catch {
+ return "";
+ }
+}
+
+function safeHttpUrl(value) {
+ try {
+ const url = new URL(clean(value));
+ return ["http:", "https:"].includes(url.protocol) ? url.href : "";
+ } catch {
+ return "";
+ }
+}
+
+function epochSecondsToIso(value) {
+ const number = Number(value);
+ return Number.isFinite(number) && number > 0 ? new Date(number * 1000).toISOString() : "";
+}
+
+function positiveInteger(value) {
+ const number = Number(value);
+ return Number.isSafeInteger(number) && number > 0 ? number : 0;
+}
+
+function nonNegativeInteger(value) {
+ const number = Number(value);
+ return Number.isSafeInteger(number) && number >= 0 ? number : 0;
+}
+
+function clean(value) {
+ return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "").replace(/\s+/g, " ").trim();
+}
+
+function cleanMultiline(value) {
+ return String(value ?? "").replace(/\r\n?/g, "\n").replace(/[\t ]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim();
+}
diff --git a/page-capture.js b/page-capture.js
index 84b9bd3..ced4512 100644
--- a/page-capture.js
+++ b/page-capture.js
@@ -1,27 +1,85 @@
+import { PAGE_CAPTURE_ADAPTERS, resolvePageCaptureAdapter } from "./page-capture-adapter-registry.js";
+import { PAGE_CAPTURE_QUALITY_LIMITS } from "./resource-limits.js";
+import { normalizeArticleDocument, remapArticleDocumentAssets } from "./article-document.js";
+import { isSupportedDocumentMimeType } from "./bounded-media.js";
+
+export { PAGE_CAPTURE_ADAPTERS, PAGE_CAPTURE_PLATFORM_ADAPTERS } from "./page-capture-adapter-registry.js";
+
const PAGE_TYPES = new Set(["article", "artwork", "post", "gallery", "feed", "video", "generic"]);
const COMPLETENESS = new Set(["complete", "partial"]);
-export const PAGE_CAPTURE_ADAPTERS = Object.freeze([
- { id: "jimeng", hosts: ["jimeng.jianying.com"], cardSelectors: ["[data-testid*=work]", "[class*=masonry] > *"], fields: { title: ["[class*=title]"], author: ["[class*=author]"], model: ["[class*=model]"] } },
- { id: "liblibai", hosts: ["liblib.art", "liblibai.com"], cardSelectors: ["[class*=work-card]", "[class*=waterfall] > *"], fields: { title: ["[class*=title]"], author: ["[class*=user]"], model: ["[class*=model]"] } },
- { id: "higgsfield", hosts: ["higgsfield.ai"], cardSelectors: ["[data-testid*=creation]", "[class*=feed] > article"], fields: { title: ["[data-testid*=title]"], author: ["[data-testid*=author]"] } },
- { id: "krea", hosts: ["krea.ai"], cardSelectors: ["[data-testid*=generation]", "[class*=gallery] > *"], fields: { title: ["[data-testid*=title]"], model: ["[data-testid*=model]"] } },
- { id: "tapnow", hosts: ["tapnow.ai"], cardSelectors: ["[data-testid*=work]", "[class*=gallery] > *"], fields: { title: ["[class*=title]"], author: ["[class*=author]"] } },
- { id: "pinterest", hosts: ["pinterest.com", "pin.it"], cardSelectors: ["[data-test-id=pin]", "[data-grid-item]"], fields: { title: ["[data-test-id*=title]"], author: ["[data-test-id*=creator]"] } },
- { id: "artstation", hosts: ["artstation.com"], cardSelectors: [".project", "[data-test=project-card]"], fields: { title: [".project-title", "[class*=title]"], author: [".user-name", "[class*=artist]"] } },
- { id: "x", hosts: ["x.com", "twitter.com"], cardSelectors: ["article[data-testid=tweet]"], fields: { author: ["[data-testid=User-Name]"], publishedAt: ["time"], likes: ["[data-testid=like]"], reposts: ["[data-testid=retweet]"] } },
- { id: "reddit", hosts: ["reddit.com"], cardSelectors: ["shreddit-post", "article"], fields: { title: ["[slot=title]", "h1,h2,h3"], author: ["[slot=authorName]", "[class*=author]"], publishedAt: ["time"] } },
- { id: "youtube", hosts: ["youtube.com", "youtu.be"], cardSelectors: ["ytd-rich-item-renderer", "ytd-video-renderer"], fields: { title: ["#video-title"], author: ["#channel-name"], views: ["#metadata-line span"] } },
- { id: "bilibili", hosts: ["bilibili.com", "b23.tv"], cardSelectors: [".bili-video-card", ".video-card"], fields: { title: ["[class*=title]"], author: ["[class*=owner]"], views: ["[class*=play]"] } },
- { id: "steam", hosts: ["steampowered.com", "steamcommunity.com"], cardSelectors: [".apphub_Card", ".search_result_row", ".workshopItem"], fields: { title: [".title", "[class*=title]"], author: ["[class*=author]"], publishedAt: ["time", "[class*=date]"] } }
-]);
-
export function detectPageCaptureAdapter(value, adapters = PAGE_CAPTURE_ADAPTERS) {
- let host;
- try { host = new URL(value).hostname.toLocaleLowerCase("en-US"); }
- catch { host = String(value ?? "").toLocaleLowerCase("en-US"); }
- return adapters.find((item) => item.hosts.some((suffix) => host === suffix || host.endsWith(`.${suffix}`)))
- || { id: "generic", hosts: [], cardSelectors: ["main article", "[role=main] article"] };
+ return resolvePageCaptureAdapter(value, {}, adapters);
+}
+
+export function pageCaptureDefaultMediaIds(candidateValue = {}) {
+ return (normalizePageCaptureCandidate(candidateValue)?.media || [])
+ .filter((item) => item.placement === "inline")
+ .map((item) => item.id);
+}
+
+export function resolvePageCapturePageType({
+ adapterPageType = "generic",
+ structuredTypes = [],
+ articleTextLength = 0,
+ cardCount = 0,
+ metadataType = ""
+} = {}) {
+ if (adapterPageType === "post") return "post";
+ if (structuredTypes.includes("VideoObject") || ["youtube", "bilibili"].includes(adapterPageType)) return "video";
+ if (structuredTypes.some((type) => ["Article", "NewsArticle", "BlogPosting"].includes(type)) || articleTextLength > 500) return "article";
+ if (cardCount > 1) return metadataType === "website" ? "gallery" : "feed";
+ return PAGE_TYPES.has(adapterPageType) ? adapterPageType : "generic";
+}
+
+export function reconcilePageCaptureArticlePlacement({ articleDocument, media: mediaValue, contentTargets } = {}) {
+ const documentValue = normalizeArticleDocument(articleDocument) || { version: 1, blocks: [] };
+ const media = uniqueMedia(mediaValue);
+ const mediaById = new Map(media.map((item) => [item.id, item]));
+ const blocksById = new Map(documentValue.blocks.map((block) => [block.id, block]));
+ const blocksByAssetId = new Map(documentValue.blocks.flatMap((block) => block.assetId ? [[block.assetId, block]] : []));
+ const inlineIds = new Set(documentValue.blocks.flatMap((block) => block.assetId && mediaById.has(block.assetId) ? [block.assetId] : []));
+ const emittedBlockIds = new Set();
+ const emittedAssetIds = new Set();
+ const orderedBlocks = [];
+ const emit = (block) => {
+ if (!block || emittedBlockIds.has(block.id) || block.assetId && emittedAssetIds.has(block.assetId)) return;
+ emittedBlockIds.add(block.id);
+ if (block.assetId) emittedAssetIds.add(block.assetId);
+ orderedBlocks.push(block);
+ };
+ const mediaBlock = (item) => ({
+ id: `article:${item.kind}:${item.id}`,
+ kind: item.kind,
+ assetId: item.id,
+ sourceUrl: item.url,
+ ...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
+ label: item.alt || item.filename || ""
+ });
+
+ for (const target of (Array.isArray(contentTargets) ? contentTargets : [])
+ .filter((item) => item?.kind !== "group")
+ .sort((left, right) => Number(left.sourceOrder || 0) - Number(right.sourceOrder || 0))) {
+ for (const blockId of target.articleBlockIds || []) emit(blocksById.get(blockId));
+ for (const mediaId of target.mediaIds || []) {
+ const item = mediaById.get(mediaId);
+ if (!item) continue;
+ inlineIds.add(mediaId);
+ emit(blocksByAssetId.get(mediaId) || mediaBlock(item));
+ }
+ }
+ for (const block of documentValue.blocks) {
+ if (block.assetId && !inlineIds.has(block.assetId)) continue;
+ emit(block);
+ }
+
+ return {
+ articleDocument: normalizeArticleDocument({
+ version: documentValue.version || 1,
+ blocks: orderedBlocks.map((block, sourceOrder) => ({ ...block, sourceOrder }))
+ }),
+ media: media.map((item) => ({ ...item, placement: inlineIds.has(item.id) ? "inline" : "unplaced" }))
+ };
}
export function normalizePageCaptureBatch(value = {}) {
@@ -44,7 +102,13 @@ export function normalizePageCaptureBatch(value = {}) {
tabId: Number.isInteger(Number(value.tabId)) ? Number(value.tabId) : null,
sourceUrl: safeUrl(value.sourceUrl),
adapter: clean(value.adapter) || "generic",
+ captureMode: value.captureMode === "list" ? "list" : "single",
+ saveMode: value.saveMode === "combined" ? "combined" : value.saveMode === "multiple" ? "multiple" : value.captureMode === "list" ? "" : "single",
+ combinedTitle: clean(value.combinedTitle),
+ targetCount: positiveInteger(value.targetCount, 0),
+ stopReason: ["target-reached", "no-new-items", "no-next-page", "layout-changed", "pagination-failed", "cancelled"].includes(value.stopReason) ? value.stopReason : "",
status: ["preview", "scanning", "saving", "completed", "cancelled", "failed"].includes(value.status) ? value.status : "preview",
+ sessionMediaAllowed: value.sessionMediaAllowed !== false,
candidates,
selections,
discoveredCount: candidates.length,
@@ -53,6 +117,57 @@ export function normalizePageCaptureBatch(value = {}) {
};
}
+export function combinePageCaptureCandidates(values = [], options = {}) {
+ const candidates = (Array.isArray(values) ? values : []).map(normalizePageCaptureCandidate).filter(Boolean);
+ if (!candidates.length) return null;
+ const canonicalUrl = safeUrl(options.canonicalUrl) || candidates[0].canonicalUrl;
+ const title = clean(options.title) || candidates[0].title;
+ const ordered = candidates.map((candidate, index) => ({ candidate, index }));
+ const textBlocks = ordered.flatMap(({ candidate, index }) => {
+ const text = [candidate.title, candidate.contentText].filter(Boolean).join("\n");
+ return text ? [{
+ id: stableCandidateId(canonicalUrl, `combined\n${index}\n${text}`),
+ text,
+ html: "",
+ kind: "section",
+ sourceOrder: index
+ }] : [];
+ });
+ const articleBlocks = ordered.flatMap(({ candidate, index }) => {
+ const documentValue = normalizeArticleDocument(candidate.articleDocument);
+ const blocks = documentValue?.blocks || [];
+ return [
+ { id: `combined:${index}:title`, kind: "heading", level: 2, text: candidate.title, sourceOrder: 0 },
+ ...blocks.map((block) => ({ ...block, id: `combined:${index}:${block.id}` }))
+ ];
+ }).map((block, sourceOrder) => ({ ...block, sourceOrder }));
+ return normalizePageCaptureCandidate({
+ id: stableCandidateId(canonicalUrl, `combined\n${candidates.map((item) => item.id).join("\n")}`),
+ title,
+ canonicalUrl,
+ pageType: "gallery",
+ contentText: textBlocks.map((item) => item.text).join("\n\n"),
+ textBlocks,
+ articleDocument: { version: 1, blocks: articleBlocks },
+ media: candidates.flatMap((candidate) => candidate.media.map((media) => ({
+ ...media,
+ sourceTitle: candidate.title,
+ sourceAuthor: candidate.sourceFacts.author,
+ originalWorkUrl: candidate.canonicalUrl
+ }))),
+ sourceFacts: {
+ provider: hostname(canonicalUrl),
+ pageType: "gallery",
+ captureScope: "document",
+ extractionMethod: "page",
+ status: "complete"
+ },
+ completeness: "complete",
+ extraction: { scope: "document", method: "page" },
+ adapter: "generic"
+ });
+}
+
export function normalizePageCaptureSelection(value = {}, candidatesValue = []) {
const candidates = Array.isArray(candidatesValue) ? candidatesValue : [];
const candidateId = clean(value.candidateId);
@@ -61,8 +176,74 @@ export function normalizePageCaptureSelection(value = {}, candidatesValue = [])
const mediaIds = new Set(candidate.media.map((item) => item.id));
const selectedMediaIds = [...new Set((Array.isArray(value.selectedMediaIds) ? value.selectedMediaIds : [])
.map(clean).filter((id) => mediaIds.has(id)))];
- const includeText = value.includeText === true && Boolean(candidate.contentText || candidate.excerpt);
- return includeText || selectedMediaIds.length ? { candidateId, includeText, selectedMediaIds } : null;
+ const mediaDecision = value.mediaDecision === "confirmed"
+ ? "confirmed"
+ : value.mediaDecision === "none" ? "none" : "pending";
+ const hasTextBlockSelection = Array.isArray(value.selectedTextBlockIds);
+ const textBlockIds = new Set(candidate.textBlocks.map((item) => item.id));
+ const selectedTextBlockIds = [...new Set((hasTextBlockSelection ? value.selectedTextBlockIds : [])
+ .map(clean).filter((id) => textBlockIds.has(id)))];
+ const includeText = hasTextBlockSelection
+ ? selectedTextBlockIds.length > 0
+ : value.includeText === true && Boolean(candidate.contentText || candidate.excerpt);
+ if (!includeText && !selectedMediaIds.length) return null;
+ return {
+ candidateId,
+ includeText,
+ ...(hasTextBlockSelection ? { selectedTextBlockIds } : {}),
+ selectedMediaIds: mediaDecision === "none" ? [] : selectedMediaIds,
+ mediaDecision
+ };
+}
+
+export function mergePageCaptureRegionEdit(originalValue, revisedValue) {
+ const original = normalizePageCaptureCandidate(originalValue);
+ const revised = normalizePageCaptureCandidate(revisedValue);
+ if (!original || !revised) return original || revised;
+ const revisedToOriginalIds = new Map();
+ const media = revised.media.map((item) => {
+ const originalItem = original.media.find((candidate) => mediaValuesOverlap(candidate, item));
+ if (!originalItem) return item;
+ revisedToOriginalIds.set(item.id, originalItem.id);
+ return {
+ ...item,
+ ...originalItem,
+ id: originalItem.id,
+ variants: [...(originalItem.variants || []), ...(item.variants || [])]
+ };
+ });
+ return normalizePageCaptureCandidate({
+ ...revised,
+ id: original.id,
+ title: original.title,
+ canonicalUrl: original.canonicalUrl,
+ pageType: original.pageType,
+ sourceFacts: original.sourceFacts,
+ adapter: original.adapter,
+ region: revised.region
+ ? {
+ ...original.region,
+ contentTargets: (revised.region.contentTargets?.length ? revised.region.contentTargets : original.region?.contentTargets || [])
+ .map((target) => ({
+ ...target,
+ mediaIds: (target.mediaIds || []).map((id) => revisedToOriginalIds.get(id) || id)
+ })),
+ edits: revised.region.edits || []
+ }
+ : original.region,
+ media,
+ articleDocument: remapArticleDocumentAssets(revised.articleDocument, revisedToOriginalIds)
+ });
+}
+
+function mediaValuesOverlap(left, right) {
+ if (left?.kind && right?.kind && left.kind !== right.kind) return false;
+ const identity = (value) => pageCaptureMediaIdentity(value) || value;
+ const leftUrls = new Set([left.url, left.posterUrl, ...(left.variants || []).map((item) => item.url)].filter(Boolean).map(identity));
+ return [right.url, right.posterUrl, ...(right.variants || []).map((item) => item.url)]
+ .filter(Boolean)
+ .map(identity)
+ .some((url) => leftUrls.has(url));
}
export function applyPageCaptureSelections(batchValue = {}) {
@@ -70,36 +251,257 @@ export function applyPageCaptureSelections(batchValue = {}) {
return batch.selections.flatMap((selection) => {
const candidate = batch.candidates.find((item) => item.id === selection.candidateId);
if (!candidate) return [];
- const selectedMediaIds = new Set(selection.selectedMediaIds);
+ const selectedMediaIds = new Set(selection.mediaDecision === "confirmed" ? selection.selectedMediaIds : []);
+ const hasTextBlockSelection = Array.isArray(selection.selectedTextBlockIds);
+ const selectedTextBlockIds = new Set(selection.selectedTextBlockIds || []);
+ const selectedTextBlocks = (hasTextBlockSelection
+ ? candidate.textBlocks.filter((item) => selectedTextBlockIds.has(item.id))
+ : candidate.textBlocks)
+ .sort((left, right) => (left.sourceOrder ?? 0) - (right.sourceOrder ?? 0));
+ const selectedAllText = !hasTextBlockSelection || selectedTextBlocks.length === candidate.textBlocks.length;
+ const selectedText = selection.includeText
+ ? selectedTextBlocks.map((item) => item.text).join("\n\n")
+ : "";
+ const selectedHtml = selection.includeText && selectedTextBlocks.every((item) => item.html)
+ ? selectedTextBlocks.map((item) => item.html).join("")
+ : "";
+ const articleDocument = filterCandidateArticleDocument(candidate.articleDocument, {
+ includeText: selection.includeText,
+ selectedAllText,
+ selectedTextBlockIds,
+ selectedMediaIds
+ });
return [{
...candidate,
- contentHtml: selection.includeText ? candidate.contentHtml : "",
- contentText: selection.includeText ? candidate.contentText : "",
- excerpt: selection.includeText ? candidate.excerpt : "",
- media: candidate.media.filter((item) => selectedMediaIds.has(item.id))
+ contentHtml: selection.includeText
+ ? selectedAllText ? candidate.contentHtml : selectedHtml
+ : "",
+ contentText: hasTextBlockSelection ? selectedText : selection.includeText ? candidate.contentText : "",
+ excerpt: selection.includeText
+ ? selectedAllText ? candidate.excerpt : selectedTextBlocks[0]?.text || ""
+ : "",
+ media: candidate.media.filter((item) => selectedMediaIds.has(item.id)),
+ articleDocument
}];
});
}
+export function pageCaptureMediaDecisionsResolved(batchValue = {}) {
+ const batch = normalizePageCaptureBatch(batchValue);
+ return batch.selections.length > 0 && batch.selections.every((selection) => selection.mediaDecision !== "pending");
+}
+
+export function pageCaptureStructureMatches(referenceValue, candidateValue) {
+ const signature = (value) => {
+ const candidate = normalizePageCaptureCandidate(value);
+ if (!candidate) return null;
+ const articleKinds = new Set((candidate.articleDocument?.blocks || [])
+ .map((block) => block.kind)
+ .filter((kind) => !["heading", "link"].includes(kind)));
+ return {
+ hasText: Boolean(candidate.textBlocks.length || candidate.contentText),
+ articleKinds: [...articleKinds].sort(),
+ mediaKinds: [...new Set(candidate.media.map((media) => media.kind))].sort()
+ };
+ };
+ const reference = signature(referenceValue);
+ const candidate = signature(candidateValue);
+ return Boolean(reference && candidate
+ && reference.hasText === candidate.hasText
+ && reference.articleKinds.join("|") === candidate.articleKinds.join("|")
+ && reference.mediaKinds.join("|") === candidate.mediaKinds.join("|"));
+}
+
+function filterCandidateArticleDocument(value, selection) {
+ const documentValue = normalizeArticleDocument(value);
+ if (!documentValue) return null;
+ return normalizeArticleDocument({
+ ...documentValue,
+ blocks: documentValue.blocks.filter((block) => {
+ if (["image", "video", "document"].includes(block.kind)) return selection.selectedMediaIds.has(block.assetId);
+ if (block.kind === "link") return true;
+ return selection.includeText && (selection.selectedAllText || selection.selectedTextBlockIds.has(block.id));
+ })
+ });
+}
+
export function normalizePageCaptureCandidate(value = {}) {
const canonicalUrl = safeUrl(value.canonicalUrl || value.url);
const title = clean(value.title);
if (!canonicalUrl && !title) return null;
+ const sourceFacts = normalizeSourceFacts(value.sourceFacts, canonicalUrl);
+ const rawContentText = normalizeText(value.contentText);
+ const rawTextBlocks = normalizeTextBlocks(value.textBlocks, rawContentText, canonicalUrl);
+ const prepared = rawTextBlocks.some((item) => item.kind && item.kind !== "section")
+ ? prepareCreativeSections(rawTextBlocks, { canonicalUrl, title, sourceFacts })
+ : {
+ textBlocks: rawTextBlocks,
+ possibleOmissions: normalizeTextBlocks(value.possibleOmissions, "", canonicalUrl),
+ contentText: rawContentText,
+ contentHtml: String(value.contentHtml ?? "")
+ };
+ const textBlocks = prepared.textBlocks;
+ const contentText = prepared.contentText;
+ const media = suppressVideoPosterImages(uniqueMedia(value.media));
+ const mediaIds = new Set(media.map((item) => item.id));
+ const normalizedArticleDocument = normalizeArticleDocument(value.articleDocument);
+ const articleDocument = normalizedArticleDocument && normalizeArticleDocument({
+ ...normalizedArticleDocument,
+ blocks: normalizedArticleDocument.blocks.filter((block) => !block.assetId || mediaIds.has(block.assetId))
+ });
return {
id: clean(value.id) || stableCandidateId(canonicalUrl, title),
pageType: PAGE_TYPES.has(value.pageType) ? value.pageType : "generic",
title: title || hostname(canonicalUrl),
canonicalUrl,
- contentHtml: String(value.contentHtml ?? ""),
- contentText: normalizeText(value.contentText),
+ contentHtml: prepared.contentHtml,
+ contentText,
+ textBlocks,
+ articleDocument,
+ possibleOmissions: prepared.possibleOmissions,
+ batchStructureStatus: value.batchStructureStatus === "review" ? "review" : value.batchStructureStatus === "matched" ? "matched" : "",
+ region: normalizeCaptureRegion(value.region),
excerpt: clean(value.excerpt),
- media: uniqueMedia(value.media),
- sourceFacts: normalizeSourceFacts(value.sourceFacts, canonicalUrl),
+ media,
+ sourceFacts,
completeness: COMPLETENESS.has(value.completeness) ? value.completeness : "partial",
+ extraction: {
+ scope: value.extraction?.scope === "selection" ? "selection" : "document",
+ method: ["selection", "readability", "structured", "page"].includes(value.extraction?.method)
+ ? value.extraction.method
+ : "page",
+ textBlockCount: textBlocks.length
+ },
adapter: clean(value.adapter) || "generic"
};
}
+function suppressVideoPosterImages(values) {
+ const posterIdentities = new Set(values
+ .filter((item) => item.kind === "video")
+ .map((item) => pageCaptureMediaIdentity(item.posterUrl) || item.posterUrl)
+ .filter(Boolean));
+ return values.filter((item) => item.kind !== "image" || !posterIdentities.has(pageCaptureMediaIdentity(item.url) || item.url));
+}
+
+function normalizeCaptureRegion(value = {}) {
+ value = value && typeof value === "object" ? value : {};
+ const marker = clean(value.marker);
+ if (!marker) return null;
+ return {
+ id: clean(value.id) || marker,
+ marker,
+ label: clean(value.label),
+ score: Number.isFinite(Number(value.score)) ? Number(value.score) : 0,
+ textLength: positiveInteger(value.textLength, 0),
+ mediaCount: positiveInteger(value.mediaCount, 0),
+ contentTargets: (Array.isArray(value.contentTargets) ? value.contentTargets : []).flatMap((target, index) => {
+ const path = clean(target?.path);
+ const kind = ["text", "image", "video", "document", "group"].includes(target?.kind) ? target.kind : "";
+ if (!path || !kind) return [];
+ return [{
+ id: clean(target.id) || `target:${index}`,
+ kind,
+ path,
+ groupId: clean(target.groupId),
+ articleBlockIds: [...new Set((Array.isArray(target.articleBlockIds) ? target.articleBlockIds : []).map(clean).filter(Boolean))],
+ mediaIds: [...new Set((Array.isArray(target.mediaIds) ? target.mediaIds : []).map(clean).filter(Boolean))],
+ sourceOrder: Number.isSafeInteger(Number(target.sourceOrder)) ? Number(target.sourceOrder) : index
+ }];
+ }).slice(0, PAGE_CAPTURE_QUALITY_LIMITS.maxContentTargetsPerCandidate),
+ edits: (Array.isArray(value.edits) ? value.edits : []).flatMap((edit) => {
+ const path = clean(edit?.path);
+ const mode = edit?.mode === "exclude" ? "exclude" : edit?.mode === "include" ? "include" : "";
+ return path && mode ? [{ mode, path }] : [];
+ }).slice(0, 200)
+ };
+}
+
+function normalizeTextBlocks(values, contentText, canonicalUrl) {
+ const provided = (Array.isArray(values) ? values : []).flatMap((value, index) => {
+ const text = normalizeText(typeof value === "string" ? value : value?.text);
+ if (!text) return [];
+ const kind = ["heading", "paragraph", "list", "quote", "code", "figure", "table", "noise", "section"].includes(value?.kind) ? value.kind : "";
+ const hasSourceOrder = Number.isSafeInteger(Number(value?.sourceOrder));
+ return [{
+ id: clean(value?.id) || stableCandidateId(canonicalUrl, `${index}\n${text}`),
+ text,
+ html: String(typeof value === "string" ? "" : value?.html ?? ""),
+ ...(kind ? { kind } : {}),
+ ...(value?.relevance === "explicit-creative" ? { relevance: "explicit-creative" } : {}),
+ ...(clean(value?.reason) ? { reason: clean(value.reason) } : {}),
+ ...(Number.isFinite(Number(value?.score)) ? { score: Number(value.score) } : {}),
+ ...(hasSourceOrder ? { sourceOrder: Number(value.sourceOrder) } : {})
+ }];
+ });
+ if (provided.length) return provided;
+ return normalizeText(contentText).split(/\n\s*\n/g).flatMap((text, index) => {
+ const normalized = normalizeText(text);
+ return normalized ? [{ id: stableCandidateId(canonicalUrl, `${index}\n${normalized}`), text: normalized, html: "" }] : [];
+ });
+}
+
+function prepareCreativeSections(blocks, context) {
+ const sourceBlocks = blocks
+ .map((block, index) => ({ ...block, sourceOrder: Number.isSafeInteger(block.sourceOrder) ? block.sourceOrder : index }))
+ .sort((left, right) => left.sourceOrder - right.sourceOrder);
+ const omitted = [];
+ const sections = [];
+ let current = null;
+ const flush = () => {
+ if (!current?.blocks.length) return;
+ const text = current.blocks.map((item) => item.text).join("\n");
+ const html = current.blocks.map((item) => item.html).join("");
+ const promptLike = current.blocks.some((item) => item.relevance === "explicit-creative") || isPromptSection(text);
+ const item = {
+ id: stableCandidateId(context.canonicalUrl, `section\n${current.sourceOrder}\n${text}`),
+ text,
+ html,
+ kind: "section",
+ sourceOrder: current.sourceOrder,
+ relevance: promptLike ? "explicit-creative" : "general-content",
+ score: (promptLike ? 1_000_000 : 0) + [...text].length
+ };
+ if (promptLike || [...text].length >= PAGE_CAPTURE_QUALITY_LIMITS.minOrdinarySectionCharacters) sections.push(item);
+ else omitted.push({ ...item, reason: "short-or-uncertain" });
+ current = null;
+ };
+
+ for (const block of sourceBlocks) {
+ if (block.text === context.title || block.text === context.sourceFacts.author) continue;
+ if (block.kind === "noise") {
+ flush();
+ omitted.push({ ...block, reason: "page-chrome" });
+ continue;
+ }
+ if (block.kind === "heading") {
+ flush();
+ current = { sourceOrder: block.sourceOrder, blocks: [block] };
+ continue;
+ }
+ if (!current) current = { sourceOrder: block.sourceOrder, blocks: [] };
+ current.blocks.push(block);
+ }
+ flush();
+
+ const textBlocks = sections
+ .sort((left, right) => right.score - left.score || left.sourceOrder - right.sourceOrder)
+ .slice(0, PAGE_CAPTURE_QUALITY_LIMITS.maxCreativeSections);
+ const retained = [...textBlocks].sort((left, right) => left.sourceOrder - right.sourceOrder);
+ return {
+ textBlocks,
+ possibleOmissions: omitted
+ .sort((left, right) => [...right.text].length - [...left.text].length || left.sourceOrder - right.sourceOrder)
+ .slice(0, PAGE_CAPTURE_QUALITY_LIMITS.maxPossibleOmissions),
+ contentText: retained.map((item) => item.text).join("\n\n"),
+ contentHtml: retained.every((item) => item.html) ? retained.map((item) => item.html).join("") : ""
+ };
+}
+
+function isPromptSection(value) {
+ return /(?:^|\n)\s*(?:prompt|negative prompt|system prompt|提示词|反向提示词|项目\s*brief|creative brief|brief|创作说明)\s*[::]?\s*(?:\n|$)/iu.test(String(value || ""));
+}
+
export function normalizeSourceFacts(value = {}, canonicalUrl = "") {
const engagement = Object.fromEntries(Object.entries(value.engagement || {}).flatMap(([key, amount]) => {
const number = Number(amount);
@@ -122,6 +524,10 @@ export function normalizeSourceFacts(value = {}, canonicalUrl = "") {
engagementObservedAt: Object.keys(engagement).length
? validIso(value.engagementObservedAt) || capturedAt
: "",
+ captureScope: value.captureScope === "selection" ? "selection" : "document",
+ extractionMethod: ["selection", "readability", "structured", "page"].includes(value.extractionMethod)
+ ? value.extractionMethod
+ : "page",
status: value.status === "complete" ? "complete" : "partial"
};
}
@@ -130,16 +536,69 @@ export function pageCapturePermissionOrigins(candidates = []) {
const origins = new Set();
for (const candidate of candidates) {
for (const media of normalizePageCaptureCandidate(candidate)?.media || []) {
- try {
- const url = new URL(media.url || media.posterUrl);
- if (["http:", "https:"].includes(url.protocol)) origins.add(`${url.origin}/*`);
- } catch {
+ if (media.kind === "document" && !isSupportedDocumentMimeType(media.mimeType)) continue;
+ for (const value of [media.posterUrl, ...pageCaptureMediaFetchCandidates(media)]) {
+ try {
+ const url = new URL(value);
+ if (["http:", "https:"].includes(url.protocol)) origins.add(`${url.origin}/*`);
+ } catch {
+ }
}
}
}
return [...origins].sort();
}
+export function pageCaptureMediaFetchCandidates(value = {}) {
+ const seen = new Set();
+ return [
+ ...(Array.isArray(value.variants) ? value.variants.map((variant) => variant?.url) : []),
+ value.url
+ ].flatMap((candidate) => {
+ const url = safeUrl(candidate);
+ if (!url || seen.has(url)) return [];
+ seen.add(url);
+ return [url];
+ });
+}
+
+export async function resolvePageCaptureImage(mediaValue = {}, options = {}) {
+ if (typeof options.fetchMedia !== "function" || typeof options.decodeDataUrl !== "function") {
+ throw new Error("网页媒体解析器缺少下载能力");
+ }
+ const failures = [];
+ for (const url of pageCaptureMediaFetchCandidates(mediaValue)) {
+ try {
+ const downloaded = await options.fetchMedia(url);
+ const blob = downloaded?.blob instanceof Blob ? downloaded.blob : downloaded;
+ return { blob, metadata: downloaded?.metadata || null, sourceUrl: url, captureMethod: "source", usedPixelFallback: false, failures };
+ } catch (error) {
+ failures.push({ url, message: String(error?.message || error) });
+ }
+ }
+ if (options.sessionMediaAllowed !== false && typeof options.fetchSessionMedia === "function") {
+ for (const url of pageCaptureMediaFetchCandidates(mediaValue)) {
+ try {
+ const downloaded = await options.fetchSessionMedia(url);
+ const blob = downloaded?.blob instanceof Blob ? downloaded.blob : downloaded;
+ return { blob, metadata: downloaded?.metadata || null, sourceUrl: url, captureMethod: "page-session", usedPixelFallback: false, failures };
+ } catch (error) {
+ failures.push({ url, method: "page-session", message: String(error?.message || error) });
+ }
+ }
+ }
+ const dataUrl = safeImageDataUrl(mediaValue.dataUrl || mediaValue.previewDataUrl);
+ if (dataUrl) {
+ try {
+ return { blob: await options.decodeDataUrl(dataUrl), sourceUrl: "", captureMethod: "pixel-fallback", usedPixelFallback: true, failures };
+ } catch (error) {
+ failures.push({ url: "pixel-fallback", message: String(error?.message || error) });
+ }
+ }
+ const reason = failures.at(-1)?.message || "没有可用的图片来源";
+ throw new Error(reason);
+}
+
export async function collectPageCaptureSnapshot(options = {}) {
function clean(value) {
return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").trim();
@@ -164,34 +623,89 @@ export async function collectPageCaptureSnapshot(options = {}) {
const originalScroll = { x: window.scrollX, y: window.scrollY };
try {
+ const editedRegion = options.editedRegion && typeof options.editedRegion === "object" ? options.editedRegion : null;
+ const editedBaseRoot = editedRegion?.marker
+ ? [...document.querySelectorAll?.("[data-promptdirector-capture-region]") || []]
+ .find((element) => element.getAttribute?.("data-promptdirector-capture-region") === clean(editedRegion.marker))
+ : null;
+ const editedRoot = editedBaseRoot && clean(editedRegion?.token)
+ ? buildEditedRegionRoot(editedBaseRoot, clean(editedRegion.token))
+ : null;
+ for (const element of document.querySelectorAll?.("[data-promptdirector-capture-region]") || []) {
+ element.removeAttribute?.("data-promptdirector-capture-region");
+ }
const adapter = detectAdapter(location.hostname);
const canonicalUrl = safeHttpUrl(document.querySelector('link[rel="canonical"]')?.href || location.href);
const metadata = collectMetadata();
const structured = collectStructuredData();
const article = readArticle();
+ const siteData = options.siteData && typeof options.siteData === "object" ? options.siteData : null;
+ const pageSelection = options.mode === "whole" ? null : collectPageSelection();
+ if (editedRoot) {
+ const pageType = detectPageType({ adapter, metadata, structured, article, cardCount: 0 });
+ const candidate = candidateForRoot(editedRoot, 0, {
+ adapter, metadata, structured, article: null, siteData: null, canonicalUrl, pageType, maxMedia
+ });
+ if (candidate) candidate.region = editedRegion.region || null;
+ editedBaseRoot.setAttribute?.("data-promptdirector-capture-region", clean(editedRegion.marker));
+ return { id: sessionId, sourceUrl: canonicalUrl, adapter: adapter.id, candidates: candidate ? [candidate] : [], capturedAt };
+ }
+ if (siteData?.pageKind === "feed") {
+ if (wholePage) await scanLoadedPage(() => undefined);
+ return {
+ id: sessionId,
+ sourceUrl: canonicalUrl,
+ adapter: adapter.id,
+ candidates: Array.isArray(siteData.candidates) ? siteData.candidates.slice(0, maxCandidates) : [],
+ capturedAt,
+ siteStatus: siteData.completeness === "complete" ? "complete" : "partial"
+ };
+ }
const accumulated = new Map();
const collectVisible = () => {
- const cardRoots = adapter.cardSelectors.flatMap((selector) => [...document.querySelectorAll(selector)]);
+ const current = [];
+ const adapterRoots = adapter.cardSelectors.flatMap((selector) => [...document.querySelectorAll(selector)]);
+ const repeatedRoots = adapterRoots.length > 1 ? [] : collectRepeatedCardRoots(maxCandidates);
+ const cardRoots = [...adapterRoots, ...repeatedRoots];
const roots = [...new Set(cardRoots)].filter(isContentRoot);
const pageType = detectPageType({ adapter, metadata, structured, article, cardCount: roots.length });
for (const [index, root] of roots.entries()) {
const candidate = candidateForRoot(root, index, {
- adapter, metadata, structured, article: null, canonicalUrl, pageType, maxMedia
+ adapter, metadata, structured, article: null, siteData: null, canonicalUrl, pageType, maxMedia
});
- if (candidate && !accumulated.has(candidate.id) && accumulated.size < maxCandidates) accumulated.set(candidate.id, candidate);
+ if (candidate) current.push(candidate);
}
+ return current;
};
- collectVisible();
- if (wholePage) await scanLoadedPage(collectVisible);
- collectVisible();
+ const collectVisibleWithFallbacks = async () => {
+ const current = collectVisible();
+ await attachViewportFallbacks(current);
+ for (const candidate of current) {
+ if (accumulated.has(candidate.id) || accumulated.size < maxCandidates) accumulated.set(candidate.id, candidate);
+ }
+ };
+ await collectVisibleWithFallbacks();
+ if (wholePage) await scanLoadedPage(collectVisibleWithFallbacks);
+ await collectVisibleWithFallbacks();
const capturedCards = [...accumulated.values()];
const pageType = detectPageType({ adapter, metadata, structured, article, cardCount: capturedCards.length });
const bodyCandidate = candidateForRoot(document.body, 0, {
- adapter, metadata, structured, article, canonicalUrl, pageType, maxMedia
+ adapter, metadata, structured, article, siteData, pageSelection, canonicalUrl, pageType, maxMedia
});
+ if (bodyCandidate) await attachViewportFallbacks([bodyCandidate]);
+ const regionCandidates = !siteData && !pageSelection && !["feed", "gallery"].includes(pageType)
+ ? collectSubjectRegionRoots(positiveInteger(options.maxRegionCandidates, 5)).flatMap((root, index) => {
+ const candidate = candidateForRoot(root, index, {
+ adapter, metadata, structured, article: null, siteData: null, canonicalUrl, pageType, maxMedia
+ });
+ return candidate ? [candidate] : [];
+ })
+ : [];
+ if (regionCandidates.length) await attachViewportFallbacks(regionCandidates);
const candidates = capturedCards.length > 1 && ["feed", "gallery"].includes(pageType)
? capturedCards.slice(0, maxCandidates)
- : bodyCandidate ? [bodyCandidate] : capturedCards.slice(0, maxCandidates);
+ : regionCandidates.length ? regionCandidates
+ : bodyCandidate ? [bodyCandidate] : capturedCards.slice(0, maxCandidates);
return {
id: sessionId,
sourceUrl: canonicalUrl,
@@ -213,8 +727,8 @@ export async function collectPageCaptureSnapshot(options = {}) {
const viewport = Math.max(1, Number(window.innerHeight) || 720);
const nextTop = Math.min(Math.max(0, height - viewport), Math.max(0, window.scrollY) + Math.round(viewport * 0.85));
window.scrollTo({ top: nextTop, behavior: "instant" });
- await new Promise((resolve) => setTimeout(resolve, 450));
- collectVisible();
+ await waitForVisibleMedia();
+ await collectVisible();
const nextHeight = Math.max(document.body?.scrollHeight || 0, document.documentElement.scrollHeight);
const position = Math.max(0, Number(window.scrollY) || nextTop);
stableRounds = position === previousPosition && position + viewport >= nextHeight ? stableRounds + 1 : 0;
@@ -222,10 +736,73 @@ export async function collectPageCaptureSnapshot(options = {}) {
}
}
+ async function attachViewportFallbacks(candidates) {
+ if (!wholePage || !sessionId || !globalThis.chrome?.runtime?.sendMessage) return;
+ const positions = [];
+ for (const [candidateIndex, candidate] of candidates.entries()) {
+ for (const [mediaIndex, media] of candidate.media.entries()) {
+ if (media.kind === "image" && media.fallbackRect && !media.dataUrl) {
+ positions.push({ candidateIndex, mediaIndex, selection: media.fallbackRect });
+ }
+ }
+ }
+ if (!positions.length) return;
+ const boundedPositions = positions.slice(0, maxCandidates);
+ try {
+ const response = await globalThis.chrome.runtime.sendMessage({
+ type: "PAGE_CAPTURE_VIEWPORT_FALLBACKS",
+ sessionId,
+ selections: boundedPositions.map((item) => item.selection)
+ });
+ if (!response?.ok || response.dataUrls?.length !== boundedPositions.length) return;
+ response.dataUrls.forEach((dataUrl, index) => {
+ if (!dataUrl) return;
+ const position = boundedPositions[index];
+ candidates[position.candidateIndex].media[position.mediaIndex].dataUrl = dataUrl;
+ candidates[position.candidateIndex].media[position.mediaIndex].previewDataUrl = dataUrl;
+ });
+ } catch {
+ }
+ }
+
+ async function waitForVisibleMedia() {
+ const visibleImages = [...(document.images || [])].filter((image) => {
+ const rect = image.getBoundingClientRect();
+ const viewportHeight = Number(window.innerHeight) || 720;
+ return rect.width >= 48 && rect.height >= 48 && rect.bottom >= 0 && rect.top <= viewportHeight;
+ });
+ await Promise.race([
+ Promise.allSettled(visibleImages.map((image) => typeof image.decode === "function" ? image.decode() : Promise.resolve())),
+ new Promise((resolve) => setTimeout(resolve, 1200))
+ ]);
+ const frame = typeof globalThis.requestAnimationFrame === "function"
+ ? globalThis.requestAnimationFrame.bind(globalThis)
+ : (callback) => setTimeout(callback, 16);
+ await new Promise((resolve) => frame(() => frame(resolve)));
+ }
+
function detectAdapter(host) {
const adapters = Array.isArray(options.adapters) ? options.adapters : [];
- return adapters.find((item) => item.hosts.some((suffix) => host === suffix || host.endsWith(`.${suffix}`)))
- || { id: "generic", hosts: [], cardSelectors: ["main article", "[role=main] article"] };
+ const direct = adapters.find((item) => item.hosts.some((suffix) => host === suffix || host.endsWith(`.${suffix}`)));
+ if (direct) return direct;
+ const signals = collectPlatformSignals();
+ const platformAdapters = Array.isArray(options.platformAdapters) ? options.platformAdapters : [];
+ return platformAdapters.find((item) => Object.entries(item.signalPatterns || {}).some(([key, patterns]) => {
+ const values = Array.isArray(signals[key]) ? signals[key] : [signals[key]];
+ return patterns.some((pattern) => values.some((value) => {
+ try { return new RegExp(pattern, "iu").test(value); } catch { return false; }
+ }));
+ })) || { id: "generic", hosts: [], cardSelectors: ["main article", "[role=main] article"], fields: {} };
+ }
+
+ function collectPlatformSignals() {
+ const meta = (name) => cleanText(document.querySelector(`meta[name="${name}"]`)?.content);
+ return {
+ generator: meta("generator"),
+ applicationName: meta("application-name") || meta("applicationName"),
+ scripts: [...document.querySelectorAll("script[src]")].map((element) => safeHttpUrl(element.src)).filter(Boolean),
+ links: [...document.querySelectorAll("link[href]")].map((element) => safeHttpUrl(element.href)).filter(Boolean)
+ };
}
function collectMetadata() {
@@ -262,61 +839,674 @@ export async function collectPageCaptureSnapshot(options = {}) {
}
}
+ function collectPageSelection() {
+ try {
+ const selection = window.getSelection?.();
+ const text = cleanBlockText(selection?.toString?.());
+ if (!selection || selection.isCollapsed || !selection.rangeCount || !text) return null;
+ const container = document.createElement("div");
+ for (let index = 0; index < selection.rangeCount; index += 1) {
+ container.appendChild(selection.getRangeAt(index).cloneContents());
+ }
+ const html = String(container.innerHTML || "");
+ return {
+ text,
+ html,
+ textBlocks: collectTextBlocks(container, html, text)
+ };
+ } catch {
+ return null;
+ }
+ }
+
function detectPageType({ adapter, metadata, structured, article, cardCount }) {
const types = structured.flatMap((item) => Array.isArray(item["@type"]) ? item["@type"] : [item["@type"]]).filter(Boolean);
+ if (adapter.pageType === "post") return "post";
if (types.includes("VideoObject") || ["youtube", "bilibili"].includes(adapter.id)) return "video";
if (types.some((type) => ["Article", "NewsArticle", "BlogPosting"].includes(type)) || (article?.length || 0) > 500) return "article";
if (cardCount > 1) return metadata.type === "website" ? "gallery" : "feed";
- if (["x", "reddit"].includes(adapter.id)) return "post";
- if (["jimeng", "liblibai", "higgsfield", "krea", "tapnow", "pinterest", "artstation", "steam"].includes(adapter.id)) return "artwork";
- return "generic";
+ return ["article", "artwork", "video"].includes(adapter.pageType) ? adapter.pageType : "generic";
+ }
+
+ function reconcileArticlePlacement(articleDocument, mediaValue, contentTargets) {
+ const blocks = Array.isArray(articleDocument?.blocks) ? articleDocument.blocks : [];
+ const media = Array.isArray(mediaValue) ? mediaValue : [];
+ const mediaById = new Map(media.map((item) => [item.id, item]));
+ const blocksById = new Map(blocks.map((block) => [block.id, block]));
+ const blocksByAssetId = new Map(blocks.flatMap((block) => block.assetId ? [[block.assetId, block]] : []));
+ const inlineIds = new Set(blocks.flatMap((block) => block.assetId && mediaById.has(block.assetId) ? [block.assetId] : []));
+ const emittedBlockIds = new Set();
+ const emittedAssetIds = new Set();
+ const orderedBlocks = [];
+ const emit = (block) => {
+ if (!block || emittedBlockIds.has(block.id) || block.assetId && emittedAssetIds.has(block.assetId)) return;
+ emittedBlockIds.add(block.id);
+ if (block.assetId) emittedAssetIds.add(block.assetId);
+ orderedBlocks.push(block);
+ };
+ for (const target of (Array.isArray(contentTargets) ? contentTargets : [])
+ .filter((item) => item?.kind !== "group")
+ .sort((left, right) => Number(left.sourceOrder || 0) - Number(right.sourceOrder || 0))) {
+ for (const blockId of target.articleBlockIds || []) emit(blocksById.get(blockId));
+ for (const mediaId of target.mediaIds || []) {
+ const item = mediaById.get(mediaId);
+ if (!item) continue;
+ inlineIds.add(mediaId);
+ emit(blocksByAssetId.get(mediaId) || {
+ id: `article:${item.kind}:${item.id}`,
+ kind: item.kind,
+ assetId: item.id,
+ sourceUrl: item.url,
+ ...(item.posterUrl ? { posterUrl: item.posterUrl } : {}),
+ label: item.alt || item.filename || ""
+ });
+ }
+ }
+ for (const block of blocks) {
+ if (block.assetId && !inlineIds.has(block.assetId)) continue;
+ emit(block);
+ }
+ return {
+ articleDocument: { version: 1, blocks: orderedBlocks.map((block, sourceOrder) => ({ ...block, sourceOrder })) },
+ media: media.map((item) => ({ ...item, placement: inlineIds.has(item.id) ? "inline" : "unplaced" }))
+ };
}
function candidateForRoot(root, index, context) {
+ const siteData = root === document.body ? context.siteData : null;
const adapterFields = collectAdapterFields(root, context.adapter);
- const cardLink = root === document.body ? "" : safeHttpUrl(root.querySelector("a[href]")?.href);
- const canonicalUrl = cardLink || context.canonicalUrl;
+ const cardLink = root === document.body || context.pageType === "article" ? "" : safeHttpUrl(root.querySelector("a[href]")?.href);
+ const canonicalUrl = adapterFields.canonicalUrl || cardLink || safeHttpUrl(siteData?.canonicalUrl) || context.canonicalUrl;
const structured = context.structured.find((item) => sameUrl(item.url || item.mainEntityOfPage, canonicalUrl)) || context.structured[0] || {};
- const title = cleanText(root === document.body
- ? context.article?.title || structured.headline || structured.name || context.metadata.title
- : adapterFields.title || root.querySelector("h1,h2,h3,[role=heading]")?.textContent || root.querySelector("img[alt]")?.alt || structured.name);
- const text = cleanText(root === document.body
- ? context.article?.textContent || structured.articleBody || context.metadata.description
- : root.innerText);
- const media = collectMedia(root, context.maxMedia);
+ let title = cleanText(root === document.body
+ ? siteData?.title || context.article?.title || structured.headline || structured.name || (context.pageType === "post" ? "" : context.metadata.title)
+ : adapterFields.title || root.querySelector("h1,h2,h3,[role=heading]")?.textContent || structured.headline || structured.name || (context.pageType === "post" ? "" : root.querySelector("img[alt]")?.alt));
+ const pageSelection = root === document.body ? context.pageSelection : null;
+ const text = cleanBlockText(root === document.body
+ ? pageSelection?.text || siteData?.contentText || context.article?.textContent || structured.articleBody || root.innerText || context.metadata.description
+ : root.innerText || root.textContent);
+ const contentHtml = root === document.body
+ ? pageSelection?.html || context.article?.content || ""
+ : "";
+ const structuredTextBlocks = siteData?.contentText
+ ? [{
+ id: "text:structured:" + hashText(siteData.contentText),
+ text: cleanBlockText(siteData.contentText),
+ html: "",
+ kind: "paragraph",
+ relevance: "explicit-creative",
+ sourceOrder: 0
+ }]
+ : null;
+ const textBlocks = pageSelection?.textBlocks || structuredTextBlocks || collectTextBlocks(root, contentHtml, text);
+ const siteMedia = Array.isArray(siteData?.media) ? siteData.media : [];
+ const domMedia = pageSelection || root.isConnected === false ? [] : collectMedia(root, context.maxMedia);
+ const pairedDomIds = new Set();
+ const pairedSiteMedia = siteMedia.map((item) => {
+ const visible = domMedia.find((candidate) => mediaValuesOverlap(item, candidate));
+ if (visible) pairedDomIds.add(visible.id);
+ return visible ? {
+ ...item,
+ variants: [...(item.variants || []), ...(visible.variants || [])],
+ fallbackRect: visible.fallbackRect,
+ dataUrl: visible.dataUrl,
+ previewDataUrl: visible.previewDataUrl
+ } : item;
+ });
+ let media = mergeCollectedMedia([
+ ...pairedSiteMedia,
+ ...collectStructuredMedia(structured),
+ ...domMedia.filter((item) => !pairedDomIds.has(item.id))
+ ], context.maxMedia);
+ const article = collectArticleDocument(root, contentHtml, textBlocks, media, context.maxMedia);
+ media = mergeCollectedMedia([...media, ...article.media], context.maxMedia);
if (!title && !text && !media.length) return null;
- const pageType = root === document.body ? context.pageType : ["x", "reddit"].includes(context.adapter.id) ? "post" : "artwork";
- const author = cleanText(adapterFields.author || structured.author?.name || structured.author || context.metadata.author || root.querySelector('[rel=author],[data-testid*=author],[class*=author]')?.textContent);
- const itemId = itemIdFromUrl(canonicalUrl);
+ const pageType = root === document.body ? context.pageType : ["post", "video"].includes(context.adapter.pageType) ? context.adapter.pageType : "artwork";
+ const author = cleanText(siteData?.sourceFacts?.author || adapterFields.author || structuredAuthorName(structured.author) || context.metadata.author || root.querySelector('[rel=author],[data-testid*=author],[class*=author]')?.textContent);
+ if (!title && pageType === "post") {
+ const identity = author || (adapterFields.handle ? `@${adapterFields.handle}` : "");
+ title = [identity, cleanText(text).slice(0, 96)].filter(Boolean).join(" · ") || context.metadata.siteName || location.hostname;
+ }
+ const itemId = cleanText(siteData?.sourceFacts?.itemId || structured.identifier?.value || structured.identifier) || itemIdFromUrl(canonicalUrl);
+ const captureScope = pageSelection ? "selection" : "document";
+ const extractionMethod = pageSelection
+ ? "selection"
+ : siteData?.sourceFacts?.extractionMethod === "structured" ? "structured"
+ : context.article?.content ? "readability" : structured.articleBody ? "structured" : "page";
+ const complete = siteData?.completeness === "complete" || Boolean(title && (text || media.length));
+ const region = markCaptureRegion(root, index, text, media.length);
+ if (region && root.isConnected !== false) {
+ region.contentTargets = collectContentTargets(
+ root,
+ article.blocks,
+ media,
+ positiveInteger(options.maxContentTargets, 200)
+ );
+ }
+ const placed = reconcileArticlePlacement({ version: 1, blocks: article.blocks }, media, region?.contentTargets || []);
+ media = placed.media;
return {
id: `${context.adapter.id}:${itemId || index}:${hashText(`${canonicalUrl}\n${title}`)}`,
pageType,
title: title || context.metadata.siteName || location.hostname,
canonicalUrl,
- contentHtml: root === document.body ? context.article?.content || "" : "",
+ contentHtml,
contentText: text,
+ textBlocks,
+ articleDocument: placed.articleDocument,
+ region,
excerpt: cleanText(context.article?.excerpt || context.metadata.description),
media,
sourceFacts: {
- provider: context.adapter.id === "generic" ? location.hostname : context.adapter.id,
+ provider: cleanText(siteData?.sourceFacts?.provider) || (context.adapter.id === "generic" ? location.hostname : context.adapter.id),
pageType,
itemId,
author,
- handle: author.startsWith("@") ? author.slice(1) : "",
- publishedAt: adapterFields.publishedAt || structured.datePublished || context.metadata.publishedAt || "",
+ handle: cleanText(siteData?.sourceFacts?.handle || adapterFields.handle) || (author.startsWith("@") ? author.slice(1) : ""),
+ publishedAt: siteData?.sourceFacts?.publishedAt || adapterFields.publishedAt || structured.datePublished || context.metadata.publishedAt || "",
capturedAt,
- model: cleanText(adapterFields.model || structured.model || root.querySelector('[class*=model],[data-testid*=model]')?.textContent),
- dimensions: cleanText(structured.width && structured.height ? `${structured.width}×${structured.height}` : ""),
+ model: cleanText(siteData?.sourceFacts?.model || adapterFields.model || structured.model || root.querySelector('[class*=model],[data-testid*=model]')?.textContent),
+ dimensions: cleanText(siteData?.sourceFacts?.dimensions || (structured.width && structured.height ? `${structured.width}×${structured.height}` : "")),
duration: cleanText(structured.duration),
license: cleanText(structured.license),
- engagement: adapterFields.engagement,
- status: title && (text || media.length) ? "complete" : "partial"
+ engagement: { ...structuredEngagement(structured.interactionStatistic), ...adapterFields.engagement, ...(siteData?.sourceFacts?.engagement || {}) },
+ captureScope,
+ extractionMethod,
+ status: complete ? "complete" : "partial"
+ },
+ completeness: complete ? "complete" : "partial",
+ extraction: {
+ scope: captureScope,
+ method: extractionMethod,
+ textBlockCount: textBlocks.length
},
- completeness: title && (text || media.length) ? "complete" : "partial",
adapter: context.adapter.id
};
}
+ function buildEditedRegionRoot(baseRoot, token) {
+ const attributeValue = String(token).replace(/["\\]/gu, "");
+ const includeSelector = `[data-promptdirector-page-edit-include="${attributeValue}"]`;
+ const excludeSelector = `[data-promptdirector-page-edit-exclude="${attributeValue}"]`;
+ const includes = [...document.querySelectorAll?.(includeSelector) || []]
+ .filter((element) => element !== baseRoot && !baseRoot.contains?.(element));
+ const roots = [baseRoot, ...includes].sort((left, right) => {
+ const position = left.compareDocumentPosition?.(right) || 0;
+ return position & 2 ? 1 : -1;
+ });
+ const wrapper = document.createElement("div");
+ for (const root of roots) {
+ if (root.matches?.(excludeSelector)) continue;
+ const clone = root.cloneNode(true);
+ clone.querySelectorAll?.(excludeSelector).forEach((element) => element.remove());
+ clone.removeAttribute?.("data-promptdirector-page-edit-include");
+ clone.removeAttribute?.("data-promptdirector-page-edit-exclude");
+ clone.querySelectorAll?.(`${includeSelector},${excludeSelector}`).forEach((element) => {
+ element.removeAttribute("data-promptdirector-page-edit-include");
+ element.removeAttribute("data-promptdirector-page-edit-exclude");
+ });
+ wrapper.append(clone);
+ }
+ for (const element of document.querySelectorAll?.(`${includeSelector},${excludeSelector}`) || []) {
+ element.removeAttribute?.("data-promptdirector-page-edit-include");
+ element.removeAttribute?.("data-promptdirector-page-edit-exclude");
+ }
+ return wrapper;
+ }
+
+ function collectSubjectRegionRoots(limit) {
+ const semantic = [...document.querySelectorAll?.("main,article,[role=main],[itemprop=articleBody]") || []];
+ const bodyChildren = [...(document.body?.children || [])].filter((element) => element.matches?.("section,div"));
+ const candidates = [...new Set([...semantic, ...bodyChildren])]
+ .filter(isContentRoot)
+ .map((root) => ({ root, score: regionRootScore(root) }))
+ .filter((item) => item.score > 0)
+ .sort((left, right) => right.score - left.score);
+ const accepted = [];
+ const signatures = new Set();
+ for (const item of candidates) {
+ const signature = hashText(`${cleanBlockText(item.root.innerText)}\n${[...item.root.querySelectorAll?.("img,video,iframe,canvas") || []].length}`);
+ if (signatures.has(signature)) continue;
+ signatures.add(signature);
+ accepted.push(item.root);
+ if (accepted.length >= limit) break;
+ }
+ return accepted;
+ }
+
+ function collectRepeatedCardRoots(limit) {
+ const parents = [...document.querySelectorAll?.("main,[role=main],section,ul,ol,[class*=grid],[class*=gallery],[class*=feed],[class*=list]") || []];
+ const groups = [];
+ for (const parent of parents) {
+ if (parent.closest?.("nav,aside,header,footer,[role=navigation],[role=complementary],[role=contentinfo]")) continue;
+ const bySignature = new Map();
+ for (const child of [...(parent.children || [])]) {
+ if (!isContentRoot(child)) continue;
+ const textLength = [...cleanText(child.innerText)].length;
+ const mediaCount = [...child.querySelectorAll?.("img,video,iframe,canvas") || []].filter((item) => !isExcludedMedia(item)).length;
+ if (!mediaCount && textLength < 20) continue;
+ const classShape = [...(child.classList || [])]
+ .filter((token) => token.length <= 48 && !/\d{4,}/u.test(token))
+ .sort()
+ .slice(0, 3)
+ .join(".");
+ const signature = [
+ cleanText(child.tagName).toLowerCase(),
+ cleanText(child.getAttribute?.("role")),
+ child.querySelector?.("h1,h2,h3,[role=heading]") ? "heading" : "",
+ mediaCount ? "media" : "",
+ classShape
+ ].join(":");
+ const group = bySignature.get(signature) || [];
+ group.push({ root: child, score: textLength + mediaCount * Math.max(120, textLength) });
+ bySignature.set(signature, group);
+ }
+ for (const group of bySignature.values()) {
+ if (group.length < 2) continue;
+ groups.push({
+ items: group,
+ score: group.reduce((total, item) => total + item.score, 0)
+ });
+ }
+ }
+ const best = groups.sort((left, right) => right.score - left.score)[0];
+ return best ? best.items.map((item) => item.root).slice(0, limit) : [];
+ }
+
+ function regionRootScore(root) {
+ const text = cleanBlockText(root.innerText);
+ const textLength = [...text].length;
+ const mediaCount = [...root.querySelectorAll?.("img,video,iframe,canvas") || []].filter((item) => !isExcludedMedia(item)).length;
+ const linkTextLength = [...root.querySelectorAll?.("a[href]") || []]
+ .reduce((total, link) => total + [...cleanText(link.textContent)].length, 0);
+ const controls = [...root.querySelectorAll?.("button,input,select,textarea,[role=button]") || []].length;
+ const semanticBoost = root.matches?.("main,article,[role=main],[itemprop=articleBody]") ? Math.max(200, textLength * 0.35) : 0;
+ const linkPenalty = textLength ? Math.min(textLength, linkTextLength) : 0;
+ return textLength + mediaCount * Math.max(120, Math.min(600, textLength || 120)) + semanticBoost - linkPenalty - controls * 40;
+ }
+
+ function markCaptureRegion(root, index, text, mediaCount) {
+ if (!root?.setAttribute) return null;
+ const marker = `${sessionId || "page"}:${hashText(`${index}\n${cleanBlockText(text).slice(0, 512)}`)}`;
+ root.setAttribute("data-promptdirector-capture-region", marker);
+ return {
+ id: marker,
+ marker,
+ label: `主体方案 ${index + 1}`,
+ score: regionRootScore(root),
+ textLength: [...cleanBlockText(text)].length,
+ mediaCount
+ };
+ }
+
+ function collectContentTargets(root, articleBlocks, media, limit) {
+ const excludedSelector = "nav,aside,header,footer,[role=navigation],[role=banner],[role=complementary],[role=contentinfo],[class*=comment],[class*=recommend],[data-testid*=comment],[data-testid*=recommend]";
+ const semanticSelector = "h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,table,img,video,iframe,a[href]";
+ const pathFor = (element) => {
+ const parts = [];
+ let current = element;
+ while (current?.nodeType === 1) {
+ const tag = cleanText(current.tagName).toLocaleLowerCase("en-US");
+ const siblings = [...(current.parentElement?.children || [])].filter((item) => item.tagName === current.tagName);
+ parts.unshift(`${tag}:nth-of-type(${Math.max(1, siblings.indexOf(current) + 1)})`);
+ if (current === document.body) break;
+ current = current.parentElement;
+ }
+ return parts.join(" > ");
+ };
+ const backgroundUrl = (element) => {
+ try {
+ const match = getComputedStyle(element).backgroundImage.match(/url\(["']?([^"')]+)["']?\)/iu);
+ return safeHttpUrl(match?.[1]);
+ } catch {
+ return "";
+ }
+ };
+ const mediaIdsFor = (element, kind) => {
+ const urls = new Set();
+ if (kind === "image" && element.matches?.("img")) {
+ for (const variant of collectImageVariants(element)) urls.add(variant.url);
+ }
+ if (kind === "image") urls.add(backgroundUrl(element));
+ if (kind === "video") {
+ urls.add(safeHttpUrl(element.currentSrc || element.src));
+ urls.add(safeHttpUrl(element.poster));
+ }
+ if (kind === "document") urls.add(safeHttpUrl(element.href || element.getAttribute?.("href")));
+ urls.delete("");
+ return media.filter((item) => [item.url, item.posterUrl, ...(item.variants || []).map((variant) => variant.url)]
+ .some((url) => urls.has(url))).map((item) => item.id);
+ };
+ const kindFor = (element) => {
+ if (element.matches?.("video,iframe")) return element.matches("iframe") && !isSupportedVideoFrame(element) ? "" : "video";
+ if (element.matches?.("img") || backgroundUrl(element)) return "image";
+ if (element.matches?.("a[href]")) {
+ const sourceUrl = safeHttpUrl(element.href || element.getAttribute?.("href"));
+ if (!sourceUrl) return "";
+ if (attachmentDescriptor(element, sourceUrl, cleanText(element.textContent))) return "document";
+ if (isVideoUrl(sourceUrl)) return "video";
+ return "";
+ }
+ return cleanBlockText(element.textContent) ? "text" : "";
+ };
+ const candidates = [...root.querySelectorAll?.(`${semanticSelector},div,section,figure`) || []]
+ .filter((element) => !element.closest?.(excludedSelector));
+ const leafElements = candidates.filter((element) => {
+ const kind = kindFor(element);
+ if (!kind) return false;
+ if (kind !== "text") return true;
+ if (element.matches?.(semanticSelector)) return true;
+ return !element.querySelector?.(semanticSelector) && cleanBlockText(element.textContent);
+ });
+ const leaves = leafElements.flatMap((element, sourceOrder) => {
+ const kind = kindFor(element);
+ const text = kind === "text" ? cleanBlockText(element.textContent) : "";
+ const articleBlockIds = kind === "text"
+ ? articleBlocks.filter((block) => !block.assetId && cleanBlockText(block.text) === text).map((block) => block.id)
+ : [];
+ const mediaIds = mediaIdsFor(element, kind);
+ if (kind !== "text" && !mediaIds.length) return [];
+ const path = pathFor(element);
+ if (!path) return [];
+ return [{
+ id: `content:${kind}:${sourceOrder}:${hashText(path)}`,
+ kind,
+ path,
+ groupId: "",
+ articleBlockIds,
+ mediaIds,
+ sourceOrder,
+ element
+ }];
+ });
+ const groups = candidates.filter((element) => element.matches?.("div,section,article,figure") && element !== root).flatMap((element) => {
+ const children = leaves.filter((target) => element.contains?.(target.element));
+ if (children.length < 2) return [];
+ const path = pathFor(element);
+ if (!path) return [];
+ const id = `content:group:${hashText(path)}`;
+ for (const child of children) if (!child.groupId) child.groupId = id;
+ return [{
+ id,
+ kind: "group",
+ path,
+ groupId: "",
+ articleBlockIds: [...new Set(children.flatMap((target) => target.articleBlockIds))],
+ mediaIds: [...new Set(children.flatMap((target) => target.mediaIds))],
+ sourceOrder: Math.min(...children.map((target) => target.sourceOrder))
+ }];
+ });
+ return [...leaves.map(({ element, ...target }) => target), ...groups]
+ .sort((left, right) => left.sourceOrder - right.sourceOrder || (left.kind === "group" ? 1 : -1))
+ .slice(0, limit);
+ }
+
+ function collectTextBlocks(root, contentHtml, contentText) {
+ let blockRoot = root;
+ if (contentHtml) {
+ try {
+ const template = document.createElement("template");
+ template.innerHTML = contentHtml;
+ blockRoot = template.content || template;
+ } catch {
+ }
+ }
+ const selector = "h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,figure,table";
+ const containers = "li,blockquote,pre,figure,table";
+ const blocks = [];
+ for (const node of blockRoot?.querySelectorAll?.(selector) || []) {
+ const parentContainer = node.parentElement?.closest?.(containers);
+ if (parentContainer && parentContainer !== node) continue;
+ const text = cleanBlockText(node.textContent);
+ if (!text) continue;
+ const tagName = cleanText(node.tagName).toLowerCase();
+ blocks.push({
+ id: "text:" + blocks.length + ":" + hashText(text),
+ text,
+ html: serializeBlockHtml(node),
+ kind: /^h[1-6]$/u.test(tagName)
+ ? "heading"
+ : node.closest?.("nav,aside,header,footer,[role=navigation],[role=complementary],[role=contentinfo],[class*=comment],[class*=recommend],[data-testid*=comment],[data-testid*=recommend]")
+ ? "noise"
+ : tagName === "li" ? "list" : tagName === "blockquote" ? "quote" : tagName === "pre" ? "code" : tagName === "figure" ? "figure" : tagName === "table" ? "table" : "paragraph",
+ sourceOrder: blocks.length
+ });
+ }
+ if (blocks.length) return blocks;
+ const text = cleanBlockText(contentText);
+ return text ? [{ id: "text:0:" + hashText(text), text, html: String(contentHtml || "") }] : [];
+ }
+
+ function collectArticleDocument(root, contentHtml, textBlocks, knownMedia, limit) {
+ let blockRoot = root;
+ if (contentHtml) {
+ try {
+ const template = document.createElement("template");
+ template.innerHTML = contentHtml;
+ blockRoot = template.content || template;
+ } catch {
+ }
+ }
+ const media = [];
+ const blocks = [];
+ const textByValue = new Map();
+ for (const block of textBlocks || []) {
+ const key = cleanBlockText(block.text);
+ if (key && !textByValue.has(key)) textByValue.set(key, block);
+ }
+ const selector = "h1,h2,h3,h4,h5,h6,p,ul,ol,blockquote,pre,table,figcaption,img,video,iframe,a[href]";
+ const structuralContainers = "p,ul,ol,blockquote,pre,table,figcaption";
+ const elements = [...(blockRoot?.querySelectorAll?.(selector) || [])];
+ for (const element of elements) {
+ if (element.closest?.("nav,aside,header,footer,[role=navigation],[role=complementary],[role=contentinfo],[class*=comment],[class*=recommend],[data-testid*=comment],[data-testid*=recommend]")) continue;
+ const tagName = cleanText(element.tagName).toLowerCase();
+ if (element.matches?.("a[href]")) {
+ const sourceUrl = safeHttpUrl(element.href || element.getAttribute?.("href"));
+ if (!sourceUrl) continue;
+ const label = cleanText(element.textContent || element.getAttribute?.("download")) || filenameFromUrl(sourceUrl);
+ const attachment = attachmentDescriptor(element, sourceUrl, label);
+ if (attachment) {
+ if (attachment.mimeType) {
+ media.push(attachment);
+ blocks.push({ id: `article:document:${hashText(sourceUrl)}`, kind: "document", assetId: attachment.id, sourceUrl, label, mimeType: attachment.mimeType, sourceOrder: blocks.length });
+ } else {
+ blocks.push({ id: `article:link:${hashText(sourceUrl)}`, kind: "link", sourceUrl, label, sourceOrder: blocks.length });
+ }
+ } else if (isVideoUrl(sourceUrl)) {
+ const video = { id: `article:video:${hashText(sourceUrl)}`, kind: "video", url: sourceUrl, posterUrl: "", alt: label, captureMethod: "source" };
+ media.push(video);
+ blocks.push({ id: `article:video-link:${hashText(sourceUrl)}`, kind: "video", assetId: video.id, sourceUrl, label, sourceOrder: blocks.length });
+ }
+ continue;
+ }
+ if (element.matches?.("img")) {
+ if (blockRoot === root && root.isConnected !== false && isExcludedMedia(element)) continue;
+ if (playerForCompanionPoster(element, blockRoot)) continue;
+ const variants = collectImageVariants(element);
+ const sourceUrl = variants[0]?.url || safeHttpUrl(element.currentSrc || element.src);
+ const existing = findKnownMedia(knownMedia, sourceUrl, variants, "image");
+ const item = existing || (sourceUrl ? {
+ id: `article:image:${hashText(sourceUrl)}`,
+ kind: "image",
+ url: sourceUrl,
+ posterUrl: "",
+ alt: cleanText(element.alt),
+ width: Number(element.naturalWidth || element.width) || 0,
+ height: Number(element.naturalHeight || element.height) || 0,
+ captureMethod: "source",
+ sourceKind: variants[0]?.sourceKind || "source",
+ variants
+ } : null);
+ if (!item) continue;
+ if (!existing) media.push(item);
+ blocks.push({ id: `article:image-block:${hashText(item.id)}`, kind: "image", assetId: item.id, sourceUrl: item.url, label: cleanText(item.alt), sourceOrder: blocks.length });
+ continue;
+ }
+ if (element.matches?.("video,iframe")) {
+ if (element.matches?.("iframe") && !isSupportedVideoFrame(element)) continue;
+ const sourceUrl = safeHttpUrl(element.currentSrc || element.src);
+ const posterElement = companionPosterForPlayer(element, blockRoot);
+ const posterUrl = safeHttpUrl(element.poster || "") || (posterElement ? collectImageVariants(posterElement)[0]?.url : "") || "";
+ const existing = findKnownMedia(knownMedia, sourceUrl || posterUrl, [], "video");
+ const item = existing || (sourceUrl || posterUrl ? {
+ id: `article:video:${hashText(sourceUrl || posterUrl)}`,
+ kind: "video",
+ url: sourceUrl,
+ posterUrl,
+ alt: cleanText(element.getAttribute?.("aria-label")),
+ captureMethod: "source"
+ } : null);
+ if (!item) continue;
+ if (!existing) media.push(item);
+ blocks.push({ id: `article:video-block:${hashText(item.id)}`, kind: "video", assetId: item.id, sourceUrl: item.url, posterUrl: item.posterUrl, label: cleanText(item.alt), sourceOrder: blocks.length });
+ continue;
+ }
+ const parentContainer = element.parentElement?.closest?.(structuralContainers);
+ if (parentContainer && parentContainer !== element) continue;
+ const text = cleanBlockText(element.textContent);
+ if (!text) continue;
+ const known = textByValue.get(text);
+ const kind = /^h[1-6]$/u.test(tagName)
+ ? "heading"
+ : ["ul", "ol"].includes(tagName) ? "list"
+ : tagName === "blockquote" ? "quote"
+ : tagName === "pre" ? "code"
+ : tagName === "table" ? "table" : "paragraph";
+ blocks.push({
+ id: known?.id || `article:text:${blocks.length}:${hashText(text)}`,
+ kind,
+ text,
+ ...(kind === "heading" ? { level: Number(tagName.slice(1)) || 2 } : {}),
+ ...(kind === "list" ? { ordered: tagName === "ol" } : {}),
+ sourceOrder: blocks.length
+ });
+ }
+ if (!blocks.length) {
+ for (const block of textBlocks || []) {
+ blocks.push({ id: block.id, kind: articleTextKind(block.kind), text: block.text, sourceOrder: blocks.length });
+ }
+ }
+ return { blocks, media: media.slice(0, Math.max(0, limit - knownMedia.length)) };
+ }
+
+ function articleTextKind(value) {
+ return ["heading", "paragraph", "list", "quote", "code", "table"].includes(value) ? value : "paragraph";
+ }
+
+ function findKnownMedia(values, sourceUrl, variants, kind) {
+ const urls = new Set([sourceUrl, ...(variants || []).map((item) => item.url)].filter(Boolean));
+ return (values || []).find((item) => item.kind === kind && [item.url, item.posterUrl, ...(item.variants || []).map((variant) => variant.url)].some((url) => urls.has(url))) || null;
+ }
+
+ function attachmentDescriptor(element, sourceUrl, label) {
+ const declaredType = cleanText(element.type || element.getAttribute?.("type")).toLocaleLowerCase("en-US").split(";", 1)[0];
+ const extension = fileExtension(sourceUrl);
+ const mimeByExtension = {
+ pdf: "application/pdf",
+ md: "text/markdown",
+ markdown: "text/markdown",
+ txt: "text/plain",
+ html: "text/html",
+ htm: "text/html",
+ rtf: "application/rtf"
+ };
+ const mimeType = mimeByExtension[extension] || (/[\w.+-]+\/[\w.+-]+/u.test(declaredType) ? declaredType : "");
+ const explicitlyDownloadable = element.hasAttribute?.("download") || /\bdownload\b/iu.test(`${element.rel || ""} ${element.className || ""} ${element.getAttribute?.("aria-label") || ""}`);
+ if (!mimeType && !explicitlyDownloadable) return null;
+ return {
+ id: `article:document:${hashText(sourceUrl)}`,
+ kind: "document",
+ url: sourceUrl,
+ filename: cleanText(element.getAttribute?.("download")) || label || filenameFromUrl(sourceUrl),
+ mimeType,
+ alt: label,
+ captureMethod: "source"
+ };
+ }
+
+ function fileExtension(value) {
+ try {
+ const name = new URL(value).pathname.split("/").filter(Boolean).at(-1) || "";
+ return cleanText(name.split(".").at(-1)).toLocaleLowerCase("en-US");
+ } catch {
+ return "";
+ }
+ }
+
+ function filenameFromUrl(value) {
+ try { return decodeURIComponent(new URL(value).pathname.split("/").filter(Boolean).at(-1) || ""); }
+ catch { return ""; }
+ }
+
+ function isVideoUrl(value) {
+ try {
+ const url = new URL(value);
+ return /\.(?:mp4|webm|mov)(?:$|[?#])/iu.test(url.pathname) || ["youtube.com", "youtu.be", "vimeo.com", "bilibili.com", "douyin.com", "x.com"].some((host) => url.hostname === host || url.hostname.endsWith(`.${host}`));
+ } catch {
+ return false;
+ }
+ }
+
+ function structuredAuthorName(value) {
+ const authors = Array.isArray(value) ? value : value ? [value] : [];
+ return authors.map((author) => cleanText(typeof author === "string" ? author : author?.name)).filter(Boolean).join("、");
+ }
+
+ function structuredEngagement(value) {
+ const statistics = Array.isArray(value) ? value : value ? [value] : [];
+ const engagement = {};
+ for (const statistic of statistics) {
+ const type = cleanText(statistic?.interactionType?.["@type"] || statistic?.interactionType).toLocaleLowerCase("en-US");
+ const amount = Number(statistic?.userInteractionCount);
+ if (!Number.isFinite(amount) || amount < 0) continue;
+ if (type.includes("like")) engagement.likes = amount;
+ else if (type.includes("share")) engagement.shares = amount;
+ else if (type.includes("view") || type.includes("watch")) engagement.views = amount;
+ }
+ return engagement;
+ }
+
+ function collectStructuredMedia(value) {
+ const images = [];
+ const addImage = (candidate) => {
+ const item = typeof candidate === "string" ? { url: candidate } : candidate || {};
+ const url = safeHttpUrl(item.contentUrl || item.url || item["@id"]);
+ if (!url) return;
+ const width = Number(item.width?.value || item.width) || 0;
+ const height = Number(item.height?.value || item.height) || 0;
+ images.push({
+ id: `structured:${hashText(url)}`,
+ kind: "image",
+ url,
+ width,
+ height,
+ sourceKind: "structured",
+ captureMethod: "source",
+ variants: [{ url, width, height, sourceKind: "structured" }]
+ });
+ };
+ for (const image of Array.isArray(value?.image) ? value.image : value?.image ? [value.image] : []) addImage(image);
+ if (!images.length && value?.thumbnailUrl) addImage(value.thumbnailUrl);
+ return images;
+ }
+
+ function serializeBlockHtml(node) {
+ try {
+ const clone = node.cloneNode(true);
+ const elements = [clone, ...(clone.querySelectorAll?.("[href],[src],[poster]") || [])];
+ for (const element of elements) {
+ for (const attribute of ["href", "src", "poster"]) {
+ if (!element.hasAttribute?.(attribute)) continue;
+ const absoluteUrl = safeHttpUrl(element.getAttribute(attribute));
+ if (absoluteUrl) element.setAttribute(attribute, absoluteUrl);
+ }
+ }
+ return String(clone.outerHTML || "");
+ } catch {
+ return String(node.outerHTML || "");
+ }
+ }
+
function collectAdapterFields(root, adapter) {
const fields = adapter?.fields && typeof adapter.fields === "object" ? adapter.fields : {};
const firstText = (selectors) => {
@@ -335,6 +1525,23 @@ export async function collectPageCaptureSnapshot(options = {}) {
const match = text.replace(/,/g, "").match(/\d+(?:\.\d+)?/);
return match ? Number(match[0]) : null;
};
+ const firstUrl = (selectors) => {
+ for (const selector of Array.isArray(selectors) ? selectors : []) {
+ try {
+ const node = root.querySelector(selector);
+ const value = safeHttpUrl(node?.href || node?.getAttribute?.("href"));
+ if (value) return value;
+ } catch {
+ }
+ }
+ return "";
+ };
+ const handleFromLink = (selectors) => {
+ const value = firstUrl(selectors);
+ if (!value) return "";
+ try { return cleanText(new URL(value).pathname.split("/").filter(Boolean)[0]).replace(/^@/u, ""); }
+ catch { return ""; }
+ };
const engagement = Object.fromEntries(["likes", "reposts", "views"].flatMap((name) => {
const value = numeric(name);
return Number.isFinite(value) ? [[name, value]] : [];
@@ -342,6 +1549,8 @@ export async function collectPageCaptureSnapshot(options = {}) {
return {
title: firstText(fields.title),
author: firstText(fields.author),
+ handle: handleFromLink(fields.handle),
+ canonicalUrl: firstUrl(fields.canonicalUrl),
model: firstText(fields.model),
publishedAt: firstText(fields.publishedAt),
engagement
@@ -352,6 +1561,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
const media = [];
for (const [elementIndex, element] of [...root.querySelectorAll("img,video,iframe,canvas")].entries()) {
if (isExcludedMedia(element)) continue;
+ if (element.matches?.("img") && playerForCompanionPoster(element, root)) continue;
if (element instanceof HTMLCanvasElement) {
try {
const dataUrl = element.toDataURL("image/webp", 0.92);
@@ -363,13 +1573,36 @@ export async function collectPageCaptureSnapshot(options = {}) {
if (media.length >= limit) break;
continue;
}
+ if (element.matches("iframe") && !isSupportedVideoFrame(element)) continue;
const kind = element.matches("video,iframe") ? "video" : "image";
- const url = kind === "image"
- ? bestImageUrl(element)
- : safeHttpUrl(element.currentSrc || element.src);
- const posterUrl = kind === "video" ? safeHttpUrl(element.poster || "") : "";
- if (!url && !posterUrl) continue;
- media.push({ kind, url, posterUrl, alt: cleanText(element.alt), width: Number(element.naturalWidth || element.videoWidth || element.width) || 0, height: Number(element.naturalHeight || element.videoHeight || element.height) || 0, captureMethod: "source" });
+ const variants = kind === "image" ? collectImageVariants(element) : [];
+ const imageSource = variants[0] || null;
+ const url = imageSource?.url || safeHttpUrl(element.currentSrc || element.src);
+ const posterElement = kind === "video" ? companionPosterForPlayer(element, root) : null;
+ const posterUrl = kind === "video" ? safeHttpUrl(element.poster || "") || (posterElement ? collectImageVariants(posterElement)[0]?.url : "") || "" : "";
+ const pixelFallback = kind === "image" ? visibleImagePixels(element) : "";
+ if (!url && !posterUrl && !pixelFallback) continue;
+ const rect = element.getBoundingClientRect();
+ const fallbackRect = kind === "image" && rect.width >= 48 && rect.height >= 48 && rect.bottom >= 0 && rect.top <= (Number(window.innerHeight) || 720)
+ ? { rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, viewportWidth: Number(window.innerWidth) || document.documentElement.clientWidth, viewportHeight: Number(window.innerHeight) || document.documentElement.clientHeight }
+ : null;
+ const responsiveCandidate = Boolean(imageSource?.declaredWidth || imageSource?.density > 1);
+ media.push({
+ id: `${kind}:${elementIndex}:${hashText(cleanText(element.alt || element.getAttribute?.("aria-label")))}`,
+ kind,
+ url,
+ posterUrl,
+ alt: cleanText(element.alt),
+ width: imageSource?.declaredWidth || (responsiveCandidate ? 0 : Number(element.naturalWidth || element.videoWidth || element.width) || 0),
+ height: responsiveCandidate ? 0 : Number(element.naturalHeight || element.videoHeight || element.height) || 0,
+ captureMethod: "source",
+ sourceKind: imageSource?.sourceKind || "current",
+ declaredWidth: imageSource?.declaredWidth || 0,
+ density: imageSource?.density || 0,
+ variants,
+ ...(fallbackRect ? { fallbackRect } : {}),
+ ...(pixelFallback ? { dataUrl: pixelFallback, previewDataUrl: pixelFallback } : {})
+ });
if (media.length >= limit) break;
}
if (media.length < limit) {
@@ -379,7 +1612,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
const url = safeHttpUrl(match?.[1]);
const rect = element.getBoundingClientRect();
if (!url || sameUrl(url, location.href) || rect.width < 48 || rect.height < 48) continue;
- media.push({ kind: "image", url, posterUrl: "", alt: "", width: element.clientWidth, height: element.clientHeight, captureMethod: "css-background" });
+ media.push({ id: `background:${hashText(url)}`, kind: "image", url, posterUrl: "", alt: "", width: element.clientWidth, height: element.clientHeight, captureMethod: "css-background", sourceKind: "css-background", variants: [{ url, sourceKind: "css-background", width: element.clientWidth, height: element.clientHeight }] });
if (media.length >= limit) break;
}
}
@@ -392,18 +1625,195 @@ export async function collectPageCaptureSnapshot(options = {}) {
});
}
- function bestImageUrl(image) {
- const srcset = String(image.srcset || "").split(",").map((item) => item.trim().split(/\s+/)).filter((item) => item[0]);
- const ranked = srcset.map(([url, descriptor]) => ({ url: safeHttpUrl(url), score: Number.parseFloat(descriptor) || 1 })).filter((item) => item.url).sort((left, right) => right.score - left.score);
- return safeHttpUrl(image.currentSrc) || ranked[0]?.url || safeHttpUrl(image.src);
+ function companionPosterForPlayer(player, root) {
+ if (!player?.matches?.("video,iframe")) return null;
+ const figure = player.closest?.("figure,[role=group]");
+ const container = figure && root.contains?.(figure) ? figure : player.parentElement;
+ if (!container || !root.contains?.(container)) return null;
+ const players = [...container.querySelectorAll?.("video,iframe") || []].filter((item) => item.matches?.("video") || isSupportedVideoFrame(item));
+ const images = [...container.querySelectorAll?.("img") || []].filter((image) => {
+ const link = image.closest?.("a[href]");
+ const linkedUrl = safeHttpUrl(link?.href || link?.getAttribute?.("href"));
+ return !linkedUrl || !/\.(?:avif|gif|jpe?g|png|webp)(?:$|[?#])/iu.test(linkedUrl);
+ });
+ return players.length === 1 && images.length === 1 ? images[0] : null;
+ }
+
+ function playerForCompanionPoster(image, root) {
+ if (!image?.matches?.("img")) return null;
+ const figure = image.closest?.("figure,[role=group]");
+ const container = figure && root.contains?.(figure) ? figure : image.parentElement;
+ if (!container || !root.contains?.(container)) return null;
+ const player = [...container.querySelectorAll?.("video,iframe") || []]
+ .find((item) => item.matches?.("video") || isSupportedVideoFrame(item));
+ return player && companionPosterForPlayer(player, root) === image ? player : null;
+ }
+
+ function collectImageVariants(image) {
+ const pictureCandidates = [];
+ const imageCandidates = [];
+ const addSrcset = (value, sourceKind, target) => {
+ for (const candidate of parseSrcset(value)) {
+ const url = safeHttpUrl(candidate.url);
+ if (url) target.push({ ...candidate, url, sourceKind });
+ }
+ };
+ const picture = image.closest?.("picture");
+ for (const source of picture?.querySelectorAll?.("source[srcset],source[data-srcset]") || []) {
+ const media = cleanText(source.getAttribute("media"));
+ if (media && typeof window.matchMedia === "function" && !window.matchMedia(media).matches) continue;
+ addSrcset(source.getAttribute("srcset") || source.getAttribute("data-srcset"), "picture-srcset", pictureCandidates);
+ if (pictureCandidates.length) break;
+ }
+ addSrcset(image.getAttribute?.("srcset") || image.srcset, "img-srcset", imageCandidates);
+ addSrcset(image.getAttribute?.("data-srcset") || image.getAttribute?.("data-lazy-srcset"), "deferred-srcset", imageCandidates);
+ const candidates = [];
+ for (const attribute of [
+ "data-full-image", "data-full", "data-full-size", "data-hi-res", "data-high-res", "data-hires",
+ "data-zoom-image", "data-large-image", "data-large", "data-src-large", "data-image-url", "data-pin-media",
+ "data-orig-file", "data-original", "data-original-src", "data-src-original"
+ ]) {
+ const originalUrl = safeHttpUrl(image.getAttribute?.(attribute));
+ if (originalUrl) candidates.push({ url: originalUrl, sourceKind: "site-original", declaredWidth: urlWidthHint(originalUrl), density: 0 });
+ }
+ const imageLink = image.closest?.("a[href]");
+ const linkedUrl = safeHttpUrl(imageLink?.href || imageLink?.getAttribute?.("href"));
+ if (linkedUrl && (imageLink?.hasAttribute?.("download") || /\.(?:avif|gif|jpe?g|png|webp)(?:$|[?#])/iu.test(linkedUrl))) {
+ candidates.push({ url: linkedUrl, sourceKind: "site-original", declaredWidth: 0, density: 0 });
+ }
+ candidates.push(...pictureCandidates, ...imageCandidates);
+ for (const attribute of ["data-lazy-src", "data-src"]) {
+ const deferredUrl = safeHttpUrl(image.getAttribute?.(attribute));
+ if (deferredUrl) candidates.push({ url: deferredUrl, sourceKind: "deferred-src", declaredWidth: 0, density: 0 });
+ }
+ const currentUrl = safeHttpUrl(image.currentSrc);
+ if (currentUrl) candidates.push({ url: currentUrl, sourceKind: "current", declaredWidth: 0, density: 0 });
+ const sourceUrl = safeHttpUrl(image.src);
+ if (sourceUrl) candidates.push({ url: sourceUrl, sourceKind: "source", declaredWidth: 0, density: 0 });
+ const seen = new Set();
+ return candidates.filter((candidate) => candidate.url && !seen.has(candidate.url) && seen.add(candidate.url))
+ .sort((left, right) => imageVariantScore(right) - imageVariantScore(left));
+ }
+
+ function urlWidthHint(value) {
+ try {
+ const url = new URL(value);
+ for (const key of ["width", "w", "resize", "size"]) {
+ const match = String(url.searchParams.get(key) || "").match(/\d{2,6}/u);
+ const width = Number(match?.[0]);
+ if (Number.isSafeInteger(width) && width > 0) return width;
+ }
+ } catch {
+ }
+ return 0;
+ }
+
+ function visibleImagePixels(image) {
+ try {
+ if (!image.complete || !image.naturalWidth || !image.naturalHeight) return "";
+ const rect = image.getBoundingClientRect();
+ if (rect.width < 48 || rect.height < 48 || rect.bottom < 0 || rect.top > (Number(window.innerHeight) || 720)) return "";
+ const pixelBudget = Math.max(1, Math.floor(maxInlinePixelDataCharacters * 0.72 / 4));
+ const requestedScale = Math.max(1, Number(window.devicePixelRatio) || 1);
+ const scale = Math.min(requestedScale, Math.sqrt(pixelBudget / Math.max(1, rect.width * rect.height)));
+ const width = Math.max(1, Math.round(rect.width * scale));
+ const height = Math.max(1, Math.round(rect.height * scale));
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ canvas.getContext("2d", { alpha: false })?.drawImage(image, 0, 0, width, height);
+ const dataUrl = canvas.toDataURL("image/webp", 0.92);
+ return dataUrl.length <= maxInlinePixelDataCharacters ? dataUrl : "";
+ } catch {
+ return "";
+ }
+ }
+
+ function imageVariantScore(value) {
+ const sourcePriority = {
+ "site-original": 600,
+ "picture-srcset": 500,
+ structured: 550,
+ "deferred-srcset": 450,
+ "deferred-src": 400,
+ "img-srcset": 350,
+ current: 200,
+ source: 100
+ }[value?.sourceKind] || 0;
+ return sourcePriority + Math.min(100000, Number(value?.declaredWidth || 0)) + Math.min(100, Number(value?.density || 0) * 10);
+ }
+
+ function isSupportedVideoFrame(element) {
+ const url = safeHttpUrl(element.src);
+ if (!url) return false;
+ try {
+ const host = new URL(url).hostname.toLocaleLowerCase("en-US");
+ return ["youtube.com", "youtube-nocookie.com", "youtu.be", "player.vimeo.com", "player.bilibili.com", "douyin.com", "open.douyin.com", "platform.twitter.com"].some((suffix) => host === suffix || host.endsWith(`.${suffix}`));
+ } catch {
+ return false;
+ }
+ }
+
+ function mergeCollectedMedia(values, limit) {
+ const seenIds = new Set();
+ const seenUrls = new Set();
+ return values.flatMap((item, index) => {
+ if (!item || typeof item !== "object") return [];
+ const variants = (Array.isArray(item.variants) ? item.variants : []).filter((variant) => safeHttpUrl(variant?.url));
+ const primaryUrl = safeHttpUrl(item.url) || variants[0]?.url || "";
+ const itemKind = ["video", "document"].includes(item.kind) ? item.kind : "image";
+ const id = cleanText(item.id) || `${itemKind}:${index}:${hashText(primaryUrl || item.dataUrl)}`;
+ if (seenIds.has(id) || primaryUrl && seenUrls.has(primaryUrl)) return [];
+ seenIds.add(id);
+ if (primaryUrl) seenUrls.add(primaryUrl);
+ return [{ ...item, id, kind: itemKind, url: primaryUrl, variants }];
+ }).slice(0, limit);
+ }
+
+ function parseSrcset(value) {
+ const input = String(value || "");
+ const candidates = [];
+ let position = 0;
+ while (position < input.length) {
+ while (position < input.length && (input[position] === "," || /\s/.test(input[position]))) position += 1;
+ if (position >= input.length) break;
+ const urlStart = position;
+ while (position < input.length && !/\s/.test(input[position])) position += 1;
+ let url = input.slice(urlStart, position);
+ const descriptors = [];
+ if (url.endsWith(",")) {
+ url = url.replace(/,+$/, "");
+ } else {
+ while (position < input.length) {
+ while (position < input.length && /\s/.test(input[position])) position += 1;
+ if (input[position] === ",") {
+ position += 1;
+ break;
+ }
+ const descriptorStart = position;
+ while (position < input.length && input[position] !== "," && !/\s/.test(input[position])) position += 1;
+ if (position > descriptorStart) descriptors.push(input.slice(descriptorStart, position));
+ }
+ }
+ const widthDescriptor = descriptors.find((item) => /^\d+w$/.test(item));
+ const densityDescriptor = descriptors.find((item) => /^(?:\d+|\d*\.\d+)x$/.test(item));
+ candidates.push({
+ url,
+ declaredWidth: widthDescriptor ? Number.parseInt(widthDescriptor, 10) : 0,
+ density: densityDescriptor ? Number.parseFloat(densityDescriptor) : descriptors.length ? 0 : 1
+ });
+ }
+ return candidates;
}
function isExcludedMedia(element) {
if (element.closest("nav,aside,header,[role=banner],[aria-label*=广告],[aria-label*=advertisement]")) return true;
const rect = element.getBoundingClientRect();
- if (rect.width > 0 && rect.height > 0 && (rect.width < 48 || rect.height < 48)) return true;
- const description = `${element.alt || ""} ${element.className || ""}`.toLowerCase();
- return /avatar|emoji|icon|logo|badge|advert/.test(description);
+ if (rect.width <= 0 || rect.height <= 0 || rect.width < 48 || rect.height < 48) return true;
+ const style = typeof globalThis.getComputedStyle === "function" ? globalThis.getComputedStyle(element) : null;
+ if (style?.display === "none" || style?.visibility === "hidden" || Number(style?.opacity) === 0) return true;
+ const description = `${element.alt || ""} ${element.className || ""} ${element.id || ""} ${element.getAttribute?.("aria-label") || ""}`.toLowerCase();
+ return /avatar|emoji|icon|logo|badge|advert|qr[-_ ]?code|二维码/.test(description);
}
function isContentRoot(root) {
@@ -426,7 +1836,9 @@ export async function collectPageCaptureSnapshot(options = {}) {
function safeHttpUrl(value) {
try {
- const url = new URL(String(value || ""), document.baseURI);
+ const input = String(value || "").trim();
+ if (!input) return "";
+ const url = new URL(input, document.baseURI);
return ["http:", "https:"].includes(url.protocol) ? url.href : "";
} catch {
return "";
@@ -437,6 +1849,16 @@ export async function collectPageCaptureSnapshot(options = {}) {
return String(value ?? "").replace(/\s+/g, " ").trim();
}
+ function cleanBlockText(value) {
+ return String(value ?? "")
+ .replace(/\r\n?/g, "\n")
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, " ")
+ .replace(/[\t ]+/g, " ")
+ .replace(/ *\n */g, "\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+ }
+
function hashText(value) {
let hash = 2166136261;
for (const character of String(value)) hash = Math.imul(hash ^ character.charCodeAt(0), 16777619);
@@ -453,7 +1875,7 @@ function uniqueCandidates(values) {
const seen = new Set();
return (Array.isArray(values) ? values : []).flatMap((value) => {
const candidate = normalizePageCaptureCandidate(value);
- const key = candidate ? `${candidate.canonicalUrl}\n${candidate.sourceFacts.itemId}\n${candidate.title}` : "";
+ const key = candidate ? `${candidate.canonicalUrl}\n${candidate.sourceFacts.itemId}\n${candidate.title}\n${candidate.region?.id || ""}` : "";
if (!candidate || seen.has(key)) return [];
seen.add(key);
return [candidate];
@@ -461,27 +1883,144 @@ function uniqueCandidates(values) {
}
function uniqueMedia(values) {
- const seen = new Set();
- return (Array.isArray(values) ? values : []).flatMap((value) => {
- const url = safeUrl(value?.url);
+ const items = [];
+ const indexById = new Map();
+ const indexByIdentity = new Map();
+ for (const value of Array.isArray(values) ? values : []) {
+ const variants = normalizeMediaVariants(value);
+ const url = variants[0]?.url || safeUrl(value?.url);
const posterUrl = safeUrl(value?.posterUrl);
const dataUrl = safeImageDataUrl(value?.dataUrl);
- const key = url || posterUrl || clean(value?.id) || dataUrl;
- const kind = value?.kind === "video" ? "video" : "image";
- if (!key || seen.has(key)) return [];
- seen.add(key);
- return [{
- id: clean(value.id) || stableCandidateId(key, kind),
+ const previewDataUrl = safeImageDataUrl(value?.previewDataUrl);
+ const id = clean(value?.id) || stableCandidateId(url || posterUrl || dataUrl || previewDataUrl, value?.kind);
+ const keyUrl = url || posterUrl;
+ const kind = ["video", "document"].includes(value?.kind) ? value.kind : "image";
+ if (!keyUrl && !dataUrl && !previewDataUrl) continue;
+ const item = {
+ id,
kind,
+ placement: value?.placement === "inline" ? "inline" : "unplaced",
url,
posterUrl,
...(dataUrl ? { dataUrl } : {}),
+ ...(previewDataUrl ? { previewDataUrl } : {}),
+ ...(normalizeFallbackRect(value?.fallbackRect) ? { fallbackRect: normalizeFallbackRect(value.fallbackRect) } : {}),
+ variants,
alt: clean(value.alt),
- width: positiveInteger(value.width, 0),
- height: positiveInteger(value.height, 0),
- captureMethod: ["source", "css-background", "pixel-fallback"].includes(value.captureMethod) ? value.captureMethod : "source"
+ filename: clean(value.filename),
+ mimeType: clean(value.mimeType).toLocaleLowerCase("en-US"),
+ sourceTitle: clean(value.sourceTitle),
+ sourceAuthor: clean(value.sourceAuthor),
+ originalWorkUrl: safeUrl(value.originalWorkUrl),
+ width: positiveInteger(variants[0]?.width || value.width, 0),
+ height: positiveInteger(variants[0]?.height || value.height, 0),
+ sourceKind: variants[0]?.sourceKind || normalizeMediaSourceKind(value.sourceKind),
+ declaredWidth: positiveInteger(variants[0]?.declaredWidth || value.declaredWidth, 0),
+ density: positiveNumber(variants[0]?.density || value.density, 0),
+ captureMethod: ["source", "css-background", "page-session", "pixel-fallback"].includes(value.captureMethod) ? value.captureMethod : "source"
+ };
+ const identity = kind === "image" ? pageCaptureMediaIdentity(url) : keyUrl;
+ const existingIndex = indexById.get(id) ?? (identity ? indexByIdentity.get(identity) : undefined);
+ if (existingIndex !== undefined) {
+ const existing = items[existingIndex];
+ const mergedVariants = normalizeMediaVariants({ variants: [...existing.variants, ...item.variants] });
+ items[existingIndex] = {
+ ...existing,
+ url: mergedVariants[0]?.url || existing.url,
+ variants: mergedVariants,
+ width: positiveInteger(mergedVariants[0]?.width || existing.width || item.width, 0),
+ height: positiveInteger(mergedVariants[0]?.height || existing.height || item.height, 0),
+ sourceKind: mergedVariants[0]?.sourceKind || existing.sourceKind,
+ declaredWidth: positiveInteger(mergedVariants[0]?.declaredWidth || existing.declaredWidth || item.declaredWidth, 0),
+ density: positiveNumber(mergedVariants[0]?.density || existing.density || item.density, 0),
+ dataUrl: existing.dataUrl || item.dataUrl,
+ previewDataUrl: existing.previewDataUrl || item.previewDataUrl,
+ fallbackRect: existing.fallbackRect || item.fallbackRect,
+ alt: existing.alt || item.alt,
+ placement: existing.placement === "inline" || item.placement === "inline" ? "inline" : "unplaced"
+ };
+ indexById.set(id, existingIndex);
+ continue;
+ }
+ const index = items.push(item) - 1;
+ indexById.set(id, index);
+ if (identity) indexByIdentity.set(identity, index);
+ }
+ return items;
+}
+
+function pageCaptureMediaIdentity(value) {
+ try {
+ const url = new URL(value);
+ for (const key of [...url.searchParams.keys()]) {
+ if (/^(?:w|width|h|height|q|quality|resize|size|dpr|format)$/iu.test(key)) url.searchParams.delete(key);
+ }
+ url.hash = "";
+ return url.href;
+ } catch {
+ return "";
+ }
+}
+
+function normalizeFallbackRect(value) {
+ const rect = value?.rect;
+ const numbers = [rect?.x, rect?.y, rect?.width, rect?.height, value?.viewportWidth, value?.viewportHeight].map(Number);
+ if (!numbers.every(Number.isFinite) || numbers[2] <= 0 || numbers[3] <= 0 || numbers[4] <= 0 || numbers[5] <= 0) return null;
+ return {
+ rect: { x: numbers[0], y: numbers[1], width: numbers[2], height: numbers[3] },
+ viewportWidth: numbers[4],
+ viewportHeight: numbers[5]
+ };
+}
+
+function normalizeMediaVariants(value = {}) {
+ const seen = new Set();
+ const variants = [...(Array.isArray(value.variants) ? value.variants : []), {
+ url: value.url,
+ sourceKind: value.sourceKind,
+ width: value.width,
+ height: value.height,
+ declaredWidth: value.declaredWidth,
+ density: value.density
+ }].flatMap((variant, index) => {
+ const url = safeUrl(variant?.url);
+ if (!url || seen.has(url)) return [];
+ seen.add(url);
+ return [{
+ url,
+ sourceKind: normalizeMediaSourceKind(variant?.sourceKind),
+ width: positiveInteger(variant?.width, 0),
+ height: positiveInteger(variant?.height, 0),
+ declaredWidth: positiveInteger(variant?.declaredWidth, 0),
+ density: positiveNumber(variant?.density, 0),
+ order: index
}];
});
+ return variants.sort((left, right) => mediaVariantScore(right) - mediaVariantScore(left) || left.order - right.order)
+ .map(({ order, ...variant }) => variant);
+}
+
+function normalizeMediaSourceKind(value) {
+ const sourceKind = clean(value);
+ return ["site-original", "structured", "picture-srcset", "deferred-srcset", "deferred-src", "img-srcset", "css-background", "current", "source"].includes(sourceKind)
+ ? sourceKind
+ : "source";
+}
+
+function mediaVariantScore(value) {
+ const sourcePriority = {
+ "site-original": 600000,
+ structured: 550000,
+ "picture-srcset": 500000,
+ "deferred-srcset": 450000,
+ "deferred-src": 400000,
+ "img-srcset": 350000,
+ "css-background": 250000,
+ current: 200000,
+ source: 100000
+ }[value?.sourceKind] || 0;
+ const width = positiveInteger(value?.width || value?.declaredWidth, 0);
+ return sourcePriority + Math.min(width, 99999) + Math.min(99, positiveNumber(value?.density, 0) * 10);
}
function safeImageDataUrl(value) {
@@ -516,6 +2055,11 @@ function positiveInteger(value, fallback = 0) {
return Number.isSafeInteger(number) && number > 0 ? number : fallback;
}
+function positiveNumber(value, fallback = 0) {
+ const number = Number(value);
+ return Number.isFinite(number) && number > 0 ? number : fallback;
+}
+
function normalizeText(value) {
return String(value ?? "").replace(/\r\n?/g, "\n").replace(/[\t ]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
}
diff --git a/page-session-media.js b/page-session-media.js
new file mode 100644
index 0000000..18a6bbf
--- /dev/null
+++ b/page-session-media.js
@@ -0,0 +1,95 @@
+export const PAGE_SESSION_MEDIA_CHUNK_BYTES = 512 * 1024;
+
+export async function preparePageSessionMedia(value = {}) {
+ const clean = (input) => String(input ?? "").trim();
+ const token = clean(value.token);
+ const maxBytes = Number(value.maxBytes);
+ const chunkBytes = Number(value.chunkBytes);
+ if (!token || token.length > 128) throw new Error("页面媒体读取令牌无效");
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || !Number.isSafeInteger(chunkBytes) || chunkBytes <= 0 || chunkBytes > maxBytes) {
+ throw new Error("页面媒体读取上限无效");
+ }
+ let url;
+ try { url = new URL(clean(value.url)); } catch { throw new Error("页面媒体地址无效"); }
+ if (url.protocol !== "https:" || url.username || url.password) throw new Error("页面媒体只允许无凭据 HTTPS 地址");
+ const allowed = new Set((Array.isArray(value.allowedUrls) ? value.allowedUrls : []).flatMap((item) => {
+ try {
+ const candidate = new URL(clean(item));
+ return candidate.protocol === "https:" && !candidate.username && !candidate.password ? [candidate.href] : [];
+ } catch {
+ return [];
+ }
+ }));
+ if (!allowed.has(url.href)) throw new Error("页面媒体地址不在本次选择范围内");
+ if (typeof globalThis.fetch !== "function") throw new Error("当前页面无法读取媒体");
+
+ const response = await globalThis.fetch(url.href, {
+ credentials: "include",
+ redirect: "error",
+ referrerPolicy: "no-referrer",
+ cache: "no-store"
+ });
+ if (!response?.ok) throw new Error(`页面媒体读取失败(HTTP ${response?.status || 0})`);
+ const declared = Number(response.headers?.get?.("content-length"));
+ if (Number.isFinite(declared) && declared > maxBytes) throw new Error(`页面媒体超过读取上限(${maxBytes} bytes)`);
+ if (!response.body?.getReader) throw new Error("页面媒体无法流式读取");
+
+ const reader = response.body.getReader();
+ const rawChunks = [];
+ let totalBytes = 0;
+ try {
+ while (true) {
+ const { done, value: part } = await reader.read();
+ if (done) break;
+ totalBytes += part.byteLength;
+ if (totalBytes > maxBytes) {
+ await reader.cancel().catch(() => undefined);
+ throw new Error(`页面媒体超过读取上限(${maxBytes} bytes)`);
+ }
+ rawChunks.push(part);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ if (!totalBytes) throw new Error("页面媒体为空");
+
+ const bytes = new Uint8Array(totalBytes);
+ let offset = 0;
+ for (const part of rawChunks) {
+ bytes.set(part, offset);
+ offset += part.byteLength;
+ }
+ const encode = (part) => {
+ let binary = "";
+ for (let start = 0; start < part.length; start += 8192) {
+ binary += String.fromCharCode(...part.subarray(start, Math.min(part.length, start + 8192)));
+ }
+ return globalThis.btoa(binary);
+ };
+ const chunks = [];
+ for (let start = 0; start < bytes.length; start += chunkBytes) chunks.push(encode(bytes.subarray(start, start + chunkBytes)));
+ const stateKey = "__PROMPTDIRECTOR_PAGE_SESSION_MEDIA__";
+ const state = globalThis[stateKey] instanceof Map ? globalThis[stateKey] : new Map();
+ if (!(globalThis[stateKey] instanceof Map)) Object.defineProperty(globalThis, stateKey, { value: state, configurable: true });
+ state.set(token, { chunks });
+ return {
+ token,
+ chunkCount: chunks.length,
+ totalBytes,
+ contentType: clean(response.headers?.get?.("content-type")).split(";", 1)[0].toLocaleLowerCase("en-US")
+ };
+}
+
+export function readPageSessionMediaChunk(value = {}) {
+ const token = String(value.token ?? "").trim();
+ const index = Number(value.index);
+ const state = globalThis.__PROMPTDIRECTOR_PAGE_SESSION_MEDIA__;
+ if (!(state instanceof Map) || !Number.isSafeInteger(index) || index < 0) return "";
+ return String(state.get(token)?.chunks?.[index] || "");
+}
+
+export function discardPageSessionMedia(value = {}) {
+ const token = String(value.token ?? "").trim();
+ const state = globalThis.__PROMPTDIRECTOR_PAGE_SESSION_MEDIA__;
+ return state instanceof Map ? state.delete(token) : false;
+}
diff --git a/resource-limits.js b/resource-limits.js
index d646ca8..e85f0a5 100644
--- a/resource-limits.js
+++ b/resource-limits.js
@@ -17,9 +17,20 @@ export const PAGE_CAPTURE_LIMITS = Object.freeze({
maxCandidates: 100,
maxMediaPerCandidate: 24,
maxScrollSteps: 30,
+ navigationTimeoutMs: 30_000,
maxInlinePixelDataCharacters: Math.ceil(PORTABLE_LIBRARY_LIMITS.maxImageBytes * 4 / 3) + 512
});
+// Product limits confirmed for the local, non-AI page-capture review flow.
+export const PAGE_CAPTURE_QUALITY_LIMITS = Object.freeze({
+ maxRegionCandidates: 5,
+ maxCandidateChoices: 10,
+ maxCreativeSections: 5,
+ maxPossibleOmissions: 5,
+ maxContentTargetsPerCandidate: 200,
+ minOrdinarySectionCharacters: 200
+});
+
export function portableLibraryLimits(value = {}) {
const result = {};
for (const [key, fallback] of Object.entries(PORTABLE_LIBRARY_LIMITS)) {
diff --git a/skill-contact-sheet.js b/skill-contact-sheet.js
index 31188bf..ff9e3fc 100644
--- a/skill-contact-sheet.js
+++ b/skill-contact-sheet.js
@@ -3,16 +3,18 @@ import { entryMediaAssets } from "./media.js";
export const CONTACT_SHEET_MAX_IMAGES = 9;
export const CONTACT_SHEET_COLUMNS = 3;
-export function selectedSkillContentImages(entriesValue = [], entryIdsValue = []) {
- const selected = new Set((Array.isArray(entryIdsValue) ? entryIdsValue : []).map(String));
+export function selectedSkillContentImages(entriesValue = [], selectionsValue = []) {
+ const selections = normalizeSelections(selectionsValue);
const result = [];
let caseNumber = 0;
for (const entry of Array.isArray(entriesValue) ? entriesValue : []) {
- if (!selected.has(String(entry?.id ?? ""))) continue;
+ const selection = selections.get(String(entry?.id ?? ""));
+ if (!selection) continue;
caseNumber += 1;
let imageNumber = 0;
for (const asset of entryMediaAssets(entry)) {
if (asset.kind !== "image" || asset.usage === "poster" || asset.storageMode === "reference") continue;
+ if (selection.assetIds && !selection.assetIds.has(String(asset.id))) continue;
imageNumber += 1;
result.push({ entryId: entry.id, visualId: asset.id, caseNumber, imageNumber });
}
@@ -20,6 +22,19 @@ export function selectedSkillContentImages(entriesValue = [], entryIdsValue = []
return result;
}
+function normalizeSelections(values) {
+ const source = Array.isArray(values) ? values : [];
+ const legacyIds = source.every((item) => typeof item === "string" || typeof item === "number");
+ if (legacyIds) return new Map(source.map((id) => [String(id), { assetIds: null }]));
+ return new Map(source.flatMap((selection) => {
+ const entryId = String(selection?.entryId ?? "");
+ if (!entryId) return [];
+ return [[entryId, {
+ assetIds: new Set((Array.isArray(selection?.assetIds) ? selection.assetIds : []).map(String))
+ }]];
+ }));
+}
+
export function contactSheetPlan(imagesValue = []) {
const images = Array.isArray(imagesValue) ? imagesValue : [];
if (images.length <= 1) return images.length ? [{ kind: "single", items: images }] : [];
diff --git a/skill-source-picker.js b/skill-source-picker.js
new file mode 100644
index 0000000..b65d619
--- /dev/null
+++ b/skill-source-picker.js
@@ -0,0 +1,50 @@
+import { entryMediaAssets } from "./media.js";
+
+// Keep source browsing consistent with the case library's established page size.
+export const SKILL_SOURCE_BATCH_SIZE = 24;
+
+export function availableSkillSourceAssets(entry = {}) {
+ return entryMediaAssets(entry).filter((asset) => asset.usage !== "poster");
+}
+
+export function filterSkillSourceEntries(entries = [], options = {}) {
+ const projectEntryIds = options.projectEntryIds instanceof Set ? options.projectEntryIds : null;
+ const query = String(options.query ?? "").trim().toLocaleLowerCase();
+ return entries.filter((entry) => {
+ if (projectEntryIds && !projectEntryIds.has(entry.id)) return false;
+ if (!query) return true;
+ return `${entry.title ?? ""}\n${entry.text ?? ""}`.toLocaleLowerCase().includes(query);
+ });
+}
+
+export function pageSkillSourceEntries(entries = [], visibleCount = SKILL_SOURCE_BATCH_SIZE) {
+ const limit = Math.max(0, Number(visibleCount) || 0);
+ return entries.slice(0, limit);
+}
+
+export function cloneSkillSourceSelection(selection = {}) {
+ return {
+ entryId: String(selection.entryId ?? ""),
+ includeEntryText: Boolean(selection.includeEntryText),
+ assetIds: new Set(selection.assetIds ?? [])
+ };
+}
+
+export function skillSourceSelectionSummary(entries = [], selections = new Map()) {
+ const entryById = new Map(entries.map((entry) => [entry.id, entry]));
+ const summary = { cases: 0, images: 0, videos: 0, documents: 0, texts: 0 };
+ for (const selection of selections.values()) {
+ const entry = entryById.get(selection.entryId);
+ if (!entry) continue;
+ summary.cases += 1;
+ if (selection.includeEntryText) summary.texts += 1;
+ const selectedIds = selection.assetIds instanceof Set ? selection.assetIds : new Set(selection.assetIds ?? []);
+ for (const asset of availableSkillSourceAssets(entry)) {
+ if (!selectedIds.has(asset.id)) continue;
+ if (asset.kind === "image") summary.images += 1;
+ else if (asset.kind === "video") summary.videos += 1;
+ else if (asset.kind === "document") summary.documents += 1;
+ }
+ }
+ return summary;
+}
diff --git a/skills-page.css b/skills-page.css
index 6f33ddd..ce77cdb 100644
--- a/skills-page.css
+++ b/skills-page.css
@@ -14,46 +14,74 @@
.skills-brand img { width: 34px; height: 34px; border-radius: 7px; }
.skills-brand span { display: grid; min-width: 0; }
.skills-brand small { font-size: 10px; color: var(--muted, #697069); }
+.skills-brand strong { color: var(--ink); }
.skills-search input { width: 100%; }
.skills-top-actions, .skill-step-actions, .skill-import-dialog > div { display: flex; align-items: center; justify-content: flex-end; gap: 8px; }
.skills-top-actions > button, .skill-detail-actions button { min-height: 36px; }
.skills-main { max-width: 1520px; margin: 0 auto; padding: clamp(20px, 3vw, 44px); }
+body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skills-heading { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 22px; }
-.skills-heading h1, .skill-workspace-header h1 { margin: 3px 0 0; font-size: clamp(24px, 3vw, 38px); letter-spacing: 0; }
-.skills-heading > p { color: var(--muted, #697069); }
+.skills-heading > div:first-child { display: grid; gap: 5px; }
+.skills-heading h1, .skill-workspace-header h1 { margin: 3px 0 0; color: var(--ink); font-size: clamp(24px, 3vw, 38px); letter-spacing: 0; }
+.skills-heading p { margin: 0; color: var(--muted, #697069); }
+.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: 164px; display: flex; flex-direction: column; align-items: stretch; padding: 18px; text-align: left; border: 1px solid var(--skill-line); border-radius: 10px; background: var(--skill-panel); color: var(--ink); box-shadow: none; }
+.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 header { display: flex; justify-content: space-between; gap: 12px; }
-.skill-card h2 { margin: 0; font-size: 19px; letter-spacing: 0; overflow-wrap: anywhere; }
+.skill-card h2 { margin: 0; font-size: 17px; letter-spacing: 0; overflow-wrap: anywhere; }
.skill-card code { color: var(--accent, #39784d); font-size: 12px; }
-.skill-card p { display: -webkit-box; flex: 1; overflow: hidden; margin: 12px 0; color: var(--muted, #697069); line-height: 1.55; -webkit-box-orient: vertical; -webkit-line-clamp: 3; }
+.skill-card p { display: -webkit-box; flex: 1; overflow: hidden; margin: 10px 0; color: var(--muted, #697069); font-size: 12px; line-height: 1.55; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
.skill-card footer { display: flex; justify-content: space-between; color: var(--muted, #697069); font-size: 12px; }
.skill-empty { max-width: 520px; margin: 12vh auto; text-align: center; }
.skill-empty strong { font-size: 24px; }
.skill-empty p { color: var(--muted, #697069); }
.skill-feedback { min-height: 20px; color: var(--muted, #697069); }
.skill-feedback.error { color: var(--danger, #b43a3a); }
-.skill-workspace-header { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 14px; margin-bottom: 22px; }
-.skill-builder { display: grid; grid-template-columns: 250px minmax(0, 1fr); gap: 12px; }
+.skill-workspace-header { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 14px; margin-bottom: 14px; }
+.skill-workspace-header h1 { font-size: clamp(25px, 2.4vw, 32px); }
+.skill-builder { display: grid; grid-template-columns: 240px minmax(0, 1fr); gap: 12px; }
.skill-builder[data-mode="editor"] { grid-template-columns: minmax(0, 1fr); }
-.skill-source-sidebar { position: sticky; top: 86px; align-self: start; display: grid; gap: 14px; padding: 16px; border: 1px solid var(--skill-line); border-radius: 6px; background: var(--skill-panel); }
+.skill-source-sidebar { position: sticky; top: 78px; align-self: start; display: grid; gap: 13px; padding: 14px; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); background: var(--skill-panel); }
.skill-source-sidebar label, .skill-draft-step label { display: grid; gap: 7px; }
.skill-source-sidebar label > span, .skill-draft-step label > span { font-size: 12px; color: var(--muted, #697069); }
-.skill-source-sidebar > p { margin: 0; color: var(--muted, #697069); font-size: 12px; line-height: 1.5; }
+.skill-field-label { display: block; margin-bottom: 7px; color: var(--muted); font-size: 12px; }
+.skill-project-picker { position: relative; }
+.skill-project-picker > summary { min-height: var(--ui-control-height); display: flex; align-items: center; justify-content: space-between; gap: 8px; border: 1px solid var(--skill-line); border-radius: var(--ui-control-radius); padding: 7px 10px; color: var(--ink); background: var(--input); cursor: pointer; font-size: 12px; list-style: none; }
+.skill-project-picker > summary::-webkit-details-marker { display: none; }
+.skill-project-picker > summary .ui-icon { width: 14px; height: 14px; color: var(--muted); transition: transform 140ms ease; }
+.skill-project-picker[open] > summary .ui-icon { transform: rotate(180deg); }
+.skill-project-filter { position: absolute; z-index: 12; top: calc(100% + 5px); right: 0; left: 0; display: grid; gap: 2px; max-height: 240px; overflow: auto; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); padding: 5px; background: var(--raised); box-shadow: var(--shadow); }
+.skill-project-filter button { width: 100%; min-height: 32px; justify-content: flex-start; border-color: transparent; padding: 6px 8px; color: var(--muted); background: transparent; text-align: left; }
+.skill-project-filter button[aria-selected="true"] { color: var(--ink); border-color: var(--selection-edge); background: var(--selection); box-shadow: inset 2px 0 var(--accent); }
+#skill-clear-selection { width: 100%; }
.skill-builder-content { display: grid; gap: 12px; min-width: 0; }
-.skill-step { padding: clamp(14px, 2vw, 24px); border: 1px solid var(--skill-line); border-radius: 6px; background: var(--skill-panel); }
+.skill-step { padding: clamp(14px, 1.6vw, 20px); border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); background: var(--skill-panel); }
.skill-section-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
.skill-section-heading > div { display: flex; align-items: baseline; gap: 10px; }
+.skill-section-heading strong { color: var(--ink); }
.skill-section-heading small, .skill-section-heading > span { color: var(--muted, #697069); font-size: 11px; }
.skill-visible-select { min-height: 30px; padding: 5px 9px; font-size: 11px; }
-.skill-case-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 3px; max-height: 560px; overflow: auto; }
-.skill-case { position: relative; aspect-ratio: 4 / 3; overflow: hidden; border: 1px solid transparent; border-radius: 2px; padding: 0; background: #171817; color: #fff; }
-.skill-case img { width: 100%; height: 100%; object-fit: cover; display: block; }
-.skill-case span { position: absolute; inset: auto 0 0; padding: 24px 8px 7px; background: linear-gradient(transparent, rgba(0,0,0,.78)); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px; }
-.skill-case::after { content: ""; position: absolute; inset: 5px; border: 2px solid transparent; border-radius: 2px; pointer-events: none; }
-.skill-case[data-selected="true"]::after { border-color: var(--accent, #56a86c); }
-.skill-case[data-selected="true"]::before { content: "✓"; position: absolute; z-index: 1; top: 8px; right: 8px; width: 24px; height: 24px; display: grid; place-items: center; border-radius: 50%; background: var(--accent, #39784d); }
+.skill-selection-summary { display: flex; flex-wrap: wrap; align-items: center; gap: 5px 12px; min-height: 34px; margin: -4px 0 10px; border-bottom: 1px solid var(--skill-line); padding: 0 0 10px; color: var(--muted); font-size: 11px; }
+.skill-selection-summary strong { color: var(--ink); font-size: 12px; }
+.skill-selection-summary small { margin-left: auto; color: var(--muted); }
+.skill-case-scroll { max-height: 540px; overflow: auto; overscroll-behavior: contain; scrollbar-gutter: stable; }
+.skill-case-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); align-content: start; gap: 8px; }
+.skill-case { position: relative; min-width: 0; overflow: hidden; border: 1px solid var(--skill-line); border-radius: var(--visual-card-radius); background: var(--card); color: var(--ink); }
+.skill-case:hover { border-color: var(--selection-edge); box-shadow: 0 8px 20px color-mix(in srgb, var(--ink) 8%, transparent); }
+.skill-case[data-selected="true"] { border-color: var(--selection-indicator); box-shadow: inset 0 0 0 1px var(--selection-indicator); }
+.skill-case-toggle { width: 100%; min-height: 0; display: grid; grid-template-rows: auto 52px; overflow: hidden; border: 0; border-radius: 0; padding: 0; color: inherit; background: transparent; text-align: left; }
+.skill-case-visual { position: relative; display: grid; aspect-ratio: 4 / 3; place-items: center; overflow: hidden; color: var(--empty-ink); background: var(--viewer-bg); font-size: 12px; }
+.skill-case-visual img { width: 100%; height: 100%; object-fit: cover; display: block; }
+.skill-case-copy { min-width: 0; display: grid; align-content: center; gap: 3px; padding: 7px 76px 7px 9px; background: var(--card); }
+.skill-case-copy strong, .skill-case-copy small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.skill-case-copy strong { font-size: 12px; line-height: 1.25; }
+.skill-case-copy small { color: var(--muted); font-size: 10px; font-weight: 500; }
+.skill-case-state { position: absolute; z-index: 2; top: 9px; right: 9px; width: 24px; height: 24px; display: grid; place-items: center; border: 1px solid color-mix(in srgb, var(--accent) 75%, white); border-radius: 50%; color: var(--accent-contrast); background: var(--accent); font-size: 12px; font-weight: 850; line-height: 1; pointer-events: none; }
+.skill-case[data-selected="true"] .skill-case-state { background: var(--accent); }
+.skill-case-state[hidden] { display: none; }
+.skill-case-detail { position: absolute; z-index: 3; right: 7px; bottom: 10px; min-height: 26px; max-width: 70px; overflow: hidden; border-color: var(--skill-line); padding: 4px 7px; color: var(--muted); background: var(--raised); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
+.skill-case-load-more { display: flex; margin: 12px auto 2px; }
.skill-evidence-note { margin: 0 0 10px; color: var(--muted, #697069); font-size: 11px; line-height: 1.5; }
.skill-run-evidence-list { display: grid; gap: 6px; }
.skill-run-evidence { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 9px; align-items: start; border: 1px solid var(--skill-line); border-radius: 4px; padding: 10px; cursor: pointer; }
@@ -61,16 +89,46 @@
.skill-run-evidence strong { font-size: 12px; }
.skill-run-evidence small { color: var(--muted, #697069); font-size: 11px; line-height: 1.45; }
.skill-target-step textarea { width: 100%; resize: vertical; }
-.skill-mode-row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; margin: 12px 0; }
-.skill-mode { display: flex; gap: 10px; padding: 12px; border: 1px solid var(--skill-line); border-radius: 5px; cursor: pointer; }
-.skill-mode span { display: grid; gap: 3px; }
-.skill-mode small { color: var(--muted, #697069); }
-.skill-vision-preview { margin: 12px 0; padding: 12px; border-left: 3px solid var(--accent, #39784d); background: color-mix(in srgb, var(--accent, #39784d) 7%, transparent); line-height: 1.5; }
+.skill-vision-toggle { display: flex; align-items: start; gap: 10px; margin: 10px 0; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); padding: 10px 12px; background: var(--subtle-card); cursor: pointer; }
+.skill-vision-toggle input { width: auto; min-height: 0; margin-top: 2px; accent-color: var(--accent); }
+.skill-vision-toggle span { display: grid; gap: 2px; }
+.skill-vision-toggle small { color: var(--muted); font-size: 11px; }
+.skill-vision-preview { margin: 10px 0; border: 1px solid var(--selection-edge); border-radius: var(--ui-container-radius); padding: 10px 12px; background: var(--raised); color: var(--muted); font-size: 11px; line-height: 1.5; }
+.skill-advanced { margin: 10px 0 14px; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); background: var(--subtle-card); }
+.skill-advanced > summary { min-height: 36px; display: flex; align-items: center; padding: 7px 11px; cursor: pointer; font-size: 12px; font-weight: 750; }
+.skill-advanced-body { display: grid; gap: 12px; border-top: 1px solid var(--skill-line); padding: 12px; }
+.skill-runtime-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
+.skill-option-menu details { position: relative; }
+.skill-option-menu summary { min-height: var(--ui-control-height); display: flex; align-items: center; justify-content: space-between; border: 1px solid var(--skill-line); border-radius: var(--ui-control-radius); padding: 7px 10px; background: var(--input); cursor: pointer; font-size: 12px; list-style: none; }
+.skill-option-menu summary::-webkit-details-marker { display: none; }
+.skill-option-menu summary::after { content: "⌄"; color: var(--muted); }
+.skill-option-panel { position: absolute; z-index: 10; top: calc(100% + 5px); right: 0; left: 0; display: grid; gap: 3px; max-height: 220px; overflow: auto; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); padding: 5px; background: var(--raised); box-shadow: var(--shadow); }
+.skill-option-panel button { width: 100%; min-height: 32px; justify-content: flex-start; border-color: transparent; padding: 6px 8px; background: transparent; text-align: left; }
+.skill-option-panel button[aria-current="true"] { color: var(--accent-ink); border-color: var(--selection-edge); background: var(--accent-soft); }
+.skill-advanced-actions { display: flex; justify-content: flex-end; }
+.skill-request-preview { border-top: 1px solid var(--skill-line); padding-top: 10px; color: var(--muted); font-size: 11px; line-height: 1.55; white-space: pre-line; }
+.skill-run-panel { display: grid; gap: 9px; margin-top: 12px; border: 1px solid var(--selection-edge); border-radius: var(--ui-container-radius); padding: 12px; background: var(--raised); }
+.skill-run-heading { display: flex; justify-content: space-between; gap: 12px; align-items: center; }
+.skill-run-heading > div { display: flex; flex-wrap: wrap; gap: 7px 12px; align-items: baseline; }
+.skill-run-heading span { color: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
+.skill-run-heading strong.error { color: var(--danger); }
+.skill-run-track { height: 3px; overflow: hidden; border-radius: 2px; background: var(--line); }
+.skill-run-track span { display: block; width: 0; height: 100%; background: var(--accent); transition: width 180ms ease; }
+.skill-run-stages { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 5px; margin: 0; padding: 0; list-style: none; }
+.skill-run-stages li { border: 1px solid var(--skill-line); border-radius: var(--ui-control-radius); padding: 6px 7px; color: var(--muted); font-size: 10px; text-align: center; }
+.skill-run-stages li[data-state="active"] { color: var(--ink); border-color: var(--selection-edge); background: var(--subtle-card); }
+.skill-run-stages li[data-state="done"] { color: var(--accent-ink); border-color: color-mix(in srgb, var(--accent) 32%, var(--line)); }
+.skill-run-log > summary { color: var(--muted); cursor: pointer; font-size: 11px; }
+.skill-run-log > div { display: grid; gap: 5px; max-height: 150px; overflow: auto; margin-top: 8px; color: var(--muted); font: 11px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }
+.skill-run-log p { margin: 0; }
.skill-name-grid { display: grid; grid-template-columns: minmax(180px, .7fr) minmax(240px, 1.3fr); gap: 10px; margin-bottom: 12px; }
.skill-call-name { display: flex; align-items: center; border: 1px solid var(--skill-line); border-radius: 4px; overflow: hidden; }
.skill-call-name b { padding-left: 10px; color: var(--accent, #39784d); }
.skill-call-name input { min-width: 0; flex: 1; border: 0; background: transparent; }
.skill-markdown-editor { width: 100%; min-height: 420px; resize: vertical; font: 13px/1.65 ui-monospace, SFMono-Regular, Menlo, monospace; }
+.skill-draft-editor { margin: 12px 0; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); }
+.skill-draft-editor > summary { min-height: 36px; display: flex; align-items: center; padding: 7px 11px; cursor: pointer; font-size: 12px; font-weight: 750; }
+.skill-draft-editor > label { border-top: 1px solid var(--skill-line); padding: 12px; }
.skill-version-list { display: grid; gap: 6px; }
.skill-version-item { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: center; padding: 10px 0; border-top: 1px solid var(--skill-line); }
.skill-version-item:first-child { border-top: 0; }
@@ -94,7 +152,7 @@
.skill-detail-more-panel button { width: 100%; min-height: 30px; justify-content: flex-start; text-align: left; font-size: 11px; }
.skill-workspace-mode { margin: 0 0 4px; color: var(--muted); font-size: 11px; }
.skill-detail-layout { display: grid; grid-template-columns: minmax(220px, 300px) minmax(0, 1fr); align-items: start; gap: 12px; }
-.skill-detail-summary, .skill-detail-markdown { border: 1px solid var(--skill-line); border-radius: 10px; background: var(--skill-panel); }
+.skill-detail-summary, .skill-detail-markdown { border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); background: var(--skill-panel); }
.skill-detail-summary { padding: 18px; }
.skill-detail-summary > p { margin: 0 0 20px; color: var(--muted, #697069); line-height: 1.6; }
.skill-detail-summary dl { display: grid; gap: 10px; margin: 0; }
@@ -105,13 +163,45 @@
.skill-detail-markdown .markdown-reader > :first-child { margin-top: 0; }
.skill-detail-markdown .markdown-reader > :last-child { margin-bottom: 0; }
+.skill-source-inspector-backdrop { position: fixed; z-index: 39; inset: 0; background: rgba(4,6,8,.52); }
+.skill-source-inspector { position: fixed; z-index: 40; top: 0; right: 0; display: grid; width: min(440px, 100vw); height: 100dvh; grid-template-rows: auto auto auto minmax(0,1fr) auto; border-left: 1px solid var(--skill-line); background: var(--card); box-shadow: -18px 0 50px rgba(0,0,0,.28); }
+.skill-source-inspector[hidden], .skill-source-inspector-backdrop[hidden] { display: none; }
+.skill-source-inspector header { display: flex; justify-content: space-between; align-items: center; gap: 12px; min-height: 64px; border-bottom: 1px solid var(--skill-line); padding: 10px 14px; }
+.skill-source-inspector header small { color: var(--muted); font-size: 11px; }
+.skill-source-inspector h2 { margin: 2px 0 0; font-size: 18px; }
+.skill-source-inspector-actions { display: flex; gap: 7px; border-bottom: 1px solid var(--skill-line); padding: 9px 14px; }
+.skill-source-inspector-actions #skill-source-clear { margin-left: auto; color: var(--danger); }
+.skill-source-text-option { display: flex; align-items: center; gap: 9px; border-bottom: 1px solid var(--skill-line); padding: 11px 14px; font-size: 12px; }
+.skill-source-text-option input { width: auto; min-height: 0; accent-color: var(--accent); }
+.skill-source-asset-list { display: grid; align-content: start; gap: 3px; overflow: auto; padding: 10px; }
+.skill-source-asset { display: grid; grid-template-columns: 76px minmax(0,1fr) auto; align-items: center; gap: 10px; min-height: 70px; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); padding: 6px; background: var(--subtle-card); }
+.skill-source-asset[data-selected="true"] { border-color: var(--selection-indicator); }
+.skill-source-asset-preview { display: grid; width: 76px; height: 56px; place-items: center; overflow: hidden; border-radius: var(--visual-card-radius); color: var(--muted); background: var(--viewer-bg); font-size: 10px; }
+.skill-source-asset-preview img { width: 100%; height: 100%; object-fit: cover; }
+.skill-source-asset-copy { display: grid; gap: 3px; min-width: 0; }
+.skill-source-asset-copy strong { font-size: 12px; }
+.skill-source-asset-copy small { overflow: hidden; color: var(--muted); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
+.skill-source-asset input { width: auto; min-height: 0; accent-color: var(--accent); }
+.skill-source-inspector-footer { display: flex; justify-content: flex-end; gap: 8px; border-top: 1px solid var(--skill-line); padding: 12px 14px; background: var(--bar); }
+
+@media (max-width: 1320px) {
+ .skill-case-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+}
+
+@media (max-width: 1000px) {
+ .skill-builder { grid-template-columns: 1fr; }
+ .skill-source-sidebar { position: static; grid-template-columns: minmax(180px, .8fr) minmax(220px, 1.2fr) auto; align-items: end; }
+ .skill-source-sidebar .skill-section-heading { grid-column: 1 / -1; }
+}
+
@media (max-width: 760px) {
.skills-topbar { grid-template-columns: 1fr auto; }
.skills-search { grid-column: 1 / -1; grid-row: 2; }
.skills-main { padding: 14px; }
.skills-heading { align-items: start; flex-direction: column; }
- .skill-builder { grid-template-columns: 1fr; }
- .skill-source-sidebar { position: static; }
+ .skills-heading-actions { width: 100%; }
+ .skills-heading-actions button { flex: 1; }
+ .skill-source-sidebar { display: grid; grid-template-columns: 1fr; }
.skill-detail-header { align-items: stretch; flex-direction: column; }
.skill-detail-actions { justify-content: stretch; }
.skill-detail-actions > button { flex: 1 1 140px; }
@@ -119,7 +209,9 @@
.skill-detail-more > summary { justify-content: center; }
.skill-detail-layout { grid-template-columns: 1fr; }
.skill-case-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
- .skill-mode-row, .skill-name-grid { grid-template-columns: 1fr; }
+ .skill-case-scroll { max-height: 520px; }
+ .skill-runtime-grid, .skill-name-grid { grid-template-columns: 1fr; }
+ .skill-run-stages { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.skill-step-actions { justify-content: stretch; flex-wrap: wrap; }
.skill-step-actions button { flex: 1 1 140px; }
}
diff --git a/skills-page.js b/skills-page.js
index 6707ece..2d1e2e4 100644
--- a/skills-page.js
+++ b/skills-page.js
@@ -1,6 +1,6 @@
-import { normalizeAiSettings } from "./deepseek.js";
+import { DEFAULT_COMPOSER_REQUEST_TIMEOUT_MS, normalizeAiSettings } from "./deepseek.js";
import { normalizeComposerSettings } from "./composer.js";
-import { composerServiceCatalog } from "./composer-service.js";
+import { requireAiRuntimeProtocolVersion } from "./ai-runtime.js";
import {
currentCreativeSkillVersion,
normalizeCreativeSkillsState
@@ -14,6 +14,8 @@ import {
import {
analyzeCreativeSkillVisualBatch,
anonymousSkillSources,
+ defaultSkillExtractionInstruction,
+ defaultSkillVisualInstruction,
creativeRunEvidenceCandidates,
selectedCreativeRunEvidenceSources,
extractCreativeSkillDraftBatched,
@@ -24,12 +26,21 @@ import {
renderContactSheetBatch,
selectedSkillContentImages
} from "./skill-contact-sheet.js";
+import {
+ SKILL_SOURCE_BATCH_SIZE,
+ availableSkillSourceAssets,
+ cloneSkillSourceSelection,
+ filterSkillSourceEntries,
+ pageSkillSourceEntries,
+ skillSourceSelectionSummary
+} from "./skill-source-picker.js";
import {
deleteMediaBlobs,
+ getDerivedMedia,
getMediaBlob,
saveSkillPackageBlob
} from "./media-store.js";
-import { primaryImageAsset } from "./media.js";
+import { entryMediaAssets, primaryImageAsset } from "./media.js";
import { renderMarkdownDocument } from "./markdown-renderer.js";
import { blobToDataUrl, normalizeVisionSettings } from "./vision.js";
import { currentLocale, initializeUi, t, translateUiMessage } from "./i18n.js";
@@ -42,14 +53,15 @@ import {
import { bindTransientMenus } from "./transient-menu.js";
await initializeUi();
-bindTransientMenus(document, ".skill-detail-more");
+bindTransientMenus(document, ".skill-detail-more, .skill-project-picker");
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-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-filter", "skill-case-search", "skill-visible-select", "skill-case-grid",
+ "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-vision-preview", "skill-generate", "skill-retry-vision", "skill-generation-status", "skill-draft-step", "skill-version-label", "skill-call-name", "skill-description", "skill-markdown", "skill-save", "skill-test", "skill-save-status", "skill-versions-step", "skill-version-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"
].map((id) => [camel(id), document.querySelector(`#${id}`)]));
@@ -61,12 +73,22 @@ let activeView = "list";
let sourcePage = "library";
let activeSkillId = "";
let selectedEntryIds = new Set();
+let sourceSelections = new Map();
let selectedEvidenceIds = new Set();
let visibleEntryIds = [];
+let selectedProjectId = "";
+let inspectedEntryId = "";
+let inspectorDraftSelection = null;
+let inspectorReturnFocus = null;
+let renderedSourceCount = SKILL_SOURCE_BATCH_SIZE;
let thumbnailUrls = new Map();
let visualSuccesses = [];
let visualFailures = [];
let pendingAfterVision = false;
+let runtimeOverrides = { text: null, vision: null };
+let skillRuntimeSettings = null;
+let activeSkillRun = null;
+let visionPreferenceTouched = false;
bindEvents();
await refreshState();
@@ -86,17 +108,33 @@ function bindEvents() {
elements.skillImportFolder.addEventListener("click", () => elements.skillFolderFiles.click());
elements.skillZipFile.addEventListener("change", () => safely(importZip)());
elements.skillFolderFiles.addEventListener("change", () => safely(importFolder)());
- elements.skillProjectFilter.addEventListener("change", renderCases);
- elements.skillCaseSearch.addEventListener("input", renderCases);
+ elements.skillCaseSearch.addEventListener("input", () => renderCases({ reset: true }));
+ elements.skillClearSelection.addEventListener("click", clearAllSourceSelections);
elements.skillVisibleSelect.addEventListener("click", toggleVisibleCases);
- document.querySelectorAll('input[name="skill-analysis-mode"]').forEach((input) => input.addEventListener("change", renderVisionPreview));
+ elements.skillCaseLoadMore.addEventListener("click", loadMoreSourceCases);
+ elements.skillGoal.addEventListener("input", renderRequestPreview);
+ elements.skillUseVision.addEventListener("change", () => { visionPreferenceTouched = true; renderVisionPreview(); renderRequestPreview(); });
+ elements.skillTextInstruction.addEventListener("input", renderRequestPreview);
+ elements.skillVisionInstruction.addEventListener("input", renderRequestPreview);
+ elements.skillRestoreInstructions.addEventListener("click", restoreDefaultInstructions);
elements.skillGenerate.addEventListener("click", () => safely(generateDraft)());
elements.skillRetryVision.addEventListener("click", () => safely(retryVisualFailures)());
+ elements.skillStopRun.addEventListener("click", stopSkillRun);
+ elements.skillSourceInspectorClose.addEventListener("click", cancelSourceInspector);
+ elements.skillSourceInspectorBackdrop.addEventListener("click", cancelSourceInspector);
+ elements.skillSourceSelectAll.addEventListener("click", selectAllInspectedSource);
+ elements.skillSourceClear.addEventListener("click", clearInspectedSource);
+ elements.skillSourceIncludeText.addEventListener("change", updateInspectedTextSelection);
+ elements.skillSourceCancel.addEventListener("click", cancelSourceInspector);
+ elements.skillSourceApply.addEventListener("click", applySourceInspector);
elements.skillSave.addEventListener("click", () => safely(saveSkill)());
elements.skillTest.addEventListener("click", () => safely(testSkill)());
elements.skillDelete.addEventListener("click", () => safely(deleteSkill)());
addEventListener("popstate", renderLocation);
- addEventListener("beforeunload", releaseThumbnails);
+ addEventListener("keydown", (event) => {
+ if (event.key === "Escape" && !elements.skillSourceInspector.hidden) cancelSourceInspector();
+ });
+ addEventListener("beforeunload", () => { activeSkillRun?.controller.abort(); releaseThumbnails(); });
}
async function refreshState() {
@@ -274,11 +312,21 @@ function renderSkillDetail() {
function renderWorkspace(view, skillId = "") {
activeSkillId = skillId;
selectedEntryIds = new Set();
+ sourceSelections = new Map();
selectedEvidenceIds = new Set();
visibleEntryIds = [];
+ selectedProjectId = "";
+ inspectedEntryId = "";
+ inspectorDraftSelection = null;
+ inspectorReturnFocus = null;
+ renderedSourceCount = SKILL_SOURCE_BATCH_SIZE;
visualSuccesses = [];
visualFailures = [];
pendingAfterVision = false;
+ runtimeOverrides = { text: null, vision: null };
+ skillRuntimeSettings = null;
+ visionPreferenceTouched = false;
+ finishSkillRun();
const skill = activeSkill();
const selectingSources = view === "create" || view === "refine";
elements.skillBuilder.dataset.mode = view;
@@ -290,10 +338,11 @@ function renderWorkspace(view, skillId = "") {
elements.skillDelete.hidden = !skill;
elements.skillGoal.value = "";
elements.skillCaseSearch.value = "";
- document.querySelector('input[name="skill-analysis-mode"][value="text"]').checked = true;
+ elements.skillUseVision.checked = false;
+ restoreDefaultInstructions();
if (selectingSources) {
renderProjectControls();
- renderCases();
+ renderCases({ reset: true });
}
renderRunEvidence(view);
if (skill) {
@@ -302,6 +351,7 @@ function renderWorkspace(view, skillId = "") {
elements.skillDescription.value = skill.description;
elements.skillMarkdown.value = version.skillMarkdown;
elements.skillDraftStep.hidden = false;
+ elements.skillDraftEditor.open = view === "editor";
elements.skillVersionsStep.hidden = false;
elements.skillVersionLabel.textContent = t("当前 v{version}", { version: versionNumber(skill, version.id) });
renderVersions(skill);
@@ -310,11 +360,13 @@ function renderWorkspace(view, skillId = "") {
elements.skillDescription.value = "";
elements.skillMarkdown.value = "";
elements.skillDraftStep.hidden = true;
+ elements.skillDraftEditor.open = false;
elements.skillVersionsStep.hidden = true;
}
setFeedback(elements.skillGenerationStatus, "");
+ setFeedback(elements.skillGenerationFeedback, "");
setFeedback(elements.skillSaveStatus, "");
- if (selectingSources) renderVisionPreview();
+ if (selectingSources) prepareSkillRuntimeControls();
}
function renderRunEvidence(view = activeView) {
@@ -341,40 +393,72 @@ function renderRunEvidence(view = activeView) {
}
function renderProjectControls() {
- const selected = elements.skillProjectFilter.value;
const options = [["", t("全部项目")], ...organizerState.collections.map((project) => [project.id, project.name])];
+ if (!options.some(([value]) => value === selectedProjectId)) selectedProjectId = "";
+ elements.skillProjectLabel.textContent = options.find(([value]) => value === selectedProjectId)?.[1] || t("全部项目");
elements.skillProjectFilter.replaceChildren(...options.map(([value, name]) => {
- const option = document.createElement("option");
- option.value = value;
- option.textContent = name;
- return option;
+ const button = textEl("button", name);
+ button.type = "button";
+ button.setAttribute("role", "option");
+ button.setAttribute("aria-selected", String(value === selectedProjectId));
+ button.addEventListener("click", () => {
+ selectedProjectId = value;
+ elements.skillProjectPicker.open = false;
+ renderProjectControls();
+ renderCases({ reset: true });
+ });
+ return button;
}));
- elements.skillProjectFilter.value = options.some(([value]) => value === selected) ? selected : "";
}
-function renderCases() {
+function renderCases(options = {}) {
releaseThumbnails();
- const projectId = elements.skillProjectFilter.value;
+ const projectId = selectedProjectId;
const members = projectId ? new Set(organizerState.collections.find((item) => item.id === projectId)?.entryIds ?? []) : null;
- const query = elements.skillCaseSearch.value.trim().toLocaleLowerCase();
- const visible = entries.filter((entry) => {
- if (members && !members.has(entry.id)) return false;
- if (!query) return true;
- return `${entry.title ?? ""}\n${entry.text ?? ""}`.toLocaleLowerCase().includes(query);
+ const visible = filterSkillSourceEntries(entries, {
+ projectEntryIds: members,
+ query: elements.skillCaseSearch.value
});
+ if (options.reset) {
+ renderedSourceCount = SKILL_SOURCE_BATCH_SIZE;
+ elements.skillCaseScroll.scrollTop = 0;
+ }
visibleEntryIds = visible.map((entry) => entry.id);
- elements.skillCaseGrid.replaceChildren(...visible.map(caseCard));
- elements.skillSelectedCount.textContent = String(selectedEntryIds.size);
+ const rendered = pageSkillSourceEntries(visible, renderedSourceCount);
+ elements.skillCaseGrid.replaceChildren(...rendered.map(caseCard));
+ elements.skillCaseLoadMore.hidden = rendered.length >= visible.length;
+ elements.skillCaseLoadMore.textContent = t("加载更多案例(已显示 {shown}/{total})", {
+ shown: rendered.length,
+ total: visible.length
+ });
+ renderSourceSelectionSummary();
renderVisibleSelectionAction();
}
+function loadMoreSourceCases() {
+ renderedSourceCount += SKILL_SOURCE_BATCH_SIZE;
+ renderCases();
+}
+
function toggleVisibleCases() {
const allSelected = visibleEntryIds.length > 0 && visibleEntryIds.every((id) => selectedEntryIds.has(id));
- for (const id of visibleEntryIds) allSelected ? selectedEntryIds.delete(id) : selectedEntryIds.add(id);
+ for (const id of visibleEntryIds) {
+ if (allSelected) removeSourceSelection(id);
+ else if (!selectedEntryIds.has(id)) selectSourceDefaults(entries.find((entry) => entry.id === id));
+ }
renderCases();
renderVisionPreview();
}
+function clearAllSourceSelections() {
+ sourceSelections.clear();
+ selectedEntryIds.clear();
+ closeSourceInspector();
+ renderCases();
+ renderVisionPreview();
+ renderRequestPreview();
+}
+
function renderVisibleSelectionAction() {
const allSelected = visibleEntryIds.length > 0 && visibleEntryIds.every((id) => selectedEntryIds.has(id));
elements.skillVisibleSelect.disabled = visibleEntryIds.length === 0;
@@ -382,29 +466,232 @@ function renderVisibleSelectionAction() {
}
function caseCard(entry) {
- const button = el("button", "skill-case");
+ const card = el("article", "skill-case");
+ card.dataset.selected = String(selectedEntryIds.has(entry.id));
+ const button = el("button", "skill-case-toggle");
button.type = "button";
- button.dataset.selected = String(selectedEntryIds.has(entry.id));
button.setAttribute("aria-pressed", String(selectedEntryIds.has(entry.id)));
button.setAttribute("aria-label", entry.title || t("未命名案例"));
+ const visual = el("span", "skill-case-visual");
const asset = primaryImageAsset(entry);
if (asset) {
const image = document.createElement("img");
image.alt = "";
image.loading = "lazy";
hydrateThumbnail(image, asset.id);
- button.append(image);
+ visual.append(image);
+ } else {
+ const kind = availableSkillAssets(entry)[0]?.kind;
+ visual.append(textEl("span", kind === "video" ? t("视频") : kind === "document" ? t("文档") : t("文字")));
}
- button.append(textEl("span", entry.title || excerpt(entry.text, 48) || t("未命名案例")));
+ const selectedState = textEl("span", "✓");
+ selectedState.className = "skill-case-state";
+ visual.append(selectedState);
+ const copy = el("span", "skill-case-copy");
+ copy.append(
+ textEl("strong", entry.title || excerpt(entry.text, 48) || t("未命名案例")),
+ textEl("small", sourceCompositionLabel(entry))
+ );
+ button.append(visual, copy);
button.addEventListener("click", () => {
- selectedEntryIds.has(entry.id) ? selectedEntryIds.delete(entry.id) : selectedEntryIds.add(entry.id);
- button.dataset.selected = String(selectedEntryIds.has(entry.id));
+ selectedEntryIds.has(entry.id) ? removeSourceSelection(entry.id) : selectSourceDefaults(entry);
+ card.dataset.selected = String(selectedEntryIds.has(entry.id));
button.setAttribute("aria-pressed", String(selectedEntryIds.has(entry.id)));
- elements.skillSelectedCount.textContent = String(selectedEntryIds.size);
+ renderCaseState(card, entry);
+ renderSourceSelectionSummary();
renderVisibleSelectionAction();
renderVisionPreview();
+ renderRequestPreview();
});
- return button;
+ card.append(button);
+ const assets = availableSkillAssets(entry);
+ if (assets.length > 1 || String(entry.text ?? "").trim()) {
+ const details = textEl("button", sourceSelectionCountLabel(entry));
+ details.type = "button";
+ details.className = "skill-case-detail";
+ details.setAttribute("aria-label", t("精确选择 {title} 的内容", { title: entry.title || t("未命名案例") }));
+ details.addEventListener("click", () => openSourceInspector(entry.id, details));
+ card.append(details);
+ }
+ renderCaseState(card, entry);
+ return card;
+}
+
+function renderCaseState(card, entry) {
+ card.dataset.selected = String(selectedEntryIds.has(entry.id));
+ const state = card.querySelector(".skill-case-state");
+ if (state) state.hidden = !selectedEntryIds.has(entry.id);
+ const detail = card.querySelector(".skill-case-detail");
+ if (detail) detail.textContent = sourceSelectionCountLabel(entry);
+}
+
+function availableSkillAssets(entry) {
+ return availableSkillSourceAssets(entry);
+}
+
+function selectSourceDefaults(entry) {
+ if (!entry) return;
+ sourceSelections.set(entry.id, defaultSourceSelection(entry));
+ selectedEntryIds.add(entry.id);
+}
+
+function defaultSourceSelection(entry) {
+ const assets = availableSkillAssets(entry);
+ const primary = assets.find((asset) => asset.id === entry.primaryMediaId) ?? assets[0];
+ return {
+ entryId: entry.id,
+ includeEntryText: Boolean(String(entry.text ?? "").trim()),
+ assetIds: primary ? new Set([primary.id]) : new Set()
+ };
+}
+
+function removeSourceSelection(entryId) {
+ sourceSelections.delete(entryId);
+ selectedEntryIds.delete(entryId);
+ if (inspectedEntryId === entryId) closeSourceInspector();
+}
+
+function sourceSelectionSnapshots() {
+ return [...sourceSelections.values()].map((selection) => ({
+ entryId: selection.entryId,
+ includeEntryText: selection.includeEntryText,
+ assetIds: [...selection.assetIds]
+ }));
+}
+
+function sourceSelectionCountLabel(entry) {
+ const selection = sourceSelections.get(entry.id);
+ const total = availableSkillAssets(entry).length + (String(entry.text ?? "").trim() ? 1 : 0);
+ if (!selection) return total > 1 ? t("{count} 项内容", { count: total }) : t("查看内容");
+ const selected = selection.assetIds.size + (selection.includeEntryText ? 1 : 0);
+ return t("已选 {selected}/{total}", { selected, total });
+}
+
+function sourceCompositionLabel(entry) {
+ const assets = availableSkillAssets(entry);
+ const images = assets.filter((asset) => asset.kind === "image").length;
+ const videos = assets.filter((asset) => asset.kind === "video").length;
+ const documents = assets.filter((asset) => asset.kind === "document").length;
+ const parts = [
+ images ? t("{count} 图", { count: images }) : "",
+ videos ? t("{count} 视频", { count: videos }) : "",
+ documents ? t("{count} 文档", { count: documents }) : "",
+ String(entry.text ?? "").trim() ? t("案例文字") : ""
+ ].filter(Boolean);
+ return parts.join(" · ") || t("无可用内容");
+}
+
+function renderSourceSelectionSummary() {
+ const summary = skillSourceSelectionSummary(entries, sourceSelections);
+ elements.skillSelectedCount.textContent = String(summary.cases);
+ elements.skillClearSelection.disabled = summary.cases === 0;
+ if (!summary.cases) {
+ elements.skillSelectionSummary.replaceChildren(
+ textEl("strong", t("尚未选择案例")),
+ textEl("span", t("选择案例后,可点击“内容”精确调整图片、视频、文档和文字。"))
+ );
+ return;
+ }
+ elements.skillSelectionSummary.replaceChildren(
+ textEl("strong", t("已选 {count} 个案例", { count: summary.cases })),
+ textEl("span", t("图片 {images} · 视频 {videos} · 文档 {documents} · 案例文字 {texts}", summary)),
+ textEl("small", t("点击内容可精确调整"))
+ );
+}
+
+function openSourceInspector(entryId, returnFocus = null) {
+ const entry = entries.find((item) => item.id === entryId);
+ if (!entry) return;
+ inspectedEntryId = entryId;
+ inspectorDraftSelection = cloneSkillSourceSelection(sourceSelections.get(entryId) ?? defaultSourceSelection(entry));
+ inspectorReturnFocus = returnFocus;
+ renderSourceInspector();
+ elements.skillSourceInspector.hidden = false;
+ elements.skillSourceInspectorBackdrop.hidden = false;
+ elements.skillSourceInspectorClose.focus();
+}
+
+function closeSourceInspector() {
+ inspectedEntryId = "";
+ inspectorDraftSelection = null;
+ elements.skillSourceInspector.hidden = true;
+ elements.skillSourceInspectorBackdrop.hidden = true;
+ inspectorReturnFocus?.focus();
+ inspectorReturnFocus = null;
+}
+
+function cancelSourceInspector() {
+ closeSourceInspector();
+}
+
+function applySourceInspector() {
+ const entry = entries.find((item) => item.id === inspectedEntryId);
+ if (!entry || !inspectorDraftSelection) return closeSourceInspector();
+ if (inspectorDraftSelection.includeEntryText || inspectorDraftSelection.assetIds.size) {
+ sourceSelections.set(entry.id, cloneSkillSourceSelection(inspectorDraftSelection));
+ selectedEntryIds.add(entry.id);
+ } else removeSourceSelection(entry.id);
+ closeSourceInspector();
+ renderCases();
+ renderVisionPreview();
+ renderRequestPreview();
+}
+
+function renderSourceInspector() {
+ const entry = entries.find((item) => item.id === inspectedEntryId);
+ const selection = inspectorDraftSelection;
+ if (!entry || !selection) return closeSourceInspector();
+ elements.skillSourceInspectorTitle.textContent = entry.title || t("未命名案例");
+ const hasText = Boolean(String(entry.text ?? "").trim());
+ elements.skillSourceTextOption.hidden = !hasText;
+ elements.skillSourceIncludeText.checked = hasText && selection.includeEntryText;
+ elements.skillSourceAssetList.replaceChildren(...availableSkillAssets(entry).map((asset, index) => sourceAssetOption(entry, asset, index)));
+}
+
+function sourceAssetOption(entry, asset, index) {
+ const selection = inspectorDraftSelection;
+ const row = el("label", "skill-source-asset");
+ row.dataset.selected = String(selection.assetIds.has(asset.id));
+ const preview = el("span", "skill-source-asset-preview");
+ if (asset.kind === "image") {
+ const image = document.createElement("img");
+ image.alt = "";
+ hydrateThumbnail(image, asset.id);
+ preview.append(image);
+ } else preview.textContent = asset.kind === "video" ? t("视频") : t("文档");
+ const copy = el("span", "skill-source-asset-copy");
+ copy.append(textEl("strong", `${asset.kind === "image" ? t("图片") : asset.kind === "video" ? t("视频") : t("文档")} ${index + 1}`), textEl("small", asset.sourceTitle || asset.mimeType || t("本地素材")));
+ const input = document.createElement("input");
+ input.type = "checkbox";
+ input.checked = selection.assetIds.has(asset.id);
+ input.addEventListener("change", () => {
+ input.checked ? selection.assetIds.add(asset.id) : selection.assetIds.delete(asset.id);
+ renderSourceInspector();
+ });
+ row.append(preview, copy, input);
+ return row;
+}
+
+function updateInspectedTextSelection() {
+ if (!inspectorDraftSelection) return;
+ inspectorDraftSelection.includeEntryText = elements.skillSourceIncludeText.checked;
+}
+
+function selectAllInspectedSource() {
+ const entry = entries.find((item) => item.id === inspectedEntryId);
+ const selection = inspectorDraftSelection;
+ if (!entry || !selection) return;
+ selection.assetIds = new Set(availableSkillAssets(entry).map((asset) => asset.id));
+ if (String(entry.text ?? "").trim()) selection.includeEntryText = true;
+ renderSourceInspector();
+}
+
+function clearInspectedSource() {
+ const selection = inspectorDraftSelection;
+ if (!selection) return;
+ selection.assetIds.clear();
+ selection.includeEntryText = false;
+ renderSourceInspector();
}
async function hydrateThumbnail(image, assetId) {
@@ -417,40 +704,127 @@ async function hydrateThumbnail(image, assetId) {
} catch {}
}
+async function prepareSkillRuntimeControls() {
+ try {
+ skillRuntimeSettings = await getPrivateSettings({ allowUnconfiguredVision: true });
+ renderRuntimeMenus(skillRuntimeSettings);
+ const images = selectedSkillContentImages(entries, sourceSelectionSnapshots());
+ if (images.length && skillRuntimeSettings.visionRuntime.available) elements.skillUseVision.checked = true;
+ renderVisionPreview();
+ renderRequestPreview();
+ } catch (error) {
+ setFeedback(elements.skillGenerationFeedback, error.message || t("无法读取 Skill 服务配置"), true);
+ }
+}
+
+function renderRuntimeMenus(settings) {
+ renderRuntimeOptionMenu(elements.skillTextProviderMenu, settings.textRuntime, "text");
+ renderRuntimeOptionMenu(elements.skillVisionProviderMenu, settings.visionRuntime, "vision");
+}
+
+function renderRuntimeOptionMenu(container, runtime, kind) {
+ const currentKey = `${runtime.assignment?.providerId || ""}:${runtime.assignment?.model || ""}`;
+ const options = runtime.availableProviders.flatMap((provider) => provider.models.map((model) => ({
+ key: `${provider.id}:${model}`,
+ providerId: provider.id,
+ model,
+ label: `${provider.label} · ${model}`
+ })));
+ const selected = options.find((option) => option.key === currentKey);
+ const details = document.createElement("details");
+ const summary = document.createElement("summary");
+ summary.textContent = selected?.label || runtime.label || t("未配置");
+ const panel = el("div", "skill-option-panel");
+ panel.append(...options.map((option) => {
+ const button = textEl("button", option.label);
+ button.type = "button";
+ button.setAttribute("aria-current", String(option.key === currentKey));
+ button.addEventListener("click", () => {
+ runtimeOverrides[kind] = { providerId: option.providerId, model: option.model };
+ details.open = false;
+ safely(prepareSkillRuntimeControls)();
+ });
+ return button;
+ }));
+ details.append(summary, panel);
+ container.replaceChildren(details);
+}
+
+function restoreDefaultInstructions() {
+ elements.skillTextInstruction.value = defaultSkillExtractionInstruction(currentLocale());
+ elements.skillVisionInstruction.value = defaultSkillVisualInstruction(currentLocale());
+ renderRequestPreview();
+}
+
function renderVisionPreview() {
- const vision = selectedAnalysisMode() === "vision";
- elements.skillVisionPreview.hidden = !vision;
- if (!vision) return;
- const images = selectedSkillContentImages(entries, [...selectedEntryIds]);
+ const images = selectedSkillContentImages(entries, sourceSelectionSnapshots());
const plan = contactSheetPlan(images);
- getPrivateSettings().then(({ vision: settings }) => {
- const service = visionServiceProfile(settings);
- elements.skillVisionPreview.textContent = service
- ? t("{service} · {images} 张内容图 · {batches} 个视觉批次 · 预计 {requests} 次付费请求。联系表仅在本轮内存中生成,不会保存。", {
- service: service.label, images: images.length, batches: plan.length, requests: plan.length
- })
- : t("尚未配置可用的视觉模型 · {images} 张内容图 · {batches} 个视觉批次。请先在资料库设置中完成视觉服务配置。", {
- images: images.length, batches: plan.length
- });
- }).catch(() => undefined);
+ const runtime = skillRuntimeSettings?.visionRuntime;
+ if (!visionPreferenceTouched && images.length && runtime?.available) elements.skillUseVision.checked = true;
+ elements.skillUseVision.disabled = images.length === 0 || !runtime?.available;
+ if (elements.skillUseVision.disabled) elements.skillUseVision.checked = false;
+ elements.skillVisionToggleNote.textContent = !images.length
+ ? t("当前没有选择可分析的图片")
+ : runtime?.available ? `${runtime.label} · ${images.length} ${t("张图片")}` : t("尚未配置可用的图片分析模型");
+ elements.skillVisionPreview.hidden = !elements.skillUseVision.checked;
+ if (!elements.skillUseVision.checked) return;
+ elements.skillVisionPreview.textContent = t("{service} · {images} 张内容图 · {batches} 个视觉批次 · 预计 {requests} 次付费请求。", {
+ service: runtime.label,
+ images: images.length,
+ batches: plan.length,
+ requests: plan.length
+ });
+}
+
+function renderRequestPreview() {
+ if (!elements.skillRequestPreview) return;
+ const snapshots = sourceSelectionSnapshots();
+ const images = selectedSkillContentImages(entries, snapshots);
+ const assetCount = snapshots.reduce((sum, item) => sum + item.assetIds.length, 0);
+ const visionCapability = skillRuntimeSettings?.visionRuntime.descriptor?.capabilities;
+ const capabilityText = !elements.skillUseVision.checked ? "" : visionCapability?.image === true
+ ? t("图片输入:已声明支持")
+ : visionCapability?.image === false ? t("图片输入:明确不支持") : t("图片输入:能力来源未知,运行前仍按任务配置校验");
+ elements.skillRequestPreview.textContent = t("发送范围:{cases} 个匿名案例 · {assets} 项素材 · {images} 张图片\n模型:{textModel}{visionModel}\n地址:{textEndpoint}{visionEndpoint}\n{capability}\n只发送明确选择的文字、已有分析和图片;标题、网址、本地编号与未选内容不会发送。", {
+ cases: snapshots.length,
+ assets: assetCount,
+ images: elements.skillUseVision.checked ? images.length : 0,
+ textModel: skillRuntimeSettings?.textRuntime.label || t("未读取"),
+ visionModel: elements.skillUseVision.checked ? ` · ${skillRuntimeSettings?.visionRuntime.label || t("未读取")}` : "",
+ textEndpoint: skillRuntimeSettings?.textRuntime.endpointOrigin || t("未读取"),
+ visionEndpoint: elements.skillUseVision.checked ? ` · ${skillRuntimeSettings?.visionRuntime.endpointOrigin || t("未读取")}` : "",
+ capability: capabilityText
+ });
}
async function generateDraft() {
const goal = elements.skillGoal.value.trim();
- if (!selectedEntryIds.size && !selectedEvidenceIds.size) throw new Error(t("请先选择至少一项案例或人工判断证据"));
+ if (!sourceSelections.size && !selectedEvidenceIds.size) throw new Error(t("请先选择至少一项案例或人工判断证据"));
if (!goal) throw new Error(t("请先说明希望提炼什么"));
elements.skillGenerate.disabled = true;
- setFeedback(elements.skillGenerationStatus, t("正在准备匿名来源资料…"));
+ setFeedback(elements.skillGenerationFeedback, "");
+ startSkillRun();
try {
- const sources = selectedSkillSources();
- const workload = skillExtractionWorkload({ goal, sources });
- const images = selectedSkillContentImages(entries, [...selectedEntryIds]);
+ updateSkillRun("prepare", t("正在准备发送内容"), 0, 1);
+ const sources = await selectedSkillSources();
+ const workload = skillExtractionWorkload({
+ goal,
+ sources,
+ locale: currentLocale(),
+ instructionOverride: elements.skillTextInstruction.value
+ });
+ const images = selectedSkillContentImages(entries, sourceSelectionSnapshots());
const visualPlan = selectedAnalysisMode() === "vision" ? contactSheetPlan(images) : [];
- const privateSettings = routedSkillSettings(await getPrivateSettings());
+ const privateSettings = await getPrivateSettings({ allowUnconfiguredVision: selectedAnalysisMode() !== "vision" });
const approved = await confirmSkillExtractionWorkload({ workload, visualPlan, settings: privateSettings });
- if (!approved) return;
+ if (!approved) {
+ finishSkillRun(t("已取消,没有发送内容"));
+ return;
+ }
+ activeSkillRun.totalUnits = Math.max(1, visualPlan.length + workload.requestCount);
+ updateSkillRun("prepare", t("发送范围已确认"), 1, 1, true);
if (selectedAnalysisMode() === "vision") {
- if (!selectedEntryIds.size) throw new Error(t("视觉分析需要至少一个带内容图的来源案例"));
+ if (!visualPlan.length) throw new Error(t("视觉分析需要至少一张已选择的内容图"));
visualSuccesses = [];
visualFailures = [];
pendingAfterVision = true;
@@ -458,6 +832,13 @@ async function generateDraft() {
if (!completed) return;
}
await generateTextDraft(privateSettings, sources);
+ } catch (error) {
+ if (error?.name === "AbortError") {
+ failSkillRun(t("已停止,本次不完整输出没有保存"), false);
+ return;
+ }
+ failSkillRun(error.message || t("提炼失败"), true);
+ throw error;
} finally {
elements.skillGenerate.disabled = false;
}
@@ -465,26 +846,12 @@ async function generateDraft() {
async function runVisualBatches(plan, options = {}) {
if (!plan.length) throw new Error(t("所选案例没有可用于视觉分析的内容图"));
- const settings = options.settings ?? routedSkillSettings(await getPrivateSettings());
- const service = visionServiceProfile(settings.vision);
- if (!service) throw new Error(t("当前没有已配置且已同意使用的视觉模型,请先在设置中完成配置"));
- const approved = options.skipConfirmation || await confirmAppAction({
- title: t("确认付费视觉分析"),
- description: t("{service}\n内容图:{images} 张\n视觉批次:{batches}\n预计请求:{requests} 次\n\n这些请求会产生额外费用。", {
- service: service.label,
- images: plan.reduce((sum, item) => sum + item.items.length, 0),
- batches: plan.length,
- requests: plan.length
- }),
- confirmLabel: t("确认并继续")
- });
- if (!approved) {
- setFeedback(elements.skillGenerationStatus, t("已取消视觉分析,没有发送图片"));
- return false;
- }
+ const settings = options.settings ?? await getPrivateSettings({ allowUnconfiguredVision: false });
+ const service = settings.visionRuntime;
+ if (!service.available) throw new Error(t("当前没有已配置且已同意使用的视觉模型,请先在设置中完成配置"));
const failures = [];
for (const [index, batch] of plan.entries()) {
- setFeedback(elements.skillGenerationStatus, t("正在分析视觉批次 {current}/{total}…", { current: index + 1, total: plan.length }));
+ updateSkillRun("vision", t("正在分析图片 {current}/{total}", { current: index + 1, total: plan.length }), index, plan.length);
try {
const rendered = await renderContactSheetBatch(batch, getMediaBlob);
const dataUrl = await blobToDataUrl(rendered.blob);
@@ -494,17 +861,26 @@ async function runVisualBatches(plan, options = {}) {
items: batch.items,
dataUrl,
mimeType: rendered.blob.type,
- aiProfile: service.profile
- }, settings);
+ aiProfile: service.profile,
+ instructionOverride: elements.skillVisionInstruction.value
+ }, settings, {
+ signal: activeSkillRun?.controller.signal,
+ timeoutMs: null,
+ onDelta: () => touchSkillRun(t("正在接收图片分析结果"))
+ });
visualSuccesses.push(result.description);
+ completeSkillRunUnit();
+ appendSkillRunLog(t("图片批次 {current}/{total} 完成 · {model}", { current: index + 1, total: plan.length, model: result.model }));
} catch (error) {
+ if (error?.name === "AbortError") throw error;
failures.push({ batch, error: error.message || t("视觉批次失败") });
+ appendSkillRunLog(t("图片批次 {current}/{total} 失败:{message}", { current: index + 1, total: plan.length, message: error.message || t("服务错误") }));
}
}
visualFailures = failures;
elements.skillRetryVision.hidden = failures.length === 0;
if (failures.length) {
- setFeedback(elements.skillGenerationStatus, t("{success} 个视觉批次成功,{failures} 个失败。可只重试失败批次,或切回文字提炼。", {
+ failSkillRun(t("{success} 个视觉批次成功,{failures} 个失败。可只重试失败批次。", {
success: visualSuccesses.length, failures: failures.length
}), true);
return false;
@@ -517,6 +893,8 @@ async function retryVisualFailures() {
elements.skillRetryVision.disabled = true;
const plan = visualFailures.map((item) => item.batch);
visualFailures = [];
+ startSkillRun();
+ activeSkillRun.totalUnits = Math.max(1, plan.length + (pendingAfterVision ? 1 : 0));
try {
const completed = await runVisualBatches(plan);
if (completed && pendingAfterVision) await generateTextDraft();
@@ -526,25 +904,32 @@ async function retryVisualFailures() {
}
async function generateTextDraft(settingsValue = null, sourcesValue = null) {
- const settings = settingsValue ?? routedSkillSettings(await getPrivateSettings());
- const sources = sourcesValue ?? selectedSkillSources();
- setFeedback(elements.skillGenerationStatus, t("正在围绕你的目标提炼可复用方法…"));
+ const settings = settingsValue ?? await getPrivateSettings({ allowUnconfiguredVision: true });
+ const sources = sourcesValue ?? await selectedSkillSources();
const result = await extractCreativeSkillDraftBatched({
goal: elements.skillGoal.value,
sources,
visualAnalyses: visualSuccesses,
locale: currentLocale(),
- aiProfile: settings.skillTextProfile
+ aiProfile: settings.skillTextProfile,
+ instructionOverride: elements.skillTextInstruction.value
}, settings, {
- onProgress: ({ phase, current, total }) => setFeedback(elements.skillGenerationStatus,
- phase === "synthesis" ? t("正在汇总全部批次…") : t("正在提炼文字批次 {current}/{total}…", { current, total }))
+ signal: activeSkillRun?.controller.signal,
+ timeoutMs: null,
+ onDelta: () => touchSkillRun(t("正在接收 Skill 草稿")),
+ onProgress: ({ phase, current, total }) => {
+ updateSkillRun("text", phase === "synthesis" ? t("正在汇总全部批次") : t("正在提炼文字 {current}/{total}", { current, total }), current - 1, total);
+ if (current > 1 || phase === "synthesis") completeSkillRunUnit();
+ }
});
+ completeSkillRunUnit();
elements.skillMarkdown.value = result.markdown;
- if (!elements.skillDescription.value.trim()) elements.skillDescription.value = elements.skillGoal.value.trim().slice(0, 240);
+ if (!elements.skillCallName.value.trim()) elements.skillCallName.value = result.callName;
+ if (!elements.skillDescription.value.trim()) elements.skillDescription.value = result.description;
elements.skillDraftStep.hidden = false;
- elements.skillDraftStep.scrollIntoView({ behavior: "smooth", block: "start" });
pendingAfterVision = false;
- setFeedback(elements.skillGenerationStatus, t("草稿已生成 · {model}", { model: result.model }));
+ finishSkillRun(t("草稿已生成 · {model}", { model: result.model }));
+ appendSkillRunLog(t("文字提炼完成 · {model}", { model: result.model }));
}
async function saveSkill() {
@@ -556,12 +941,12 @@ async function saveSkill() {
elements.skillSave.disabled = true;
try {
const evidenceSources = selectedCreativeRunEvidenceSources(creativeRuns, [...selectedEvidenceIds], activeSkillId);
- const hasSelectedEvidence = selectedEntryIds.size > 0 || evidenceSources.length > 0;
+ const hasSelectedEvidence = sourceSelections.size > 0 || evidenceSources.length > 0;
const provenanceMarkdown = hasSelectedEvidence ? buildProvenanceMarkdown({
locale: currentLocale(),
target: elements.skillGoal.value,
contributions: [
- ...anonymousSkillSources(entries, [...selectedEntryIds]).map((_source, index) =>
+ ...sourceSelectionSnapshots().map((_source, index) =>
t("匿名案例来源 {index} 参与了本次方法提炼。", { index: index + 1 })
),
...evidenceSources.map((_source, index) =>
@@ -742,33 +1127,66 @@ async function importParsedSkill(parsed, sourceName) {
}
}
-async function getPrivateSettings() {
+async function getPrivateSettings(options = {}) {
const [text, image, stored] = await Promise.all([
- chrome.runtime.sendMessage({ type: "GET_AI_TASK_RUNTIME", taskId: "skillExtraction" }),
- chrome.runtime.sendMessage({ type: "GET_AI_TASK_RUNTIME", taskId: "imageAnalysis", allowUnconfigured: true }),
+ chrome.runtime.sendMessage({ type: "GET_AI_TASK_RUNTIME", taskId: "skillExtraction", assignment: runtimeOverrides.text }),
+ chrome.runtime.sendMessage({
+ type: "GET_AI_TASK_RUNTIME",
+ taskId: "imageAnalysis",
+ allowUnconfigured: options.allowUnconfiguredVision === true,
+ assignment: runtimeOverrides.vision
+ }),
chrome.storage.local.get("composerSettings")
]);
if (!text?.ok || !image?.ok) throw new Error(text?.message || image?.message || t("无法读取 Skill 服务配置"));
+ requireAiRuntimeProtocolVersion(text.aiRuntimeProtocolVersion);
+ requireAiRuntimeProtocolVersion(image.aiRuntimeProtocolVersion);
+ const visionSettings = normalizeVisionSettings(image.visionSettings);
+ const visionProfile = {
+ serviceId: visionSettings.activeProvider === "compatible" ? "compatible" : "openai",
+ model: image.assignment?.model,
+ thinking: false
+ };
return {
ai: normalizeAiSettings(text.aiSettings),
- vision: normalizeVisionSettings(image.visionSettings),
+ vision: visionSettings,
composer: normalizeComposerSettings(stored.composerSettings),
skillTextProfile: { serviceId: "deepseek", model: text.assignment?.model },
- skillTextLabel: `${text.providerLabel || t("文字服务")} · ${text.assignment?.model || t("未选择模型")}`
+ skillTextLabel: `${text.providerLabel || t("文字服务")} · ${text.assignment?.model || t("未选择模型")}`,
+ textRuntime: runtimePresentation(text, { profile: { serviceId: "deepseek", model: text.assignment?.model } }),
+ visionRuntime: runtimePresentation(image, { profile: visionProfile })
+ };
+}
+
+function runtimePresentation(response, extras = {}) {
+ const descriptor = response.runtimeDescriptor ?? {};
+ const configured = (response.availableProviders ?? []).some((provider) => provider.id === response.assignment?.providerId && provider.models.includes(response.assignment?.model));
+ return {
+ ...extras,
+ assignment: response.assignment,
+ descriptor,
+ availableProviders: Array.isArray(response.availableProviders) ? response.availableProviders : [],
+ available: configured,
+ label: `${response.providerLabel || t("AI 服务")} · ${response.assignment?.model || t("未选择模型")}`,
+ endpointOrigin: descriptor.endpointOrigin || ""
};
}
-function selectedSkillSources() {
+async function selectedSkillSources() {
+ const selections = sourceSelectionSnapshots();
+ const documentIds = selections.flatMap((selection) => {
+ const entry = entries.find((item) => item.id === selection.entryId);
+ const selected = new Set(selection.assetIds);
+ return entryMediaAssets(entry).filter((asset) => asset.kind === "document" && selected.has(asset.id)).map((asset) => asset.id);
+ });
+ const derived = await Promise.all(documentIds.map(async (assetId) => [assetId, await getDerivedMedia(assetId).catch(() => null)]));
+ const documentTextByAsset = new Map(derived.flatMap(([assetId, value]) => value?.searchText ? [[assetId, value.searchText]] : []));
return [
- ...anonymousSkillSources(entries, [...selectedEntryIds]),
+ ...anonymousSkillSources(entries, selections, { documentTextByAsset }),
...selectedCreativeRunEvidenceSources(creativeRuns, [...selectedEvidenceIds], activeSkillId)
];
}
-function routedSkillSettings(value) {
- return value;
-}
-
async function confirmSkillExtractionWorkload({ workload, visualPlan, settings }) {
const fields = workload.overSingleRequest ? [{
id: "overflowAction", label: t("超量处理"), type: "select", value: "batch",
@@ -776,14 +1194,17 @@ async function confirmSkillExtractionWorkload({ workload, visualPlan, settings }
}] : [];
const result = await showAppDialog({
title: t("确认 Skill 提炼"),
- description: t("案例与证据:{cases} 项\n文字量:{characters} 字符 · 文字批次:{textBatches}\n图片:{images} 张 · 视觉批次:{visualBatches}\n预计请求:{requests} 次\n文字服务:{service}\n\n不会抽样或截断;视觉请求会产生额外费用。", {
+ description: t("案例与证据:{cases} 项\n文字量:{characters} 字符 · 约 {tokenMin}–{tokenMax} tokens\n文字批次:{textBatches} · 图片:{images} 张 · 视觉批次:{visualBatches}\n预计请求:{requests} 次\n文字模型:{service}\n图片模型:{visionService}\n\n不会抽样、截断、自动换模型或自动重试。", {
cases: workload.sourceCount,
characters: workload.textCharacters.toLocaleString(),
+ tokenMin: workload.tokenEstimate.min.toLocaleString(),
+ tokenMax: workload.tokenEstimate.max.toLocaleString(),
textBatches: workload.textBatchCount,
images: visualPlan.reduce((sum, batch) => sum + batch.items.length, 0),
visualBatches: visualPlan.length,
requests: workload.requestCount + visualPlan.length,
- service: settings.skillTextLabel
+ service: settings.skillTextLabel,
+ visionService: visualPlan.length ? settings.visionRuntime.label : t("不发送图片")
}),
fields,
confirmLabel: workload.overSingleRequest ? t("继续") : t("开始提炼")
@@ -796,15 +1217,131 @@ async function confirmSkillExtractionWorkload({ workload, visualPlan, settings }
return true;
}
-function visionServiceProfile(visionSettings) {
- const catalog = composerServiceCatalog({}, visionSettings).filter((item) => item.vision && item.configured);
- const active = visionSettings.activeProvider === "compatible" ? "compatible" : "openai";
- const service = catalog.find((item) => item.serviceId === active) ?? catalog[0];
- return service ? { label: service.label, profile: { serviceId: service.serviceId, model: service.model, thinking: false } } : null;
+function selectedAnalysisMode() {
+ return elements.skillUseVision.checked ? "vision" : "text";
}
-function selectedAnalysisMode() {
- return document.querySelector('input[name="skill-analysis-mode"]:checked')?.value === "vision" ? "vision" : "text";
+function startSkillRun() {
+ if (activeSkillRun?.controller && !activeSkillRun.controller.signal.aborted) activeSkillRun.controller.abort();
+ activeSkillRun = {
+ controller: new AbortController(),
+ startedAt: Date.now(),
+ completedUnits: 0,
+ totalUnits: 1,
+ elapsedTimer: null,
+ slowTimer: null,
+ stage: "prepare"
+ };
+ elements.skillRunPanel.hidden = false;
+ elements.skillStopRun.hidden = false;
+ elements.skillStopRun.disabled = false;
+ elements.skillRunLog.replaceChildren();
+ elements.skillRunProgress.style.width = "0%";
+ renderSkillRunStages("prepare");
+ activeSkillRun.elapsedTimer = setInterval(renderSkillRunElapsed, 1000);
+ renderSkillRunElapsed();
+ touchSkillRun(t("正在准备发送内容"));
+}
+
+function updateSkillRun(stage, message, current = 0, total = 1) {
+ if (!activeSkillRun) return;
+ activeSkillRun.stage = stage;
+ setFeedback(elements.skillGenerationStatus, message);
+ renderSkillRunStages(stage);
+ const detail = total > 1 ? ` ${Math.max(0, current)}/${total}` : "";
+ appendSkillRunLog(`${stageLabel(stage)}${detail} · ${message}`);
+ touchSkillRun();
+}
+
+function completeSkillRunUnit() {
+ if (!activeSkillRun) return;
+ activeSkillRun.completedUnits = Math.min(activeSkillRun.totalUnits, activeSkillRun.completedUnits + 1);
+ const percent = Math.round(activeSkillRun.completedUnits / activeSkillRun.totalUnits * 100);
+ elements.skillRunProgress.style.width = `${percent}%`;
+}
+
+function touchSkillRun(message = "") {
+ if (!activeSkillRun) return;
+ if (message) setFeedback(elements.skillGenerationStatus, message);
+ if (activeSkillRun.slowTimer !== null) clearTimeout(activeSkillRun.slowTimer);
+ activeSkillRun.slowTimer = setTimeout(() => {
+ if (!activeSkillRun) return;
+ setFeedback(elements.skillGenerationStatus, t("服务响应较慢,仍在等待;你可以继续等待或停止"));
+ appendSkillRunLog(t("服务响应较慢,未自动中止"));
+ }, DEFAULT_COMPOSER_REQUEST_TIMEOUT_MS);
+}
+
+function finishSkillRun(message = "") {
+ if (!activeSkillRun) {
+ elements.skillRunPanel.hidden = !message;
+ return;
+ }
+ clearSkillRunTimers();
+ if (!message) {
+ elements.skillRunPanel.hidden = true;
+ activeSkillRun = null;
+ return;
+ }
+ activeSkillRun.completedUnits = activeSkillRun.totalUnits;
+ elements.skillRunProgress.style.width = "100%";
+ setFeedback(elements.skillGenerationStatus, message);
+ renderSkillRunStages("complete", true);
+ elements.skillStopRun.hidden = true;
+ activeSkillRun = null;
+}
+
+function failSkillRun(message, error = true) {
+ if (activeSkillRun) clearSkillRunTimers();
+ setFeedback(elements.skillGenerationStatus, message, error);
+ elements.skillStopRun.hidden = true;
+ appendSkillRunLog(message);
+ activeSkillRun = null;
+}
+
+function stopSkillRun() {
+ if (!activeSkillRun) return;
+ elements.skillStopRun.disabled = true;
+ activeSkillRun.controller.abort();
+}
+
+function clearSkillRunTimers() {
+ if (!activeSkillRun) return;
+ if (activeSkillRun.elapsedTimer !== null) clearInterval(activeSkillRun.elapsedTimer);
+ if (activeSkillRun.slowTimer !== null) clearTimeout(activeSkillRun.slowTimer);
+}
+
+function renderSkillRunElapsed() {
+ if (!activeSkillRun) return;
+ const seconds = Math.max(0, Math.floor((Date.now() - activeSkillRun.startedAt) / 1000));
+ const minutes = Math.floor(seconds / 60);
+ elements.skillRunElapsed.textContent = minutes ? `${minutes}:${String(seconds % 60).padStart(2, "0")}` : `${seconds}s`;
+}
+
+function renderSkillRunStages(activeStage, complete = false) {
+ const stages = [
+ ["prepare", t("准备")],
+ ["vision", t("图片分析")],
+ ["text", t("文字提炼")],
+ ["complete", t("完成")]
+ ];
+ const activeIndex = stages.findIndex(([id]) => id === activeStage);
+ elements.skillRunStages.replaceChildren(...stages.map(([id, label], index) => {
+ const item = textEl("li", label);
+ item.dataset.state = complete || index < activeIndex ? "done" : index === activeIndex ? "active" : "pending";
+ return item;
+ }));
+}
+
+function appendSkillRunLog(message) {
+ if (!elements.skillRunLog || !message) return;
+ const row = textEl("p", `${new Date().toLocaleTimeString(currentLocale() === "en" ? "en" : "zh-CN", { hour12: false })} ${translateUiMessage(message)}`);
+ elements.skillRunLog.append(row);
+ while (elements.skillRunLog.children.length > 80) elements.skillRunLog.firstElementChild.remove();
+ elements.skillRunLog.scrollTop = elements.skillRunLog.scrollHeight;
+}
+
+function stageLabel(stage) {
+ return ({ prepare: t("准备"), vision: t("图片分析"), text: t("文字提炼"), complete: t("完成") })[stage] || stage;
}
function activeSkill() {
@@ -842,7 +1379,7 @@ function safely(action) {
? elements.skillDetailFeedback
: activeView === "list"
? elements.skillFeedback
- : elements.skillGenerationStatus;
+ : elements.skillGenerationFeedback;
setFeedback(target, error.message || t("操作失败"), true);
}
};
diff --git a/skills.html b/skills.html
index 7282679..2610612 100644
--- a/skills.html
+++ b/skills.html
@@ -14,8 +14,6 @@
<a class="skills-brand" href="library.html"><img src="assets/icons/icon-source.svg" alt="" /><span><small>PromptDirector</small><strong data-i18n="创作 Skill">创作 Skill</strong></span></a>
<label class="skills-search"><span class="sr-only" data-i18n="搜索 Skill">搜索 Skill</span><input id="skill-search" type="search" placeholder="搜索调用名或说明" data-i18n-placeholder="搜索调用名或说明" /></label>
<div class="skills-top-actions">
- <button id="skill-import" class="button-secondary" type="button" data-i18n="导入">导入</button>
- <button id="skill-create" type="button" data-i18n="新建 Skill">新建 Skill</button>
<button id="skill-context-back" class="button-secondary skill-context-back" 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-arrow-left"></use></svg><span>返回案例库</span></button>
</div>
<input id="skill-zip-file" class="sr-only" type="file" accept=".zip,application/zip" />
@@ -24,7 +22,7 @@
<main class="skills-main">
<section id="skill-library" class="skill-library">
- <div class="skills-heading"><h1 data-i18n="创作 Skill 中心">创作 Skill 中心</h1><p id="skill-summary"></p></div>
+ <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>
<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>
@@ -65,15 +63,16 @@
<div id="skill-builder" class="skill-builder">
<aside id="skill-source-sidebar" class="skill-source-sidebar">
<div class="skill-section-heading"><div><small>01</small><strong data-i18n="选择来源案例">选择来源案例</strong></div><span id="skill-selected-count">0</span></div>
- <label><span data-i18n="按项目筛选">按项目筛选</span><select id="skill-project-filter"><option value="" data-i18n="全部项目">全部项目</option></select></label>
+ <div><span class="skill-field-label" data-i18n="按项目筛选">按项目筛选</span><details id="skill-project-picker" class="skill-project-picker"><summary><span id="skill-project-label" data-i18n="全部项目">全部项目</span><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-chevron-down"></use></svg></summary><div id="skill-project-filter" class="skill-project-filter" role="listbox" aria-label="按项目筛选"></div></details></div>
<label><span data-i18n="搜索案例">搜索案例</span><input id="skill-case-search" type="search" placeholder="搜索提示词或标题" data-i18n-placeholder="搜索提示词或标题" /></label>
- <p data-i18n="项目只帮助选材,保存后的 Skill 不属于任何项目。">项目只帮助选材,保存后的 Skill 不属于任何项目。</p>
+ <button id="skill-clear-selection" class="button-secondary" type="button" disabled data-i18n="清空全部案例">清空全部案例</button>
</aside>
<div class="skill-builder-content">
<section id="skill-source-step" class="skill-step">
<div class="skill-section-heading"><div><small data-i18n="来源">来源</small><strong data-i18n="案例组合">案例组合</strong></div><button id="skill-visible-select" class="button-secondary skill-visible-select" type="button" data-i18n="全选当前结果">全选当前结果</button></div>
- <div id="skill-case-grid" class="skill-case-grid"></div>
+ <div id="skill-selection-summary" class="skill-selection-summary"></div>
+ <div id="skill-case-scroll" class="skill-case-scroll"><div id="skill-case-grid" class="skill-case-grid"></div><button id="skill-case-load-more" class="button-secondary skill-case-load-more" type="button" hidden data-i18n="加载更多案例">加载更多案例</button></div>
</section>
<section id="skill-run-evidence-step" class="skill-step" hidden>
@@ -84,14 +83,30 @@
<section id="skill-target-step" class="skill-step skill-target-step">
<div class="skill-section-heading"><div><small>02</small><strong data-i18n="说明提炼目标">说明提炼目标</strong></div></div>
- <textarea id="skill-goal" rows="4" placeholder="说清楚你想从这些案例中学什么,例如只提炼色彩组织、构图逻辑、角色塑造或动作设计。" data-i18n-placeholder="说清楚你想从这些案例中学什么,例如只提炼色彩组织、构图逻辑、角色塑造或动作设计。"></textarea>
- <div class="skill-mode-row">
- <label class="skill-mode"><input type="radio" name="skill-analysis-mode" value="text" checked /><span><strong data-i18n="文字提炼">文字提炼</strong><small data-i18n="使用原提示词和已有画面分析">使用原提示词和已有画面分析</small></span></label>
- <label class="skill-mode"><input type="radio" name="skill-analysis-mode" value="vision" /><span><strong data-i18n="增加视觉分析">增加视觉分析</strong><small data-i18n="发送临时联系表,会产生额外费用">发送临时联系表,会产生额外费用</small></span></label>
- </div>
+ <textarea id="skill-goal" rows="3" placeholder="例如:只提炼这些案例的人物构图与动作节奏" data-i18n-placeholder="例如:只提炼这些案例的人物构图与动作节奏"></textarea>
+ <label class="skill-vision-toggle"><input id="skill-use-vision" type="checkbox" /><span><strong data-i18n="分析所选图片">分析所选图片</strong><small id="skill-vision-toggle-note"></small></span></label>
<div id="skill-vision-preview" class="skill-vision-preview" hidden></div>
+ <details id="skill-advanced" class="skill-advanced">
+ <summary data-i18n="运行设置">运行设置</summary>
+ <div class="skill-advanced-body">
+ <div class="skill-runtime-grid">
+ <div><span class="skill-field-label" data-i18n="文字提炼模型">文字提炼模型</span><div id="skill-text-provider-menu" class="skill-option-menu"></div></div>
+ <div><span class="skill-field-label" data-i18n="图片分析模型">图片分析模型</span><div id="skill-vision-provider-menu" class="skill-option-menu"></div></div>
+ </div>
+ <label><span class="skill-field-label" data-i18n="本次提炼指令">本次提炼指令</span><textarea id="skill-text-instruction" rows="5"></textarea></label>
+ <label><span class="skill-field-label" data-i18n="本次视觉分析指令">本次视觉分析指令</span><textarea id="skill-vision-instruction" rows="4"></textarea></label>
+ <div class="skill-advanced-actions"><button id="skill-restore-instructions" class="button-secondary" type="button" data-i18n="恢复默认指令">恢复默认指令</button></div>
+ <div id="skill-request-preview" class="skill-request-preview"></div>
+ </div>
+ </details>
<div class="skill-step-actions"><button id="skill-generate" type="button" data-i18n="生成可编辑草稿">生成可编辑草稿</button><button id="skill-retry-vision" class="button-secondary" type="button" hidden data-i18n="重试失败批次">重试失败批次</button></div>
- <p id="skill-generation-status" class="skill-feedback" role="status"></p>
+ <section id="skill-run-panel" class="skill-run-panel" hidden aria-live="polite">
+ <div class="skill-run-heading"><div><strong id="skill-generation-status"></strong><span id="skill-run-elapsed"></span></div><button id="skill-stop-run" class="button-secondary" type="button" data-i18n="停止">停止</button></div>
+ <div class="skill-run-track"><span id="skill-run-progress"></span></div>
+ <ol id="skill-run-stages" class="skill-run-stages"></ol>
+ <details class="skill-run-log"><summary data-i18n="运行记录">运行记录</summary><div id="skill-run-log"></div></details>
+ </section>
+ <p id="skill-generation-feedback" class="skill-feedback" role="status"></p>
</section>
<section id="skill-draft-step" class="skill-step skill-draft-step" hidden>
@@ -100,7 +115,7 @@
<label><span data-i18n="调用名">调用名</span><div class="skill-call-name"><b>/</b><input id="skill-call-name" maxlength="80" placeholder="你的 Skill 名称" data-i18n-placeholder="你的 Skill 名称" /></div></label>
<label><span data-i18n="说明">说明</span><input id="skill-description" maxlength="240" placeholder="它在什么创作任务中发挥作用" data-i18n-placeholder="它在什么创作任务中发挥作用" /></label>
</div>
- <label><span data-i18n="SKILL.md 正文">SKILL.md 正文</span><textarea id="skill-markdown" class="skill-markdown-editor" rows="22"></textarea></label>
+ <details id="skill-draft-editor" class="skill-draft-editor"><summary data-i18n="查看并编辑 SKILL.md">查看并编辑 SKILL.md</summary><label><span data-i18n="SKILL.md 正文">SKILL.md 正文</span><textarea id="skill-markdown" class="skill-markdown-editor" rows="22"></textarea></label></details>
<div class="skill-step-actions"><button id="skill-save" type="button" data-i18n="保存 Skill">保存 Skill</button></div>
<p id="skill-save-status" class="skill-feedback" role="status"></p>
</section>
@@ -114,6 +129,15 @@
</section>
</main>
+ <div id="skill-source-inspector-backdrop" class="skill-source-inspector-backdrop" hidden></div>
+ <aside id="skill-source-inspector" class="skill-source-inspector" hidden role="dialog" aria-modal="true" aria-labelledby="skill-source-inspector-title">
+ <header><div><small data-i18n="精确选择">精确选择</small><h2 id="skill-source-inspector-title"></h2></div><button id="skill-source-inspector-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>
+ <div class="skill-source-inspector-actions"><button id="skill-source-select-all" class="button-secondary" type="button" data-i18n="全选可用内容">全选可用内容</button><button id="skill-source-clear" class="button-secondary" type="button" data-i18n="清空本案例">清空本案例</button></div>
+ <label id="skill-source-text-option" class="skill-source-text-option"><input id="skill-source-include-text" type="checkbox" /><span data-i18n="包含案例文字">包含案例文字</span></label>
+ <div id="skill-source-asset-list" class="skill-source-asset-list"></div>
+ <footer class="skill-source-inspector-footer"><button id="skill-source-cancel" class="button-secondary" type="button" data-i18n="取消">取消</button><button id="skill-source-apply" type="button" data-i18n="应用选择">应用选择</button></footer>
+ </aside>
+
<dialog id="skill-import-dialog" class="skill-import-dialog">
<header><h2 data-i18n="导入外部 Skill">导入外部 Skill</h2><button id="skill-import-close" class="icon-button" type="button" aria-label="关闭" data-i18n-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 data-i18n="完整包会随私人备份保留;PromptDirector 只读取 SKILL.md 和 Markdown references,不执行脚本、程序、MCP 或二进制文件。">完整包会随私人备份保留;PromptDirector 只读取 SKILL.md 和 Markdown references,不执行脚本、程序、MCP 或二进制文件。</p>
diff --git a/store/LISTING_EN.md b/store/LISTING_EN.md
index 504f974..5934a8a 100644
--- a/store/LISTING_EN.md
+++ b/store/LISTING_EN.md
@@ -15,14 +15,21 @@ PromptDirector is a local-first creative reference library for AI image and vide
Use it to:
- capture highlighted text with a matching visual;
+- identify responsive originals, lazy-loaded originals, and public source details on ordinary pages and common design, gallery, social, publishing, and commerce sites;
+- confirm a locally detected creative-subject region, correct its meaningful text, media, and download blocks on the page, then explicitly confirm which proposed images, GIFs, videos, and documents may be saved;
+- when explicitly started, collect a user-bounded target from the same public list through scrolling or list pagination, without opening item detail pages, and save the result as one combined case or separate cases;
- save images, videos, PDFs, Markdown, text files, HTML, time notes, and quick notes;
- search, filter, edit, and combine cases in an image-first library;
-- organize references into projects and compose editable image or video prompts from selected material;
+- browse curated cases and selectively save them into your own local library;
+- organize references into projects, extract reusable creative Skills, and create editable prompts, images, or videos in the composer;
+- generate with original images by default, or use a text-only mode that neither reads nor sends images when case prompts or valid analysis text are available;
- create full-folder backups, share selected cases, or sync your own devices with encrypted folders;
- optionally analyze text and visuals to make references easier to find.
Your cases, media, tags, and settings stay in your browser by default. PromptDirector has no account, analytics, advertising, or developer-operated data server. Optional AI features use your own API key only after you initiate them, and send only the material needed for that action.
+Confirming the subject does not confirm its media. Public URLs may be shown for review, but only media you explicitly confirm is written to a case. If a confirmed public image fails, it may be read through the current page session. PromptDirector does not read, store, or export sign-in information.
+
## Single purpose
Help visual creators capture web visuals with their prompts, media, and notes as reusable local references.
diff --git a/store/LISTING_ZH_CN.md b/store/LISTING_ZH_CN.md
index 5bc829f..6bbd03b 100644
--- a/store/LISTING_ZH_CN.md
+++ b/store/LISTING_ZH_CN.md
@@ -15,14 +15,23 @@
你可以:
- 高亮网页文字并框选或选择对应画面;
+- 从普通网页以及常见设计、图库、社交、内容与电商页面识别响应式原图、懒加载原图和公开来源信息;
+- 在本地识别创作主体,再直接在原网页修正内部正文、媒体和下载内容;正文默认纳入,图片、GIF、视频和文档必须预览并明确确认后才会保存;
+- 用户明确启动时,可按目标数量采集同一公开列表的滚动或分页结果,并选择合并为一个案例或分别保存;不会自动进入作品详情页;
- 保存图片、视频、PDF、Markdown、TXT、HTML、时间点笔记和快速笔记;
- 在图片优先的资料墙中搜索、筛选、编辑和组合案例;
-- 用项目整理资料,选择参考后生成可编辑的图片或视频提示词;
+- 浏览精选案例并选择性保存到自己的本地资料库;
+- 用项目整理资料,把案例提炼成创作 Skill,并在创作台生成可编辑提示词、图片或视频;
+- 图片创作默认带原图;有案例提示词或有效分析文字时,也可以选择不读图、不发送图片的纯文字模式;
- 备份完整资料夹、生成分享包,或在自己的设备间加密同步;
- 按需启用文字分析和画面分析,让资料更容易检索。
本地优先:资料、媒体、标签和设置默认只保存在浏览器。不创建账号、不收集使用统计、不投放广告。可选 AI 功能只在你主动开启后使用你的服务密钥,并仅发送当次操作所需内容。
+网页原图优先通过公开地址预览。确认主体不等于确认媒体;只有用户明确确认并点击保存的媒体,才会写入案例。公开地址失败时,已确认图片可通过当前网页已有会话读取;扩展不会读取、保存或导出登录信息。
+
+用户明确确认的 PDF、Markdown、SKILL.md、TXT、HTML 和 RTF 仅在真实类型与容量校验通过后保存本地副本;压缩包、程序和未知文件只保留来源链接,不会自动下载或导入。
+
## 单一用途
帮助视觉创作者将网页画面与提示词、媒体和笔记保存为可检索、可复用的本地资料。
diff --git a/store/PRIVACY_POLICY.md b/store/PRIVACY_POLICY.md
index 693161a..c9a71af 100644
--- a/store/PRIVACY_POLICY.md
+++ b/store/PRIVACY_POLICY.md
@@ -1,6 +1,6 @@
# 提示词导演隐私政策
-生效日期:2026 年 8 月 10 日
+生效日期:2026 年 8 月 16 日
提示词导演是一个本地优先的 Chrome 扩展,用于收藏、整理、检索、备份和分享个人创作资料。扩展不提供开发者服务器,不创建账号,不收集使用统计,不投放广告,也不出售用户数据。
@@ -8,7 +8,7 @@
只有在用户主动收藏、导入、导出、分析、生成或进行提示词创作时,扩展才会处理相关数据:
-- 用户高亮、保存或明确选择的网页文字、图片、视频、截图,以及对应的来源信息;
+- 用户高亮、保存、确认主体区域或明确启动同一列表批量采集时涉及的网页文字、图片、视频、GIF、文档、下载资源链接和截图,以及对应的标题、作者和来源信息;
- 用户主动创建或确认的提示词、内容类型、标签、别名、色卡、创作 Skill、项目和管理设置;
- 用户主动填写或连接的 AI 服务地址、模型、API Key、发送授权和服务能力信息;
- 用户主动导入、导出或分享的资料及其本地生成的预览文件。
@@ -17,6 +17,10 @@
- 案例文字、媒体、来源、标签、色卡、创作 Skill、设置和 API Key 默认保存在浏览器扩展的本地存储中。
- 截图裁剪、压缩、缩略图、色卡提取、资料整理和 ZIP 分享包生成在本机完成。
+- 网页采集先在当前标签页本地提出外层主体区域,并在确认后展示内部有意义的正文、媒体、下载和整组内容块。用户可以在原网页添加遗漏内容、排除错误内容、整组修正、撤销或恢复自动识别。正文在主体确认后默认纳入;正文内已定位媒体默认进入保存方案,无法确认文章位置的媒体默认不选并显示为可能遗漏媒体。底部“保存案例”按钮会显示媒体数量;“保存案例”按钮是当前媒体方案的最终授权,用户也可以选择“只保存正文”。
+- 用户明确启动同一列表批量采集后,扩展可在当前标签页滚动公开列表,并沿同一来源的列表分页链接继续采集;不会自动进入作品详情页,也不会绕过登录、验证码、付费墙、访问控制或反自动化限制。完成后会返回原列表页,并以实际识别数量和停止原因结束。
+- 预检会显示主体内识别到的公开媒体地址和预览,但不会在最终保存动作前把媒体写入案例或请求媒体域名权限。只有最终保存方案中的媒体会尝试读取原始文件;公开图片失败时,扩展才会让当前网页使用已有登录会话读取该图片。扩展不读取、导出、保存或传输 Cookie、Token 与登录请求头。
+- PDF、Markdown、SKILL.md、TXT、HTML 和 RTF 只有属于用户最终保存方案时,才会从公开 HTTPS 地址读取,并在真实文件类型和容量限制校验通过后保存本地副本;请求不携带登录凭据。读取失败时只保留原始来源链接。压缩包、程序和未知类型文件不会自动下载,也不会作为 Skill 静默导入。
- API Key 不进入导出 ZIP、Markdown、JSON、分享包、创作草稿、诊断包或日志。
- 用户主动导出或分享时,扩展在本机生成资料夹或 ZIP 分享包;离线预览只读取包内内容和固定本地脚本,不会上传数据。用户决定分享包中包含哪些资料,并应自行判断分享对象与内容。
@@ -27,6 +31,7 @@
- AI 功能默认不因安装而自动执行。发送授权是所有真实外部请求的前置条件;已保存 API Key、已选模型或单次付费确认都不能替代发送授权。
- 对新增的付费媒体分析或生成,扩展还会要求单次付费确认。该确认只授权当前操作,且与发送授权相互独立;两者不能互相替代。
- 发送时,扩展只发送完成当前任务所必需、且由用户明确选择或提交的内容。根据任务,这可能包括文字提示词、用户创作要求、本次选择的参考图片或视频、画面描述、生成参数或当前会话中用户可见的消息。
+- 图片创作默认可以使用用户选择的原图。若每项参考已有案例提示词或有效画面分析文字,用户可改为“全程只用案例/分析文字”;该模式不会读取、分析或发送图片,图片载荷为零。
- 扩展不会自动发送整库、全部案例、未选择案例、API Key,或为了失败恢复而静默改用另一家付费服务、重新发起付费请求。
- 图片和视频仅会在用户对相应任务明确选择或提交,并完成上述所需确认后,直接通过 HTTPS 发送给所选第三方 AI 服务或自定义兼容接口。开发者不会接收或中转这些内容。
- 第三方 AI 服务和自定义兼容接口对收到数据的处理,受用户与该服务商之间适用的隐私政策、服务条款和账户设置约束。用户应在启用前审阅这些规则。
@@ -39,7 +44,7 @@
## 权限用途
-- `activeTab`:仅在用户主动触发的当前标签页操作中访问页面内容。
+- `activeTab`:仅在用户主动触发的当前标签页操作中访问页面内容;用户明确启动列表批量采集时,可在同一标签页内滚动或沿列表分页继续,并在结束后返回原列表页。
- `alarms`:安排本地后台任务的延后、轮询或恢复,不用于跟踪用户。
- `contextMenus`:提供右键收藏入口。
- `downloads`:将用户请求的备份、分享包或媒体保存到本机。
diff --git a/test/ai-background-v4.test.js b/test/ai-background-v4.test.js
new file mode 100644
index 0000000..411f8ce
--- /dev/null
+++ b/test/ai-background-v4.test.js
@@ -0,0 +1,39 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const source = await readFile(new URL("../background.js", import.meta.url), "utf8");
+
+test("background accepts only the Registry v4 AI configuration message", () => {
+ assert.match(source, /case "UPDATE_AI_PROVIDER_CONFIGURATION"/);
+ for (const legacyType of [
+ "UPDATE_AI_SETTINGS",
+ "UPDATE_AI_TEXT_PROVIDER",
+ "UPDATE_VISION_SETTINGS",
+ "UPDATE_AI_VISION_PROVIDER",
+ "PROBE_VISION_MODELS"
+ ]) {
+ assert.doesNotMatch(source, new RegExp(`case "${legacyType}"`));
+ }
+});
+
+test("background AI persistence reads and writes only the three Registry v4 keys", () => {
+ const storageKeys = source.slice(source.indexOf("const STORAGE_KEYS"), source.indexOf("const SYNCED_STORAGE_KEYS"));
+ for (const legacyKey of ["aiSettings", "visionSettings", "aiServiceProfiles", "aiTaskRoutes"]) {
+ assert.doesNotMatch(storageKeys, new RegExp(`${legacyKey}:`));
+ }
+
+ const persistence = source.slice(
+ source.indexOf("async function loadAiConfiguration"),
+ source.indexOf("function aiConfigurationResponse")
+ );
+ assert.match(persistence, /STORAGE_KEYS\.aiProviderRegistry/);
+ assert.match(persistence, /STORAGE_KEYS\.aiTaskAssignments/);
+ assert.match(persistence, /STORAGE_KEYS\.aiPreferences/);
+ assert.doesNotMatch(persistence, /chrome\.storage\.local\.remove/);
+});
+
+test("background keeps service profiles for job execution but stops publishing obsolete task routes", () => {
+ assert.match(source, /aiServiceProfiles: publicAiServiceProfiles/);
+ assert.doesNotMatch(source, /aiTaskRoutes:/);
+});
diff --git a/test/ai-provider-module.test.js b/test/ai-provider-module.test.js
index 170da6f..0b9a846 100644
--- a/test/ai-provider-module.test.js
+++ b/test/ai-provider-module.test.js
@@ -1,6 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
+import { AI_MODEL_CAPABILITIES, getAiModelCapability } from "../ai-model-capabilities.js";
import { createAiProviderModule } from "../ai-provider-module.js";
import { PORTABLE_LIBRARY_LIMITS } from "../resource-limits.js";
@@ -39,6 +40,140 @@ test("DeepSeek discovery treats identity-only models as text protocol capability
assert.equal(result.cache.etag, '"models-v1"');
});
+test("Kimi discovery uses its declared catalog fields without inventing generation capabilities", async () => {
+ const calls = [];
+ const module = createAiProviderModule({ fetchImpl: async (url, options) => {
+ calls.push({ url, options });
+ return jsonResponse({ data: [
+ { id: "moonshot-text", context_length: 131072 },
+ { id: "moonshot-vision", context_length: 262144, supports_image_in: true },
+ { id: "moonshot-video", supports_image_in: true, supports_video_in: true,
+ input_modalities: ["text", "image", "video"], output_modalities: ["text", "image", "video"] }
+ ] });
+ } });
+ const result = await module.discoverModels({
+ id: "kimi",
+ endpoint: "https://api.moonshot.cn/v1/chat/completions",
+ apiKey: "secret",
+ protocol: "chat_completions"
+ });
+ assert.equal(calls[0].url, "https://api.moonshot.cn/v1/models");
+ assert.deepEqual(result.models[0].tasks, ["textTags", "skillExtraction", "creativePlanning"]);
+ assert.equal(result.models[1].contextLength, 262144);
+ assert.deepEqual(result.models[1].tasks, ["textTags", "skillExtraction", "creativePlanning", "imageAnalysis"]);
+ assert.deepEqual(result.models[2].tasks, [
+ "textTags", "skillExtraction", "creativePlanning", "imageAnalysis", "videoAnalysis"
+ ]);
+ assert.equal(result.models.some((model) => model.tasks.includes("imageGeneration") || model.tasks.includes("videoGeneration")), false);
+});
+
+test("Gemini discovery grants Nano Banana image generation only to exact official models visible in the live catalog", async () => {
+ const calls = [];
+ const module = createAiProviderModule({ fetchImpl: async (url, options) => {
+ calls.push({ url, options });
+ return jsonResponse({ models: [
+ { name: "models/gemini-3.1-flash-lite-image", supportedGenerationMethods: ["generateContent"] },
+ { name: "models/gemini-3.1-flash-image", supportedGenerationMethods: ["generateContent"] },
+ { name: "models/gemini-3-pro-image", supportedGenerationMethods: ["generateContent"] },
+ { name: "models/gemini-2.5-flash-image", supportedGenerationMethods: ["generateContent"] },
+ { name: "models/gemini-3.1-flash", supportedGenerationMethods: ["generateContent"] },
+ { name: "models/future-image-model", supportedGenerationMethods: ["generateContent"] },
+ { name: "models/gemini-3.1-flash-image-preview", supportedGenerationMethods: ["generateContent"] }
+ ] });
+ } });
+
+ const result = await module.discoverModels({
+ id: "gemini",
+ endpoint: "https://generativelanguage.googleapis.com",
+ apiKey: "gemini-secret",
+ protocol: "gemini",
+ models: { imageGeneration: "gemini-3.1-flash-image" }
+ });
+
+ assert.equal(calls[0].url, "https://generativelanguage.googleapis.com/v1beta/models");
+ assert.equal(calls[0].options.headers.Authorization, undefined);
+ assert.equal(calls[0].options.headers["x-goog-api-key"], "gemini-secret");
+ assert.deepEqual(
+ result.models.filter((model) => model.tasks.includes("imageGeneration")).map((model) => model.id),
+ ["gemini-3.1-flash-lite-image", "gemini-3.1-flash-image", "gemini-3-pro-image", "gemini-2.5-flash-image"]
+ );
+ assert.equal(result.models.find((model) => model.id === "gemini-3.1-flash").tasks.includes("imageGeneration"), false);
+ assert.equal(result.models.find((model) => model.id === "future-image-model").tasks.includes("imageGeneration"), false);
+ assert.equal(result.models.find((model) => model.id === "gemini-3.1-flash-image-preview").tasks.includes("imageGeneration"), false);
+ const configuredFlash = result.models.find((model) => model.id === "gemini-3.1-flash-image");
+ assert.deepEqual(configuredFlash.configuredTasks, ["imageGeneration"]);
+ assert.deepEqual(configuredFlash.referenceImages, {
+ supported: true, maxItems: 14, source: "declared", observedAt: ""
+ });
+ assert.deepEqual(configuredFlash.parameterDescriptors.reference_images, {
+ maxItems: 14, objectReferences: 10, characterReferences: 4
+ });
+ assert.deepEqual(configuredFlash.supportedMethods, ["generateContent"]);
+});
+
+test("Nano Banana capability metadata exposes official Interactions parameters and per-model reference limits", () => {
+ assert.deepEqual(AI_MODEL_CAPABILITIES.map((item) => item.id), [
+ "gemini-3.1-flash-lite-image",
+ "gemini-3.1-flash-image",
+ "gemini-3-pro-image",
+ "gemini-2.5-flash-image"
+ ]);
+ const flash = getAiModelCapability("gemini", "models/gemini-3.1-flash-image");
+ assert.equal(flash.protocol, "gemini_interactions");
+ assert.deepEqual(flash.supportedResolutions, ["512px", "1K", "2K", "4K"]);
+ assert.deepEqual(flash.referenceImages, {
+ supported: true, maxItems: 14, source: "declared", observedAt: ""
+ });
+ assert.deepEqual(flash.parameterDescriptors.reference_images, {
+ maxItems: 14, objectReferences: 10, characterReferences: 4
+ });
+ assert.equal(flash.source.url, "https://ai.google.dev/gemini-api/docs/image-generation");
+ assert.deepEqual(getAiModelCapability("gemini", "gemini-3.1-flash-lite-image").supportedResolutions, ["1K"]);
+ assert.deepEqual(getAiModelCapability("gemini", "gemini-3-pro-image").parameterDescriptors.reference_images, {
+ maxItems: 14, objectReferences: 6, characterReferences: 5, styleReferences: 3
+ });
+ assert.equal(getAiModelCapability("gemini", "gemini-2.5-flash-image").referenceImages.maxItems, 3);
+ assert.equal(getAiModelCapability("gemini", "gemini-3.1-flash-image-preview"), null);
+ assert.equal(getAiModelCapability("openrouter", "gemini-3.1-flash-image"), null);
+});
+
+test("a manually configured Gemini image model records the selection without acquiring official generation capability", async () => {
+ const module = createAiProviderModule({ fetchImpl: async () => jsonResponse({ models: [
+ { name: "models/account-image-model", supportedGenerationMethods: ["generateContent"] }
+ ] }) });
+ const result = await module.discoverModels({
+ id: "gemini",
+ endpoint: "https://generativelanguage.googleapis.com",
+ apiKey: "secret",
+ protocol: "gemini",
+ models: { imageGeneration: "account-image-model" }
+ });
+ const model = result.models[0];
+ assert.deepEqual(model.configuredTasks, ["imageGeneration"]);
+ assert.equal(model.tasks.includes("imageGeneration"), false);
+ assert.equal(model.referenceImages, null);
+ assert.equal(model.parameterDescriptors, null);
+});
+
+test("discovery failure stays visible and does not erase the last in-memory catalog", async () => {
+ let attempt = 0;
+ const module = createAiProviderModule({ fetchImpl: async () => {
+ attempt += 1;
+ return attempt === 1
+ ? jsonResponse({ data: [{ id: "available-model" }] })
+ : jsonResponse({ error: { message: "catalog temporarily unavailable" } }, 503);
+ } });
+ const profile = {
+ id: "deepseek",
+ endpoint: "https://api.deepseek.com/chat/completions",
+ apiKey: "secret",
+ protocol: "chat_completions"
+ };
+ await module.discoverModels(profile);
+ await assert.rejects(() => module.discoverModels(profile), /catalog temporarily unavailable/);
+ assert.equal(module.describeCapabilities("deepseek", "available-model").id, "available-model");
+});
+
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 3d32d47..d14f244 100644
--- a/test/ai-provider-registry.test.js
+++ b/test/ai-provider-registry.test.js
@@ -5,117 +5,231 @@ import {
AI_ASSIGNMENT_TASKS,
availableAiProvidersForTask,
mergeAiProviderRegistry,
- migrateLegacyAiConfiguration,
normalizeAiProviderRegistry,
+ normalizeAiTaskAssignments,
publicAiProviderRegistry,
resolveAiProviderAssignment
} from "../ai-provider-registry.js";
+import { AI_PROVIDER_PRESETS, getAiProviderPreset } from "../ai-provider-presets.js";
-const legacy = {
- aiSettings: {
- activeProvider: "deepseek",
- apiKey: "deepseek-secret",
- analysisModel: "deepseek-text"
- },
- visionSettings: {
- activeProvider: "openai",
+function configuredRegistry() {
+ return normalizeAiProviderRegistry({ providers: {
+ deepseek: {
+ apiKey: "deepseek-secret", consent: true,
+ models: { textTags: "deepseek-text", skillExtraction: "deepseek-text", creativePlanning: "deepseek-text" }
+ },
openai: {
- apiKey: "openai-secret",
- model: "openai-vision",
- videoGeneration: { model: "openai-video" }
+ apiKey: "openai-secret", consent: true,
+ models: {
+ textTags: "openai-text", skillExtraction: "openai-text", creativePlanning: "openai-text",
+ imageAnalysis: "openai-vision", imageGeneration: "openai-image", videoGeneration: "openai-video"
+ }
+ },
+ gemini: { apiKey: "gemini-secret", consent: true, models: { videoAnalysis: "gemini-video" } },
+ xai: {
+ apiKey: "xai-secret", consent: true,
+ models: {
+ textTags: "grok-text", skillExtraction: "grok-text", creativePlanning: "grok-text",
+ imageAnalysis: "grok-image", imageGeneration: "grok-image", videoGeneration: "grok-video"
+ }
}
- },
- aiServiceProfiles: {
- gemini: { apiKey: "gemini-secret", model: "gemini-video" },
- xai: { apiKey: "xai-secret", textModel: "grok-text", imageModel: "grok-image", videoModel: "grok-video" }
- },
- aiTaskRoutes: {
- "video-analysis": { serviceId: "gemini" },
- "image-generation": { serviceId: "xai" }
- }
-};
-
-test("legacy AI settings migrate once into connected providers and seven independent assignments", () => {
- const migrated = migrateLegacyAiConfiguration(legacy);
- assert.deepEqual(Object.keys(migrated.assignments), AI_ASSIGNMENT_TASKS.map((task) => task.id));
- assert.equal(migrated.registry.providers.deepseek.apiKey, "deepseek-secret");
- assert.equal(migrated.registry.providers.openai.apiKey, "openai-secret");
- assert.equal(migrated.registry.providers.gemini.models.videoAnalysis, "gemini-video");
- assert.equal(migrated.assignments.textTags.providerId, "deepseek");
- assert.equal(migrated.assignments.skillExtraction.providerId, "deepseek");
- assert.equal(migrated.assignments.creativePlanning.providerId, "deepseek");
- assert.equal(migrated.assignments.imageAnalysis.providerId, "openai");
- assert.equal(migrated.assignments.videoAnalysis.providerId, "gemini");
- assert.equal(migrated.assignments.imageGeneration.providerId, "xai");
+ } });
+}
+
+function configuredAssignments() {
+ return normalizeAiTaskAssignments({
+ textTags: { providerId: "deepseek", model: "deepseek-text" },
+ skillExtraction: { providerId: "deepseek", model: "deepseek-text" },
+ creativePlanning: { providerId: "deepseek", model: "deepseek-text" },
+ imageAnalysis: { providerId: "openai", model: "openai-vision" },
+ videoAnalysis: { providerId: "gemini", model: "gemini-video" },
+ imageGeneration: { providerId: "xai", model: "grok-image" },
+ videoGeneration: { providerId: "openai", model: "openai-video" }
+ });
+}
+
+test("provider presets are the single model-free source for official and aggregator services", () => {
+ assert.deepEqual(AI_PROVIDER_PRESETS.map((preset) => preset.id), [
+ "deepseek", "openai", "gemini", "xai", "kimi", "minimax", "volcengine", "openrouter",
+ "custom-text", "custom-media"
+ ]);
+ assert.equal(AI_PROVIDER_PRESETS.every((preset) =>
+ preset.label && (preset.endpoint || preset.category === "custom") && preset.protocol && preset.discovery?.adapter
+ && ["official", "aggregator", "custom"].includes(preset.category)
+ && Array.isArray(preset.capabilities)
+ ), true);
+ assert.equal(Object.hasOwn(getAiProviderPreset("kimi"), "models"), false);
+ assert.equal(getAiProviderPreset("gemini").capabilities.includes("imageGeneration"), true);
+ assert.deepEqual(getAiProviderPreset("gemini").catalogRequiredTasks, ["imageGeneration"]);
+ assert.equal(getAiProviderPreset("openrouter").category, "aggregator");
+ assert.equal(getAiProviderPreset("missing"), null);
+});
+
+test("registry v4 exposes provider categories and leaves all new-install tasks unassigned", () => {
+ const registry = normalizeAiProviderRegistry({ providers: {
+ kimi: { discovery: { etag: "catalog-version" } }
+ } });
+ const assignments = normalizeAiTaskAssignments({}, registry);
+ assert.equal(registry.version, 4);
+ assert.equal(registry.providers.kimi.endpoint, "https://api.moonshot.cn/v1/chat/completions");
+ assert.deepEqual(registry.providers.kimi.discovery, {
+ adapter: "kimi",
+ discoveredAt: "",
+ source: "",
+ etag: "catalog-version",
+ cacheControl: "",
+ error: ""
+ });
+ assert.equal(publicAiProviderRegistry(registry).providers.kimi.category, "official");
+ assert.deepEqual(assignments, Object.fromEntries(AI_ASSIGNMENT_TASKS.map(({ id }) => [id, {
+ providerId: "", model: ""
+ }])));
+ assert.throws(() => resolveAiProviderAssignment("textTags", registry, assignments), /未分配/);
+ const bounded = normalizeAiProviderRegistry({ providers: {
+ kimi: { discoveredModels: [{ id: "declared-model", tasks: ["videoAnalysis", "imageGeneration", "videoGeneration"] }] }
+ } });
+ assert.deepEqual(bounded.providers.kimi.discoveredModels[0].tasks, ["videoAnalysis"]);
+});
+
+test("new installs retain both custom connection entries without inventing a saved generic profile", () => {
+ const providers = publicAiProviderRegistry(normalizeAiProviderRegistry({})).providers;
+ assert.equal(providers["custom-text"].category, "custom");
+ assert.equal(providers["custom-media"].category, "custom");
+ assert.equal(Object.hasOwn(providers, "custom"), false);
+});
+
+test("unknown saved provider ids do not become hidden v4 connections", () => {
+ const providers = normalizeAiProviderRegistry({ providers: {
+ custom: { endpoint: "https://old.example/v1", apiKey: "obsolete-secret" },
+ "retired-provider": { endpoint: "https://retired.example/v1", apiKey: "obsolete-secret" }
+ } }).providers;
+ assert.equal(Object.hasOwn(providers, "custom"), false);
+ assert.equal(Object.hasOwn(providers, "retired-provider"), false);
+});
+
+test("empty v4 storage normalizes without inventing task assignments", () => {
+ const registry = normalizeAiProviderRegistry({});
+ const assignments = normalizeAiTaskAssignments({});
+ assert.equal(registry.version, 4);
+ assert.deepEqual(assignments, Object.fromEntries(AI_ASSIGNMENT_TASKS.map(({ id }) => [id, {
+ providerId: "",
+ model: ""
+ }])));
+});
+
+test("obsolete shared text routes are ignored instead of entering v4 assignments", () => {
+ const assignments = normalizeAiTaskAssignments({
+ text: { providerId: "deepseek", model: "obsolete-shared-model" }
+ });
+ assert.deepEqual(assignments, Object.fromEntries(AI_ASSIGNMENT_TASKS.map(({ id }) => [id, {
+ providerId: "",
+ model: ""
+ }])));
+});
+
+test("explicit task assignments survive v4 normalization unchanged", () => {
+ const explicit = Object.fromEntries(AI_ASSIGNMENT_TASKS.map(({ id }, index) => [id, {
+ providerId: index % 2 ? "openai" : "deepseek",
+ model: `account-model-${index}`
+ }]));
+ assert.deepEqual(normalizeAiTaskAssignments(explicit), explicit);
+ assert.equal(configuredRegistry().providers.deepseek.apiKey, "deepseek-secret");
});
test("public provider registry never exposes credentials", () => {
- const migrated = migrateLegacyAiConfiguration(legacy);
- const publicRegistry = publicAiProviderRegistry(migrated.registry);
+ const publicRegistry = publicAiProviderRegistry(configuredRegistry());
assert.equal(JSON.stringify(publicRegistry).includes("secret"), false);
assert.equal(publicRegistry.providers.openai.configured, true);
assert.equal(publicRegistry.providers.gemini.configured, true);
});
test("task pickers show only configured providers that declare the requested capability", () => {
- const migrated = migrateLegacyAiConfiguration(legacy);
- assert.deepEqual(availableAiProvidersForTask("videoAnalysis", migrated.registry).map((item) => item.id), ["gemini"]);
- assert.deepEqual(availableAiProvidersForTask("textTags", migrated.registry).map((item) => item.id), ["deepseek", "openai", "xai"]);
+ const registry = configuredRegistry();
+ assert.deepEqual(availableAiProvidersForTask("videoAnalysis", registry).map((item) => item.id), ["gemini"]);
+ assert.deepEqual(availableAiProvidersForTask("textTags", registry).map((item) => item.id), ["deepseek", "openai", "xai"]);
+});
+
+test("a connected provider with discovered task models is selectable without silently choosing a model", () => {
+ const registry = normalizeAiProviderRegistry({ providers: {
+ kimi: {
+ apiKey: "kimi-secret",
+ discoveredModels: [{
+ id: "account-visible-model",
+ tasks: ["textTags", "skillExtraction", "creativePlanning"],
+ status: "available"
+ }]
+ }
+ } });
+ assert.equal(registry.providers.kimi.models.textTags, "");
+ assert.deepEqual(availableAiProvidersForTask("textTags", registry).find(({ id }) => id === "kimi"), {
+ id: "kimi",
+ label: "Kimi",
+ model: ""
+ });
+ assert.deepEqual(resolveAiProviderAssignment("textTags", registry, {
+ textTags: { providerId: "kimi", model: "account-visible-model" }
+ }), {
+ taskId: "textTags",
+ providerId: "kimi",
+ provider: "Kimi",
+ model: "account-visible-model"
+ });
+ assert.throws(() => resolveAiProviderAssignment("textTags", registry, {
+ textTags: { providerId: "kimi", model: "" }
+ }), /尚未完成文字标签配置/);
});
test("task resolution reports the actual provider and model without silent fallback", () => {
- const migrated = migrateLegacyAiConfiguration(legacy);
- assert.deepEqual(resolveAiProviderAssignment("videoAnalysis", migrated.registry, migrated.assignments), {
+ const registry = configuredRegistry();
+ const assignments = configuredAssignments();
+ assert.deepEqual(resolveAiProviderAssignment("videoAnalysis", registry, assignments), {
taskId: "videoAnalysis",
providerId: "gemini",
provider: "Google Gemini",
model: "gemini-video"
});
- migrated.assignments.videoAnalysis = { providerId: "xai", model: "" };
- assert.throws(() => resolveAiProviderAssignment("videoAnalysis", migrated.registry, migrated.assignments), /不支持视频分析/);
+ assignments.videoAnalysis = { providerId: "xai", model: "" };
+ assert.throws(() => resolveAiProviderAssignment("videoAnalysis", registry, assignments), /不支持视频分析/);
});
test("a disappeared selected model is blocked instead of silently replaced", () => {
- const migrated = migrateLegacyAiConfiguration(legacy);
- migrated.registry.providers.openai.discoveredModels = [{
+ const registry = configuredRegistry();
+ const assignments = configuredAssignments();
+ registry.providers.openai.discoveredModels = [{
id: "openai-video", name: "openai-video", status: "unavailable", confidence: "declared",
source: "provider_models", tasks: ["videoGeneration"], inputModalities: ["text"], outputModalities: ["video"],
supportedParameters: [], supportedResolutions: [], supportedAspectRatios: [], contextLength: null, pricing: null
}];
- assert.throws(() => resolveAiProviderAssignment("videoGeneration", migrated.registry, migrated.assignments), /已下架|不可用/);
- assert.equal(migrated.assignments.videoGeneration.model, "openai-video");
+ assert.throws(() => resolveAiProviderAssignment("videoGeneration", registry, assignments), /已下架|不可用/);
+ assert.equal(assignments.videoGeneration.model, "openai-video");
});
-test("legacy custom media keeps its configured image tasks after registry normalization", () => {
- const migrated = migrateLegacyAiConfiguration({
- ...legacy,
- visionSettings: {
- activeProvider: "compatible",
+test("custom media keeps its configured image tasks after registry normalization", () => {
+ const registry = normalizeAiProviderRegistry({ providers: {
+ "custom-media": {
+ endpoint: "https://vision.example.com/v1/chat/completions",
+ protocol: "chat_completions",
+ apiKey: "vision-secret",
consent: true,
- compatible: {
- endpoint: "https://vision.example.com/v1/chat/completions",
- model: "vision-model",
- apiKey: "vision-secret",
- imageGeneration: {
- protocol: "images_generations",
- endpoint: "https://vision.example.com/v1/images/generations",
- editsEndpoint: "https://vision.example.com/v1/images/edits",
- model: "image-model",
- apiKey: "image-secret",
- sizes: ["1024x1024"]
- }
+ models: { imageAnalysis: "vision-model", imageGeneration: "image-model" },
+ imageGeneration: {
+ protocol: "images_generations",
+ endpoint: "https://vision.example.com/v1/images/generations",
+ editsEndpoint: "https://vision.example.com/v1/images/edits",
+ model: "image-model",
+ apiKey: "image-secret",
+ sizes: ["1024x1024"]
}
- },
- aiTaskRoutes: {
- ...legacy.aiTaskRoutes,
- "image-analysis": { serviceId: "current-vision", model: "vision-model" },
- "image-generation": { serviceId: "current-vision", model: "image-model" }
}
+ } });
+ const assignments = normalizeAiTaskAssignments({
+ imageAnalysis: { providerId: "custom-media", model: "vision-model" },
+ imageGeneration: { providerId: "custom-media", model: "image-model" }
});
- const restored = normalizeAiProviderRegistry(migrated.registry);
+ const restored = normalizeAiProviderRegistry(registry);
assert.deepEqual(restored.providers["custom-media"].capabilities, ["imageAnalysis", "imageGeneration"]);
- assert.equal(resolveAiProviderAssignment("imageAnalysis", restored, migrated.assignments).model, "vision-model");
- assert.equal(resolveAiProviderAssignment("imageGeneration", restored, migrated.assignments).model, "image-model");
+ assert.equal(resolveAiProviderAssignment("imageAnalysis", restored, assignments).model, "vision-model");
+ assert.equal(resolveAiProviderAssignment("imageGeneration", restored, assignments).model, "image-model");
});
test("model reference-image limits retain their declared or observed source", () => {
@@ -137,6 +251,44 @@ test("model reference-image limits retain their declared or observed source", ()
});
});
+test("registry keeps provider-declared model methods for capability diagnostics", () => {
+ const registry = normalizeAiProviderRegistry({ providers: { gemini: {
+ discoveredModels: [{
+ id: "gemini-3.1-flash-image",
+ confidence: "declared",
+ tasks: ["imageGeneration"],
+ supportedMethods: ["generateContent"]
+ }]
+ } } });
+ assert.deepEqual(registry.providers.gemini.discoveredModels[0].supportedMethods, ["generateContent"]);
+});
+
+test("Gemini image generation requires an exact available catalog model", () => {
+ const manual = normalizeAiProviderRegistry({ providers: { gemini: {
+ apiKey: "gemini-secret", consent: true,
+ models: { imageGeneration: "gemini-image-lookalike" }
+ } } });
+ assert.equal(manual.providers.gemini.catalogRequiredTasks.includes("imageGeneration"), true);
+ const cannotDisableGuard = normalizeAiProviderRegistry({ providers: { gemini: {
+ catalogRequiredTasks: [], apiKey: "gemini-secret", consent: true,
+ models: { imageGeneration: "gemini-image-lookalike" }
+ } } });
+ assert.deepEqual(cannotDisableGuard.providers.gemini.catalogRequiredTasks, ["imageGeneration"]);
+ assert.throws(() => resolveAiProviderAssignment("imageGeneration", manual, {
+ imageGeneration: { providerId: "gemini", model: "gemini-image-lookalike" }
+ }), /尚未完成图片生成配置/);
+
+ manual.providers.gemini.discoveredModels = [{
+ id: "gemini-3.1-flash-image", status: "available", confidence: "declared",
+ tasks: ["imageGeneration"]
+ }];
+ assert.deepEqual(resolveAiProviderAssignment("imageGeneration", manual, {
+ imageGeneration: { providerId: "gemini", model: "gemini-3.1-flash-image" }
+ }), {
+ taskId: "imageGeneration", providerId: "gemini", provider: "Google Gemini", model: "gemini-3.1-flash-image"
+ });
+});
+
test("reference-image capability keeps four states and remains idempotent", () => {
const registry = normalizeAiProviderRegistry({ providers: {
openrouter: {
diff --git a/test/ai-runtime.test.js b/test/ai-runtime.test.js
index 25cf3c2..ef57b17 100644
--- a/test/ai-runtime.test.js
+++ b/test/ai-runtime.test.js
@@ -18,30 +18,37 @@ test("Composer and background share one AI runtime protocol version", () => {
assert.throws(() => requireAiRuntimeProtocolVersion(0), /没有发起付费请求/);
});
-const legacy = {
- aiSettings: {
- activeProvider: "deepseek",
- apiKey: "deepseek-key",
- consent: true,
- analysisModel: "deepseek-tags",
- analysisInstructionsByLocale: { "zh-CN": "文字规则", en: "Text rules" }
- },
- visionSettings: {
- activeProvider: "openai",
- consent: true,
- openai: { apiKey: "openai-key", model: "openai-vision" }
- },
- aiServiceProfiles: {
- xai: { apiKey: "xai-key", textModel: "grok-plan", imageModel: "grok-image", mediaConsent: true }
+const storedConfiguration = {
+ aiProviderRegistry: { version: 4, providers: {
+ deepseek: {
+ apiKey: "deepseek-key", consent: true,
+ models: { textTags: "deepseek-tags", skillExtraction: "deepseek-tags" }
+ },
+ openai: {
+ apiKey: "openai-key", consent: true,
+ models: { imageAnalysis: "openai-vision" }
+ },
+ xai: {
+ apiKey: "xai-key", consent: true,
+ models: { creativePlanning: "grok-plan", imageAnalysis: "grok-image" }
+ }
+ } },
+ aiTaskAssignments: {
+ textTags: { providerId: "deepseek", model: "deepseek-tags" },
+ skillExtraction: { providerId: "deepseek", model: "deepseek-tags" },
+ creativePlanning: { providerId: "xai", model: "grok-plan" },
+ imageAnalysis: { providerId: "openai", model: "openai-vision" },
+ videoAnalysis: { providerId: "", model: "" },
+ imageGeneration: { providerId: "", model: "" },
+ videoGeneration: { providerId: "", model: "" }
},
- aiTaskRoutes: {
- "creative-planning": { serviceId: "xai", model: "grok-plan" },
- "image-analysis": { serviceId: "current-vision", model: "openai-vision" }
+ aiPreferences: {
+ textInstructionsByLocale: { "zh-CN": "文字规则", en: "Text rules" }
}
};
-test("one canonical configuration preserves independent text task assignments after legacy migration", () => {
- const configuration = aiConfigurationFromStorage(legacy);
+test("one canonical v4 configuration preserves independent text task assignments", () => {
+ const configuration = aiConfigurationFromStorage(storedConfiguration);
assert.equal(configuration.assignments.textTags.providerId, "deepseek");
assert.equal(configuration.assignments.creativePlanning.providerId, "xai");
assert.equal(resolveTextTaskSettings("textTags", configuration).analysisModel, "deepseek-tags");
@@ -51,16 +58,79 @@ test("one canonical configuration preserves independent text task assignments af
assert.equal(planning.compatible.apiKey, "xai-key");
});
+test("obsolete AI storage keys are ignored instead of becoming a second configuration path", () => {
+ const configuration = aiConfigurationFromStorage({
+ aiSettings: { apiKey: "obsolete-key", analysisModel: "obsolete-model" },
+ visionSettings: { openai: { apiKey: "obsolete-vision-key", model: "obsolete-vision-model" } },
+ aiTaskRoutes: { "text-tags": { serviceId: "deepseek", model: "obsolete-model" } }
+ });
+
+ assert.equal(configuration.registry.providers.deepseek.apiKey, "");
+ assert.deepEqual(configuration.assignments.textTags, { providerId: "", model: "" });
+ assert.equal(JSON.stringify(configuration).includes("obsolete-key"), false);
+});
+
test("runtime projections are derived views and task resolvers keep credentials private", () => {
- const configuration = aiConfigurationFromStorage(legacy);
+ const configuration = aiConfigurationFromStorage(storedConfiguration);
const runtime = projectAiRuntime(configuration);
assert.equal(runtime.aiTaskAssignments.imageAnalysis.providerId, "openai");
+ assert.equal(runtime.aiSettings.compatible.model, "grok-plan");
+ assert.equal(runtime.aiSettings.compatible.apiKey, "xai-key");
assert.equal(runtime.aiSettings.analysisInstructionsByLocale["zh-CN"], "文字规则");
const vision = resolveVisionTaskSettings("imageAnalysis", configuration);
assert.equal(vision.openai.apiKey, "openai-key");
assert.equal(vision.openai.model, "openai-vision");
});
+test("new-install runtime previews remain unassigned instead of inventing providers or models", () => {
+ const configuration = aiConfigurationFromStorage({});
+ const runtime = projectAiRuntime(configuration);
+
+ assert.equal(runtime.aiSettings.activeProvider, "compatible");
+ assert.equal(runtime.aiSettings.analysisModel, "");
+ assert.deepEqual(runtime.aiSettings.compatible, { endpoint: "", model: "", apiKey: "" });
+ assert.equal(resolveTextTaskSettings("textTags", configuration, { requireConfigured: false }).analysisModel, "");
+ assert.throws(() => resolveTextTaskSettings("textTags", configuration), /尚未分配/);
+ assert.throws(() => resolveVideoAnalysisTask(configuration), /尚未分配/);
+
+ configuration.assignments.textTags = { providerId: "deepseek", model: "" };
+ assert.equal(resolveTextTaskSettings("textTags", configuration, { requireConfigured: false }).analysisModel, "");
+ assert.throws(() => resolveTextTaskSettings("textTags", configuration), /尚未完成文字标签配置/);
+});
+
+test("Kimi text and video runtimes use the explicit assignment and declared chat protocol", () => {
+ const configuration = {
+ registry: { providers: { kimi: {
+ label: "Kimi",
+ endpoint: "https://api.moonshot.cn/v1/chat/completions",
+ protocol: "chat_completions",
+ apiKey: "kimi-secret",
+ consent: true,
+ capabilities: ["textTags", "videoAnalysis"]
+ } } },
+ assignments: {
+ textTags: { providerId: "kimi", model: "moonshot-account-text" },
+ videoAnalysis: { providerId: "kimi", model: "moonshot-account-video" }
+ }
+ };
+
+ const textSettings = resolveTextTaskSettings("textTags", configuration);
+ assert.equal(textSettings.activeProvider, "compatible");
+ assert.equal(textSettings.compatible.endpoint, "https://api.moonshot.cn/v1/chat/completions");
+ assert.equal(textSettings.compatible.model, "moonshot-account-text");
+ assert.equal(textSettings.compatible.apiKey, "kimi-secret");
+ assert.deepEqual(resolveVideoAnalysisTask(configuration), {
+ taskId: "videoAnalysis",
+ providerId: "kimi",
+ provider: "Kimi",
+ providerLabel: "Kimi",
+ model: "moonshot-account-video",
+ protocol: "chat_completions",
+ apiKey: "kimi-secret",
+ endpoint: "https://api.moonshot.cn/v1/chat/completions"
+ });
+});
+
test("video analysis requires the provider sending authorization before exposing credentials", () => {
const configuration = {
registry: {
@@ -82,7 +152,9 @@ test("video analysis requires the provider sending authorization before exposing
taskId: "videoAnalysis",
providerId: "gemini",
provider: "Google Gemini",
+ providerLabel: "Google Gemini",
model: "gemini-video",
+ protocol: "gemini",
apiKey: "gemini-video-secret",
endpoint: "https://generativelanguage.googleapis.com"
});
diff --git a/test/ai-service-profiles.test.js b/test/ai-service-profiles.test.js
new file mode 100644
index 0000000..e560e7c
--- /dev/null
+++ b/test/ai-service-profiles.test.js
@@ -0,0 +1,40 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ normalizeAiServiceProfiles,
+ publicAiServiceProfiles
+} from "../ai-service-profiles.js";
+
+test("runtime service profiles are normalized without inventing defaults", () => {
+ assert.deepEqual(normalizeAiServiceProfiles(), {
+ gemini: { apiKey: "", model: "" },
+ xai: {
+ apiKey: "",
+ textModel: "",
+ imageModel: "",
+ videoModel: "",
+ mediaConsent: false
+ }
+ });
+});
+
+test("public runtime profiles expose readiness but never credentials", () => {
+ const profiles = publicAiServiceProfiles({
+ gemini: { apiKey: "gemini-secret", model: "video-model" },
+ xai: {
+ apiKey: "xai-secret",
+ textModel: "text-model",
+ mediaConsent: true
+ }
+ });
+
+ assert.deepEqual(profiles.gemini, { model: "video-model", configured: true });
+ assert.deepEqual(profiles.xai, {
+ textModel: "text-model",
+ imageModel: "",
+ videoModel: "",
+ mediaConsent: true,
+ configured: true
+ });
+ assert.doesNotMatch(JSON.stringify(profiles), /gemini-secret|xai-secret/);
+});
diff --git a/test/ai-task-routing.test.js b/test/ai-task-routing.test.js
deleted file mode 100644
index a2cdbb6..0000000
--- a/test/ai-task-routing.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-import {
- AI_TASKS,
- mergeAiServiceProfiles,
- normalizeAiTaskRoutes,
- publicAiServiceProfiles,
- resolveAiTaskRoute
-} from "../ai-task-routing.js";
-
-test("every AI task has one explicit valid default route", () => {
- const routes = normalizeAiTaskRoutes();
- assert.deepEqual(Object.keys(routes), AI_TASKS.map((item) => item.id));
- assert.equal(routes["video-analysis"].serviceId, "gemini");
-});
-
-test("service credentials remain private and blank updates preserve existing keys", () => {
- const profiles = mergeAiServiceProfiles({ gemini: { apiKey: "secret", model: "video-model" } }, { gemini: { apiKey: "", model: "next-model" } });
- assert.equal(profiles.gemini.apiKey, "secret");
- assert.deepEqual(publicAiServiceProfiles(profiles).gemini, { model: "next-model", configured: true });
- assert.equal(JSON.stringify(publicAiServiceProfiles(profiles)).includes("secret"), false);
-});
-
-test("video analysis never silently routes to a non-video service", () => {
- assert.throws(() => resolveAiTaskRoute("video-analysis", {}, { profiles: {} }), /Gemini/);
- assert.deepEqual(resolveAiTaskRoute("video-analysis", {}, { profiles: { gemini: { apiKey: "key", model: "video-model" } } }), {
- taskId: "video-analysis", serviceId: "gemini", provider: "Google Gemini", model: "video-model"
- });
-});
-
-test("xAI video generation uses its video model without becoming a video-analysis route", () => {
- const routes = normalizeAiTaskRoutes({ "video-generation": { serviceId: "xai" } });
- const resolved = resolveAiTaskRoute("video-generation", routes, {
- profiles: { xai: { apiKey: "xai-key", textModel: "text", videoModel: "video", mediaConsent: true } }
- });
- assert.deepEqual(resolved, {
- taskId: "video-generation",
- serviceId: "xai",
- provider: "xAI",
- model: "video"
- });
- assert.equal(normalizeAiTaskRoutes({ "video-analysis": { serviceId: "xai" } })["video-analysis"].serviceId, "gemini");
-});
diff --git a/test/ai_provider_registry_e2e.py b/test/ai_provider_registry_e2e.py
index a02be2b..47f9556 100644
--- a/test/ai_provider_registry_e2e.py
+++ b/test/ai_provider_registry_e2e.py
@@ -1,13 +1,128 @@
from __future__ import annotations
+import re
+
from playwright.sync_api import expect
from e2e_support import extension_session
+TASK_IDS = {
+ "textTags",
+ "skillExtraction",
+ "creativePlanning",
+ "imageAnalysis",
+ "videoAnalysis",
+ "imageGeneration",
+ "videoGeneration",
+}
+
+
+def open_ai_settings(run):
+ library = run.open_page("library.html", wait_until="networkidle")
+ if not library.locator("#settings-dialog").is_visible():
+ library.locator("#open-settings").click()
+ library.locator('[data-settings-tab="ai"]').click()
+ return library
+
+
+def assert_new_install_defaults() -> None:
+ with extension_session("prompt-director-ai-registry-new-") as run:
+ library = open_ai_settings(run)
+
+ expect(library.locator("#ai-provider-list .ai-provider-row")).to_have_count(10)
+ expect(library.locator('#ai-provider-list [data-provider-category="official"]')).to_contain_text("官方服务")
+ expect(library.locator('#ai-provider-list [data-provider-category="aggregator"]')).to_contain_text("聚合平台")
+ expect(library.locator('#ai-provider-list [data-provider-category="custom"]')).to_contain_text("自定义兼容服务")
+ expect(library.locator('[data-provider-id="kimi"]')).to_contain_text("Kimi")
+ expect(library.locator("#ai-assignment-list .ai-assignment-row")).to_have_count(7)
+ expect(library.locator("#ai-assignment-list .ai-assignment-row", has_text="尚未分配")).to_have_count(7)
+ expect(library.locator("#ai-provider-list")).to_contain_text("模型目录未读取")
+
+ stored = library.evaluate("() => chrome.storage.local.get(['aiProviderRegistry', 'aiTaskAssignments'])")
+ assert set(stored["aiTaskAssignments"].keys()) == TASK_IDS, stored
+ assert all(value == {"providerId": "", "model": ""} for value in stored["aiTaskAssignments"].values()), stored
+ assert stored["aiProviderRegistry"]["version"] == 4, stored
+
+ execution_state = library.evaluate(
+ "() => chrome.runtime.sendMessage({type: 'GET_CREATIVE_JOB_EXECUTION_STATE'})"
+ )
+ assert execution_state["ok"] is True, execution_state
+ assert execution_state["aiSettings"]["analysisModel"] == "", execution_state
+ assert execution_state["aiSettings"]["compatible"] == {
+ "endpoint": "", "model": "", "apiKey": ""
+ }, execution_state
+
+ library.evaluate(
+ """async () => {
+ const stored = await chrome.storage.local.get(['aiProviderRegistry', 'aiTaskAssignments']);
+ stored.aiProviderRegistry.providers.deepseek.discoveredModels = [{
+ id: 'retired-model', name: 'retired-model', status: 'unavailable',
+ confidence: 'declared', tasks: ['textTags']
+ }];
+ stored.aiProviderRegistry.providers.deepseek.discovery = {
+ discoveredAt: '2026-08-12T00:00:00.000Z', source: 'provider_cache', error: '目录服务暂时不可用'
+ };
+ stored.aiProviderRegistry.providers.kimi.discoveredModels = [{
+ id: 'kimi-current', name: 'kimi-current', status: 'available',
+ confidence: 'declared', tasks: ['textTags']
+ }];
+ stored.aiProviderRegistry.providers.kimi.discovery = {
+ discoveredAt: '2026-08-12T00:00:00.000Z', source: 'provider_models', error: ''
+ };
+ stored.aiTaskAssignments.textTags = {providerId: 'deepseek', model: 'retired-model'};
+ await chrome.storage.local.set(stored);
+ location.reload();
+ }"""
+ )
+ library.wait_for_load_state("networkidle")
+ if not library.locator("#settings-dialog").is_visible():
+ library.locator("#open-settings").click()
+ library.locator('[data-settings-tab="ai"]').click()
+ expect(library.locator('[data-provider-id="deepseek"]')).to_contain_text("模型目录读取失败:目录服务暂时不可用;保留 1 个模型")
+ expect(library.locator('[data-provider-id="kimi"]')).to_contain_text("模型目录已读取 · 1 个模型 · 尚未执行模型调用验证")
+ expect(library.locator("#ai-assignment-list .ai-assignment-row", has_text="文字标签")).to_contain_text("已下架或当前不可用")
+
+
+def assert_english_ai_settings() -> None:
+ with extension_session("prompt-director-ai-registry-en-", viewport={"width": 1280, "height": 900}) as run:
+ setup = run.open_page("collector.html")
+ run.seed_storage(setup, {
+ "schemaVersion": 24,
+ "entries": [],
+ "uiPreferences": {"locale": "en", "theme": "system", "motion": "system"},
+ })
+ library = open_ai_settings(run)
+ chinese = re.compile(r"[\u3400-\u9fff]")
+
+ expect(library.locator("html")).to_have_attribute("lang", "en")
+ expect(library.locator("#settings-ai-panel")).not_to_contain_text(chinese, use_inner_text=True)
+ expect(library.locator("#ai-assignment-list .ai-assignment-row", has_text="Not assigned")).to_have_count(7)
+ expect(library.locator('[data-provider-id="volcengine"]')).to_contain_text("Volcengine")
+
+ 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")
+ dialog.locator(".app-dialog-close").click()
+
+ library.locator("#open-ai-routing").click()
+ dialog = library.locator("#promptdirector-app-dialog")
+ expect(dialog).not_to_contain_text(chinese, use_inner_text=True)
+ dialog.locator("#promptdirector-app-dialog-providerEditor").select_option("custom-media")
+ dialog.locator(".app-dialog-advanced-settings > summary").click()
+ expect(dialog).not_to_contain_text(chinese, use_inner_text=True)
+ expect(dialog.get_by_role("button", name="Fill Micu personal relay preset")).to_be_visible()
+ dialog.locator(".app-dialog-close").click()
+
+
def main() -> None:
+ assert_new_install_defaults()
+ assert_english_ai_settings()
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]] = []
+ gemini_interaction_calls = 0
def mock_models(route) -> None:
model_authorizations.append(route.request.headers.get("authorization", ""))
@@ -17,68 +132,131 @@ def main() -> None:
body='{"data":[{"id":"gpt-5.6-terra"},{"id":"gpt-image-2"}]}',
)
+ def mock_openai_models(route) -> None:
+ route.fulfill(
+ status=200,
+ content_type="application/json",
+ body='{"data":[{"id":"gpt-text-catalog-only"}]}',
+ )
+
+ def mock_gemini_models(route) -> None:
+ gemini_model_requests.append({
+ "url": route.request.url,
+ "api_key": route.request.headers.get("x-goog-api-key", ""),
+ "authorization": route.request.headers.get("authorization", ""),
+ })
+ route.fulfill(
+ status=200,
+ content_type="application/json",
+ body=(
+ '{"models":['
+ '{"name":"models/gemini-2.5-flash","displayName":"Gemini 2.5 Flash",'
+ '"supportedGenerationMethods":["generateContent"]},'
+ '{"name":"models/gemini-3.1-flash-image","displayName":"Nano Banana 2",'
+ '"supportedGenerationMethods":["generateContent"]},'
+ '{"name":"models/gemini-image-preview","displayName":"Image Preview",'
+ '"supportedGenerationMethods":["generateContent"]}'
+ ']}'
+ ),
+ )
+
+ def block_gemini_interactions(route) -> None:
+ nonlocal gemini_interaction_calls
+ gemini_interaction_calls += 1
+ route.fulfill(status=500, content_type="application/json", body='{"error":{"message":"unexpected paid call"}}')
+
run.context.route("https://www.micuapi.ai/v1/models", mock_models)
+ run.context.route("https://api.openai.com/v1/models", mock_openai_models)
+ run.context.route("https://generativelanguage.googleapis.com/v1beta/models", mock_gemini_models)
+ run.context.route("https://generativelanguage.googleapis.com/v1beta/interactions", block_gemini_interactions)
setup = run.open_page("collector.html")
run.seed_storage(setup, {
"schemaVersion": 24,
"entries": [],
- "aiSettings": {
- "activeProvider": "deepseek",
- "apiKey": "deepseek-secret",
- "analysisModel": "deepseek-text",
- "consent": True,
- },
- "visionSettings": {
- "activeProvider": "compatible",
- "consent": True,
- "openai": {"apiKey": "openai-secret", "model": "openai-vision"},
- "compatible": {
- "protocol": "responses",
- "endpoint": "https://www.micuapi.ai/v1/responses",
- "apiKey": "micu-vision-secret",
- "model": "gpt-5.6-terra",
- "imageGeneration": {
- "protocol": "images_generations",
- "endpoint": "https://www.micuapi.ai/v1/images/generations",
- "editsEndpoint": "https://www.micuapi.ai/v1/images/edits",
- "apiKey": "micu-image-secret",
- "model": "gpt-image-2",
+ "uiPreferences": {"locale": "zh-CN", "theme": "system", "motion": "system"},
+ "aiProviderRegistry": {
+ "version": 4,
+ "providers": {
+ "deepseek": {
+ "apiKey": "deepseek-secret",
+ "consent": True,
+ "models": {"textTags": "deepseek-text", "skillExtraction": "deepseek-text", "creativePlanning": "deepseek-text"},
+ },
+ "openai": {
+ "apiKey": "openai-secret",
+ "consent": True,
+ "models": {"imageAnalysis": "openai-vision"},
+ },
+ "gemini": {
+ "apiKey": "gemini-secret",
+ "consent": True,
+ "models": {"videoAnalysis": "gemini-video"},
+ },
+ "xai": {
+ "apiKey": "xai-secret",
+ "consent": True,
+ "models": {"creativePlanning": "grok-text", "imageGeneration": "grok-image"},
+ },
+ "custom-media": {
+ "endpoint": "https://www.micuapi.ai/v1/responses",
+ "protocol": "responses",
+ "apiKey": "micu-vision-secret",
+ "consent": True,
+ "models": {"imageAnalysis": "gpt-5.6-terra", "imageGeneration": "gpt-image-2"},
+ "imageGeneration": {
+ "protocol": "images_generations",
+ "endpoint": "https://www.micuapi.ai/v1/images/generations",
+ "editsEndpoint": "https://www.micuapi.ai/v1/images/edits",
+ "apiKey": "micu-image-secret",
+ "model": "gpt-image-2",
+ },
},
},
},
- "aiServiceProfiles": {
- "gemini": {"apiKey": "gemini-secret", "model": "gemini-video"},
- "xai": {"apiKey": "xai-secret", "textModel": "grok-text", "imageModel": "grok-image"},
+ "aiTaskAssignments": {
+ "textTags": {"providerId": "deepseek", "model": "deepseek-text"},
+ "skillExtraction": {"providerId": "deepseek", "model": "deepseek-text"},
+ "creativePlanning": {"providerId": "xai", "model": "grok-text"},
+ "imageAnalysis": {"providerId": "custom-media", "model": "gpt-5.6-terra"},
+ "videoAnalysis": {"providerId": "gemini", "model": "gemini-video"},
+ "imageGeneration": {"providerId": "custom-media", "model": "gpt-image-2"},
+ "videoGeneration": {"providerId": "", "model": ""},
},
})
- library = run.open_page("library.html", wait_until="networkidle")
- if not library.locator("#settings-dialog").is_visible():
- library.locator("#open-settings").click()
- library.locator('[data-settings-tab="ai"]').click()
+ library = open_ai_settings(run)
- expect(library.locator("#ai-provider-list .ai-provider-row")).to_have_count(5)
+ expect(library.locator("#ai-provider-list .ai-provider-row")).to_have_count(10)
expect(library.locator("#ai-assignment-list .ai-assignment-row")).to_have_count(7)
expect(library.locator("#ai-provider-list")).to_contain_text("DeepSeek")
expect(library.locator("#ai-provider-list")).to_contain_text("OpenAI")
expect(library.locator("#ai-provider-list")).to_contain_text("Google Gemini")
expect(library.locator("#ai-provider-list")).to_contain_text("xAI")
expect(library.locator("#ai-provider-list")).to_contain_text("自定义兼容服务(图片与生成)")
- expect(library.locator("#open-ai-routing")).to_have_text("添加 AI 服务")
+ expect(library.locator("#ai-provider-list")).to_contain_text("Kimi")
+ expect(library.locator("#open-ai-routing")).to_have_text("连接 AI 服务")
expect(library.locator("#ai-provider-list").get_by_role("button", name="编辑配置")).to_have_count(5)
- expect(library.locator(".ai-advanced-settings")).not_to_have_attribute("open", "")
- expect(library.locator("#deepseek-api-key")).to_be_hidden()
- library.locator(".ai-advanced-settings > summary").click()
- expect(library.locator("#deepseek-api-key")).to_be_visible()
- expect(library.locator("#ai-settings-status")).to_contain_text("API Key 已配置")
+ expect(library.locator("#settings-ai-panel > .ai-advanced-settings")).not_to_have_attribute("open", "")
+ expect(library.locator("#settings-ai-panel > .ai-advanced-settings > summary")).to_contain_text("分析规则与创作方法(高级)")
+ expect(library.locator("#deepseek-api-key")).to_have_count(0)
+ expect(library.locator("#vision-provider")).to_have_count(0)
+ expect(library.locator("#text-ai-provider")).to_have_count(0)
+ library.locator("#settings-ai-panel > .ai-advanced-settings > summary").click()
+ expect(library.locator("#analysis-instructions-zh")).to_be_visible()
+ expect(library.locator("#ai-settings-status")).to_contain_text("规则保存在本机")
+ 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.locator('[data-analysis-kind="vision"]').click()
- expect(library.locator("#vision-compatible-api-key")).to_be_visible()
- expect(library.locator("#vision-settings-status")).to_contain_text("服务已配置")
- library.locator("#vision-provider").select_option("openai")
- expect(library.locator("#vision-openai-api-key")).to_be_visible()
- library.locator("#vision-provider").select_option("compatible")
- expect(library.locator("#vision-compatible-api-key")).to_be_visible()
- expect(library.locator("#vision-settings-form")).not_to_contain_text("图片生成协议")
- expect(library.locator("#vision-settings-form")).not_to_contain_text("图片尺寸")
+ 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("分析规则已保存")
+ 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
image_runtime = library.evaluate("() => chrome.runtime.sendMessage({type: 'GET_AI_TASK_RUNTIME', taskId: 'imageAnalysis'})")
assert image_runtime["ok"] is True, image_runtime
@@ -90,7 +268,10 @@ def main() -> None:
dialog.locator("#promptdirector-app-dialog-providerEditor").select_option("openrouter")
expect(dialog.locator("#promptdirector-app-dialog-providerEditor")).to_have_value("openrouter")
expect(dialog.locator("#promptdirector-app-dialog-provider_openrouter_apiKey")).to_be_visible()
- expect(dialog.locator("#promptdirector-app-dialog-providerEditor option")).to_have_count(9)
+ expect(dialog.locator("#promptdirector-app-dialog-providerEditor option")).to_have_count(10)
+ expect(dialog.locator("#promptdirector-app-dialog-providerEditor option", has_text="官方服务 · Kimi")).to_have_count(1)
+ expect(dialog.locator("#promptdirector-app-dialog-providerEditor option", has_text="聚合平台 · OpenRouter")).to_have_count(1)
+ expect(dialog.locator("#promptdirector-app-dialog-providerEditor option", has_text="自定义兼容服务 · 自定义兼容服务(图片与生成)")).to_have_count(1)
expect(dialog.locator('[data-field-id^="provider_"]:visible')).to_have_count(2)
expect(dialog.locator('[data-field-id^="assignment_"]')).to_have_count(0)
password_values = dialog.locator('input[type="password"]').evaluate_all("nodes => nodes.map(node => node.value)")
@@ -119,11 +300,17 @@ def main() -> None:
expect(image_key).to_have_attribute("placeholder", "已保存(尾号 cret);留空保持不变")
expect(image_endpoint).to_be_hidden()
dialog.locator(".app-dialog-advanced-settings > summary").click()
+ micu_preset = dialog.get_by_role("button", name="填入米醋个人中转预设")
+ expect(micu_preset).to_be_visible()
+ micu_preset.click()
+ expect(dialog.locator("#promptdirector-app-dialog-provider_custom_media_endpoint")).to_have_value("https://www.micuapi.ai/v1/responses")
+ expect(dialog.locator("#promptdirector-app-dialog-provider_custom_media_protocol")).to_have_value("responses")
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")
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)")
library.evaluate("() => { chrome.permissions.request = async () => true; }")
dialog.get_by_role("button", name="保存配置").click()
expect(dialog).to_be_hidden()
@@ -133,10 +320,36 @@ def main() -> None:
"Bearer replacement-image-secret",
"Bearer replacement-analysis-secret",
], model_authorizations
- saved_keys = library.evaluate("() => chrome.storage.local.get('aiProviderRegistry')")
+ saved_keys = library.evaluate("() => chrome.storage.local.get(['aiProviderRegistry', 'aiTaskAssignments'])")
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
+
+ library.locator('[data-provider-id="openai"]').get_by_role("button", name="编辑配置").click()
+ openai_dialog = library.locator("#promptdirector-app-dialog")
+ expect(openai_dialog).to_be_visible()
+ expect(openai_dialog.locator("#promptdirector-app-dialog-providerEditor")).to_have_value("openai")
+ openai_image_model = openai_dialog.locator("#promptdirector-app-dialog-provider_openai_model_imageGeneration")
+ expect(openai_image_model).to_be_hidden()
+ openai_dialog.locator(".app-dialog-advanced-settings > summary").click()
+ expect(openai_image_model).to_be_visible()
+ assert openai_image_model.evaluate("node => node.tagName") == "INPUT"
+ openai_image_model.fill("openai-account-image-model")
+ openai_assignments_before_save = library.evaluate("() => chrome.storage.local.get('aiTaskAssignments').then(value => value.aiTaskAssignments)")
+ openai_dialog.get_by_role("button", name="保存配置").click()
+ 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
+
+ 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()
image_task = library.locator("#ai-assignment-list .ai-assignment-row", has_text="图片分析")
expect(image_task).to_contain_text("自定义兼容服务(图片与生成) · gpt-5.6-terra")
@@ -149,8 +362,88 @@ 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()) == {"textTags", "skillExtraction", "creativePlanning", "imageAnalysis", "videoAnalysis", "imageGeneration", "videoGeneration"}
- print({"connectedProviders": 5, "taskAssignments": 7, "legacyCompatibleVisionRestored": True, "credentialsExposed": False})
+ assert set(stored["aiTaskAssignments"].keys()) == TASK_IDS
+ assert stored["aiTaskAssignments"] == assignments_before_save
+
+ assignments_before_nano = stored["aiTaskAssignments"]
+ library.locator('[data-provider-id="gemini"]').get_by_role("button", name="刷新模型").click()
+ expect(library.locator("#feedback")).to_contain_text("Google Gemini 已发现")
+ assert gemini_model_requests, gemini_model_requests
+ assert all(request == {
+ "url": "https://generativelanguage.googleapis.com/v1beta/models",
+ "api_key": "gemini-secret",
+ "authorization": "",
+ } for request in gemini_model_requests), gemini_model_requests
+
+ gemini_catalog = library.evaluate(
+ "() => chrome.storage.local.get('aiProviderRegistry').then(value => value.aiProviderRegistry.providers.gemini.discoveredModels)"
+ )
+ nano = next(model for model in gemini_catalog if model["id"] == "gemini-3.1-flash-image")
+ ordinary = next(model for model in gemini_catalog if model["id"] == "gemini-2.5-flash")
+ preview = next(model for model in gemini_catalog if model["id"] == "gemini-image-preview")
+ assert "imageGeneration" in nano["tasks"]
+ assert nano["supportedResolutions"] == ["512px", "1K", "2K", "4K"]
+ assert nano["referenceImages"]["maxItems"] == 14
+ assert "imageGeneration" not in ordinary["tasks"]
+ assert "imageGeneration" not in preview["tasks"]
+
+ generation_task = library.locator("#ai-assignment-list .ai-assignment-row", has_text="图片生成")
+ generation_task.get_by_role("button", name="更换").click()
+ nano_dialog = library.locator("#promptdirector-app-dialog")
+ nano_dialog.locator('[data-field-id="providerId"] select').select_option("gemini")
+ nano_model = nano_dialog.locator('[data-field-id="model"] select')
+ expect(nano_model.locator("option")).to_have_count(1)
+ expect(nano_model).to_have_value("gemini-3.1-flash-image")
+ expect(nano_dialog).to_contain_text("Nano Banana 2")
+ nano_dialog.get_by_role("button", name="保存任务默认").click()
+ expect(nano_dialog).to_be_hidden()
+
+ nano_saved = library.evaluate("() => chrome.storage.local.get(['aiProviderRegistry', 'aiTaskAssignments'])")
+ assert nano_saved["aiTaskAssignments"]["imageGeneration"] == {
+ "providerId": "gemini", "model": "gemini-3.1-flash-image"
+ }
+ assert {
+ task: value for task, value in nano_saved["aiTaskAssignments"].items() if task != "imageGeneration"
+ } == {
+ 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)
+
+ library.evaluate(
+ """async () => {
+ const now = new Date().toISOString();
+ await chrome.storage.local.set({composerSessions: [{
+ id: 'nano-parameter-session', title: 'Nano Banana 参数验证',
+ targetType: 'image', routeMode: 'compose', outputMode: 'create_image',
+ aiProfile: {serviceId: 'xai', model: 'grok-text', thinking: false},
+ generationAiProfile: {serviceId: 'gemini', model: 'gemini-3.1-flash-image', thinking: false},
+ generationParameters: {},
+ messages: [{id: 'nano-request', role: 'user', type: 'request', content: '生成电影海报', createdAt: now}],
+ createdAt: now, updatedAt: now
+ }]});
+ }"""
+ )
+ composer = run.open_page("composer.html?session=nano-parameter-session", wait_until="networkidle")
+ composer.locator("#composer-options summary").click()
+ expect(composer.locator("#composer-generation-settings")).to_be_visible()
+ expect(composer.locator("#composer-image-size-field > span")).to_have_text("画幅比例")
+ expect(composer.locator("#composer-image-quality-field > span")).to_have_text("图片尺寸")
+ expect(composer.locator("#composer-image-size")).to_have_value("1:1")
+ expect(composer.locator("#composer-image-quality")).to_have_value("512px")
+ composer.locator("#composer-image-size").select_option("16:9")
+ composer.locator("#composer-image-quality").select_option("2K")
+ expect(composer.locator("#composer-image-size")).to_have_value("16:9")
+ expect(composer.locator("#composer-image-quality")).to_have_value("2K")
+ composer_parameters = composer.evaluate(
+ """() => chrome.runtime.sendMessage({
+ type: 'GET_COMPOSER_SESSION', sessionId: 'nano-parameter-session'
+ }).then(response => response.session.generationParameters)"""
+ )
+ assert composer_parameters["aspectRatio"] == "16:9", composer_parameters
+ assert composer_parameters["imageSize"] == "2K", composer_parameters
+ assert gemini_interaction_calls == 0
+ print({"providersShown": 10, "connectedProviders": 5, "taskAssignments": 7, "newInstallUnassigned": True, "nanoBananaCatalogAssigned": True, "nanoBananaComposerParameters": True, "paidCalls": 0, "unifiedPreferencesSaved": True, "credentialsExposed": False})
if __name__ == "__main__":
diff --git a/test/analysis-candidates.test.js b/test/analysis-candidates.test.js
index 86a7e8d..454664c 100644
--- a/test/analysis-candidates.test.js
+++ b/test/analysis-candidates.test.js
@@ -333,12 +333,6 @@ test("text compatible API key is cleared when the endpoint origin changes", () =
assert.equal(settings.compatible.apiKey, "");
});
-test("legacy AI model setting migrates to the remaining batch-analysis setting", () => {
- const settings = normalizeAiSettings({ model: "legacy-analysis", apiKey: "secret", consent: true });
- assert.equal(settings.analysisModel, "legacy-analysis");
- assert.equal(Object.hasOwn(settings, "generationModel"), false);
-});
-
test("composer planner sends only prompt originals and vision descriptions as untrusted text references", async () => {
let request;
const fetchStub = async (_url, options) => {
diff --git a/test/article-document.test.js b/test/article-document.test.js
new file mode 100644
index 0000000..e2da1dc
--- /dev/null
+++ b/test/article-document.test.js
@@ -0,0 +1,62 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ articleDocumentText,
+ finalizeArticleDocumentAssets,
+ normalizeArticleDocument,
+ removeArticleDocumentAsset,
+ remapArticleDocumentAssets
+} from "../article-document.js";
+
+test("article documents preserve readable block order while discarding invalid blocks", () => {
+ const document = normalizeArticleDocument({
+ version: 1,
+ blocks: [
+ { id: "heading", kind: "heading", level: 2, text: "创作过程", sourceOrder: 0 },
+ { id: "paragraph", kind: "paragraph", text: "先确定光线,再安排人物。", sourceOrder: 1 },
+ { id: "image", kind: "image", assetId: "capture:image", sourceUrl: "https://example.com/full.webp", sourceOrder: 2 },
+ { id: "download", kind: "document", assetId: "capture:pdf", sourceUrl: "https://example.com/brief.pdf", label: "下载 Brief", sourceOrder: 3 },
+ { id: "empty", kind: "paragraph", text: "", sourceOrder: 4 }
+ ]
+ });
+
+ assert.deepEqual(document.blocks.map((block) => block.id), ["heading", "paragraph", "image", "download"]);
+ assert.equal(articleDocumentText(document), "创作过程\n\n先确定光线,再安排人物。");
+});
+
+test("article media references remap on save and disappear when an asset is removed", () => {
+ const source = normalizeArticleDocument({
+ version: 1,
+ blocks: [
+ { id: "paragraph", kind: "paragraph", text: "正文", sourceOrder: 0 },
+ { id: "image", kind: "image", assetId: "capture:image", sourceUrl: "https://example.com/full.webp", sourceOrder: 1 },
+ { id: "video", kind: "video", assetId: "capture:video", sourceUrl: "https://example.com/watch", sourceOrder: 2 }
+ ]
+ });
+ const saved = remapArticleDocumentAssets(source, new Map([
+ ["capture:image", "asset:image"],
+ ["capture:video", "asset:video"]
+ ]));
+
+ assert.deepEqual(saved.blocks.map((block) => block.assetId || ""), ["", "asset:image", "asset:video"]);
+ const removed = removeArticleDocumentAsset(saved, "asset:image");
+ assert.deepEqual(removed.blocks.map((block) => block.id), ["paragraph", "video"]);
+});
+
+test("failed media saves keep their original article link without a stale asset id", () => {
+ const finalized = finalizeArticleDocumentAssets({
+ version: 1,
+ blocks: [
+ { id: "image", kind: "image", assetId: "capture:missing", sourceUrl: "https://example.com/missing.webp", sourceOrder: 0 }
+ ]
+ }, new Map());
+
+ assert.equal(finalized.blocks[0].sourceUrl, "https://example.com/missing.webp");
+ assert.equal("assetId" in finalized.blocks[0], false);
+});
+
+test("legacy cases can omit an article document", () => {
+ assert.equal(normalizeArticleDocument(null), null);
+ assert.equal(normalizeArticleDocument({ blocks: [] }), null);
+});
diff --git a/test/bounded-media.test.js b/test/bounded-media.test.js
index 22d0a12..6a4a0e5 100644
--- a/test/bounded-media.test.js
+++ b/test/bounded-media.test.js
@@ -4,7 +4,9 @@ import assert from "node:assert/strict";
import {
assertRemoteMediaUrl,
boundedMediaBlobFromResponse,
- fetchBoundedMedia
+ detectImageDimensions,
+ fetchBoundedMedia,
+ isSupportedDocumentMimeType
} from "../bounded-media.js";
const PNG = Uint8Array.from([
@@ -58,3 +60,63 @@ test("remote media URLs require HTTPS and cannot contain credentials", () => {
assert.throws(() => assertRemoteMediaUrl("https://name:[email protected]/image.png"), /登录凭据/);
assert.equal(assertRemoteMediaUrl("http://127.0.0.1:8080/image.png", { allowLoopback: true }).hostname, "127.0.0.1");
});
+
+test("bounded images report real header dimensions and reject excessive pixel counts", async () => {
+ const sizedPng = Uint8Array.from([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x0f, 0xa0, 0x00, 0x00, 0x0b, 0xb8
+ ]);
+ assert.deepEqual(detectImageDimensions(sizedPng, "image/png"), { width: 4000, height: 3000 });
+ let metadata = null;
+ const blob = await boundedMediaBlobFromResponse(new Response(sizedPng), {
+ kind: "image",
+ maxBytes: 1024,
+ maxPixels: 12_000_000,
+ onMetadata: (value) => { metadata = value; }
+ });
+ assert.equal(blob.type, "image/png");
+ assert.deepEqual(metadata, { mimeType: "image/png", width: 4000, height: 3000 });
+ await assert.rejects(
+ () => boundedMediaBlobFromResponse(new Response(sizedPng), { kind: "image", maxBytes: 1024, maxPixels: 11_999_999 }),
+ /图片像素超过/
+ );
+});
+
+test("bounded documents accept only verified safe document content", async () => {
+ const pdf = new TextEncoder().encode("%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF");
+ const pdfBlob = await boundedMediaBlobFromResponse(new Response(pdf, {
+ headers: { "content-type": "application/octet-stream" }
+ }), { kind: "document", expectedMimeType: "application/pdf", maxBytes: 1024 });
+ assert.equal(pdfBlob.type, "application/pdf");
+
+ const html = new TextEncoder().encode("<!doctype html><html><body>Reference</body></html>");
+ const htmlBlob = await boundedMediaBlobFromResponse(new Response(html, {
+ headers: { "content-type": "text/plain" }
+ }), { kind: "document", expectedMimeType: "text/html", maxBytes: 1024 });
+ assert.equal(htmlBlob.type, "text/html");
+
+ assert.equal(isSupportedDocumentMimeType("text/markdown; charset=utf-8"), true);
+ assert.equal(isSupportedDocumentMimeType("application/zip"), false);
+});
+
+test("bounded documents reject spoofed, binary and unsupported files", async () => {
+ await assert.rejects(
+ () => boundedMediaBlobFromResponse(new Response(new TextEncoder().encode("not a pdf"), {
+ headers: { "content-type": "application/pdf" }
+ }), { kind: "document", expectedMimeType: "application/pdf", maxBytes: 1024 }),
+ /有效文档文件/
+ );
+ await assert.rejects(
+ () => boundedMediaBlobFromResponse(new Response(Uint8Array.from([0x50, 0x4b, 0x03, 0x04, 0, 0, 0]), {
+ headers: { "content-type": "text/plain" }
+ }), { kind: "document", expectedMimeType: "text/plain", maxBytes: 1024 }),
+ /有效文档文件/
+ );
+ await assert.rejects(
+ () => boundedMediaBlobFromResponse(new Response(new TextEncoder().encode("plain"), {
+ headers: { "content-type": "application/zip" }
+ }), { kind: "document", expectedMimeType: "application/zip", maxBytes: 1024 }),
+ /支持的安全文档类型/
+ );
+});
diff --git a/test/capture-draft.test.js b/test/capture-draft.test.js
index faabe4f..142fa7d 100644
--- a/test/capture-draft.test.js
+++ b/test/capture-draft.test.js
@@ -45,14 +45,23 @@ test("X capture uses a compact account title while preserving the original sourc
assert.equal(captureTitleForSource("https://example.com/post", original), original);
});
-test("capture draft v2 groups repeated selections from one source into one ordered part", () => {
+test("capture draft v3 groups repeated selections and retains normalized source context", () => {
let draft = createCaptureDraft({ targetCaseId: "compound:target" });
({ draft } = addDraftFragment(draft, { text: "第一段", sourceUrl: "https://a.example/post", sourceTitle: "A" }));
({ draft } = addDraftFragment(draft, { text: "第二段", sourceUrl: "https://a.example/post", sourceTitle: "A" }));
({ draft } = addDraftFragment(draft, { text: "第三段", sourceUrl: "https://b.example/work", sourceTitle: "B" }));
- assert.equal(draft.version, 2);
+ draft = createCaptureDraft({
+ ...draft,
+ sourceContexts: [{
+ canonicalUrl: "https://a.example/post",
+ displayTitle: "作者甲 · 2026-08-13",
+ sourceFacts: { provider: "example", itemId: "work-1", author: "作者甲" }
+ }]
+ });
+ assert.equal(draft.version, 3);
assert.equal(draft.targetCaseId, "compound:target");
+ assert.equal(draft.sourceContexts[0].sourceFacts.author, "作者甲");
assert.deepEqual(draftParts(draft).map((part) => ({ url: part.sourceUrl, text: part.text })), [
{ url: "https://a.example/post", text: "第一段\n\n第二段" },
{ url: "https://b.example/work", text: "第三段" }
diff --git a/test/capture-permission-flow.test.js b/test/capture-permission-flow.test.js
index 06d078a..748a436 100644
--- a/test/capture-permission-flow.test.js
+++ b/test/capture-permission-flow.test.js
@@ -7,7 +7,7 @@ import {
CONTINUOUS_CAPTURE_ORIGINS,
ensureClipboardReadPermission,
hasClipboardReadPermission,
- readClipboardTextAfterFocus,
+ readClipboardContentAfterFocus,
ensureContinuousCapturePermission,
ensurePagePermission,
pagePermissionPattern
@@ -42,16 +42,22 @@ test("explicit clipboard extraction uses one optional permission with a recovera
]);
});
-test("clipboard reading waits for focus stability and retries one transient post-permission failure", async () => {
+test("clipboard reading returns copied text and the first supported image after focus recovery", async () => {
const calls = [];
let reads = 0;
- const text = await readClipboardTextAfterFocus({
+ const copiedImage = new Blob(["image-bytes"], { type: "image/png" });
+ const content = await readClipboardContentAfterFocus({
clipboardApi: {
- readText: async () => {
+ read: async () => {
reads += 1;
calls.push(`read-${reads}`);
if (reads === 1) throw new DOMException("Document is not focused", "NotAllowedError");
- return "已复制的提示词";
+ return [{
+ types: ["text/plain", "image/png"],
+ getType: async (type) => type === "image/png"
+ ? copiedImage
+ : new Blob(["已复制的提示词"], { type: "text/plain" })
+ }];
}
},
documentObject: { hasFocus: () => true },
@@ -63,7 +69,8 @@ test("clipboard reading waits for focus stability and retries one transient post
}
});
- assert.equal(text, "已复制的提示词");
+ assert.equal(content.text, "已复制的提示词");
+ assert.equal(content.image, copiedImage);
assert.deepEqual(calls, ["frame", "frame", "read-1", "frame", "frame", "read-2"]);
});
@@ -212,6 +219,14 @@ test("text capture resolves the active page before requesting only that page per
]);
});
+test("page capture requests the active site permission before starting background extraction", async () => {
+ const source = await readFile(new URL("collector.js", projectRoot), "utf8");
+ const start = source.indexOf("async function startPageCapture");
+ const end = source.indexOf("async function savePageCapture", start);
+ const flow = source.slice(start, end);
+ assert.ok(flow.indexOf("ensurePagePermission(tab.url") < flow.indexOf('type: "START_PAGE_CAPTURE"'));
+});
+
test("creative result capture and commit use one background transaction", async () => {
const messages = [];
const capturedDraft = { id: "captured", visuals: [{ id: "visual-1" }] };
diff --git a/test/capture-runtime-wiring.test.js b/test/capture-runtime-wiring.test.js
index 03b92c2..fb8b24d 100644
--- a/test/capture-runtime-wiring.test.js
+++ b/test/capture-runtime-wiring.test.js
@@ -53,3 +53,12 @@ test("creative result capture and metadata commit cross both queues as one trans
assert.match(transaction, /await enqueue\(\(\) => commitCreativeOutputsTransaction\(\)\)/);
assert.ok(transaction.indexOf("dispatchCaptureMessage") < transaction.indexOf("commitCreativeOutputsTransaction"));
});
+
+test("a text-bearing captured post is classified from its text instead of its video attachment", async () => {
+ const source = await readFile(new URL("../background.js", import.meta.url), "utf8");
+ const start = source.indexOf("async function commitPageCapture");
+ const end = source.indexOf("async function", start + 20);
+ const save = source.slice(start, end);
+ assert.match(save, /candidate\.sourceFacts\.pageType === "post" && base\.text/);
+ assert.match(save, /classificationMediaAssets/);
+});
diff --git a/test/capture-workspace.test.js b/test/capture-workspace.test.js
index 5344a55..66e71f7 100644
--- a/test/capture-workspace.test.js
+++ b/test/capture-workspace.test.js
@@ -61,6 +61,30 @@ test("automatic text capture reads only the active highlight", async () => {
assert.equal(result.draft.fragments[0].sourceUrl, "https://example.com/");
});
+test("Jimeng highlight and smart visual capture reuse resolved work identity instead of the tab title", async () => {
+ const stored = {};
+ const sourceContext = {
+ canonicalUrl: "https://jimeng.jianying.com/ai-tool/work-detail/7490123456789012345",
+ displayTitle: "AIGC大叔 · 2026-05-30",
+ sourceFacts: { provider: "jimeng", itemId: "7490123456789012345", author: "AIGC大叔", model: "即梦 4.7" }
+ };
+ const chromeApi = fakeChrome(stored, {
+ query: async () => [{ id: 7, windowId: 3, url: sourceContext.canonicalUrl, title: "即梦AI - 一站式AI创作平台" }],
+ executeScript: async () => [{ result: "网页高亮文字" }]
+ });
+ const workspace = createCaptureWorkspace({
+ chromeApi, captureDraftStorageKey: "captureDraft",
+ ensureOffscreenDocument: async () => undefined, deleteVisual: async () => undefined,
+ resolveSourceContext: async () => sourceContext
+ });
+
+ const result = await workspace.dispatch("try-active-selection");
+
+ assert.equal(result.draft.title, "AIGC大叔 · 2026-05-30");
+ assert.equal(result.draft.fragments[0].sourceTitle, "AIGC大叔 · 2026-05-30");
+ assert.equal(result.draft.sourceContexts[0].sourceFacts.author, "AIGC大叔");
+});
+
test("automatic text capture stays empty when there is no highlight", async () => {
const stored = {};
const chromeApi = fakeChrome(stored, {
@@ -202,6 +226,11 @@ test("smart visual capture verifies the active page, restores it, and persists t
captureClipboardFingerprintStorageKey: "lastCommittedClipboardFingerprint",
ensureOffscreenDocument: async () => calls.push("ensure-offscreen"),
deleteVisual: async () => calls.push("delete"),
+ resolveSourceContext: async () => ({
+ canonicalUrl: "https://example.com/",
+ displayTitle: "作者甲 · 2026-08-13",
+ sourceFacts: { provider: "example", itemId: "work-1", author: "作者甲" }
+ }),
createId: () => "visual-1",
now: () => "2026-07-28T10:00:00.000Z"
});
@@ -211,6 +240,8 @@ test("smart visual capture verifies the active page, restores it, and persists t
assert.equal(result.ok, true);
assert.equal(result.draft.visuals[0].id, "visual-1");
assert.equal(result.draft.visuals[0].capturedAt, "2026-07-28T10:00:00.000Z");
+ assert.equal(result.draft.visuals[0].sourceTitle, "作者甲 · 2026-08-13");
+ assert.equal(result.draft.sourceContexts[0].sourceFacts.author, "作者甲");
assert.deepEqual(calls, [
"active-tab",
"select-visual",
@@ -223,6 +254,54 @@ test("smart visual capture verifies the active page, restores it, and persists t
assert.equal(stored.captureDraft.visuals.length, 1);
});
+test("region capture keeps its existing steps while attaching resolved work identity", async () => {
+ const stored = {};
+ let executeCount = 0;
+ const chromeApi = fakeChrome(stored, {
+ executeScript: async () => {
+ executeCount += 1;
+ if (executeCount === 1) {
+ return [{ result: {
+ captureToken: "region-token",
+ x: 10, y: 20, width: 640, height: 480,
+ viewportWidth: 1200, viewportHeight: 800
+ } }];
+ }
+ return [{ result: true }];
+ },
+ captureVisibleTab: async () => "data:image/png;base64,AA==",
+ sendMessage: async () => ({
+ ok: true,
+ width: 640,
+ height: 480,
+ mimeType: "image/webp",
+ byteSize: 1234,
+ palette: { colors: [] }
+ })
+ });
+ const workspace = createCaptureWorkspace({
+ chromeApi,
+ captureDraftStorageKey: "captureDraft",
+ ensureOffscreenDocument: async () => undefined,
+ deleteVisual: async () => undefined,
+ resolveSourceContext: async () => ({
+ canonicalUrl: "https://example.com/",
+ displayTitle: "作者乙 · 2026-08-13",
+ sourceFacts: { provider: "example", itemId: "work-2", author: "作者乙" }
+ }),
+ createId: () => "region-visual",
+ now: () => "2026-08-13T00:00:00.000Z"
+ });
+
+ const result = await workspace.dispatch("capture-tab", {
+ tab: { id: 7, windowId: 3, url: "https://example.com/", title: "Generic site title" }
+ });
+
+ assert.equal(result.ok, true);
+ assert.equal(result.draft.visuals[0].sourceTitle, "作者乙 · 2026-08-13");
+ assert.equal(result.draft.sourceContexts[0].sourceFacts.itemId, "work-2");
+});
+
test("failed smart visual storage removes every partial visual and leaves the draft unchanged", async () => {
const stored = {};
const deleted = [];
diff --git a/test/clipboard_capture_e2e.py b/test/clipboard_capture_e2e.py
index d731bf2..f770118 100644
--- a/test/clipboard_capture_e2e.py
+++ b/test/clipboard_capture_e2e.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import re
+
from playwright.sync_api import expect
from e2e_support import extension_session
@@ -11,7 +13,7 @@ def main() -> None:
viewport={"width": 390, "height": 844},
) as session:
session.context.add_init_script(
- """window.__promptDirectorClipboardText = '第一段剪贴板文字';
+ """window.__promptDirectorClipboardMode = 'image';
window.__promptDirectorClipboardReads = 0;
if (globalThis.chrome?.permissions) {
const originalContains = chrome.permissions.contains.bind(chrome.permissions);
@@ -34,7 +36,7 @@ def main() -> None:
Object.defineProperty(chrome.tabs, 'query', {
configurable: true,
value: async query => query?.active
- ? [{id: 999, url: 'https://example.com/article', title: '示例网页'}]
+ ? [{id: 999, url: 'chrome://extensions/', title: '扩展程序'}]
: originalQuery(query)
});
}
@@ -49,9 +51,17 @@ def main() -> None:
}
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
- value: {readText: async () => {
+ value: {read: async () => {
window.__promptDirectorClipboardReads += 1;
- return window.__promptDirectorClipboardText;
+ if (window.__promptDirectorClipboardMode === 'image') {
+ const bytes = Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='), value => value.charCodeAt(0));
+ const image = new Blob([bytes], {type: 'image/png'});
+ return [{types: ['image/png'], getType: async () => image}];
+ }
+ return [{
+ types: ['text/plain'],
+ getType: async () => new Blob(['第一段剪贴板文字'], {type: 'text/plain'})
+ }];
}}
});"""
)
@@ -61,26 +71,48 @@ def main() -> None:
collector.locator("#start-selection").click()
expect(collector.locator("#preview-state")).to_be_visible()
- expect(collector.locator("#quick-preview")).to_contain_text("第一段剪贴板文字")
+ expect(collector.locator("#content-summary")).to_have_text("1 张图片")
+ expect(collector.locator("#quick-preview .quick-visuals img")).to_have_count(1)
+ expect(collector.locator("#quick-preview .quick-visuals img")).to_have_attribute("src", re.compile(r"^blob:"))
assert collector.evaluate("window.__promptDirectorClipboardReads") == 1
+ collector.get_by_role("button", name="删除第 1 张图片").click()
+ expect(collector.locator("#start-state")).to_be_visible()
+ cleared_image_draft = collector.evaluate("() => chrome.runtime.sendMessage({type: 'GET_CAPTURE_WORKSPACE'}).then(result => result.draft)")
+ assert cleared_image_draft["visuals"] == [], cleared_image_draft
+
+ collector.locator("#start-selection").click()
+ expect(collector.locator("#preview-state")).to_be_visible()
+ expect(collector.locator("#content-summary")).to_have_text("1 张图片")
+ assert collector.evaluate("window.__promptDirectorClipboardReads") == 2
+
collector.locator("#save-draft").click()
expect(collector.locator("#start-state")).to_be_visible()
+ saved = collector.evaluate("() => chrome.runtime.sendMessage({type: 'GET_STATE'}).then(result => result.entries)")
+ assert len(saved) == 1 and len(saved[0]["mediaAssets"]) == 1, saved
collector.evaluate("window.dispatchEvent(new Event('focus'))")
collector.wait_for_timeout(250)
expect(collector.locator("#preview-state")).to_be_hidden()
- assert collector.evaluate("window.__promptDirectorClipboardReads") == 1
+ assert collector.evaluate("window.__promptDirectorClipboardReads") == 2
+ collector.evaluate("window.__promptDirectorClipboardMode = 'text'")
collector.locator("#start-selection").click()
expect(collector.locator("#preview-state")).to_be_visible()
expect(collector.locator("#quick-preview")).to_contain_text("第一段剪贴板文字")
- assert collector.evaluate("window.__promptDirectorClipboardReads") == 2
+ assert collector.evaluate("window.__promptDirectorClipboardReads") == 3
+
+ collector.get_by_role("button", name="删除第 1 段文字").click()
+ expect(collector.locator("#start-state")).to_be_visible()
+ cleared_text_draft = collector.evaluate("() => chrome.runtime.sendMessage({type: 'GET_CAPTURE_WORKSPACE'}).then(result => result.draft)")
+ assert cleared_text_draft["fragments"] == [], cleared_text_draft
print({
"automatic_clipboard_reads": 0,
- "explicit_clipboard_reads": 2,
+ "explicit_clipboard_reads": 3,
+ "copied_image_imported": True,
"saved_clipboard_can_be_extracted_again": True,
+ "single_item_removal": True,
"mobile_sidebar": True,
})
diff --git a/test/collector-view.test.js b/test/collector-view.test.js
index b676720..3ed0a30 100644
--- a/test/collector-view.test.js
+++ b/test/collector-view.test.js
@@ -40,6 +40,95 @@ test("one captured item stays in quick preview until the user asks to edit it",
assert.equal(editing.showOrganizer, true);
});
+test("quick preview exposes one-step removal for every captured text and image", async () => {
+ const collectorSource = await readFile(new URL("../collector.js", import.meta.url), "utf8");
+ const quickPreview = collectorSource.slice(
+ collectorSource.indexOf("function createQuickPreview"),
+ collectorSource.indexOf("function createFragmentCard")
+ );
+
+ assert.match(collectorSource, /import \{ createUiIcon \} from "\.\/ui-icons\.js"/);
+ assert.match(quickPreview, /draft\.fragments\.forEach/);
+ assert.match(quickPreview, /REMOVE_CAPTURE_FRAGMENT/);
+ assert.match(quickPreview, /删除第 \$\{index \+ 1\} 段文字/);
+ assert.match(quickPreview, /draft\.visuals\.forEach/);
+ assert.match(quickPreview, /REMOVE_CAPTURE_VISUAL/);
+ assert.match(quickPreview, /删除第 \$\{index \+ 1\} 张图片/);
+ assert.match(quickPreview, /createUiIcon\("x"\)/);
+ assert.match(collectorSource, /URL\.revokeObjectURL\(removedVisualUrl\)/);
+ assert.match(collectorSource, /visualUrls\.delete\(payload\.visualId\)/);
+});
+
+test("page capture replaces failed remote thumbnails with an explicit unavailable preview", async () => {
+ const collectorSource = await readFile(new URL("../collector.js", import.meta.url), "utf8");
+ const pageCaptureRenderer = collectorSource.slice(
+ collectorSource.indexOf("function renderPageCapture"),
+ collectorSource.indexOf("function updatePageCaptureSelection")
+ );
+ assert.match(pageCaptureRenderer, /media\.previewDataUrl \|\| media\.dataUrl \|\| media\.url/);
+ assert.match(pageCaptureRenderer, /image\.addEventListener\("error"/);
+ assert.match(pageCaptureRenderer, /preview\.replaceChildren\(textNode\("span", t\("预览不可用"\)\)\)/);
+ assert.match(pageCaptureRenderer, /pageCaptureMediaSourceLabel\(media\.sourceKind, media\.captureMethod\)/);
+ const collectorHtml = await readFile(new URL("../collector.html", import.meta.url), "utf8");
+ assert.match(collectorHtml, /公开原图失败时,只会使用当前网页已有登录状态读取已确认主体内的相关媒体;不会读取或保存登录信息。/);
+});
+
+test("page capture uses the final save as media authorization and keeps uncertain media separate", async () => {
+ const [collectorSource, collectorHtml, backgroundSource] = await Promise.all([
+ readFile(new URL("../collector.js", import.meta.url), "utf8"),
+ readFile(new URL("../collector.html", import.meta.url), "utf8"),
+ readFile(new URL("../background.js", import.meta.url), "utf8")
+ ]);
+ const pageCaptureRenderer = collectorSource.slice(
+ collectorSource.indexOf("function renderPageCapture"),
+ collectorSource.indexOf("function pageCaptureExtractionLabel")
+ );
+ assert.match(pageCaptureRenderer, /confirmPageCaptureCandidate/);
+ assert.match(pageCaptureRenderer, /selectedTextBlockIds: candidate\.textBlocks\.map/);
+ assert.match(pageCaptureRenderer, /pageCaptureDefaultMediaIds\(candidate\)/);
+ assert.match(pageCaptureRenderer, /mediaDecision: "pending"/);
+ assert.match(pageCaptureRenderer, /finalizePageCaptureSelectionsForSave/);
+ assert.match(pageCaptureRenderer, /t\("保存案例 · 含 \{count\} 项媒体"/);
+ assert.match(pageCaptureRenderer, /可能遗漏媒体/);
+ assert.match(pageCaptureRenderer, /batchStructureStatus === "review"/);
+ assert.match(pageCaptureRenderer, /updatePageCaptureMediaSelection/);
+ assert.match(pageCaptureRenderer, /openPageCaptureMediaViewer/);
+ assert.match(pageCaptureRenderer, /possibleOmissions/);
+ assert.match(collectorHtml, /id="page-capture-media-review"/);
+ assert.doesNotMatch(collectorHtml, /id="page-capture-confirm-media"/);
+ assert.match(collectorHtml, /id="page-capture-save-text-only"/);
+ assert.match(collectorHtml, /id="page-capture-media-viewer"/);
+ assert.match(collectorHtml, /id="page-capture-media-stage"/);
+ assert.doesNotMatch(collectorHtml, /page-capture-select-text|page-capture-select-images/);
+ assert.match(backgroundSource, /case "PREVIEW_PAGE_CAPTURE_REGION"/);
+ assert.match(backgroundSource, /previewPageCaptureRegion/);
+});
+
+test("page capture can correct the confirmed DOM region and previews one ordered article", async () => {
+ const [collectorSource, collectorHtml, backgroundSource, librarySource] = await Promise.all([
+ readFile(new URL("../collector.js", import.meta.url), "utf8"),
+ readFile(new URL("../collector.html", import.meta.url), "utf8"),
+ readFile(new URL("../background.js", import.meta.url), "utf8"),
+ readFile(new URL("../library.js", import.meta.url), "utf8")
+ ]);
+ assert.match(collectorHtml, /id="page-capture-add-region"/);
+ assert.match(collectorHtml, /id="page-capture-exclude-region"/);
+ assert.match(collectorHtml, /id="page-capture-undo-region"/);
+ assert.match(collectorHtml, /id="page-capture-reset-region"/);
+ assert.match(collectorSource, /createPageCaptureArticlePreview/);
+ assert.match(collectorSource, /EDIT_PAGE_CAPTURE_REGION/);
+ assert.match(backgroundSource, /runPageCaptureRegionEditor/);
+ assert.match(backgroundSource, /contentTargetsValue/);
+ assert.match(backgroundSource, /整组选择/);
+ assert.match(backgroundSource, /data-promptdirector-page-edit-include/);
+ assert.match(backgroundSource, /data-promptdirector-page-edit-exclude/);
+ assert.match(backgroundSource, /data-promptdirector-page-edit-hover/);
+ assert.match(backgroundSource, /case "CLEAR_PAGE_CAPTURE_MARKERS"/);
+ assert.match(backgroundSource, /clearPageCapturePageState/);
+ assert.match(collectorSource, /await clearPageCaptureMarkers\(\)/);
+ assert.match(librarySource, /createArticleDocumentReader/);
+});
+
test("multi-page material reveals only the controls that have something to organize", () => {
const view = collectorViewState({
fragments: [
@@ -77,22 +166,24 @@ test("the collector auto-reads only highlights and reserves clipboard access for
]);
assert.match(collectorSource, /TRY_ACTIVE_SELECTION_TO_DRAFT/);
- assert.match(collectorSource, /ADD_CLIPBOARD_TEXT_TO_DRAFT/);
+ assert.match(collectorSource, /readClipboardContentAfterFocus/);
assert.match(collectorSource, /window\.addEventListener\("focus", \(\) => void tryAutoSelection\(\)\)/);
- const autoFlow = collectorSource.slice(collectorSource.indexOf("async function tryAutoSelection"), collectorSource.indexOf("async function extractText"));
- assert.doesNotMatch(autoFlow, /clipboard|readClipboardTextAfterFocus|ensureClipboardReadPermission/);
- const explicitFlow = collectorSource.slice(collectorSource.indexOf("async function extractText"), collectorSource.indexOf("function render"));
+ const autoFlow = collectorSource.slice(collectorSource.indexOf("async function tryAutoSelection"), collectorSource.indexOf("async function extractClipboardOrSelection"));
+ assert.doesNotMatch(autoFlow, /clipboard|readClipboardContentAfterFocus|ensureClipboardReadPermission/);
+ const explicitFlow = collectorSource.slice(collectorSource.indexOf("async function extractClipboardOrSelection"), collectorSource.indexOf("function render"));
assert.match(explicitFlow, /ADD_ACTIVE_SELECTION_TO_DRAFT/);
assert.match(explicitFlow, /ensureClipboardReadPermission/);
- assert.match(explicitFlow, /readClipboardTextAfterFocus/);
+ assert.match(explicitFlow, /readClipboardContentAfterFocus/);
+ assert.match(explicitFlow, /prepareLocalMedia/);
+ assert.match(explicitFlow, /saveScreenshotBlob/);
assert.match(collectorSource, /CAPTURE_VISIBLE_VISUALS_TO_DRAFT/);
assert.match(collectorSource, /contentTypeExplicit: true/);
assert.match(collectorSource, /customLabelsExplicit: true/);
assert.match(backgroundSource, /case "TRY_ACTIVE_SELECTION_TO_DRAFT"/);
assert.match(backgroundSource, /case "ADD_CLIPBOARD_TEXT_TO_DRAFT"/);
assert.doesNotMatch(backgroundSource, /lastCommittedClipboardFingerprint/);
- assert.match(collectorHtml, /id="start-selection"[^>]*>[\s\S]*?<strong[^>]*>提取文字<\/strong>/);
- assert.match(collectorHtml, /id="add-selection"[^>]*>+ 提取文字<\/button>/);
+ assert.match(collectorHtml, /id="start-selection"[^>]*>[\s\S]*?<strong[^>]*>提取文字\/图片<\/strong>/);
+ assert.match(collectorHtml, /id="add-selection"[^>]*>[\s\S]*?提取文字\/图片<\/button>/);
assert.doesNotMatch(collectorHtml, /自动识别已复制文字|id="clipboard-access"|id="enable-clipboard"/);
assert.doesNotMatch(collectorSource, /querySelectorAll\("button"\)/);
assert.ok(collectorHtml.indexOf('id="start-smart-visuals"') < collectorHtml.indexOf('id="start-selection"'));
diff --git a/test/composer-page.test.js b/test/composer-page.test.js
index a00295c..eee46e6 100644
--- a/test/composer-page.test.js
+++ b/test/composer-page.test.js
@@ -33,6 +33,9 @@ test("composer combines cases and Skills in one reference workspace while keepin
assert.match(composerHtml, /id="composer-generation-settings"/);
assert.match(composerHtml, /id="composer-image-size"/);
assert.match(composerHtml, /id="composer-image-quality"/);
+ assert.match(composerHtml, />带原图生成(默认)</);
+ assert.match(composerHtml, />先读图整理提示词,生图不垫图</);
+ assert.match(composerHtml, />全程只用案例\/分析文字(不读图,最省 token)</);
assert.match(composerHtml, /id="composer-model-openai"/);
assert.match(composerHtml, /id="composer-model-compatible"/);
assert.doesNotMatch(libraryHtml, /id="vision-image-protocol"|id="vision-image-endpoint"|id="vision-image-api-key"/);
@@ -104,11 +107,29 @@ test("composer reference selection is visual while Skill management stays on its
assert.match(composerJs, /composerSession\.outputMode === "create_image"/);
assert.match(composerJs, /composerServiceCapabilities\(/);
assert.match(composerJs, /normalizeImageGenerationRequest\(/);
+ const generationSettings = composerJs.slice(
+ composerJs.indexOf("function renderImageGenerationSettings"),
+ composerJs.indexOf("async function updateComposerAiProfile")
+ );
+ assert.match(generationSettings, /generationParameterKey\(capability, \["size", "aspectRatio"\]\)/);
+ assert.match(generationSettings, /generationParameterKey\(capability, \["quality", "imageSize"\]\)/);
+ assert.match(generationSettings, /field\.dataset\.parameterKey = key/);
+ assert.match(generationSettings, /label\.textContent = t\(parameter\?\.label \|\| fallbackLabel\)/);
+ const updateGenerationParameters = composerJs.slice(
+ composerJs.indexOf("async function updateImageGenerationParameters"),
+ composerJs.indexOf("async function updateComposerPreferences")
+ );
+ assert.match(updateGenerationParameters, /\[elements\.composerImageSizeField\.dataset\.parameterKey \|\| "size"\]: elements\.composerImageSize\.value/);
+ assert.match(updateGenerationParameters, /\[elements\.composerImageQualityField\.dataset\.parameterKey \|\| "quality"\]: elements\.composerImageQuality\.value/);
+ assert.match(updateGenerationParameters, /videoTask[\s\S]*size: elements\.composerImageSize\.value,[\s\S]*duration: elements\.composerVideoDuration\.value/);
assert.match(composerJs, /previousReviewEnabled === elements\.composerProductionReview\.checked/);
assert.match(composerCss, /\.composer-review-toggle input\s*\{[^}]*position:\s*absolute[^}]*opacity:\s*0/s);
assert.match(composerCss, /\.composer-review-toggle input:focus-visible \+ span/);
assert.match(composerCss, /\.composer-review-toggle input:checked \+ span/);
assert.match(composerCss, /\.composer-reference-workspace\s*\{/);
+ assert.match(composerCss, /\.composer-reference-workspace\[data-mode="skills"\] \.composer-reference-body\s*\{[^}]*grid-template-columns:\s*minmax\(0,\s*1fr\)/s);
+ assert.doesNotMatch(composerCss, /data-mode="methods"/);
+ assert.match(composerCss, /\.composer-project-card p\s*\{[^}]*-webkit-line-clamp:\s*3/s);
assert.doesNotMatch(i18nJs, /querySelectorAll\("\[data-i18n-title\]"\).*\.title\s*=/);
});
diff --git a/test/composer-service.test.js b/test/composer-service.test.js
index d0c6ec3..ce15e57 100644
--- a/test/composer-service.test.js
+++ b/test/composer-service.test.js
@@ -83,6 +83,37 @@ function visualSettings(overrides = {}) {
};
}
+function geminiImageSettings(modelOverrides = {}) {
+ return visualSettings({
+ providerProfiles: {
+ gemini: {
+ id: "gemini",
+ label: "Google Gemini",
+ endpoint: "https://generativelanguage.googleapis.com",
+ protocol: "gemini",
+ apiKey: "gemini-secret-key",
+ consent: true,
+ capabilities: ["creativePlanning", "imageAnalysis", "imageGeneration"],
+ models: {
+ creativePlanning: "gemini-planning-model",
+ imageGeneration: "account-nano-banana-model"
+ },
+ discoveredModels: [{
+ id: "account-nano-banana-model",
+ tasks: ["imageGeneration"],
+ inputModalities: ["text", "image"],
+ outputModalities: ["image"],
+ supportedParameters: ["response_format", "aspect_ratio", "image_size"],
+ supportedAspectRatios: ["1:1", "16:9"],
+ supportedResolutions: ["1K", "2K"],
+ referenceImages: { supported: true, maxItems: 3, source: "declared" },
+ ...modelOverrides
+ }]
+ }
+ }
+ });
+}
+
test("Micu planning uses lightweight JSON mode and sends high reasoning only when enabled", async () => {
const requests = [];
const fetchImpl = async (_url, options) => {
@@ -134,6 +165,75 @@ test("OpenAI Responses uses the same reasoning switch while unknown compatible s
assert.equal(Object.hasOwn(requests[1], "reasoning"), false);
});
+test("Kimi creative planning uses the assigned model without falling back to another provider", async () => {
+ const requests = [];
+ const kimiSettings = visualSettings({
+ providerProfiles: {
+ kimi: {
+ id: "kimi",
+ label: "Kimi",
+ endpoint: "https://api.moonshot.cn/v1/chat/completions",
+ protocol: "chat_completions",
+ apiKey: "kimi-secret",
+ consent: true,
+ capabilities: ["creativePlanning", "imageAnalysis", "videoAnalysis"],
+ models: { creativePlanning: "account-planning-model" },
+ discoveredModels: [{
+ id: "account-planning-model",
+ tasks: ["creativePlanning", "imageAnalysis", "videoAnalysis"]
+ }]
+ }
+ }
+ });
+ const session = createComposerSession({
+ aiProfile: { serviceId: "kimi", model: "account-planning-model" },
+ messages: [{ role: "user", type: "request", content: "整理创意方向" }]
+ });
+
+ const planned = await planComposerTurnWithService({
+ session, userMessage: "", composerSettings: settings
+ }, kimiSettings, {
+ fetchImpl: async (url, options) => {
+ requests.push({ url, headers: options.headers, body: JSON.parse(options.body) });
+ return response({
+ model: "account-planning-model",
+ choices: [{ message: { content: JSON.stringify({ route: "compose", status: "ready", instruction: "保留核心冲突" }) } }]
+ });
+ }
+ });
+
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].url, "https://api.moonshot.cn/v1/chat/completions");
+ assert.equal(requests[0].headers.Authorization, "Bearer kimi-secret");
+ assert.equal(requests[0].body.model, "account-planning-model");
+ assert.equal(planned.instruction, "保留核心冲突");
+});
+
+test("an assigned provider without creative-planning capability fails instead of using DeepSeek", async () => {
+ const providerSettings = visualSettings({
+ providerProfiles: {
+ kimi: {
+ id: "kimi",
+ label: "Kimi",
+ endpoint: "https://api.moonshot.cn/v1/chat/completions",
+ protocol: "chat_completions",
+ apiKey: "kimi-secret",
+ consent: true,
+ capabilities: ["videoAnalysis"],
+ models: {},
+ discoveredModels: [{ id: "video-only-model", tasks: ["videoAnalysis"] }]
+ }
+ }
+ });
+ const session = createComposerSession({ aiProfile: { serviceId: "kimi", model: "video-only-model" } });
+
+ await assert.rejects(() => planComposerTurnWithService({
+ session, userMessage: "", composerSettings: settings
+ }, providerSettings, {
+ fetchImpl: async () => { throw new Error("不应发起请求"); }
+ }), /未声明创作规划能力/);
+});
+
test("xAI is a real per-turn composer service and image generation uses its configured endpoints", async () => {
const xaiSettings = visualSettings({
xai: { apiKey: "xai-secret", textModel: "grok-text", imageModel: "grok-image", mediaConsent: true }
@@ -387,6 +487,191 @@ test("OpenAI create-image mode sends original images through the Responses image
assert.equal(result.finalPrompt, "参考1负责构图,参考2只负责风格");
});
+test("Gemini image capability comes only from the assigned model metadata", () => {
+ const values = geminiImageSettings().vision;
+ const profile = { serviceId: "gemini", model: "account-nano-banana-model" };
+ const capability = composerServiceCapabilities(profile, values).image;
+
+ assert.equal(capability.generate, true);
+ assert.deepEqual(capability.references, { supported: true, maxItems: 3, source: "declared" });
+ assert.deepEqual(capability.edit, { whole: true, local: false });
+ assert.deepEqual(capability.parameters.map((parameter) => [parameter.key, parameter.options.map((item) => item.value)]), [
+ ["aspectRatio", ["1:1", "16:9"]],
+ ["imageSize", ["1K", "2K"]]
+ ]);
+ assert.deepEqual(composerImageEditCapabilities(profile, values), { whole: true, local: false });
+});
+
+test("Gemini text-to-image uses one official Interactions request and keeps every final image block", async () => {
+ const calls = [];
+ const session = createComposerSession({
+ aiProfile: { serviceId: "gemini", model: "gemini-planning-model" },
+ generationAiProfile: { serviceId: "gemini", model: "account-nano-banana-model" },
+ outputMode: "create_image",
+ messages: [{ role: "user", type: "request", content: "创作一张电影感品牌海报" }]
+ });
+ session.generationParameters = { aspectRatio: "16:9", imageSize: "2K", quality: "high" };
+
+ const result = await executeComposerTurnWithService({
+ session, userMessage: "", composerSettings: settings, route: "compose", instruction: "电影感品牌海报,蓝灰色调"
+ }, geminiImageSettings(), [], {
+ fetchImpl: async (url, options) => {
+ calls.push({ url, headers: options.headers, body: JSON.parse(options.body) });
+ return response({
+ id: "interaction-one",
+ model: "account-nano-banana-model",
+ status: "completed",
+ output_image: { type: "image", mime_type: "image/jpeg", data: "d29ybGQ=" },
+ steps: [
+ { type: "thought", summary: [{ type: "image", mime_type: "image/png", data: "dGhvdWdodA==" }] },
+ { type: "model_output", content: [
+ { type: "text", text: "成品说明" },
+ { type: "image", mime_type: "image/png", data: "aGVsbG8=" },
+ { type: "image", mime_type: "image/jpeg", data: "d29ybGQ=" },
+ { type: "image", mime_type: "image/png", data: "%%%invalid%%%" }
+ ] }
+ ],
+ usage: { total_input_tokens: 12, total_output_tokens: 34, total_tokens: 51, total_thought_tokens: 5, total_cached_tokens: 2 }
+ });
+ }
+ });
+
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].url, "https://generativelanguage.googleapis.com/v1beta/interactions");
+ assert.equal(calls[0].headers["x-goog-api-key"], "gemini-secret-key");
+ assert.equal(Object.hasOwn(calls[0].headers, "Authorization"), false);
+ assert.equal(calls[0].body.model, "account-nano-banana-model");
+ assert.deepEqual(calls[0].body.input, "电影感品牌海报,蓝灰色调");
+ assert.deepEqual(calls[0].body.response_format, { type: "image", aspect_ratio: "16:9", image_size: "2K" });
+ assert.equal(JSON.stringify(calls[0].body).includes("quality"), false);
+ assert.equal(result.images.length, 2);
+ assert.deepEqual(result.images.map((item) => item.blob.type), ["image/png", "image/jpeg"]);
+ assert.equal(result.requestModel, "account-nano-banana-model");
+ assert.equal(result.model, "account-nano-banana-model");
+ assert.equal(result.finalPrompt, "成品说明");
+ assert.deepEqual(result.usage, {
+ promptTokens: 12, completionTokens: 34, totalTokens: 51, cacheHitTokens: 2, cacheMissTokens: 10
+ });
+});
+
+test("Gemini image_size is not inferred from resolutions when the model does not declare that request parameter", async () => {
+ const values = geminiImageSettings({
+ supportedParameters: ["response_format", "aspect_ratio"],
+ supportedAspectRatios: ["1:1"],
+ supportedResolutions: ["1K"]
+ });
+ const session = createComposerSession({
+ aiProfile: { serviceId: "gemini", model: "gemini-planning-model" },
+ generationAiProfile: { serviceId: "gemini", model: "account-nano-banana-model" },
+ outputMode: "create_image",
+ generationParameters: { aspectRatio: "1:1", imageSize: "1K" },
+ messages: [{ role: "user", type: "request", content: "生成图片" }]
+ });
+ const capability = composerServiceCapabilities(session.generationAiProfile, values.vision).image;
+ assert.deepEqual(capability.parameters.map((parameter) => parameter.key), ["aspectRatio"]);
+ let body;
+ await executeComposerTurnWithService({
+ session, userMessage: "", composerSettings: settings, route: "compose", instruction: "生成图片"
+ }, values, [], {
+ fetchImpl: async (_url, options) => {
+ body = JSON.parse(options.body);
+ return response({ steps: [{ type: "model_output", content: [{ type: "image", mime_type: "image/png", data: "aGVsbG8=" }] }] });
+ }
+ });
+ assert.deepEqual(body.response_format, { type: "image", aspect_ratio: "1:1" });
+ assert.equal(Object.hasOwn(body.response_format, "image_size"), false);
+});
+
+test("Gemini conditioned generation sends raw multi-image blocks and enforces the declared limit before charging", async () => {
+ const session = referenceSession("gemini", "create_image");
+ session.aiProfile = { serviceId: "gemini", model: "gemini-planning-model", thinking: false };
+ session.generationAiProfile = { serviceId: "gemini", model: "account-nano-banana-model", thinking: false };
+ const calls = [];
+ const result = await executeComposerTurnWithService({
+ session, userMessage: "", composerSettings: settings, route: "compose", instruction: "严格保持三张参考图各自职责"
+ }, geminiImageSettings(), preparedImages, {
+ fetchImpl: async (url, options) => {
+ calls.push({ url, body: JSON.parse(options.body) });
+ return response({ steps: [{ type: "model_output", content: [{ type: "image", mime_type: "image/png", data: "aGVsbG8=" }] }] });
+ }
+ });
+
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].body.input.filter((item) => item.type === "image").length, 3);
+ assert.deepEqual(calls[0].body.input.filter((item) => item.type === "image").map((item) => [item.mime_type, item.data]), [
+ ["image/png", "AAAA"], ["image/png", "BBBB"], ["image/jpeg", "CCCC"]
+ ]);
+ assert.equal(calls[0].body.input.some((item) => item.type === "text" && item.text === "@参考1/图片1"), true);
+ assert.equal(result.images.length, 1);
+
+ const limited = geminiImageSettings({ referenceImages: { supported: true, maxItems: 2, source: "declared" } });
+ let paidCalls = 0;
+ await assert.rejects(() => executeComposerTurnWithService({
+ session, userMessage: "", composerSettings: settings, route: "compose", instruction: "保持三张参考"
+ }, limited, preparedImages, {
+ fetchImpl: async () => { paidCalls += 1; throw new Error("不应调用"); }
+ }), (error) => error.kind === "reference_limit" && error.referenceLimit?.maximum === 2);
+ assert.equal(paidCalls, 0);
+});
+
+test("Gemini local mask edits and failed image responses never trigger a paid retry", async () => {
+ const session = createComposerSession({
+ aiProfile: { serviceId: "gemini", model: "gemini-planning-model" },
+ generationAiProfile: { serviceId: "gemini", model: "account-nano-banana-model" },
+ outputMode: "create_image",
+ messages: [{ role: "user", type: "request", content: "修改图片" }]
+ });
+ const localEdit = {
+ mode: "local",
+ modification: "只修改衣服",
+ baseImage: { visualId: "base", dataUrl: "data:image/png;base64,AAAA" },
+ mask: { dataUrl: "data:image/png;base64,BBBB" }
+ };
+ let calls = 0;
+ await assert.rejects(() => executeComposerTurnWithService({
+ session, userMessage: "", composerSettings: settings, route: "compose", instruction: "只修改衣服", imageEdit: localEdit
+ }, geminiImageSettings(), [], {
+ fetchImpl: async () => { calls += 1; throw new Error("不应调用"); }
+ }), /Gemini.*局部遮罩编辑/);
+ assert.equal(calls, 0);
+
+ const unassigned = createComposerSession({
+ aiProfile: { serviceId: "gemini", model: "gemini-planning-model" },
+ generationAiProfile: { serviceId: "gemini", model: "" },
+ outputMode: "create_image",
+ messages: [{ role: "user", type: "request", content: "生成图片" }]
+ });
+ await assert.rejects(() => executeComposerTurnWithService({
+ session: unassigned, userMessage: "", composerSettings: settings, route: "compose", instruction: "生成图片"
+ }, geminiImageSettings(), [], {
+ fetchImpl: async () => { calls += 1; throw new Error("不应调用"); }
+ }), /API Key 和所选模型配置/);
+ assert.equal(calls, 0);
+
+ const httpError = await executeComposerTurnWithService({
+ session, userMessage: "", composerSettings: settings, route: "compose", instruction: "生成图片"
+ }, geminiImageSettings(), [], {
+ fetchImpl: async () => {
+ calls += 1;
+ return { ok: false, status: 403, json: async () => ({ error: { message: "key gemini-secret-key has no billing" } }) };
+ }
+ }).then(() => null, (error) => error);
+ assert.equal(calls, 1);
+ assert.equal(httpError.status, 403);
+ assert.match(httpError.message, /请求失败/);
+ assert.equal(httpError.message.includes("gemini-secret-key"), false);
+
+ calls = 0;
+ const noImage = await executeComposerTurnWithService({
+ session, userMessage: "", composerSettings: settings, route: "compose", instruction: "生成图片"
+ }, geminiImageSettings(), [], {
+ fetchImpl: async () => { calls += 1; return response({ status: "completed", steps: [{ type: "model_output", content: [{ type: "text", text: "无法生成" }] }] }); }
+ }).then(() => null, (error) => error);
+ assert.equal(calls, 1);
+ assert.equal(noImage.retryable, false);
+ assert.match(noImage.message, /没有返回有效图片/);
+});
+
test("prompt-only mode lets prompt assembly see originals but sends zero originals to the final OpenAI image request", async () => {
const requests = [];
const session = referenceSessionWithMode("openai", "prompt_only");
@@ -441,6 +726,43 @@ test("text-only mode sends zero originals to prompt assembly and uses generation
assert.equal(calls[1].authorization, "Bearer image-secret");
});
+test("text-only mode uses an existing case prompt without requiring analysis or sending image payloads", async () => {
+ const calls = [];
+ const base = referenceSession("compatible", "create_image");
+ const session = createComposerSession({
+ ...base,
+ imageReferenceMode: "text_only",
+ referenceSnapshots: base.referenceSnapshots.map((reference) => ({
+ ...reference,
+ assets: reference.imageRefs.map((imageRef) => ({ assetId: imageRef.visualId }))
+ }))
+ });
+ assert.equal(session.imageReferenceMode, "text_only");
+
+ await executeComposerTurnWithService({
+ session,
+ userMessage: "",
+ composerSettings: settings,
+ route: "compose",
+ instruction: "直接使用案例提示词创建图片"
+ }, visualSettings(), [], {
+ stream: false,
+ fetchImpl: async (url, options) => {
+ const body = JSON.parse(options.body);
+ calls.push({ url, body });
+ return calls.length === 1
+ ? response({ output_text: "使用案例原提示词整理出的最终生图提示词。" })
+ : response({ data: [{ b64_json: "aGVsbG8=" }] });
+ }
+ });
+
+ assert.equal(calls.length, 2);
+ assert.equal(calls[0].url, "https://www.micuapi.ai/v1/responses");
+ assert.equal(JSON.stringify(calls[0].body).includes("input_image"), false);
+ assert.equal(JSON.stringify(calls[0].body).includes("三人构图"), true);
+ assert.equal(calls[1].url, "https://www.micuapi.ai/v1/images/generations");
+});
+
test("Micu assembles a prompt, then sends every selected original image to edits with the separate key", async () => {
const calls = [];
const session = referenceSession("compatible", "create_image");
diff --git a/test/composer.test.js b/test/composer.test.js
index fd5fcdb..3f9d112 100644
--- a/test/composer.test.js
+++ b/test/composer.test.js
@@ -66,9 +66,12 @@ test("composer AI profile keeps DeepSeek choices strict and accepts configured v
assert.deepEqual(normalizeComposerAiProfile({ model: "custom", thinking: "yes" }), DEFAULT_COMPOSER_AI_PROFILE);
assert.deepEqual(normalizeComposerAiProfile({ serviceId: "openai", model: "gpt-5-mini", thinking: true }), { serviceId: "openai", model: "gpt-5-mini", thinking: true });
assert.deepEqual(normalizeComposerAiProfile({ serviceId: "compatible", model: "vision-pro", thinking: true }), { serviceId: "compatible", model: "vision-pro", thinking: true });
- assert.deepEqual(createComposerSession({ generationParameters: { size: "1536x1024", quality: "high", secret: "drop" } }).generationParameters, {
+ assert.deepEqual(normalizeComposerAiProfile({ serviceId: "kimi", model: "account-planning-model" }), { serviceId: "kimi", model: "account-planning-model", thinking: false });
+ assert.deepEqual(createComposerSession({ generationParameters: { size: "1536x1024", quality: "high", aspectRatio: "16:9", imageSize: "2K", secret: "drop" } }).generationParameters, {
size: "1536x1024",
- quality: "high"
+ quality: "high",
+ aspectRatio: "16:9",
+ imageSize: "2K"
});
assert.deepEqual(createComposerSession({
targetType: "video",
@@ -236,7 +239,7 @@ test("multiple selected images from one case become independent reference snapsh
assert.deepEqual(references.map((item) => item.alias), ["@参考1", "@参考2"]);
});
-test("image reference modes default to conditioned and unlock text-only modes only for independently analyzed assets", () => {
+test("image reference modes default to conditioned and unlock text-only modes for prompt-backed or independently analyzed assets", () => {
const analyzedReference = {
entryId: "case-a",
alias: "@参考1",
@@ -262,16 +265,47 @@ test("image reference modes default to conditioned and unlock text-only modes on
imageReferenceMode: "text_only"
}).imageReferenceMode, "text_only");
+ const promptBackedReference = {
+ entryId: "case-with-prompt",
+ alias: "@参考1",
+ originalText: "雨夜石桥上的巨龙",
+ referenceText: "雨夜石桥上的巨龙",
+ imageRefs: [{ visualId: "prompt-image", mimeType: "image/webp" }],
+ assets: [{ assetId: "prompt-image" }]
+ };
+ assert.deepEqual(imageReferenceModeAvailability([promptBackedReference]), {
+ canDisableImages: true,
+ missingAssetIds: []
+ });
+ assert.equal(createComposerSession({
+ referenceSnapshots: [promptBackedReference],
+ imageReferenceMode: "text_only"
+ }).imageReferenceMode, "text_only");
+
const unavailable = imageReferenceModeAvailability([{
- ...analyzedReference,
+ entryId: "pure-image",
+ alias: "@参考1",
+ imageRefs: [{ visualId: "image-a", mimeType: "image/webp" }],
assets: [{ assetId: "image-a", analysisVersion: 1, reconstructionPrompt: "旧描述" }]
}]);
assert.equal(unavailable.canDisableImages, false);
assert.deepEqual(unavailable.missingAssetIds, ["image-a"]);
assert.equal(createComposerSession({
- referenceSnapshots: [{ ...analyzedReference, assets: [] }],
+ referenceSnapshots: [{ entryId: "pure-image", alias: "@参考1", imageRefs: [{ visualId: "image-a" }], assets: [] }],
imageReferenceMode: "text_only"
}).imageReferenceMode, "conditioned");
+
+ const mixed = imageReferenceModeAvailability([
+ promptBackedReference,
+ {
+ entryId: "another-pure-image",
+ alias: "@参考2",
+ imageRefs: [{ visualId: "image-b", mimeType: "image/webp" }],
+ assets: [{ assetId: "image-b" }]
+ }
+ ]);
+ assert.equal(mixed.canDisableImages, false);
+ assert.deepEqual(mixed.missingAssetIds, ["image-b"]);
});
test("a saved V2 analysis remains eligible for text-only mode when an older asset omitted its duplicate content hash", () => {
diff --git a/test/composer_generation_e2e.py b/test/composer_generation_e2e.py
index 6ca6056..f5ef24c 100644
--- a/test/composer_generation_e2e.py
+++ b/test/composer_generation_e2e.py
@@ -7,7 +7,7 @@ from threading import Event, Thread
from playwright.sync_api import expect
-from e2e_support import base_entry, extension_session
+from e2e_support import ai_configuration_fixture, base_entry, extension_session
GENERATED_PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
@@ -102,31 +102,47 @@ def main() -> None:
{
"schemaVersion": 24,
"entries": [entry, jimeng_character, retrieved_case, retrieved_guide],
- "aiSettings": {
- "activeProvider": "deepseek",
- "apiKey": "e2e-local-key",
- "consent": True,
- "analysisModel": "deepseek-v4-flash",
- },
- "visionSettings": {
- "activeProvider": "openai",
- "consent": True,
- "openai": {"apiKey": "openai-e2e-key", "model": "gpt-5-mini"},
- "compatible": {
- "protocol": "responses",
- "endpoint": f"{local_origin}/v1/responses",
- "apiKey": "micu-chat-e2e-key",
- "model": "gpt-5.4-mini",
- "imageGeneration": {
- "protocol": "images_generations",
- "endpoint": f"{local_origin}/v1/images/generations",
- "editsEndpoint": f"{local_origin}/v1/images/edits",
- "apiKey": "micu-image-e2e-key",
- "model": "gpt-image-2",
- "size": "1536x1024",
+ **ai_configuration_fixture(
+ providers={
+ "deepseek": {
+ "apiKey": "e2e-local-key",
+ "consent": True,
+ "models": {"creativePlanning": "deepseek-v4-flash"},
+ },
+ "openai": {
+ "apiKey": "openai-e2e-key",
+ "consent": True,
+ "models": {
+ "creativePlanning": "gpt-5-mini",
+ "imageAnalysis": "gpt-5-mini",
+ "imageGeneration": "gpt-5-mini",
+ },
+ },
+ "custom-media": {
+ "protocol": "responses",
+ "endpoint": f"{local_origin}/v1/responses",
+ "apiKey": "micu-chat-e2e-key",
+ "consent": True,
+ "models": {
+ "imageAnalysis": "gpt-5.4-mini",
+ "imageGeneration": "gpt-image-2",
+ },
+ "imageGeneration": {
+ "protocol": "images_generations",
+ "endpoint": f"{local_origin}/v1/images/generations",
+ "editsEndpoint": f"{local_origin}/v1/images/edits",
+ "apiKey": "micu-image-e2e-key",
+ "model": "gpt-image-2",
+ "size": "1536x1024",
+ },
},
},
- },
+ assignments={
+ "creativePlanning": {"providerId": "deepseek", "model": "deepseek-v4-flash"},
+ "imageAnalysis": {"providerId": "openai", "model": "gpt-5-mini"},
+ "imageGeneration": {"providerId": "openai", "model": "gpt-5-mini"},
+ },
+ ),
},
)
setup.evaluate(
@@ -468,6 +484,7 @@ def main() -> None:
composer.evaluate(
"""async (origin) => {
+ const {aiTaskAssignments} = await chrome.storage.local.get('aiTaskAssignments');
await chrome.runtime.sendMessage({
type: 'UPDATE_AI_PROVIDER_CONFIGURATION',
registry: {
@@ -491,6 +508,11 @@ def main() -> None:
}
}
}
+ },
+ assignments: {
+ ...aiTaskAssignments,
+ imageAnalysis: {providerId: 'custom-media', model: 'local-vision-test'},
+ imageGeneration: {providerId: 'custom-media', model: 'local-image-test'}
}
});
}""",
@@ -604,6 +626,46 @@ def main() -> None:
assert len(creative_runs) == 1
assert len(creative_runs[0]["outputs"]) == 1
+ CreativeServiceHandler.release_image.clear()
+ composer.evaluate(
+ """() => {
+ const nativeSendMessage = chrome.runtime.sendMessage.bind(chrome.runtime);
+ let releaseStaleRefresh;
+ let delayed = false;
+ window.__promptDirectorStaleRefreshCaptured = false;
+ window.__promptDirectorReleaseStaleRefresh = () => releaseStaleRefresh?.();
+ chrome.runtime.sendMessage = async (...args) => {
+ const response = await nativeSendMessage(...args);
+ const message = args[0];
+ const hasActiveJob = response?.creativeJobs?.items?.some(item => ['queued', 'running'].includes(item.status));
+ if (message?.type === 'GET_STATE' && hasActiveJob && !delayed) {
+ delayed = true;
+ window.__promptDirectorStaleRefreshCaptured = true;
+ await new Promise(resolve => { releaseStaleRefresh = resolve; });
+ }
+ return response;
+ };
+ }"""
+ )
+ composer.locator("#composer-instruction").fill("完成后立即恢复发送按钮")
+ composer.locator("#composer-action").click()
+ composer.wait_for_function("() => window.__promptDirectorStaleRefreshCaptured === true")
+ CreativeServiceHandler.release_image.set()
+ deadline = time.monotonic() + 10
+ completion_jobs = None
+ while time.monotonic() < deadline:
+ completion_jobs = composer.evaluate("() => chrome.storage.local.get('creativeJobs').then(value => value.creativeJobs)")
+ if completion_jobs and completion_jobs["items"][-1]["status"] == "completed":
+ break
+ composer.wait_for_timeout(100)
+ assert completion_jobs and completion_jobs["items"][-1]["status"] == "completed", completion_jobs
+ expect(composer.locator(".composer-result-card")).to_have_count(2)
+ expect(composer.locator("#composer-action")).to_have_attribute("data-state", "send")
+ composer.evaluate("() => window.__promptDirectorReleaseStaleRefresh()")
+ composer.wait_for_timeout(200)
+ expect(composer.locator("#composer-action")).to_have_attribute("data-state", "send")
+ expect(composer.locator("#composer-action")).to_have_attribute("aria-label", "发送")
+
CreativeServiceHandler.release_image.clear()
composer.locator("#composer-instruction").fill("启动图片任务后立即停止")
composer.locator("#composer-action").click()
diff --git a/test/composer_image_workspace_e2e.py b/test/composer_image_workspace_e2e.py
index 3b5ed92..470f521 100644
--- a/test/composer_image_workspace_e2e.py
+++ b/test/composer_image_workspace_e2e.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from playwright.sync_api import expect
-from e2e_support import base_entry, extension_session
+from e2e_support import ai_configuration_fixture, base_entry, extension_session
PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
@@ -40,6 +40,7 @@ def main() -> None:
"routeMode": "compose",
"outputMode": "create_image",
"aiProfile": {"serviceId": "openai", "model": "gpt-5-mini", "thinking": False},
+ "generationAiProfile": {"serviceId": "openai", "model": "gpt-5-mini", "thinking": False},
"referenceSnapshots": [reference_snapshot],
"messages": [
{"id": "user-one", "role": "user", "type": "request", "content": "生成三人焦点构图", "createdAt": "2026-08-07T00:00:00.000Z"},
@@ -85,10 +86,24 @@ def main() -> None:
"entries": [reference],
"composerSessions": [session_value],
"creativeRuns": [run_value],
- "visionSettings": {
- "consent": True,
- "openai": {"apiKey": "openai-e2e-key", "model": "gpt-5-mini"},
- },
+ **ai_configuration_fixture(
+ providers={
+ "openai": {
+ "apiKey": "openai-e2e-key",
+ "consent": True,
+ "models": {
+ "creativePlanning": "gpt-5-mini",
+ "imageAnalysis": "gpt-5-mini",
+ "imageGeneration": "gpt-5-mini",
+ },
+ },
+ },
+ assignments={
+ "creativePlanning": {"providerId": "openai", "model": "gpt-5-mini"},
+ "imageAnalysis": {"providerId": "openai", "model": "gpt-5-mini"},
+ "imageGeneration": {"providerId": "openai", "model": "gpt-5-mini"},
+ },
+ ),
})
setup.evaluate(
f"""async () => {{
diff --git a/test/composer_temp_references_e2e.py b/test/composer_temp_references_e2e.py
index b1b9e87..fbd9f81 100644
--- a/test/composer_temp_references_e2e.py
+++ b/test/composer_temp_references_e2e.py
@@ -5,7 +5,7 @@ import json
from playwright.sync_api import expect
-from e2e_support import extension_session
+from e2e_support import ai_configuration_fixture, extension_session
PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
@@ -34,17 +34,24 @@ def main() -> None:
run.seed_storage(setup, {
"schemaVersion": 24,
"composerSessions": [],
- "aiSettings": {
- "activeProvider": "deepseek",
- "apiKey": "deepseek-e2e-key",
- "consent": True,
- "analysisModel": "deepseek-v4-flash",
- },
- "visionSettings": {
- "activeProvider": "openai",
- "consent": True,
- "openai": {"apiKey": "openai-e2e-key", "model": "gpt-5-mini"},
- },
+ **ai_configuration_fixture(
+ providers={
+ "deepseek": {
+ "apiKey": "deepseek-e2e-key",
+ "consent": True,
+ "models": {"creativePlanning": "deepseek-v4-flash"},
+ },
+ "openai": {
+ "apiKey": "openai-e2e-key",
+ "consent": True,
+ "models": {"imageAnalysis": "gpt-5-mini"},
+ },
+ },
+ assignments={
+ "creativePlanning": {"providerId": "deepseek", "model": "deepseek-v4-flash"},
+ "imageAnalysis": {"providerId": "openai", "model": "gpt-5-mini"},
+ },
+ ),
})
vision_requests: list[dict] = []
composer_requests: list[dict] = []
diff --git a/test/copy-feedback-ui.test.js b/test/copy-feedback-ui.test.js
index bb778ff..eb6d380 100644
--- a/test/copy-feedback-ui.test.js
+++ b/test/copy-feedback-ui.test.js
@@ -6,8 +6,10 @@ const library = await readFile(new URL("../library.js", import.meta.url), "utf8"
const libraryHtml = await readFile(new URL("../library.html", import.meta.url), "utf8");
const composerHtml = await readFile(new URL("../composer.html", import.meta.url), "utf8");
const collectorHtml = await readFile(new URL("../collector.html", import.meta.url), "utf8");
+const collector = await readFile(new URL("../collector.js", import.meta.url), "utf8");
const i18n = await readFile(new URL("../i18n.js", import.meta.url), "utf8");
const styles = await readFile(new URL("../library.css", import.meta.url), "utf8");
+const foundation = await readFile(new URL("../ui-foundation.css", import.meta.url), "utf8");
const background = await readFile(new URL("../background.js", import.meta.url), "utf8");
const markdown = await readFile(new URL("../lib.js", import.meta.url), "utf8");
const preview = await readFile(new URL("../share-preview.js", import.meta.url), "utf8");
@@ -21,8 +23,9 @@ test("library clipboard actions show feedback on the clicked button", () => {
});
test("library feedback remains visible above the detail drawer", () => {
- assert.match(styles, /#feedback\s*\{[^}]*position:\s*fixed/s);
- assert.match(styles, /#feedback:empty\s*\{[^}]*display:\s*none/s);
+ assert.match(libraryHtml, /id="feedback"[^>]*class="ui-feedback-toast"/);
+ assert.match(foundation, /\.ui-feedback-toast\s*\{[^}]*position:\s*fixed/s);
+ assert.match(foundation, /\.ui-feedback-toast:empty\s*\{[^}]*display:\s*none/s);
});
test("library error feedback clears after a readable delay instead of staying forever", () => {
@@ -30,6 +33,13 @@ test("library error feedback clears after a readable delay instead of staying fo
assert.match(library, /isError \? ERROR_FEEDBACK_DURATION_MS : FEEDBACK_DURATION_MS/);
});
+test("collector capture notifications clear without leaving a permanent floating panel", () => {
+ assert.match(collector, /const FEEDBACK_DURATION_MS = 4000/);
+ assert.match(collector, /const ERROR_FEEDBACK_DURATION_MS = 8000/);
+ assert.match(collector, /error \? ERROR_FEEDBACK_DURATION_MS : FEEDBACK_DURATION_MS/);
+ assert.match(collector, /elements\.feedback\.textContent = ""/);
+});
+
test("routine save feedback does not explain that AI was unnecessary", () => {
const interfaceCopy = [library, libraryHtml, composerHtml, collectorHtml, i18n].join("\n");
assert.doesNotMatch(interfaceCopy, /不需要等待 AI|不请求 AI,不播放轮播动画|这里不会导入创作标签|不会产生人工确认任务|普通结果关联无需开启|应用前不会改变当前对话|只用于你自己的查找和整理/);
diff --git a/test/creative-skill-batching.test.js b/test/creative-skill-batching.test.js
index 9cc2100..18d948c 100644
--- a/test/creative-skill-batching.test.js
+++ b/test/creative-skill-batching.test.js
@@ -1,6 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { skillExtractionWorkload } from "../creative-skill-service.js";
+import { estimateSkillTokens, skillExtractionWorkload } from "../creative-skill-service.js";
test("Skill extraction partitions all source text without sampling or truncation", () => {
const sources = [
@@ -13,3 +13,13 @@ test("Skill extraction partitions all source text without sampling or truncation
const reconstructed = workload.batches.flat().map((source) => source.prompt + source.analysis).join("");
assert.equal(reconstructed, sources.map((source) => source.prompt + source.analysis).join(""));
});
+
+test("Skill preflight reports a transparent local token range", () => {
+ const estimate = estimateSkillTokens("人物构图 with cinematic light");
+ assert.equal(estimate.kind, "local-range");
+ assert.ok(estimate.min > 0);
+ assert.ok(estimate.max >= estimate.min);
+ const workload = skillExtractionWorkload({ goal: "构图", sources: [{ prompt: "主体清晰", analysis: "背景克制" }] });
+ assert.ok(workload.tokenEstimate.min > 0);
+ assert.ok(workload.tokenEstimate.max >= workload.tokenEstimate.min);
+});
diff --git a/test/creative_feedback_e2e.py b/test/creative_feedback_e2e.py
index 0cd6c39..d74230b 100644
--- a/test/creative_feedback_e2e.py
+++ b/test/creative_feedback_e2e.py
@@ -77,7 +77,7 @@ def main() -> None:
expect(collector.locator("#normal-start")).to_be_visible()
expect(collector.locator("#normal-start .start-copy")).to_have_count(0)
expect(collector.locator("#start-smart-visuals")).to_have_text("智能选图")
- expect(collector.locator("#start-selection")).to_have_text("提取文字")
+ expect(collector.locator("#start-selection")).to_have_text("提取文字/图片")
expect(collector.locator("#start-screenshot")).to_have_text("框选截图")
normal_geometry = collector.evaluate(
"""() => {
diff --git a/test/creative_skills_e2e.py b/test/creative_skills_e2e.py
index d6ac1b5..98a6f0a 100644
--- a/test/creative_skills_e2e.py
+++ b/test/creative_skills_e2e.py
@@ -14,6 +14,19 @@ from e2e_support import base_entry, extension_session, wait_for_download
def main() -> None:
first = base_entry("skill-source-a", "本地标题甲", "低饱和庭院,主体偏左,前景遮挡形成纵深。", "content:prompt:image")
second = base_entry("skill-source-b", "本地标题乙", "柔和逆光勾勒人物轮廓,背景保持克制。", "content:prompt:image", 1)
+ first["mediaAssets"] = [
+ {
+ "id": "skill-image-a1", "kind": "image", "usage": "content", "storageMode": "managed",
+ "mimeType": "image/png", "capturedAt": "2026-08-02T08:00:00.000Z", "reviewStatus": "verified",
+ "visionAnalysis": {"description": "默认选中的主体构图", "invalidated": False},
+ },
+ {
+ "id": "skill-image-a2", "kind": "image", "usage": "content", "storageMode": "managed",
+ "mimeType": "image/png", "capturedAt": "2026-08-02T08:00:01.000Z", "reviewStatus": "verified",
+ "visionAnalysis": {"description": "未选择素材绝不能发送", "invalidated": False},
+ },
+ ]
+ first["primaryMediaId"] = "skill-image-a1"
with tempfile.TemporaryDirectory(prefix="prompt-director-skill-fixture-") as fixture_dir, extension_session("prompt-director-skills-") as session:
fixture_root = Path(fixture_dir)
external_zip = fixture_root / "external-method.zip"
@@ -49,6 +62,18 @@ Run `scripts/helper.py` before applying the composition guidance.
"consent": True,
"analysisModel": "deepseek-v4-flash",
},
+ "aiProviderRegistry": {"providers": {
+ "deepseek": {
+ "endpoint": "https://api.deepseek.com/chat/completions", "protocol": "chat_completions",
+ "apiKey": "skill-e2e-key", "consent": True,
+ "models": {"textTags": "deepseek-v4-flash", "skillExtraction": "deepseek-v4-flash", "creativePlanning": "deepseek-v4-flash"},
+ },
+ "xai": {
+ "endpoint": "https://api.x.ai/v1", "protocol": "xai", "apiKey": "xai-e2e-key", "consent": True,
+ "models": {"skillExtraction": "grok-skill"},
+ },
+ }},
+ "aiTaskAssignments": {"skillExtraction": {"providerId": "deepseek", "model": "deepseek-v4-flash"}},
"uiPreferences": {"locale": "zh-CN", "theme": "light", "motion": "none"},
})
@@ -69,32 +94,75 @@ 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["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'}})")
+ assert overridden["runtimeDescriptor"]["providerLabel"] == "xAI"
+ assert overridden["runtimeDescriptor"]["model"] == "grok-skill"
+ assert overridden["aiSettings"]["compatible"]["model"] == "grok-skill"
skills.locator("#skill-create").click()
+ skills.locator("#skill-advanced").click()
+ expect(skills.locator("#skill-text-provider-menu summary")).to_contain_text("DeepSeek")
+ skills.locator("#skill-text-provider-menu summary").click()
+ expect(skills.locator("#skill-text-provider-menu .skill-option-panel")).to_contain_text("xAI")
+ skills.locator("#skill-text-provider-menu summary").click()
expect(skills.locator(".skill-case")).to_have_count(2)
expect(skills.locator("#skill-project-actions")).to_have_count(0)
+ expect(skills.locator("#skill-project-picker")).not_to_have_attribute("open", "")
+ skills.locator("#skill-project-picker > summary").click()
+ expect(skills.locator("#skill-project-filter")).to_contain_text("风格来源")
+ skills.locator("#skill-workspace-title").click()
+ expect(skills.locator("#skill-project-picker")).not_to_have_attribute("open", "")
+ skills.locator("#skill-project-picker > summary").click()
+ skills.locator("#skill-project-filter button", has_text="全部项目").click()
skills.locator("#skill-case-search").fill("标题甲")
expect(skills.locator(".skill-case")).to_have_count(1)
skills.locator("#skill-visible-select").click()
expect(skills.locator("#skill-selected-count")).to_have_text("1")
+ skills.locator(".skill-case-detail").click()
+ expect(skills.locator("#skill-source-inspector")).to_be_visible()
+ expect(skills.locator(".skill-source-asset")).to_have_count(2)
+ expect(skills.locator(".skill-source-asset input:checked")).to_have_count(1)
+ skills.screenshot(path="/tmp/promptdirector-skills-inspector-light.png")
+ skills.locator("#skill-source-clear").click()
+ expect(skills.locator("#skill-selected-count")).to_have_text("1")
+ skills.locator("#skill-source-cancel").click()
+ expect(skills.locator("#skill-selected-count")).to_have_text("1")
+ skills.locator(".skill-case-detail").click()
+ skills.locator("#skill-source-clear").click()
+ skills.locator("#skill-source-apply").click()
+ expect(skills.locator("#skill-selected-count")).to_have_text("0")
+ skills.locator("#skill-visible-select").click()
+ expect(skills.locator("#skill-selected-count")).to_have_text("1")
skills.locator("#skill-case-search").fill("")
expect(skills.locator(".skill-case")).to_have_count(2)
expect(skills.locator('.skill-case[data-selected="true"]')).to_have_count(1)
skills.locator("#skill-visible-select").click()
expect(skills.locator("#skill-selected-count")).to_have_text("2")
skills.locator("#skill-goal").fill("只提炼我喜欢的构图、色彩和人物光线")
+ skills.screenshot(path="/tmp/promptdirector-skills-create-light.png", full_page=True)
skills.locator("#skill-generate").click()
preflight = skills.locator("#promptdirector-app-dialog")
expect(preflight).to_be_visible()
expect(preflight).to_contain_text("案例与证据:2 项")
+ expect(preflight).to_contain_text("tokens")
expect(preflight).to_contain_text("预计请求:1 次")
preflight.get_by_role("button", name="开始提炼").click()
expect(skills.locator("#skill-draft-step")).to_be_visible()
expect(skills.locator("#skill-markdown")).to_have_value(re.compile("视觉组织方法"))
+ expect(skills.locator("#skill-run-panel")).to_be_visible()
+ expect(skills.locator("#skill-generation-status")).to_contain_text("草稿已生成")
+ expect(skills.locator("#skill-run-progress")).to_have_attribute("style", re.compile("100%"))
+ expect(skills.locator("#skill-run-log")).to_contain_text("文字提炼完成")
assert len(requests) == 1
sent = json.dumps(requests[0], ensure_ascii=False)
assert "本地标题甲" not in sent
assert "本地标题乙" not in sent
assert "fixture.invalid" not in sent
+ assert "默认选中的主体构图" in sent
+ assert "未选择素材绝不能发送" not in sent
assert "只提炼我喜欢的构图、色彩和人物光线" in sent
skills.locator("#skill-call-name").fill("国风视觉")
@@ -136,6 +204,10 @@ Run `scripts/helper.py` before applying the composition guidance.
assert len(session.context.pages) == page_count
composer = skills
expect(composer.locator(".composer-skill-chip")).to_contain_text("/国风视觉")
+ composer.locator("#composer-reference-open").click()
+ composer.locator(".composer-case-option", has_text="本地标题甲").locator(".composer-case-preview-checkbox").check()
+ composer.locator("#composer-reference-apply").click()
+ expect(composer.locator("#composer-reference-count")).to_have_text("1")
composer.locator("#composer-new").click()
composer.locator("#composer-instruction").fill("/国")
@@ -227,7 +299,7 @@ Run `scripts/helper.py` before applying the composition guidance.
};
}""")
assert card_layout["alignItems"] == "start", card_layout
- assert card_layout["lineClamp"] == "3", card_layout
+ assert card_layout["lineClamp"] == "2", card_layout
assert card_layout["verboseHeight"] < 220, card_layout
skills.locator(".skill-card", has_text="external-method").click()
expect(skills.locator("#skill-export")).to_have_count(1)
@@ -235,6 +307,36 @@ Run `scripts/helper.py` before applying the composition guidance.
skills.goto(composer_url, wait_until="domcontentloaded")
composer = skills
+ composer.set_viewport_size({"width": 1840, "height": 900})
+ composer.evaluate("""async () => chrome.storage.local.set({
+ uiPreferences: { locale: 'zh-CN', theme: 'dark', motion: 'none' }
+ })""")
+ composer.reload(wait_until="domcontentloaded")
+ 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)
+ 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')];
+ 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)),
+ 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 skill_workspace_layout["pageWidth"] <= skill_workspace_layout["viewportWidth"], skill_workspace_layout
+ composer.locator("#composer-reference-close").click()
composer.locator("#composer-instruction").fill("/external")
expect(composer.locator("#composer-skill-menu")).to_be_visible()
composer.locator("#composer-skill-menu button").first.click()
diff --git a/test/curated-catalog.test.js b/test/curated-catalog.test.js
index b632835..fba7473 100644
--- a/test/curated-catalog.test.js
+++ b/test/curated-catalog.test.js
@@ -5,10 +5,13 @@ import {
applyCuratedOrigin,
curatedSourceKey,
normalizeCuratedCatalog,
+ normalizeCuratedMetrics,
+ normalizeCuratedPreview,
prepareCuratedEntriesPackage,
prepareCuratedEntryPackage,
prepareCuratedPackageVersion,
- validateCuratedPackageContents
+ validateCuratedPackageContents,
+ validateCuratedPackageIndex
} from "../curated-catalog.js";
function catalogItem(overrides = {}) {
@@ -18,12 +21,15 @@ function catalogItem(overrides = {}) {
type: "image_prompt",
packageId: "cinematic-foundations",
packageVersion: "1.0.0",
+ authorId: "promptdirector-editorial",
author: "PromptDirector Editorial",
license: "CC BY 4.0",
updatedAt: "2026-07-29T00:00:00.000Z",
coverUrl: "https://wchao6891.github.io/PromptDirector-Curated/covers/cinematic.webp",
+ previewUrl: "https://wchao6891.github.io/PromptDirector-Curated/previews/cinematic-foundations/preview.json",
downloadUrl: "https://github.com/wchao6891/PromptDirector-Curated/releases/download/cinematic-1.0.0/cinematic.zip",
sha256: "a".repeat(64),
+ archiveBytes: 1024,
caseCount: 2,
imageCount: 2,
videoCount: 0,
@@ -58,6 +64,75 @@ test("curated catalogs expose ordered themes with trusted package assets", () =>
}), /目录版本过旧/);
});
+test("curated previews expose inert prompt text and trusted poster images for the exact package version", () => {
+ const preview = normalizeCuratedPreview({
+ format: "prompt-director-curated-preview",
+ version: 1,
+ catalogId: "feature:cinematic",
+ packageId: "cinematic-foundations",
+ packageVersion: "1.0.0",
+ entries: [
+ {
+ id: "one",
+ title: "案例一",
+ text: "只作为文字复制",
+ author: "@creator",
+ rights: "权利归原作者",
+ sourceUrl: "https://source.example/one",
+ mediaKind: "image",
+ previewImageUrl: "https://wchao6891.github.io/PromptDirector-Curated/previews/cinematic-foundations/media/one.webp",
+ width: 1200,
+ height: 900
+ },
+ {
+ id: "two",
+ title: "案例二",
+ text: "视频提示词",
+ author: "@creator",
+ rights: "权利归原作者",
+ sourceUrl: "",
+ mediaKind: "video",
+ previewImageUrl: "https://wchao6891.github.io/PromptDirector-Curated/previews/cinematic-foundations/media/two.webp",
+ videoUrl: "https://github.com/wchao6891/PromptDirector-Curated/releases/download/cinematic-media-1.0.0/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.mp4",
+ videoSha256: "b".repeat(64),
+ videoBytes: 2048,
+ videoMimeType: "video/mp4",
+ width: 1200,
+ height: 900
+ }
+ ]
+ }, catalogItem());
+ assert.equal(preview.entries[0].text, "只作为文字复制");
+ assert.equal(preview.entries[1].videoMimeType, "video/mp4");
+ assert.deepEqual(normalizeCuratedPreview(preview, catalogItem()), preview);
+ assert.throws(() => normalizeCuratedPreview({ ...preview, packageVersion: "2.0.0" }, catalogItem()), /版本不一致/);
+ assert.throws(() => normalizeCuratedPreview({
+ ...preview,
+ entries: preview.entries.map((entry, index) => index ? entry : { ...entry, previewImageUrl: "https://attacker.example/one.webp" })
+ }, catalogItem()), /不受信任/);
+});
+
+test("curated download sorting accepts only a complete real metric snapshot", () => {
+ const catalog = {
+ format: "prompt-director-curated",
+ version: 2,
+ updatedAt: "2026-07-29T00:00:00.000Z",
+ themes: [catalogItem()]
+ };
+ assert.deepEqual(normalizeCuratedMetrics({
+ format: "prompt-director-curated-metrics",
+ version: 1,
+ updatedAt: "2026-07-29T00:00:00.000Z",
+ downloads: { "feature:cinematic": 14 }
+ }, catalog).downloads, { "feature:cinematic": 14 });
+ assert.throws(() => normalizeCuratedMetrics({
+ format: "prompt-director-curated-metrics",
+ version: 1,
+ updatedAt: "2026-07-29T00:00:00.000Z",
+ downloads: {}
+ }, catalog), /不完整/);
+});
+
test("installing a curated package records provenance without retaining service or private metadata", () => {
const item = catalogItem();
const entry = applyCuratedOrigin({
@@ -202,3 +277,34 @@ test("a curated mixed-media package must match its reviewed video count", () =>
assets: new Map([...parsed.assets].filter(([id]) => id !== "video"))
}), /视频数量与目录不一致/);
});
+
+test("a curated package index validates every reviewed media path before extracting one case", () => {
+ const item = catalogItem({ imageCount: 2, videoCount: 1 });
+ const library = {
+ entries: [
+ {
+ id: "one",
+ mediaAssets: [
+ { id: "image-one", kind: "image", assetPath: "images/one.webp" },
+ { id: "video-one", kind: "video", assetPath: "videos/one.mp4" }
+ ]
+ },
+ {
+ id: "two",
+ mediaAssets: [{ id: "image-two", kind: "image", assetPath: "images/two.webp" }]
+ }
+ ]
+ };
+ const names = ["library.json", "images/one.webp", "videos/one.mp4", "images/two.webp"];
+
+ assert.doesNotThrow(() => validateCuratedPackageIndex(item, library, names));
+ assert.throws(() => validateCuratedPackageIndex(item, library, names.filter((name) => name !== "videos/one.mp4")), /ZIP 不一致/);
+ assert.throws(() => validateCuratedPackageIndex(item, {
+ ...library,
+ entries: [library.entries[0], {
+ ...library.entries[1],
+ mediaAssets: [{ id: "image-one", kind: "image", assetPath: "images/two.webp" }]
+ }]
+ }, names), /无效或重复/);
+ assert.throws(() => validateCuratedPackageIndex(catalogItem({ imageCount: 1, videoCount: 1 }), library, names), /图片数量与目录不一致/);
+});
diff --git a/test/curated-download.test.js b/test/curated-download.test.js
index c9cb710..30a1f97 100644
--- a/test/curated-download.test.js
+++ b/test/curated-download.test.js
@@ -1,7 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { fetchCuratedPackage } from "../curated-download.js";
+import { fetchCuratedPackage, readResponseBlobWithProgress } from "../curated-download.js";
const DOWNLOAD_URL =
"https://github.com/wchao6891/PromptDirector-Curated/releases/download/example-1.0.0/example.zip";
@@ -51,3 +51,54 @@ test("curated downloads retry one rejected network request", async () => {
assert.equal(response.status, 200);
assert.equal(calls, 2);
});
+
+test("curated package reads stream bytes and reports determinate progress", async () => {
+ const progress = [];
+ const response = new Response(new ReadableStream({
+ start(controller) {
+ controller.enqueue(new Uint8Array([1, 2]));
+ controller.enqueue(new Uint8Array([3, 4, 5]));
+ controller.close();
+ }
+ }), {
+ headers: {
+ "content-length": "5",
+ "content-type": "application/zip"
+ }
+ });
+
+ const blob = await readResponseBlobWithProgress(response, {
+ onProgress: (value) => progress.push(value)
+ });
+
+ assert.deepEqual([...new Uint8Array(await blob.arrayBuffer())], [1, 2, 3, 4, 5]);
+ assert.equal(blob.type, "application/zip");
+ assert.deepEqual(progress, [
+ { loaded: 2, total: 5, ratio: 0.4 },
+ { loaded: 5, total: 5, ratio: 1 }
+ ]);
+});
+
+test("curated package still reports downloaded bytes when the total is unavailable", async () => {
+ const progress = [];
+ const response = new Response(new Blob([new Uint8Array([1, 2, 3])]), {
+ headers: { "content-type": "application/octet-stream" }
+ });
+
+ const blob = await readResponseBlobWithProgress(response, {
+ onProgress: (value) => progress.push(value)
+ });
+
+ assert.equal(blob.size, 3);
+ assert.equal(progress.at(-1).loaded, 3);
+ assert.equal(progress.at(-1).total, 0);
+ assert.equal(progress.at(-1).ratio, null);
+});
+
+test("curated package rejects a declared response size that does not match the stream", async () => {
+ const response = new Response(new Blob([new Uint8Array([1, 2, 3])]), {
+ headers: { "content-length": "5" }
+ });
+
+ await assert.rejects(() => readResponseBlobWithProgress(response), /下载不完整/);
+});
diff --git a/test/curated-import.test.js b/test/curated-import.test.js
new file mode 100644
index 0000000..fea4bb3
--- /dev/null
+++ b/test/curated-import.test.js
@@ -0,0 +1,123 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { prepareCuratedPackageVersion } from "../curated-catalog.js";
+import { mergeCuratedLibraryPackage } from "../curated-import.js";
+import { createDefaultFacetCatalog } from "../facets.js";
+import { CONTENT_IDS, createDefaultTaxonomy } from "../taxonomy.js";
+
+function item(version) {
+ return {
+ id: "featured:test",
+ title: "精选测试包",
+ type: "image_prompt",
+ packageId: "test-pack",
+ packageVersion: version,
+ authorId: "editorial",
+ author: "PromptDirector 编辑精选",
+ license: "测试权利",
+ updatedAt: "2026-08-14T00:00:00.000Z",
+ coverUrl: "https://wchao6891.github.io/PromptDirector-Curated/covers/test.webp",
+ previewUrl: "https://wchao6891.github.io/PromptDirector-Curated/previews/test/preview.json",
+ downloadUrl: "https://github.com/wchao6891/PromptDirector-Curated/releases/download/test/test.zip",
+ sha256: "a".repeat(64),
+ archiveBytes: 1024,
+ caseCount: 3,
+ imageCount: 3,
+ videoCount: 0,
+ order: 1
+ };
+}
+
+function sourceLibrary(ids) {
+ return {
+ format: "prompt-case-library",
+ version: 3,
+ settings: {},
+ taxonomy: createDefaultTaxonomy(),
+ facetCatalog: createDefaultFacetCatalog(),
+ classificationRules: [],
+ organizerState: { version: 6, collections: [] },
+ entries: ids.map((id) => ({
+ id,
+ schemaVersion: 5,
+ title: `案例 ${id}`,
+ text: `prompt ${id}`,
+ url: `https://example.com/${id}`,
+ savedAt: "2026-08-14T00:00:00.000Z",
+ hasScreenshot: true,
+ screenshotPath: `images/${id}.webp`,
+ classification: { pathIds: [CONTENT_IDS.promptImage], status: "confirmed", source: "manual" },
+ facetAssignments: []
+ }))
+ };
+}
+
+function emptyState() {
+ return {
+ entries: [],
+ compoundCases: [],
+ settings: {},
+ taxonomy: createDefaultTaxonomy(),
+ facetCatalog: createDefaultFacetCatalog(),
+ classificationRules: [],
+ organizerState: { version: 6, collections: [] },
+ composerSessions: [],
+ creativeRuns: [],
+ creativeSkills: { version: 1, items: [] }
+ };
+}
+
+test("curated pack import creates one stable local project", () => {
+ const catalogItem = { ...item("1.0.0"), caseCount: 2, imageCount: 2 };
+ const library = prepareCuratedPackageVersion(sourceLibrary(["one", "two"]), catalogItem);
+ const result = mergeCuratedLibraryPackage(emptyState(), library, {
+ packageId: catalogItem.packageId,
+ projectName: catalogItem.title,
+ mode: "package"
+ });
+ assert.equal(result.importedCount, 2);
+ assert.equal(result.existingCount, 0);
+ assert.equal(result.projectId, "curated-project:test-pack");
+ assert.deepEqual(result.state.organizerState.collections[0].entryIds.toSorted(), result.importedEntryIds.toSorted());
+});
+
+test("curated updates preserve personal edits and add only missing stable sources", () => {
+ const firstItem = { ...item("1.0.0"), caseCount: 2, imageCount: 2 };
+ const firstLibrary = prepareCuratedPackageVersion(sourceLibrary(["one", "two"]), firstItem);
+ const first = mergeCuratedLibraryPackage(emptyState(), firstLibrary, {
+ packageId: firstItem.packageId,
+ projectName: firstItem.title,
+ mode: "package"
+ });
+ first.state.entries.find((entry) => entry.curatedOrigin.sourceEntryId === "one").title = "我的个人修改";
+
+ const secondItem = item("1.1.0");
+ const secondLibrary = prepareCuratedPackageVersion(sourceLibrary(["one", "two", "three"]), secondItem);
+ const second = mergeCuratedLibraryPackage(first.state, secondLibrary, {
+ packageId: secondItem.packageId,
+ projectName: secondItem.title,
+ mode: "package"
+ });
+ assert.equal(second.importedCount, 1);
+ assert.equal(second.existingCount, 2);
+ assert.equal(second.state.entries.length, 3);
+ assert.equal(second.state.entries.find((entry) => entry.curatedOrigin.sourceEntryId === "one").title, "我的个人修改");
+ assert.equal(second.state.organizerState.collections.filter((collection) => collection.id === second.projectId).length, 1);
+ assert.equal(second.state.organizerState.collections.find((collection) => collection.id === second.projectId).entryIds.length, 3);
+});
+
+test("curated imports preserve real source identities that contain namespace separators", () => {
+ const catalogItem = { ...item("1.0.0"), caseCount: 1, imageCount: 1 };
+ const sourceEntryId = "entry:evolink:361a86b9c18a46716be398cc";
+ const source = sourceLibrary(["fixture"]);
+ source.entries[0] = { ...source.entries[0], id: sourceEntryId, hasScreenshot: false, screenshotPath: "" };
+ const library = prepareCuratedPackageVersion(source, catalogItem);
+ const result = mergeCuratedLibraryPackage(emptyState(), library, {
+ packageId: catalogItem.packageId,
+ projectName: catalogItem.title,
+ mode: "case"
+ });
+ assert.equal(result.importedCount, 1);
+ assert.equal(result.entriesBySourceEntryId[sourceEntryId], result.state.entries[0].id);
+});
diff --git a/test/curated-navigation.test.js b/test/curated-navigation.test.js
index b4d779c..6e8714e 100644
--- a/test/curated-navigation.test.js
+++ b/test/curated-navigation.test.js
@@ -2,108 +2,108 @@ import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
-test("curated cases use same-tab navigation and return without creating duplicate tabs", async () => {
- const library = await readFile(new URL("../library.js", import.meta.url), "utf8");
- const curated = await readFile(new URL("../curated-page.js", import.meta.url), "utf8");
- const html = await readFile(new URL("../curated.html", import.meta.url), "utf8");
+async function sources() {
+ const [library, page, html, css] = await Promise.all([
+ readFile(new URL("../library.js", import.meta.url), "utf8"),
+ readFile(new URL("../curated-page.js", import.meta.url), "utf8"),
+ readFile(new URL("../curated.html", import.meta.url), "utf8"),
+ readFile(new URL("../curated.css", import.meta.url), "utf8")
+ ]);
+ return { library, page, html, css };
+}
+test("curated discovery stays in one extension tab and returns to the private library", async () => {
+ const { library, page, html } = await sources();
assert.match(library, /navigateWithinPromptDirector\("curated\.html"\)/);
- const promptDirectorNavigation = library.slice(
- library.indexOf("elements.openCurated"),
- library.indexOf("chrome.runtime.onMessage.addListener")
- );
- assert.doesNotMatch(promptDirectorNavigation, /chrome\.tabs\.create|openerTabId/);
assert.match(html, /<button id="return-library"/);
- assert.doesNotMatch(html, /id="back-to-themes"/);
- assert.doesNotMatch(html, /href="library\.html"/);
- assert.match(curated, /activeThemeId \? backToThemes\(\) : returnToLibrary\(\)/);
- assert.match(curated, /activeThemeId \? "返回主题" : "返回我的案例库"/);
-
- const returnFlow = curated.slice(
- curated.indexOf("function returnToLibrary"),
- curated.indexOf("async function refreshCatalog")
- );
- assert.match(returnFlow, /location\.assign\(chrome\.runtime\.getURL\("library\.html"\)\)/);
- assert.doesNotMatch(returnFlow, /chrome\.tabs\.(?:create|update|remove)|openerTabId/);
+ assert.match(html, /data-i18n="返回案例库"/);
+ assert.match(page, /location\.assign\(chrome\.runtime\.getURL\("library\.html"\)\)/);
+ assert.doesNotMatch(page, /chrome\.tabs\.(?:create|update|remove)|openerTabId/);
});
-test("curated discovery loads theme cards before any package and supports theme or single saves", async () => {
- const curated = await readFile(new URL("../curated-page.js", import.meta.url), "utf8");
- const background = await readFile(new URL("../background.js", import.meta.url), "utf8");
- const html = await readFile(new URL("../curated.html", import.meta.url), "utf8");
- const css = await readFile(new URL("../curated.css", import.meta.url), "utf8");
- const foundation = await readFile(new URL("../ui-foundation.css", import.meta.url), "utf8");
- const detail = curated.slice(curated.indexOf("function renderDetail"), curated.indexOf("async function saveCuratedCase"));
+test("curated discovery keeps the pack wall concise and opens a separate read-only case detail", async () => {
+ const { page, html, css } = await sources();
+ assert.match(html, /id="curated-search"/);
+ assert.match(html, /id="filter-button"/);
+ assert.match(html, /data-sort="recommended"/);
+ assert.match(html, /data-sort="latest"/);
+ assert.match(html, /data-sort="downloads"/);
+ assert.match(html, /<dialog id="detail-dialog"/);
+ assert.match(html, /id="case-detail-drawer"/);
+ assert.match(html, /id="case-detail-prev"/);
+ assert.match(html, /id="case-detail-next"/);
+ assert.doesNotMatch(html, /save-theme|theme-grid|themes-view|cases-view|更多|版本|更新日期|摘要/);
+ assert.match(page, /element\("article", "pack-card"\)/);
+ assert.match(page, /element\("h2", "", item\.title\)/);
+ assert.match(page, /meta\.append\(element\("span", "", item\.author\), element\("span", "", `\$\{item\.caseCount\}/);
+ assert.match(page, /actions\.append\(download, follow, copyLink\)/);
+ assert.doesNotMatch(page, /Composer|composer|以此创作|openComposer|promptVersions/);
+ const detail = page.slice(page.indexOf("function renderDetail"), page.indexOf("function createCaseCard"));
+ assert.doesNotMatch(detail, /item\.summary|packageVersion|updatedAt/);
+ assert.match(css, /grid-template-columns:\s*minmax\(0, 1fr\) clamp\(360px, 31vw, 450px\)/);
+ assert.match(css, /\.case-detail-layout\s*\{[^}]*grid-template-columns:\s*minmax\(0, 1fr\) clamp\(380px, 34vw, 480px\)/);
+});
- const refreshFlow = curated.slice(curated.indexOf("async function refreshCatalog"), curated.indexOf("async function loadCachedCatalog"));
- assert.doesNotMatch(refreshFlow, /fetchCuratedPackage|loadThemePackage/);
- assert.doesNotMatch(curated, /loadCatalogPackages/);
- assert.match(curated, /catalog\.themes/);
- assert.match(curated, /async function openTheme/);
- assert.match(curated, /async function loadThemePackage/);
- assert.match(curated, /async function saveTheme/);
- assert.match(curated, /prepareCuratedEntriesPackage/);
- assert.match(curated, /createStableMasonry\(elements\.curatedGrid/);
- assert.match(curated, /prepareCuratedEntryPackage\(record\.library, record\.entry\.id\)/);
- assert.match(curated, /preserveLibraryConfiguration:\s*true/);
- assert.match(background, /previewLibraryImport\(await readState\(\), message\.library, \{[\s\S]*preserveLibraryConfiguration/);
- assert.match(background, /preserveLibraryConfiguration:\s*message\.preserveLibraryConfiguration === true/);
- assert.match(curated, /function openDetail/);
- assert.match(curated, /document\.documentElement\.classList\.add\("detail-open"\)/);
- assert.match(curated, /event\.key === "ArrowLeft"/);
- assert.match(curated, /event\.key === "ArrowRight"/);
- assert.match(curated, /className = "case-image-wrap case-image-wrap-fixed"/);
- assert.match(curated, /className = "case-shot"/);
- assert.match(curated, /caseImageObserver\.observe\(image\)/);
- assert.match(curated, /renderedCount \+ PAGE_SIZE/);
- assert.match(detail, /metadata\.append\(textElement\("span", "", sourceRightsLabel\(record\.entry\)\)\)/);
- assert.doesNotMatch(detail, /查看原始来源|detail-source|record\.item\.title/);
- assert.doesNotMatch(html, /id="curated-search"|id="refresh-catalog"/);
- assert.match(html, /id="retry-catalog"[^>]*hidden/);
- assert.match(html, /id="active-theme-count"/);
- assert.match(html, /id="theme-grid"/);
- assert.match(html, /id="themes-view"/);
- assert.match(html, /id="cases-view"/);
- assert.match(html, /id="save-theme"/);
- assert.match(html, /class="theme-save-summary"/);
- assert.match(html, /id="detail-drawer"/);
- assert.match(html, /id="detail-drawer"[^>]*role="dialog"[^>]*aria-modal="true"/);
- assert.match(html, /选择一期主题,再浏览或保存其中的案例/);
- assert.doesNotMatch(curated, /installCuratedItem|安装到我的案例库/);
- assert.doesNotMatch(html, /id="curated-filter"/);
- assert.match(css, /\.curated-grid\s*\{[^}]*position:\s*relative/);
- assert.match(css, /\.theme-grid\s*\{[^}]*grid-template-columns/);
- assert.match(css, /\.case-image-wrap-fixed \.case-shot\s*\{[^}]*object-fit:\s*cover/);
- assert.match(css, /\.detail-drawer\s*\{[^}]*width:\s*100vw;[^}]*height:\s*100dvh/);
- assert.match(css, /\.detail-content\s*\{[^}]*grid-template-columns:\s*minmax\(0, 1fr\) var\(--detail-panel-width\)/);
- assert.match(css, /\.detail-figure\s*\{[^}]*height:\s*100dvh/);
- assert.match(css, /\.detail-figure\s*\{[^}]*background:\s*var\(--viewer-bg\)/);
- assert.match(css, /\.detail-body\s*\{[^}]*background:\s*var\(--card\)/);
- assert.match(foundation, /:root\[data-theme="dark"\][\s\S]*--viewer-bg:\s*var\(--ui-browser\)/);
- assert.match(foundation, /:root\[data-theme="system"\][\s\S]*--viewer-bg:\s*var\(--ui-browser\)/);
- assert.match(css, /@media \(max-width: 700px\)[\s\S]*--masonry-card-min-width:\s*145px/);
- assert.match(css, /@media \(max-width: 700px\)[\s\S]*\.detail-figure\s*\{[^}]*height:\s*58dvh/);
+test("package cases reuse the stable masonry and the whole image card opens detail", async () => {
+ const { page, css } = await sources();
+ assert.match(page, /import \{ createStableMasonry \} from "\.\/stable-masonry\.js"/);
+ assert.match(page, /const CURATED_CASE_PAGE_SIZE = 24/);
+ assert.match(page, /createStableMasonry\(list, \{\s*scrollContainer: elements\.detailDialog/);
+ const card = page.slice(page.indexOf("function createCaseCard"), page.indexOf("function openCaseDetail"));
+ assert.match(card, /card\.addEventListener\("click", open\)/);
+ assert.match(card, /openCaseDetail\(item, entry, card\)/);
+ assert.doesNotMatch(card, /case-footer|case-actions|iconButton/);
+ assert.match(css, /\.case-list\s*\{[^}]*position:\s*relative/);
+ assert.match(css, /\.case-card\s*\{[^}]*position:\s*absolute/);
+ assert.doesNotMatch(css, /\.case-list\s*\{[^}]*display:\s*grid/);
});
-test("curated catalog refreshes on entry and exposes retry only for permission or failure", async () => {
- const curated = await readFile(new URL("../curated-page.js", import.meta.url), "utf8");
- const startup = curated.slice(curated.indexOf("await loadLocalState()"), curated.indexOf("function returnToLibrary"));
- const refresh = curated.slice(curated.indexOf("async function refreshCatalog"), curated.indexOf("async function loadCachedCatalog"));
- assert.match(startup, /hasCatalogPermission\(\).*refreshCatalog\(false\)/s);
- assert.match(startup, /showStatus\([^\n]+true, true\)/);
- assert.match(refresh, /elements\.retryCatalog\.hidden = true/);
- assert.match(refresh, /showStatus\([^\n]+true, true\)/);
- assert.doesNotMatch(curated, /addEventListener\("input", renderCases\)/);
+test("case detail preserves real media ratio and isolates focus from the package", async () => {
+ const { page, html, css } = await sources();
+ assert.match(html, /id="case-detail-drawer"[^>]*role="dialog"[^>]*aria-modal="true"/);
+ assert.match(css, /\.case-detail-figure img\s*\{[^}]*width:\s*auto;[^}]*height:\s*auto;[^}]*max-width:\s*100%;[^}]*max-height:\s*100dvh;[^}]*object-fit:\s*contain/);
+ assert.match(css, /\.case-detail-video\s*\{[^}]*width:\s*100%;[^}]*height:\s*100%;[^}]*object-fit:\s*contain/);
+ assert.match(page, /image\.width = entry\.width/);
+ assert.match(page, /image\.height = entry\.height/);
+ assert.match(page, /setPackageDetailInert\(true\)/);
+ assert.match(page, /setPackageDetailInert\(false\)/);
+ assert.match(page, /elements\.detailContent\.inert = inert/);
+ assert.match(page, /t\("图片加载失败"\)/);
});
-test("curated and local single-case details reuse the existing composer reference route", async () => {
- const curated = await readFile(new URL("../curated-page.js", import.meta.url), "utf8");
- const library = await readFile(new URL("../library.js", import.meta.url), "utf8");
+test("search, filters, ordering, following and public deep links use public metadata only", async () => {
+ const { page } = await sources();
+ assert.match(page, /loadAllPreviews\(\)/);
+ assert.match(page, /entry\.title, entry\.author, entry\.text/);
+ assert.match(page, /typeFilters\.includes\(item\.type\)/);
+ assert.match(page, /state\.following\.has\(item\.authorId\)/);
+ assert.match(page, /curatedFollowingAuthors/);
+ assert.match(page, /right\.updatedAt/);
+ assert.match(page, /state\.metrics\.downloads\[right\.id\]/);
+ assert.match(page, /elements\.sortDownloads\.disabled = !state\.metrics/);
+ assert.match(page, /url\.searchParams\.set\("pack", id\)/);
+ assert.match(page, /new URL\(CURATED_PUBLIC_SITE_URL\)/);
+ assert.match(page, /curatedSourceKey\(\{\s*curatedOrigin: \{ packageId: item\.packageId, sourceEntryId: previewEntry\.id \}/);
+ assert.doesNotMatch(page, /粉丝|like|comment|浏览量/);
+});
- assert.match(curated, /url\.searchParams\.set\("references", savedEntry\.id\)/);
- assert.match(curated, /location\.assign\(url\.href\)/);
- assert.doesNotMatch(curated.slice(curated.indexOf("async function openComposerForRecord"), curated.indexOf("function updateThemeSaveUi")), /chrome\.tabs\.create/);
- assert.match(curated, /await saveCuratedCase\(record/);
- assert.match(library, /url\.searchParams\.set\("references", entry\.id\)/);
- assert.match(library, /isComposerEligibleEntry/);
+test("preview prompts stay inert and package bytes are verified before curated imports", async () => {
+ const { page } = await sources();
+ assert.match(page, /element\("pre", "case-detail-prompt", entry\.text/);
+ assert.match(page, /copyCasePrompt\(entry, copy\)/);
+ assert.doesNotMatch(page, /innerHTML|insertAdjacentHTML|eval\(|new Function/);
+ const verifiedArchive = page.slice(page.indexOf("async function loadVerifiedArchive"), page.indexOf("async function loadPackageIndex"));
+ assert.match(verifiedArchive, /verifyCuratedPackageBlob\(archive, item\.sha256\)/);
+ const save = page.slice(page.indexOf("async function savePreviewCase"), page.indexOf("function openSavedCase"));
+ assert.match(save, /saveCuratedSelection\(item, \[previewEntry\.id\]/);
+ assert.match(save, /prepareCuratedEntriesPackage/);
+ assert.match(save, /prepareCuratedEntryPackage/);
+ assert.match(save, /reader\.read\(mediaPaths/);
+ assert.match(page, /PREVIEW_CURATED_IMPORT/);
+ assert.match(page, /APPLY_CURATED_IMPORT/);
+ assert.match(page, /entriesBySourceEntryId/);
+ assert.match(page, /readResponseBlobWithProgress/);
+ assert.match(page, /stage: "downloading"/);
+ assert.match(page, /stage: "verifying"/);
+ assert.match(page, /stage: "saving"/);
});
diff --git a/test/curated-submission.test.js b/test/curated-submission.test.js
new file mode 100644
index 0000000..2f67740
--- /dev/null
+++ b/test/curated-submission.test.js
@@ -0,0 +1,127 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ CURATED_SUBMISSION_MAX_FILE_BYTES,
+ CURATED_SUBMISSION_PART_PAYLOAD_BYTES,
+ prepareCuratedSubmissionState,
+ sanitizeCuratedSubmissionEntry,
+ submissionManifest,
+ submissionPartManifest
+} from "../curated-submission.js";
+
+test("精选投稿只保留公开案例字段和必要媒体", () => {
+ const prepared = prepareCuratedSubmissionState(fixtureState(), { entryIds: ["case-1"] });
+ assert.equal(prepared.entries.length, 1);
+ const entry = prepared.entries[0];
+ assert.equal(entry.text, "公开提示词");
+ assert.deepEqual(entry.metadataLabels, ["作者:小明", "权利:本人原创"]);
+ assert.equal(entry.mediaAssets.length, 1);
+ assert.equal(entry.mediaAssets[0].storageMode, "managed");
+ const serialized = JSON.stringify(prepared.state);
+ for (const secret of ["私人笔记", "sk-secret", "创作会话", "模型配置", "本地标签"]) {
+ assert.equal(serialized.includes(secret), false, `投稿包不应包含:${secret}`);
+ }
+});
+
+test("投稿拒绝外链媒体、空提示词和缺少封面的视频", () => {
+ const image = fixtureState().entries[0];
+ assert.throws(() => sanitizeCuratedSubmissionEntry({
+ ...image,
+ primaryMediaId: "video-1",
+ mediaAssets: [{
+ id: "video-1",
+ kind: "video",
+ usage: "content",
+ storageMode: "reference",
+ mimeType: "video/mp4",
+ posterAssetId: "poster-1",
+ reference: { url: "https://example.com/video.mp4" }
+ }, {
+ ...image.mediaAssets[0],
+ id: "poster-1",
+ usage: "poster",
+ derivedFromAssetId: "video-1"
+ }]
+ }), /保存到本地/);
+ assert.throws(() => sanitizeCuratedSubmissionEntry({ ...image, text: "" }), /缺少可公开/);
+ assert.throws(() => sanitizeCuratedSubmissionEntry({
+ ...image,
+ mediaAssets: [{
+ ...image.mediaAssets[0],
+ id: "video-1",
+ kind: "video",
+ mimeType: "video/mp4",
+ posterAssetId: "poster-1"
+ }],
+ primaryMediaId: "video-1"
+ }), /唯一封面/);
+});
+
+test("投稿清单和分卷清单使用完整 SHA-256 身份", () => {
+ const hash = "a".repeat(64);
+ assert.equal(CURATED_SUBMISSION_MAX_FILE_BYTES, 24 * 1024 * 1024);
+ assert.ok(CURATED_SUBMISSION_PART_PAYLOAD_BYTES < CURATED_SUBMISSION_MAX_FILE_BYTES);
+ assert.equal(submissionManifest({
+ submissionId: hash,
+ payloadBytes: 100,
+ caseCount: 1,
+ mediaCount: 1
+ }).submissionId, hash);
+ assert.equal(submissionPartManifest({
+ submissionId: hash,
+ archiveSha256: hash,
+ archiveBytes: 200,
+ partIndex: 1,
+ partCount: 2,
+ payloadSha256: hash,
+ payloadBytes: 100
+ }).partCount, 2);
+ assert.throws(() => submissionManifest({
+ submissionId: "short",
+ payloadBytes: 100,
+ caseCount: 1,
+ mediaCount: 1
+ }), /摘要无效/);
+});
+
+function fixtureState() {
+ return {
+ entries: [{
+ id: "case-1",
+ title: "竖图案例",
+ text: "公开提示词",
+ note: "私人笔记",
+ url: "https://example.com/source",
+ savedAt: "2026-08-15T00:00:00.000Z",
+ classification: { pathIds: ["content:prompt:image"], status: "confirmed" },
+ facetAssignments: [{ facetId: "private", nodeId: "本地标签" }],
+ customLabels: ["本地标签"],
+ metadataLabels: ["作者:小明", "权利:本人原创", "秘密:sk-secret"],
+ primaryMediaId: "media-1",
+ mediaAssets: [{
+ id: "media-1",
+ kind: "image",
+ usage: "content",
+ storageMode: "managed",
+ mimeType: "image/webp",
+ width: 900,
+ height: 1600,
+ sourceUrl: "https://example.com/image.webp",
+ visionAnalysis: { description: "模型配置" }
+ }]
+ }],
+ taxonomy: {
+ version: 2,
+ nodes: [{ id: "content:prompt:image", name: "图片", kind: "leaf" }]
+ },
+ facetCatalog: {
+ version: 2,
+ facets: [{ id: "private", name: "私人" }],
+ nodes: [{ id: "本地标签", facetId: "private", name: "本地标签" }]
+ },
+ composerSettings: { apiKey: "sk-secret" },
+ composerSessions: [{ id: "session-1", title: "创作会话" }],
+ creativeRuns: [{ id: "run-1", model: "模型配置" }],
+ organizerState: { version: 4, collections: [] }
+ };
+}
diff --git a/test/curated_live_release_e2e.py b/test/curated_live_release_e2e.py
new file mode 100644
index 0000000..6a30510
--- /dev/null
+++ b/test/curated_live_release_e2e.py
@@ -0,0 +1,103 @@
+from __future__ import annotations
+
+import re
+import os
+
+from playwright.sync_api import TimeoutError as PlaywrightTimeoutError, expect
+
+from e2e_support import extension_session
+
+
+CATALOG_URL = "https://wchao6891.github.io/PromptDirector-Curated/catalog.json"
+
+
+def main() -> None:
+ with extension_session("prompt-director-curated-live-", viewport={"width": 1440, "height": 1000}) as session:
+ curated = session.open_page("curated.html", wait_until="networkidle")
+ page_errors = []
+ console_errors = []
+ curated.on("pageerror", lambda error: page_errors.append(str(error)))
+ curated.on("console", lambda message: console_errors.append(message.text) if message.type == "error" else None)
+ catalog = curated.evaluate(
+ "async (url) => (await fetch(url, {cache: 'no-store', credentials: 'omit'})).json()",
+ CATALOG_URL,
+ )
+ item = min(catalog["themes"], key=lambda candidate: candidate["caseCount"])
+ card = curated.locator(f'.pack-card[data-pack-id="{item["id"]}"]')
+ expect(card).to_be_visible(timeout=30_000)
+ card.click()
+ expect(curated.locator(".case-card").first).to_be_visible(timeout=30_000)
+ expect(curated.locator(".case-video-badge").first).to_be_visible()
+ curated.locator(".case-card").first.hover()
+ expect(curated.locator(".case-card").first.locator(".case-video-preview")).to_have_count(1)
+ curated.locator(".case-card").first.click()
+ expect(curated.locator(".case-detail-video")).to_have_count(1)
+ curated.wait_for_function("() => document.querySelector('.case-detail-video')?.readyState >= 1", timeout=30_000)
+ save = curated.locator(".case-save-action")
+ expect(save).to_have_text("保存到案例库")
+ curated.evaluate(
+ """async () => {
+ await chrome.storage.local.set({__curatedLiveLabels: []});
+ const button = document.querySelector('.case-save-action');
+ new MutationObserver(async () => {
+ const stored = await chrome.storage.local.get('__curatedLiveLabels');
+ const labels = stored.__curatedLiveLabels || [];
+ const label = button.textContent.trim();
+ if (labels.at(-1) !== label) await chrome.storage.local.set({__curatedLiveLabels: [...labels, label]});
+ }).observe(button, {subtree: true, childList: true, characterData: true});
+ }"""
+ )
+ save.click()
+ try:
+ expect(curated).to_have_url(
+ re.compile(r"/library\.html(?:\?.*)?$"),
+ timeout=int(os.environ.get("CURATED_SAVE_TIMEOUT_MS", "360000")),
+ )
+ except (AssertionError, PlaywrightTimeoutError):
+ diagnostics = curated.evaluate(
+ """async () => ({
+ button: document.querySelector('.case-save-action')?.textContent.trim(),
+ toast: document.querySelector('#curated-toast')?.textContent.trim(),
+ labels: (await chrome.storage.local.get('__curatedLiveLabels')).__curatedLiveLabels || [],
+ state: await chrome.runtime.sendMessage({type: 'GET_STATE'})
+ })"""
+ )
+ print({"save_timeout": diagnostics, "page_errors": page_errors, "console_errors": console_errors})
+ raise
+ expect(curated.locator("#detail-drawer")).to_have_class(re.compile(r"\bopen\b"))
+ expect(curated.locator(".detail-video")).to_have_count(1)
+ local_state = curated.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
+ assert len(local_state["entries"]) == 1, local_state
+ labels = curated.evaluate("async () => (await chrome.storage.local.get('__curatedLiveLabels')).__curatedLiveLabels || []")
+ assert not page_errors, page_errors
+ assert not console_errors, console_errors
+
+ curated.evaluate(
+ "(packId) => location.assign(`${chrome.runtime.getURL('curated.html')}?pack=${encodeURIComponent(packId)}`)",
+ item["id"],
+ )
+ expect(curated.locator("#detail-dialog")).to_be_visible(timeout=30_000)
+ curated.locator(".download-action").click()
+ expect(curated.locator("#pack-save-dialog")).to_be_visible()
+ curated.locator(".pack-save-confirm").click()
+ expect(curated).to_have_url(re.compile(r"/library\.html(?:\?.*)?$"), timeout=360_000)
+ expect(curated.locator(f'.project-filter[aria-label^="{item["title"]} "]')).to_have_attribute("aria-pressed", "true")
+ package_state = curated.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
+ project = next(collection for collection in package_state["organizerState"]["collections"] if collection["id"] == f'curated-project:{item["packageId"]}')
+ assert len(package_state["entries"]) == item["caseCount"], package_state
+ assert len(project["entryIds"]) == item["caseCount"], project
+
+ print({
+ "package": item["id"],
+ "case_count": item["caseCount"],
+ "online_video": True,
+ "opened_saved_case": True,
+ "progress": labels,
+ "saved_entries": len(local_state["entries"]),
+ "saved_package_entries": len(package_state["entries"]),
+ "project_entries": len(project["entryIds"]),
+ })
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/curated_video_workflow_e2e.py b/test/curated_video_workflow_e2e.py
index e29fafa..5b46242 100644
--- a/test/curated_video_workflow_e2e.py
+++ b/test/curated_video_workflow_e2e.py
@@ -4,6 +4,7 @@ import base64
import hashlib
import io
import json
+import re
import zipfile
from playwright.sync_api import expect
@@ -11,12 +12,15 @@ from playwright.sync_api import expect
from e2e_support import base_entry, extension_session
-PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+PNG_BYTES = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")
CATALOG_URL = "https://wchao6891.github.io/PromptDirector-Curated/catalog.json"
+METRICS_URL = "https://wchao6891.github.io/PromptDirector-Curated/metrics.json"
COVER_URL = "https://wchao6891.github.io/PromptDirector-Curated/covers/video-workflow.png"
+PREVIEW_URL = "https://wchao6891.github.io/PromptDirector-Curated/previews/video-workflow/preview.json"
+POSTER_URL = "https://wchao6891.github.io/PromptDirector-Curated/previews/video-workflow/poster.webp"
PACKAGE_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/video-workflow-1.0.0/video-workflow.zip"
VIDEO_BYTES = b"fixture-video"
-POSTER_BYTES = base64.b64decode(PNG_BASE64)
+VIDEO_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/video-workflow-media-1.0.0/" + hashlib.sha256(VIDEO_BYTES).hexdigest() + ".mp4"
def package_fixture() -> bytes:
@@ -38,7 +42,7 @@ def package_fixture() -> bytes:
"usage": "poster",
"storageMode": "managed",
"mimeType": "image/png",
- "byteSize": len(POSTER_BYTES),
+ "byteSize": len(PNG_BYTES),
"width": 1,
"height": 1,
"assetPath": "images/curated-video-poster.png",
@@ -49,107 +53,131 @@ def package_fixture() -> bytes:
"format": "prompt-case-library",
"version": 3,
"entries": [entry],
- "organizerState": {
- "version": 6,
- "collections": [{
- "id": "collection:curated-video-workflow",
- "name": "视频精选主题",
- "order": 0,
- "entryIds": [entry["id"]],
- }],
- },
+ "organizerState": {"version": 6, "collections": []},
}
stream = io.BytesIO()
with zipfile.ZipFile(stream, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr("library.json", json.dumps(package, ensure_ascii=False))
archive.writestr("videos/curated-video.mp4", VIDEO_BYTES)
- archive.writestr("images/curated-video-poster.png", POSTER_BYTES)
+ archive.writestr("images/curated-video-poster.png", PNG_BYTES)
return stream.getvalue()
def main() -> None:
archive = package_fixture()
+ item = {
+ "id": "feature:video-workflow",
+ "title": "视频精选",
+ "type": "video_prompt",
+ "packageId": "video-workflow",
+ "packageVersion": "1.0.0",
+ "authorId": "author-video-editorial",
+ "author": "视频作者",
+ "license": "权利归原作者",
+ "updatedAt": "2026-08-10T00:00:00.000Z",
+ "coverUrl": COVER_URL,
+ "previewUrl": PREVIEW_URL,
+ "downloadUrl": PACKAGE_URL,
+ "sha256": hashlib.sha256(archive).hexdigest(),
+ "archiveBytes": len(archive),
+ "caseCount": 1,
+ "imageCount": 1,
+ "videoCount": 1,
+ "summary": "视频包只公开封面。",
+ "order": 1,
+ }
catalog = {
"format": "prompt-director-curated",
"version": 2,
"updatedAt": "2026-08-10T00:00:00.000Z",
- "themes": [{
- "id": "feature:video-workflow",
- "title": "视频精选",
- "type": "video_prompt",
- "packageId": "video-workflow",
- "packageVersion": "1.0.0",
- "author": "PromptDirector Editorial",
- "license": "测试许可",
- "updatedAt": "2026-08-10T00:00:00.000Z",
- "coverUrl": COVER_URL,
- "downloadUrl": PACKAGE_URL,
- "sha256": hashlib.sha256(archive).hexdigest(),
- "caseCount": 1,
- "imageCount": 1,
- "videoCount": 1,
- "summary": "验证视频预览与保存。",
- "order": 1,
+ "themes": [item],
+ }
+ preview = {
+ "format": "prompt-director-curated-preview",
+ "version": 1,
+ "catalogId": item["id"],
+ "packageId": item["packageId"],
+ "packageVersion": item["packageVersion"],
+ "entries": [{
+ "id": "curated-video-case",
+ "title": "精选视频案例",
+ "text": "镜头沿主体缓慢环绕。",
+ "author": "视频作者",
+ "rights": "权利归原作者",
+ "sourceUrl": "https://example.com/video-case",
+ "mediaKind": "video",
+ "previewImageUrl": POSTER_URL,
+ "videoUrl": VIDEO_URL,
+ "videoSha256": hashlib.sha256(VIDEO_BYTES).hexdigest(),
+ "videoBytes": len(VIDEO_BYTES),
+ "videoMimeType": "video/mp4",
+ "width": 1280,
+ "height": 720,
}],
}
+ metrics = {
+ "format": "prompt-director-curated-metrics",
+ "version": 1,
+ "updatedAt": "2026-08-10T01:00:00.000Z",
+ "downloads": {item["id"]: 3},
+ }
with extension_session("prompt-director-curated-video-", viewport={"width": 1280, "height": 900}) as session:
session.context.route(CATALOG_URL, lambda route: route.fulfill(
- status=200,
- content_type="application/json",
- body=json.dumps(catalog),
+ status=200, content_type="application/json", body=json.dumps(catalog)
+ ))
+ session.context.route(METRICS_URL, lambda route: route.fulfill(
+ status=200, content_type="application/json", body=json.dumps(metrics)
+ ))
+ session.context.route(PREVIEW_URL, lambda route: route.fulfill(
+ status=200, content_type="application/json", body=json.dumps(preview)
))
session.context.route(COVER_URL, lambda route: route.fulfill(
- status=200,
- content_type="image/png",
- body=POSTER_BYTES,
+ status=200, content_type="image/png", body=PNG_BYTES
+ ))
+ session.context.route(POSTER_URL, lambda route: route.fulfill(
+ status=200, content_type="image/webp", body=PNG_BYTES
+ ))
+ session.context.route(VIDEO_URL, lambda route: route.fulfill(
+ status=200, content_type="video/mp4", body=VIDEO_BYTES
))
session.context.route(f"{PACKAGE_URL}*", lambda route: route.fulfill(
- status=200,
- content_type="application/zip",
- body=archive,
+ status=200, content_type="application/zip", body=archive
))
- session.context.add_init_script(
- """(() => {
- if (!globalThis.chrome?.permissions) return;
- Object.defineProperty(chrome.permissions, 'contains', {value: async () => true});
- Object.defineProperty(chrome.permissions, 'request', {value: async () => true});
- })()"""
- )
-
curated = session.open_page("curated.html", wait_until="networkidle")
- curated.locator(".theme-open").click()
- curated.wait_for_timeout(500)
- expect(curated.locator("#cases-view")).to_be_visible()
- expect(curated.locator("#curated-status")).to_have_text("")
- expect(curated.locator("#curated-grid .case-shot")).to_have_count(1)
- curated.locator("#curated-grid .case-card").click()
- video = curated.locator("#detail-content video")
- expect(video).to_have_count(1)
- expect(video).to_have_attribute("controls", "")
+ curated.locator("#filter-button").click()
+ curated.locator('#filter-popover input[value="video_prompt"]').check()
+ expect(curated.locator(".pack-card")).to_have_count(1)
+ curated.locator(".pack-card").click()
+ expect(curated.locator(".case-card .case-visual")).to_have_count(1)
+ expect(curated.locator(".case-card .case-copy, .case-actions")).to_have_count(0)
+ expect(curated.locator(".case-card .case-video-badge")).to_have_count(1)
- curated.locator("#detail-close").click()
- curated.locator("#save-theme").click()
- expect(curated.locator("#save-theme")).to_have_text("已全部保存")
- saved = curated.evaluate(
- """async () => {
- const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});
- const entry = state.entries.find((item) => item.title === '精选视频案例');
- const store = await import(chrome.runtime.getURL('media-store.js'));
- const assets = await Promise.all(entry.mediaAssets.map(async (asset) => {
- const blob = await store.getMediaBlob(asset.id);
- return {kind: asset.kind, usage: asset.usage, type: blob?.type, size: blob?.size};
- }));
- return {entry, assets};
- }"""
+ curated.locator(".case-card").click()
+ expect(curated.locator(".case-detail-video")).to_have_count(1)
+ expect(curated.locator(".case-detail-video")).to_have_attribute("poster", POSTER_URL)
+ curated.locator(".case-save-action").click()
+ expect(curated).to_have_url(re.compile(r"/library\.html(?:\?.*)?$"))
+ expect(curated.locator("#detail-drawer")).to_have_class(re.compile(r"\bopen\b"))
+ expect(curated.locator(".detail-video")).to_have_count(1)
+ state = curated.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
+ assert len(state["entries"]) == 1, state
+ saved = state["entries"][0]
+ assert len(saved["mediaAssets"]) == 2, saved
+ assets = curated.evaluate(
+ """async (entry) => Promise.all(entry.mediaAssets.map(async (asset) => {
+ const {getMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
+ const blob = await getMediaBlob(asset.id);
+ return {id: asset.id, kind: asset.kind, type: blob?.type, size: blob?.size};
+ }))""",
+ saved,
)
- assert saved["entry"]["mediaAssets"][0]["kind"] == "video", saved
- assert saved["assets"] == [
- {"kind": "video", "usage": "content", "type": "video/mp4", "size": len(VIDEO_BYTES)},
- {"kind": "image", "usage": "poster", "type": "image/png", "size": len(POSTER_BYTES)},
- ], saved
+ assert assets == [
+ {"id": saved["mediaAssets"][0]["id"], "kind": "video", "type": "video/mp4", "size": len(VIDEO_BYTES)},
+ {"id": saved["mediaAssets"][1]["id"], "kind": "image", "type": "image/png", "size": len(PNG_BYTES)},
+ ], assets
- print({"video_preview": True, "video_saved": True, "assets": saved["assets"]})
+ print({"video_online_player": True, "video_single_save": True, "assets": assets})
if __name__ == "__main__":
diff --git a/test/curated_workflow_e2e.py b/test/curated_workflow_e2e.py
index b369de3..3c1df25 100644
--- a/test/curated_workflow_e2e.py
+++ b/test/curated_workflow_e2e.py
@@ -4,8 +4,11 @@ import base64
import hashlib
import io
import json
+import re
+import struct
import tempfile
import zipfile
+import zlib
from pathlib import Path
from playwright.sync_api import expect
@@ -13,25 +16,41 @@ from playwright.sync_api import expect
from e2e_support import base_entry, extension_session
-PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+PNG_BYTES = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")
CATALOG_URL = "https://wchao6891.github.io/PromptDirector-Curated/catalog.json"
+METRICS_URL = "https://wchao6891.github.io/PromptDirector-Curated/metrics.json"
COVER_URL = "https://wchao6891.github.io/PromptDirector-Curated/covers/workflow.png"
+PREVIEW_URL = "https://wchao6891.github.io/PromptDirector-Curated/previews/workflow/preview.json"
+PREVIEW_IMAGE_URL = "https://wchao6891.github.io/PromptDirector-Curated/previews/workflow/case.webp"
+PORTRAIT_IMAGE_URL = "https://wchao6891.github.io/PromptDirector-Curated/previews/workflow/portrait.webp"
PACKAGE_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/workflow-1.0.0/workflow.zip"
+PUBLIC_DEEP_LINK = "https://wchao6891.github.io/PromptDirector-Curated/?pack=feature%3Aworkflow"
+
+
+def png_bytes(width: int, height: int, rgb: tuple[int, int, int]) -> bytes:
+ signature = b"\x89PNG\r\n\x1a\n"
+ rows = b"".join(b"\x00" + bytes(rgb) * width for _ in range(height))
+
+ def chunk(kind: bytes, data: bytes) -> bytes:
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
+
+ return signature + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(rows, 9)) + chunk(b"IEND", b"")
def package_fixture() -> bytes:
entry = base_entry("curated-workflow-case", "精选工作流案例", "统一层级并保留清晰主体。", "content:prompt:image")
+ portrait = base_entry("curated-portrait-case", "竖版工作流案例", "保留竖版构图和主体比例。", "content:prompt:image")
package = {
"format": "prompt-case-library",
- "version": 2,
- "entries": [entry],
+ "version": 3,
+ "entries": [entry, portrait],
"organizerState": {
"version": 6,
"collections": [{
"id": "collection:curated-workflow",
"name": "工作流主题",
"order": 0,
- "entryIds": [entry["id"]],
+ "entryIds": [entry["id"], portrait["id"]],
}],
},
}
@@ -43,32 +62,76 @@ def package_fixture() -> bytes:
def main() -> None:
archive = package_fixture()
+ item = {
+ "id": "feature:workflow",
+ "title": "工作流精选",
+ "type": "image_prompt",
+ "packageId": "workflow",
+ "packageVersion": "1.0.0",
+ "authorId": "author-editorial",
+ "author": "PromptDirector 编辑精选",
+ "license": "权利归原作者",
+ "updatedAt": "2026-08-08T00:00:00.000Z",
+ "coverUrl": COVER_URL,
+ "previewUrl": PREVIEW_URL,
+ "downloadUrl": PACKAGE_URL,
+ "sha256": hashlib.sha256(archive).hexdigest(),
+ "archiveBytes": len(archive),
+ "caseCount": 2,
+ "imageCount": 0,
+ "videoCount": 0,
+ "summary": "目录摘要不应显示在详情中。",
+ "order": 1,
+ }
catalog = {
"format": "prompt-director-curated",
"version": 2,
"updatedAt": "2026-08-08T00:00:00.000Z",
- "themes": [{
- "id": "feature:workflow",
- "title": "工作流精选",
- "type": "image_prompt",
- "packageId": "workflow",
- "packageVersion": "1.0.0",
- "author": "PromptDirector Editorial",
- "license": "CC BY 4.0",
- "updatedAt": "2026-08-08T00:00:00.000Z",
- "coverUrl": COVER_URL,
- "downloadUrl": PACKAGE_URL,
- "sha256": hashlib.sha256(archive).hexdigest(),
- "caseCount": 1,
- "imageCount": 0,
- "summary": "用于验证自动更新与批量保存。",
- "order": 1,
- }],
+ "themes": [item],
+ }
+ preview = {
+ "format": "prompt-director-curated-preview",
+ "version": 1,
+ "catalogId": item["id"],
+ "packageId": item["packageId"],
+ "packageVersion": item["packageVersion"],
+ "entries": [
+ {
+ "id": "curated-workflow-case",
+ "title": "精选工作流案例",
+ "text": "统一层级并保留清晰主体。",
+ "author": "原作者",
+ "rights": "权利归原作者",
+ "sourceUrl": "https://example.com/workflow-case",
+ "mediaKind": "image",
+ "previewImageUrl": PREVIEW_IMAGE_URL,
+ "width": 1200,
+ "height": 900,
+ },
+ {
+ "id": "curated-portrait-case",
+ "title": "竖版工作流案例",
+ "text": "保留竖版构图和主体比例。",
+ "author": "竖版作者",
+ "rights": "权利归原作者",
+ "sourceUrl": "https://example.com/portrait-case",
+ "mediaKind": "image",
+ "previewImageUrl": PORTRAIT_IMAGE_URL,
+ "width": 900,
+ "height": 1350,
+ },
+ ],
+ }
+ metrics = {
+ "format": "prompt-director-curated-metrics",
+ "version": 1,
+ "updatedAt": "2026-08-08T01:00:00.000Z",
+ "downloads": {item["id"]: 7},
}
requests = {"catalog": 0, "fail": True}
screenshots = Path(tempfile.gettempdir())
- with extension_session("prompt-director-curated-workflow-", viewport={"width": 1440, "height": 900}) as session:
+ with extension_session("prompt-director-curated-workflow-", viewport={"width": 1440, "height": 1000}) as session:
def serve_catalog(route) -> None:
requests["catalog"] += 1
if requests["fail"]:
@@ -77,99 +140,182 @@ def main() -> None:
route.fulfill(status=200, content_type="application/json", body=json.dumps(catalog))
session.context.route(CATALOG_URL, serve_catalog)
+ session.context.route(METRICS_URL, lambda route: route.fulfill(
+ status=200, content_type="application/json", body=json.dumps(metrics)
+ ))
+ session.context.route(PREVIEW_URL, lambda route: route.fulfill(
+ status=200, content_type="application/json", body=json.dumps(preview)
+ ))
session.context.route(COVER_URL, lambda route: route.fulfill(
- status=200,
- content_type="image/png",
- body=base64.b64decode(PNG_BASE64),
+ status=200, content_type="image/png", body=PNG_BYTES
+ ))
+ session.context.route(PREVIEW_IMAGE_URL, lambda route: route.fulfill(
+ status=200, content_type="image/png", body=png_bytes(1200, 900, (36, 52, 68))
+ ))
+ session.context.route(PORTRAIT_IMAGE_URL, lambda route: route.fulfill(
+ status=200, content_type="image/png", body=png_bytes(900, 1350, (68, 52, 36))
))
session.context.route(f"{PACKAGE_URL}*", lambda route: route.fulfill(
- status=200,
- content_type="application/zip",
- body=archive,
+ status=200, content_type="application/zip", body=archive
))
- session.context.add_init_script(
- """(() => {
- if (!globalThis.chrome?.permissions) return;
- Object.defineProperty(chrome.permissions, 'contains', {value: async () => true});
- Object.defineProperty(chrome.permissions, 'request', {value: async () => true});
- })()"""
- )
-
curated = session.open_page("curated.html", wait_until="domcontentloaded")
- expect(curated.locator("#curated-search, #refresh-catalog")).to_have_count(0)
expect(curated.locator("#curated-status")).to_contain_text("503")
expect(curated.locator("#retry-catalog")).to_be_visible()
requests["fail"] = False
curated.locator("#retry-catalog").click()
- expect(curated.locator("#theme-grid .theme-card")).to_have_count(1)
- expect(curated.locator("#retry-catalog")).to_be_hidden()
- curated.screenshot(path=str(screenshots / "promptdirector-step4-curated-themes.png"), full_page=True)
-
- curated.locator(".theme-open").click()
- expect(curated.locator("#cases-view")).to_be_visible()
- expect(curated.locator("#active-theme-title")).to_have_text("工作流精选")
- expect(curated.locator("#active-theme-count")).to_have_text("1 个精选案例")
- expect(curated.locator("#curated-grid .case-card")).to_have_count(1)
- expect(curated.locator("#save-theme")).to_have_text("全部保存")
- expect(curated.locator("#return-label")).to_have_text("返回主题")
- curated.screenshot(path=str(screenshots / "promptdirector-step4-curated-theme-detail.png"), full_page=True)
-
- curated.locator("#save-theme").click()
- expect(curated.locator("#save-theme")).to_have_text("已全部保存")
- expect(curated.locator("#theme-save-status")).to_contain_text("1/1 已保存")
+ expect(curated.locator(".pack-grid .pack-card")).to_have_count(1)
+ expect(curated.locator("#sort-downloads")).to_be_enabled()
+ expect(curated.locator("#filter-popover")).to_be_hidden()
+ expect(curated.locator(".pack-card h2")).to_have_text("工作流精选")
+ expect(curated.locator(".pack-card .pack-meta")).to_contain_text("PromptDirector 编辑精选")
+ curated.screenshot(path=str(screenshots / "promptdirector-curated-pack-wall.png"), full_page=True)
+
+ curated.locator(".pack-card").click()
+ expect(curated.locator("#detail-dialog")).to_be_visible()
+ expect(curated.locator(".detail-info h1")).to_have_text("工作流精选")
+ expect(curated.locator(".detail-meta")).to_contain_text("2 个案例")
+ expect(curated.locator(".detail-actions button")).to_have_count(3)
+ expect(curated.locator(".download-action")).to_have_text("保存整包")
+ expect(curated.locator(".follow-action")).to_have_text("关注")
+ expect(curated.locator(".detail-actions button").nth(2)).to_have_text("复制链接")
+ expect(curated.locator(".case-list .case-card")).to_have_count(2)
+ expect(curated.locator(".case-card h3, .case-card .case-copy, .case-actions")).to_have_count(0)
+ geometry = curated.locator(".case-card").evaluate_all(
+ "cards => cards.map(card => ({width: card.offsetWidth, height: card.offsetHeight}))"
+ )
+ assert geometry[0]["height"] < geometry[1]["height"], geometry
+ expect(curated.locator("text=目录摘要不应显示在详情中。")).to_have_count(0)
+ expect(curated.locator("text=版本")).to_have_count(0)
+ expect(curated.locator("text=更新日期")).to_have_count(0)
+ expect(curated.locator("text=以此创作")).to_have_count(0)
+
+ before_follow = curated.evaluate("""() => {
+ document.querySelector('.case-card').dataset.renderIdentity = 'kept';
+ document.querySelector('#detail-dialog').scrollTop = 120;
+ return document.querySelector('#detail-dialog').scrollTop;
+ }""")
+ curated.locator(".follow-action").click()
+ expect(curated.locator(".follow-action")).to_have_text("已关注")
+ assert curated.locator('.case-card[data-render-identity="kept"]').count() == 1
+ assert curated.locator("#detail-dialog").evaluate("dialog => dialog.scrollTop") == before_follow
+ following = curated.evaluate("async () => (await chrome.storage.local.get('curatedFollowingAuthors')).curatedFollowingAuthors")
+ assert following == ["author-editorial"], following
+
+ curated.locator(".detail-actions button").nth(2).click()
+ copied_link = curated.evaluate("() => navigator.clipboard.readText()")
+ assert copied_link == PUBLIC_DEEP_LINK, copied_link
+
+ curated.locator(".case-card").first.click()
+ expect(curated.locator("#case-detail-drawer")).to_have_class("case-detail-drawer open")
+ expect(curated.locator(".case-detail-heading h2")).to_have_text("精选工作流案例")
+ expect(curated.locator(".case-detail-heading p")).to_have_text("原作者")
+ expect(curated.locator(".case-detail-prompt")).to_have_text("统一层级并保留清晰主体。")
+ expect(curated.locator(".case-detail-source a")).to_have_attribute("href", "https://example.com/workflow-case")
+ assert curated.locator("#detail-content").get_attribute("inert") == ""
+ assert curated.locator("#detail-close").get_attribute("inert") == ""
+ landscape = curated.locator(".case-detail-figure img").evaluate(
+ "img => ({natural: img.naturalWidth / img.naturalHeight, rendered: img.getBoundingClientRect().width / img.getBoundingClientRect().height})"
+ )
+ assert abs(landscape["natural"] - 4 / 3) < 0.01, landscape
+ assert abs(landscape["rendered"] - landscape["natural"]) < 0.01, landscape
+
+ curated.locator("#case-detail-next").click()
+ expect(curated.locator(".case-detail-heading h2")).to_have_text("竖版工作流案例")
+ portrait = curated.locator(".case-detail-figure img").evaluate(
+ "img => ({natural: img.naturalWidth / img.naturalHeight, rendered: img.getBoundingClientRect().width / img.getBoundingClientRect().height})"
+ )
+ assert abs(portrait["natural"] - 2 / 3) < 0.01, portrait
+ assert abs(portrait["rendered"] - portrait["natural"]) < 0.01, portrait
+ curated.locator("#case-detail-prev").click()
+
+ curated.locator(".case-detail-actions .button-secondary").click()
+ copied_prompt = curated.evaluate("() => navigator.clipboard.readText()")
+ assert copied_prompt == "统一层级并保留清晰主体。", copied_prompt
+ expect(curated.locator(".case-detail-actions .button-secondary")).to_have_text("已复制")
+
+ curated.locator(".case-save-action").click()
+ expect(curated).to_have_url(re.compile(r"/library\.html(?:\?.*)?$"))
+ expect(curated.locator("#detail-drawer")).to_have_class(re.compile(r"\bopen\b"))
state = curated.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
assert len(state["entries"]) == 1, state
+ source_key = curated.evaluate(
+ """async (entry) => {
+ const {curatedSourceKey} = await import(chrome.runtime.getURL('curated-catalog.js'));
+ return curatedSourceKey(entry);
+ }""",
+ state["entries"][0],
+ )
+ assert source_key == "workflow:curated-workflow-case", source_key
+
+ curated.screenshot(path=str(screenshots / "promptdirector-curated-case-detail.png"), full_page=False)
+ curated.evaluate("location.assign(chrome.runtime.getURL('curated.html'))")
+ expect(curated.locator(".pack-card")).to_have_count(1)
+ curated.locator(".pack-card").click()
+ curated.locator(".download-action").click()
+ expect(curated.locator("#pack-save-dialog")).to_be_visible()
+ expect(curated.locator(".pack-save-meta")).to_contain_text("2 个案例")
+ curated.locator(".pack-save-confirm").click()
+ expect(curated).to_have_url(re.compile(r"/library\.html(?:\?.*)?$"))
+ expect(curated.locator('.project-filter[aria-label^="工作流精选 "]')).to_have_attribute("aria-pressed", "true")
+ state = curated.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
+ assert len(state["entries"]) == 2, state
+ assert state["organizerState"]["collections"][0]["id"] == "curated-project:workflow", state
+ curated.evaluate("location.assign(chrome.runtime.getURL('curated.html'))")
+ expect(curated.locator(".pack-card")).to_have_count(1)
+ curated.locator(".pack-card").click()
+ curated.screenshot(path=str(screenshots / "promptdirector-curated-pack-detail.png"), full_page=False)
+ curated.keyboard.press("Escape")
+ expect(curated.locator("#detail-dialog")).not_to_be_visible()
+ expect(curated.locator(".pack-card")).to_be_focused()
+
+ curated.locator("#curated-search").fill("清晰主体")
+ expect(curated.locator(".pack-card")).to_have_count(1)
+ curated.locator("#filter-button").click()
+ curated.locator('#filter-popover input[value="followed"]').check()
+ expect(curated.locator(".pack-card")).to_have_count(1)
+
+ curated.set_viewport_size({"width": 820, "height": 650})
+ curated.locator(".pack-card").click()
+ medium_geometry = curated.evaluate(
+ """() => ({viewport: innerWidth, page: document.documentElement.scrollWidth,
+ info: document.querySelector('.detail-info').getBoundingClientRect().width})"""
+ )
+ assert medium_geometry["page"] <= medium_geometry["viewport"], medium_geometry
+ assert 360 <= medium_geometry["info"] <= 450, medium_geometry
+ curated.keyboard.press("Escape")
- curated.locator("#return-library").click()
- expect(curated.locator("#themes-view")).to_be_visible()
- expect(curated.locator("#return-label")).to_have_text("返回我的案例库")
- expect(curated.locator(".theme-card-actions")).to_contain_text("1/1 已保存")
-
- auto = session.open_page("curated.html", wait_until="networkidle")
- expect(auto.locator("#theme-grid .theme-card")).to_have_count(1)
- assert requests["catalog"] >= 3, requests
-
- auto.set_viewport_size({"width": 390, "height": 844})
- auto.locator(".theme-open").click()
- expect(auto.locator("#active-theme-count")).to_be_visible()
- geometry = auto.evaluate(
- """() => ({
- viewport: innerWidth,
- page: document.documentElement.scrollWidth,
- toolbarRight: document.querySelector('.theme-toolbar').getBoundingClientRect().right,
- actionRight: document.querySelector('.theme-save-actions').getBoundingClientRect().right
- })"""
+ curated.set_viewport_size({"width": 390, "height": 844})
+ curated.locator(".pack-card").click()
+ expect(curated.locator(".detail-info")).to_be_visible()
+ geometry = curated.evaluate(
+ """() => ({viewport: innerWidth, page: document.documentElement.scrollWidth,
+ detail: document.querySelector('.detail-surface').getBoundingClientRect().right})"""
)
assert geometry["page"] <= geometry["viewport"], geometry
- assert geometry["toolbarRight"] <= geometry["viewport"] + 1, geometry
- assert geometry["actionRight"] <= geometry["viewport"] + 1, geometry
- auto.screenshot(path=str(screenshots / "promptdirector-step4-curated-mobile.png"), full_page=True)
+ assert geometry["detail"] <= geometry["viewport"] + 1, geometry
+ curated.screenshot(path=str(screenshots / "promptdirector-curated-mobile.png"), full_page=False)
- auto.evaluate("""async () => {
+ curated.keyboard.press("Escape")
+ curated.evaluate("""async () => {
await chrome.storage.local.set({uiPreferences: {locale: 'en', theme: 'dark', motion: 'reduced'}});
localStorage.setItem('promptDirectorTheme', 'dark');
localStorage.setItem('promptDirectorMotion', 'reduced');
}""")
- auto.reload(wait_until="networkidle")
- expect(auto.locator(".curated-header h1")).to_have_text("Curated cases")
- expect(auto.locator(".themes-heading h2")).to_have_text("Browse by edition")
- expect(auto.locator(".theme-card-actions button")).to_have_text("All saved")
- auto.locator(".theme-open").click()
- expect(auto.locator("#return-label")).to_have_text("Back to editions")
- expect(auto.locator("#active-theme-count")).to_have_text("1 curated cases")
+ curated.reload(wait_until="networkidle")
+ expect(curated.locator(".curated-header h1")).to_have_text("Curated cases")
+ expect(curated.locator("#curated-search")).to_have_attribute("placeholder", "Search packs or cases")
+ expect(curated.locator("#return-library")).to_have_text("Back to library")
print({
- "automatic_catalog_requests": requests["catalog"],
- "failure_retry": True,
- "theme_enter_back": True,
- "batch_save": True,
+ "catalog_retry": requests["catalog"],
+ "pack_detail": True,
+ "single_save": True,
+ "verified_pack_save": True,
+ "follow_local": following,
+ "copy_deep_link": copied_link,
+ "medium": medium_geometry,
"mobile": geometry,
"english_ui": True,
- "screenshots": [
- str(screenshots / "promptdirector-step4-curated-themes.png"),
- str(screenshots / "promptdirector-step4-curated-theme-detail.png"),
- str(screenshots / "promptdirector-step4-curated-mobile.png"),
- ],
})
diff --git a/test/e2e_support.py b/test/e2e_support.py
index fe58460..159a590 100644
--- a/test/e2e_support.py
+++ b/test/e2e_support.py
@@ -12,6 +12,15 @@ from playwright.sync_api import BrowserContext, Page, Playwright, sync_playwrigh
EXTENSION_DIR = Path(__file__).resolve().parents[1]
+AI_TASK_IDS = (
+ "textTags",
+ "skillExtraction",
+ "creativePlanning",
+ "imageAnalysis",
+ "videoAnalysis",
+ "imageGeneration",
+ "videoGeneration",
+)
@dataclass
@@ -43,6 +52,7 @@ def extension_session(
*,
viewport: dict | None = None,
accept_downloads: bool = True,
+ extension_dir: Path = EXTENSION_DIR,
) -> Iterator[ExtensionTestSession]:
with tempfile.TemporaryDirectory(prefix=profile_prefix) as profile:
with sync_playwright() as playwright:
@@ -51,6 +61,7 @@ def extension_session(
profile,
viewport=viewport or {"width": 1280, "height": 900},
accept_downloads=accept_downloads,
+ extension_dir=extension_dir,
)
page_errors: list[str] = []
context.on("page", lambda page: record_page_errors(page, page_errors))
@@ -68,6 +79,7 @@ def launch_context(
*,
viewport: dict,
accept_downloads: bool,
+ extension_dir: Path = EXTENSION_DIR,
) -> BrowserContext:
return playwright.chromium.launch_persistent_context(
profile_dir,
@@ -77,8 +89,8 @@ def launch_context(
viewport=viewport,
permissions=["clipboard-read", "clipboard-write"],
args=[
- f"--disable-extensions-except={EXTENSION_DIR}",
- f"--load-extension={EXTENSION_DIR}",
+ f"--disable-extensions-except={extension_dir}",
+ f"--load-extension={extension_dir}",
],
)
@@ -97,6 +109,23 @@ def record_page_errors(page: Page, errors: list[str]) -> None:
page.on("pageerror", record)
+def ai_configuration_fixture(
+ *,
+ providers: dict,
+ assignments: dict,
+ auto_analyze_imports: bool = False,
+) -> dict:
+ """Build the one persisted Registry v4 shape used by extension E2E fixtures."""
+ return {
+ "aiProviderRegistry": {"version": 4, "providers": providers},
+ "aiTaskAssignments": {
+ task_id: assignments.get(task_id, {"providerId": "", "model": ""})
+ for task_id in AI_TASK_IDS
+ },
+ "aiPreferences": {"autoAnalyzeImports": auto_analyze_imports},
+ }
+
+
def wait_for_download(page: Page, after_id: int = 0, timeout_seconds: float = 12) -> tuple[Path, int]:
deadline = time.monotonic() + timeout_seconds
records: list[dict] = []
diff --git a/test/i18n.test.js b/test/i18n.test.js
index f0d8465..b363ece 100644
--- a/test/i18n.test.js
+++ b/test/i18n.test.js
@@ -29,6 +29,15 @@ test("missing sync folders have localized recovery guidance", () => {
assert.equal(translateForLocale("重新选择同步文件夹", "en"), "Select sync folder again");
});
+test("composer reference-image modes explain the real image and token behavior in English", () => {
+ assert.equal(translateForLocale("参考图参与方式", "en"), "How reference images are used");
+ assert.equal(translateForLocale("带原图生成(默认)", "en"), "Generate with original images (default)");
+ assert.equal(
+ translateForLocale("全程只用案例/分析文字(不读图,最省 token)", "en"),
+ "Use case prompts or analysis text only (no image reading, lowest token use)"
+ );
+});
+
async function readJson(path) {
return JSON.parse(await readFile(new URL(path, import.meta.url), "utf8"));
}
diff --git a/test/jimeng_capture_e2e.py b/test/jimeng_capture_e2e.py
new file mode 100644
index 0000000..e679247
--- /dev/null
+++ b/test/jimeng_capture_e2e.py
@@ -0,0 +1,155 @@
+from __future__ import annotations
+
+import json
+import shutil
+import tempfile
+from pathlib import Path
+
+from playwright.sync_api import expect
+
+from e2e_support import EXTENSION_DIR, extension_session
+
+
+PNG = bytes.fromhex(
+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
+ "0000000d49444154789c6360f8cfc000000301010018dd8db10000000049454e44ae426082"
+)
+HOME_URL = "https://jimeng.jianying.com/ai-tool/home"
+WORK_ID = "7490123456789012345"
+DETAIL_URL = f"https://jimeng.jianying.com/ai-tool/work-detail/{WORK_ID}"
+
+
+def explore_item(work_id: str, author: str, prompt: str) -> dict:
+ return {
+ "extra": {"template_type": "image"},
+ "common_attr": {"id": work_id, "title": "", "create_time": 1786000000},
+ "author": {"name": author, "uid": f"author-{work_id[-4:]}"},
+ "aigc_image_params": {"text2image_params": {"prompt": prompt}},
+ "aigc_draft": {"content": json.dumps({"component_list": [{"abilities": {"generate": {"core_param": {"model": "jimeng_v47"}}}}]})},
+ "statistic": {"favorite_num": 87, "usage_num": 12},
+ "image": {"large_images": [{
+ "image_url": f"https://p3-dreamina-sign.byteimg.com/{work_id}.webp",
+ "width": 2048,
+ "height": 3072,
+ }]},
+ }
+
+
+def main() -> None:
+ feed = {"data": {"item_list": [
+ explore_item(WORK_ID, "AIGC大叔", "敦煌文化主题场景,全景,暗黑风。"),
+ explore_item("7490123456789012346", "作者乙", "山海经异兽,电影光影。"),
+ ]}}
+ home_html = f"""<!doctype html><html><head><title>即梦AI - 一站式AI创作平台</title></head><body>
+<nav>发现 技能 短片 活动</nav><main>上传参考图 输入文字 图片生成 二维码</main>
+<script>window.__get_explore_result={json.dumps(feed, ensure_ascii=False)};</script>
+</body></html>""".encode()
+ detail_html = f"""<!doctype html><html><head><title>即梦AI - 一站式AI创作平台</title></head><body>
+<main style=\"display:flex;gap:40px\">
+<img id=\"artwork\" src=\"https://p3-dreamina-sign.byteimg.com/{WORK_ID}.webp\" style=\"display:block;width:450px;height:700px\">
+<section><div>AIGC大叔</div><button>+ 关注</button><div>87</div><div>2026-05-30 | 内容由 AI 生成</div>
+<div>图片提示词</div><p id=\"prompt\">敦煌文化主题场景,全景,暗黑风。</p><div>图片 4.7 | 9:16 | 更多</div>
+<button>做同款</button><button>用作参考图</button></section></main>
+</body></html>""".encode()
+
+ with tempfile.TemporaryDirectory(prefix="prompt-director-jimeng-extension-") as extension_root:
+ extension_dir = Path(extension_root) / "extension"
+ shutil.copytree(
+ EXTENSION_DIR,
+ extension_dir,
+ ignore=shutil.ignore_patterns("node_modules", ".scratch", "test", "docs", "plan", "dist", "tmp"),
+ )
+ manifest_file = extension_dir / "manifest.json"
+ manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
+ manifest["host_permissions"] = list(dict.fromkeys([*manifest.get("host_permissions", []), "<all_urls>"]))
+ manifest_file.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ run_jimeng_flow(extension_dir, home_html, detail_html)
+
+
+def run_jimeng_flow(extension_dir: Path, home_html: bytes, detail_html: bytes) -> None:
+ with extension_session("prompt-director-jimeng-capture-", extension_dir=extension_dir) as run:
+ def route_jimeng(route) -> None:
+ if route.request.url == HOME_URL:
+ route.fulfill(status=200, body=home_html, content_type="text/html; charset=utf-8")
+ elif route.request.url == DETAIL_URL:
+ route.fulfill(status=200, body=detail_html, content_type="text/html; charset=utf-8")
+ else:
+ route.fulfill(status=404, body=b"not found", content_type="text/plain")
+
+ run.context.route("https://jimeng.jianying.com/**", route_jimeng)
+ run.context.route("https://p3-dreamina-sign.byteimg.com/**", lambda route: route.fulfill(status=200, body=PNG, content_type="image/png"))
+ collector = run.open_page("collector.html", wait_until="networkidle")
+ run.seed_storage(collector, {"schemaVersion": 24, "entries": []})
+ fixture = run.context.new_page()
+ fixture.goto(HOME_URL, wait_until="networkidle")
+ fixture.bring_to_front()
+ active_before = collector.evaluate("() => chrome.tabs.query({active: true, currentWindow: true}).then(tabs => tabs[0]?.url)")
+ assert active_before == HOME_URL, {"activeBefore": active_before}
+ collector.evaluate("() => document.querySelector('#start-page-capture').click()")
+ collector.wait_for_timeout(1200)
+ capture_state = collector.evaluate("""() => ({
+ hidden: document.querySelector('#page-capture').hidden,
+ feedback: document.querySelector('#feedback').textContent,
+ startHidden: document.querySelector('#start-state').hidden
+ })""")
+ assert not capture_state["hidden"], capture_state
+ expect(collector.locator("#page-capture")).to_be_visible(timeout=8000)
+ expect(collector.locator(".page-capture-item")).to_have_count(2)
+ preview_text = collector.locator("#page-capture-list").inner_text()
+ assert "AIGC大叔" in preview_text, preview_text
+ assert "作者乙" in preview_text, preview_text
+ assert "上传参考图" not in preview_text and "二维码" not in preview_text, preview_text
+ first_candidate = collector.locator(".page-capture-item").first
+ first_candidate.locator(".page-capture-confirm").click()
+ expect(collector.locator("#page-capture-media-review")).to_be_visible()
+ expect(collector.locator("#page-capture-media-review-list .page-capture-media-review-item")).to_have_count(1)
+ expect(collector.locator("#page-capture-save")).to_have_text("保存案例 · 含 1 项媒体")
+
+ collector.evaluate("() => document.querySelector('#page-capture-save').click()")
+ expect(collector.locator("#page-capture")).to_be_hidden(timeout=8000)
+ home_saved = collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries)")
+ assert len(home_saved) == 1, home_saved
+ assert home_saved[0]["sourceFacts"]["author"] == "AIGC大叔", home_saved[0]
+ assert home_saved[0]["sourceFacts"]["itemId"] == WORK_ID, home_saved[0]
+ assert home_saved[0]["title"] != "即梦AI - 一站式AI创作平台", home_saved[0]
+ assert len(home_saved[0].get("mediaAssets", [])) == 1, home_saved[0]
+
+ collector.evaluate("() => chrome.storage.local.set({entries: [], captureDraft: {}})")
+ fixture.goto(DETAIL_URL, wait_until="networkidle")
+ fixture.evaluate("""() => {
+ const range = document.createRange();
+ range.selectNodeContents(document.querySelector('#prompt'));
+ const selection = window.getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ }""")
+ fixture.bring_to_front()
+ collector.evaluate("() => document.querySelector('#start-selection').click()")
+ expect(collector.locator("#preview-state")).to_be_visible(timeout=8000)
+ expect(collector.locator("#quick-preview")).to_contain_text("AIGC大叔")
+
+ collector.evaluate("() => document.querySelector('#add-smart-visuals').click()")
+ expect(collector.locator("#smart-selection")).to_be_visible(timeout=8000)
+ expect(fixture.locator(".prompt-case-visual-candidate")).to_have_count(1, timeout=8000)
+ fixture.locator(".prompt-case-visual-candidate").click()
+ expect(collector.locator("#smart-selection-confirm")).to_be_enabled(timeout=5000)
+ collector.evaluate("() => document.querySelector('#smart-selection-confirm').click()")
+ expect(collector.locator("#smart-selection")).to_be_hidden(timeout=8000)
+ expect(collector.locator("#preview-state")).to_be_visible(timeout=8000)
+ expect(collector.locator("#visual-list .visual-card")).to_have_count(1)
+ expect(collector.locator("#quick-preview")).to_contain_text("AIGC大叔")
+
+ collector.evaluate("() => document.querySelector('#save-draft').click()")
+ expect(collector.locator("#start-state")).to_be_visible(timeout=8000)
+ detail_saved = collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries)")
+ assert len(detail_saved) == 1, detail_saved
+ assert detail_saved[0]["sourceFacts"]["author"] == "AIGC大叔", detail_saved[0]
+ assert detail_saved[0]["sourceFacts"]["model"] == "4.7", detail_saved[0]
+ assert detail_saved[0]["sourceFacts"]["engagement"]["favorites"] == 87, detail_saved[0]
+ assert detail_saved[0]["title"].startswith("AIGC大叔"), detail_saved[0]
+ assert len(detail_saved[0].get("mediaAssets", [])) == 1, detail_saved[0]
+ print({"homeCandidates": 2, "detailAuthor": "AIGC大叔", "detailFavorites": 87, "detailSmartImages": 1})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/large_library_e2e.py b/test/large_library_e2e.py
index 74152db..446e912 100644
--- a/test/large_library_e2e.py
+++ b/test/large_library_e2e.py
@@ -110,8 +110,13 @@ def main() -> None:
batch = library.evaluate(
"""async () => {
await chrome.runtime.sendMessage({
- type: 'UPDATE_AI_SETTINGS',
- settings: {apiKey: 'isolated-e2e-key', consent: true}
+ type: 'UPDATE_AI_PROVIDER_CONFIGURATION',
+ registry: {providers: {deepseek: {
+ apiKey: 'isolated-e2e-key',
+ consent: true,
+ models: {textTags: 'isolated-e2e'}
+ }}},
+ assignments: {textTags: {providerId: 'deepseek', model: 'isolated-e2e'}}
});
const created = await chrome.runtime.sendMessage({type: 'CREATE_ANALYSIS_BATCH'});
const claimed = await chrome.runtime.sendMessage({
diff --git a/test/library-detail-layout.test.js b/test/library-detail-layout.test.js
index 5ba1765..127b828 100644
--- a/test/library-detail-layout.test.js
+++ b/test/library-detail-layout.test.js
@@ -118,7 +118,8 @@ test("document navigation moves into the top toolbar and long documents use a re
const documentStage = rule(source, ".detail-visual-gallery.is-document-detail .detail-visual-stage");
const documentItem = rule(source, ".detail-visual-gallery.is-document-detail .detail-visual-item");
- assert.match(script, /const usesStageNavigation = entryHasMedia\(entry, "image"\) \|\| entryHasMedia\(entry, "video"\)/);
+ assert.match(script, /const hasArticleDocument = !capturedPost && Boolean\(entry\.articleDocument\?\.blocks\?\.length\)/);
+ assert.match(script, /const usesStageNavigation = !capturedPost && !hasArticleDocument && \(entryHasMedia\(entry, "image"\) \|\| entryHasMedia\(entry, "video"\)\)/);
assert.match(script, /else elements\.drawerToolbar\.prepend\(elements\.detailNavigation\)/);
assert.match(script, /gallery\.classList\.toggle\("is-document-detail", asset\.kind === "document"\)/);
assert.match(script, /stage\.scrollTop = 0/);
@@ -130,6 +131,31 @@ test("document navigation moves into the top toolbar and long documents use a re
assert.match(documentItem, /overflow:\s*visible/);
});
+test("captured posts use a compact post view while articles show only genuinely unplaced media separately", async () => {
+ const script = await readFile(new URL("../library.js", import.meta.url), "utf8");
+ const styles = await readFile(cssUrl, "utf8");
+ const detail = script.slice(script.indexOf("async function renderDetail"), script.indexOf("function createLocalDiscovery"));
+ assert.match(detail, /const capturedPost = isCapturedPost\(entry\)/);
+ assert.match(detail, /createCapturedPostView\(entry\)/);
+ assert.match(detail, /createUnplacedMediaShelf\(entry\)/);
+ assert.match(script, /function articleReferencedAssetIds/);
+ assert.match(script, /function createCapturedPostView/);
+ assert.match(script, /帖子文字/);
+ assert.match(script, /打开原帖/);
+ assert.doesNotMatch(detail, /单独查看文章媒体/);
+ assert.match(rule(styles, ".captured-post-view"), /background:\s*var\(--card\)/);
+ assert.match(rule(styles, ".unplaced-media-shelf"), /grid-template-columns:/);
+});
+
+test("media switching preserves the detail scroll anchor and locks image stage height", async () => {
+ const script = await readFile(new URL("../library.js", import.meta.url), "utf8");
+ const gallery = script.slice(script.indexOf("async function createDetailMediaGallery"), script.indexOf("function refreshActiveDetailAssetSections"));
+ assert.match(gallery, /lockedImageStageHeight/);
+ assert.match(gallery, /captureDetailScrollAnchor/);
+ assert.match(gallery, /restoreDetailScrollAnchor/);
+ assert.match(gallery, /button\.focus\(\{ preventScroll: true \}\)/);
+});
+
test("compound details retain their existing split layout", async () => {
const source = await readFile(cssUrl, "utf8");
const compound = rule(source, ".detail-content.is-compound-detail");
diff --git a/test/library-model.test.js b/test/library-model.test.js
index e833128..8244dd4 100644
--- a/test/library-model.test.js
+++ b/test/library-model.test.js
@@ -132,6 +132,29 @@ test("source metadata becomes readable rows instead of tag values", () => {
]);
});
+test("structured source facts are readable and searchable without becoming tags", () => {
+ const entry = {
+ id: "jimeng",
+ title: "案例",
+ sourceFacts: {
+ provider: "jimeng",
+ itemId: "7490123456789012345",
+ author: "AIGC大叔",
+ handle: "creator-7",
+ publishedAt: "2026-05-30T00:00:00.000Z",
+ model: "即梦 4.7",
+ dimensions: "2160×3840",
+ engagement: { favorites: 87 }
+ }
+ };
+
+ const rows = entrySourceMetadataRows(entry);
+ assert.ok(rows.some((row) => row.label === "作者" && row.value === "AIGC大叔"));
+ assert.ok(rows.some((row) => row.label === "模型" && row.value === "即梦 4.7"));
+ assert.deepEqual(filterEntries([entry], { query: "creator-7" }, createDefaultFacetCatalog()).map((item) => item.id), ["jimeng"]);
+ assert.deepEqual(entryAttributeSummary(entry, createDefaultFacetCatalog()), []);
+});
+
test("import metadata remains searchable without becoming a content tag", () => {
const entries = [{ id: "imported", title: "案例", metadataLabels: ["Higgsfield Community", "作者:creator"] }];
assert.deepEqual(filterEntries(entries, { query: "creator" }, createDefaultFacetCatalog()).map((item) => item.id), ["imported"]);
diff --git a/test/library-navigation.test.js b/test/library-navigation.test.js
index 4e8fe5d..6d52f55 100644
--- a/test/library-navigation.test.js
+++ b/test/library-navigation.test.js
@@ -88,6 +88,7 @@ test("classification manager keeps taxonomy work while settings owns AI services
assert.match(settings, /id="ai-settings-form"/);
assert.match(settings, /id="vision-settings-form"/);
assert.match(settings, /id="composer-settings-form"/);
+ assert.doesNotMatch(settings, /id="deepseek-api-key"|id="text-ai-provider"|id="vision-provider"|id="vision-compatible-endpoint"/);
});
test("collector opens a new library tab and disables the side panel for that tab", async () => {
diff --git a/test/library-package.test.js b/test/library-package.test.js
index 09f0a4d..7a69d1b 100644
--- a/test/library-package.test.js
+++ b/test/library-package.test.js
@@ -172,12 +172,20 @@ test("imports remap visual ids that would overwrite a different local case", ()
hasScreenshot: undefined,
screenshotPath: undefined,
visuals: [{ id: "shared-visual", screenshotPath: "images/remote/shared.webp" }],
- primaryVisualId: "shared-visual"
+ primaryVisualId: "shared-visual",
+ articleDocument: {
+ version: 1,
+ blocks: [
+ { id: "article-copy", kind: "paragraph", text: "正文" },
+ { id: "article-image", kind: "image", assetId: "shared-visual", sourceUrl: "https://example.com/original.webp" }
+ ]
+ }
}];
const result = mergeLibraryPackage(current, imported);
const remote = result.state.entries.find((item) => item.id === "remote");
assert.notEqual(remote.primaryMediaId, "shared-visual");
assert.equal(result.visualIdMap["shared-visual"], remote.primaryMediaId);
+ assert.equal(remote.articleDocument.blocks[1].assetId, remote.primaryMediaId);
});
test("imports remap both sides of a video poster relationship", () => {
diff --git a/test/library_core_e2e.py b/test/library_core_e2e.py
index f2805bc..4878fdd 100644
--- a/test/library_core_e2e.py
+++ b/test/library_core_e2e.py
@@ -76,7 +76,7 @@ def main() -> None:
expect(library.locator(".attribute-section")).to_contain_text("渲染6")
library.locator(".detail-analysis-menu > summary").click()
library.get_by_role("button", name="分析检索标签").click()
- expect(library.locator("#feedback")).to_contain_text("DeepSeek 尚未完成文字标签配置")
+ expect(library.locator("#feedback")).to_contain_text("文字标签尚未分配 AI 服务")
library.wait_for_timeout(8_200)
expect(library.locator("#feedback")).to_be_hidden()
library.locator("#detail-close").click()
diff --git a/test/library_import_ui_e2e.py b/test/library_import_ui_e2e.py
index 468f00a..50572d6 100644
--- a/test/library_import_ui_e2e.py
+++ b/test/library_import_ui_e2e.py
@@ -6,7 +6,7 @@ from pathlib import Path
from playwright.sync_api import expect
-from e2e_support import base_entry, extension_session
+from e2e_support import ai_configuration_fixture, base_entry, extension_session
def wait_for_confirmation(page, supported: str) -> None:
@@ -90,12 +90,19 @@ def main() -> None:
"visibility": "library",
}],
},
- "visionSettings": {
- "activeProvider": "openai",
- "consent": True,
- "autoAnalyzeImports": True,
- "openai": {"model": "gpt-4.1-mini", "apiKey": "test-only-key"},
- },
+ **ai_configuration_fixture(
+ providers={
+ "openai": {
+ "apiKey": "test-only-key",
+ "consent": True,
+ "models": {"imageAnalysis": "gpt-4.1-mini"},
+ },
+ },
+ assignments={
+ "imageAnalysis": {"providerId": "openai", "model": "gpt-4.1-mini"},
+ },
+ auto_analyze_imports=True,
+ ),
})
setup.evaluate(
"""async () => {
diff --git a/test/library_media_actions_e2e.py b/test/library_media_actions_e2e.py
index 405db83..177cf6d 100644
--- a/test/library_media_actions_e2e.py
+++ b/test/library_media_actions_e2e.py
@@ -43,7 +43,7 @@ def main() -> None:
1,
)
entry["mediaAssets"] = [
- image_asset(f"multi-image-{index}", f"2026-08-03T00:00:{index:02d}.000Z")
+ image_asset(f"multi-image-{index}", f"2026-08-03T00:00:{index:02d}.000Z", index)
for index in range(1, 16)
]
entry["primaryMediaId"] = "multi-image-1"
@@ -74,10 +74,17 @@ def main() -> None:
"""() => {
const gallery = document.querySelector('.detail-visual-gallery');
const rail = gallery.querySelector('.detail-visual-rail');
+ const detail = document.querySelector('#detail-content');
gallery.dataset.stabilityProbe = 'same-gallery';
rail.scrollLeft = rail.scrollWidth;
const rect = gallery.getBoundingClientRect();
- return {railScrollLeft: rail.scrollLeft, galleryTop: rect.top};
+ return {
+ railScrollLeft: rail.scrollLeft,
+ galleryTop: rect.top,
+ railTop: rail.getBoundingClientRect().top,
+ stageHeight: gallery.querySelector('.detail-visual-stage').getBoundingClientRect().height,
+ detailScrollTop: detail.scrollTop
+ };
}"""
)
for index in (14, 6, 11):
@@ -88,12 +95,22 @@ def main() -> None:
const gallery = document.querySelector('.detail-visual-gallery[data-stability-probe="same-gallery"]');
const rail = gallery?.querySelector('.detail-visual-rail');
const rect = gallery?.getBoundingClientRect();
- return {sameNode: Boolean(gallery), railScrollLeft: rail?.scrollLeft, galleryTop: rect?.top};
+ return {
+ sameNode: Boolean(gallery),
+ railScrollLeft: rail?.scrollLeft,
+ galleryTop: rect?.top,
+ railTop: rail?.getBoundingClientRect().top,
+ stageHeight: gallery?.querySelector('.detail-visual-stage').getBoundingClientRect().height,
+ detailScrollTop: document.querySelector('#detail-content').scrollTop
+ };
}"""
)
assert stable_after["sameNode"], stable_after
assert abs(stable_after["railScrollLeft"] - stable_before["railScrollLeft"]) <= 1, (stable_before, stable_after)
assert abs(stable_after["galleryTop"] - stable_before["galleryTop"]) <= 1, (stable_before, stable_after)
+ assert abs(stable_after["railTop"] - stable_before["railTop"]) <= 1, (stable_before, stable_after)
+ assert abs(stable_after["stageHeight"] - stable_before["stageHeight"]) <= 1, (stable_before, stable_after)
+ assert abs(stable_after["detailScrollTop"] - stable_before["detailScrollTop"]) <= 1, (stable_before, stable_after)
library.locator(".detail-visual-thumb").nth(14).click()
@@ -132,15 +149,16 @@ def main() -> None:
})
-def image_asset(asset_id: str, captured_at: str) -> dict:
+def image_asset(asset_id: str, captured_at: str, index: int) -> dict:
+ width, height = (1600, 900) if index % 2 else (900, 1600)
return {
"id": asset_id,
"kind": "image",
"usage": "content",
"storageMode": "managed",
"mimeType": "image/png",
- "width": 1,
- "height": 1,
+ "width": width,
+ "height": height,
"capturedAt": captured_at,
"reviewStatus": "verified",
}
diff --git a/test/local-media.test.js b/test/local-media.test.js
index b797431..522a5f2 100644
--- a/test/local-media.test.js
+++ b/test/local-media.test.js
@@ -7,6 +7,7 @@ import {
normalizeLocalRelativePath,
prepareLocalMedia
} from "../local-media.js";
+import { PORTABLE_LIBRARY_LIMITS } from "../resource-limits.js";
test("local media detection keeps only supported formats and safe relative paths", () => {
assert.deepEqual(detectLocalMediaFile(new File(["image"], "frame.gif", { type: "image/gif" })), {
@@ -51,6 +52,27 @@ test("GIF preparation retains the original and creates one first-frame poster",
assert.equal(prepared.poster.blob, posterBlob);
});
+test("local image preparation rejects files above the portable image limit before decoding", async () => {
+ const oversized = new File(
+ [new Uint8Array(PORTABLE_LIBRARY_LIMITS.maxImageBytes + 1)],
+ "oversized.png",
+ { type: "image/png" }
+ );
+ let dimensionReads = 0;
+
+ await assert.rejects(
+ () => prepareLocalMedia(oversized, "asset:oversized", {
+ estimateStorage: async () => ({ quota: oversized.size * 2, usage: 0 }),
+ readImageDimensions: async () => {
+ dimensionReads += 1;
+ return { width: 1, height: 1 };
+ }
+ }),
+ /16 MiB/
+ );
+ assert.equal(dimensionReads, 0);
+});
+
test("exact duplicate detection hashes only size type and name candidates", async () => {
const incoming = new File(["same bytes"], "frame.png", { type: "image/png" });
const blobs = new Map([
diff --git a/test/media.test.js b/test/media.test.js
index f65f947..0a4c183 100644
--- a/test/media.test.js
+++ b/test/media.test.js
@@ -63,6 +63,22 @@ test("one case can contain local video, image, document and ordered time notes",
assert.deepEqual(entry.timeNotes, []);
});
+test("removing media also removes its position from the saved article", () => {
+ const entry = removeEntryMedia(normalizeEntryMedia({
+ id: "case:article",
+ mediaAssets: [{ id: "image:article", kind: "image", storageMode: "managed", mimeType: "image/webp" }],
+ articleDocument: {
+ version: 1,
+ blocks: [
+ { id: "text", kind: "paragraph", text: "正文", sourceOrder: 0 },
+ { id: "image", kind: "image", assetId: "image:article", sourceUrl: "https://example.com/image.webp", sourceOrder: 1 }
+ ]
+ }
+ }), "image:article");
+
+ assert.deepEqual(entry.articleDocument.blocks.map((block) => block.kind), ["paragraph"]);
+});
+
test("video analysis keeps actual provider cost and routing metadata", () => {
const entry = normalizeEntryMedia({
id: "case:video-analysis",
@@ -150,5 +166,7 @@ test("file media kinds are derived from actual file metadata and supported exten
assert.equal(mediaKindFromFile({ name: "clip.mp4", type: "video/mp4" }), "video");
assert.equal(mediaKindFromFile({ name: "notes.pdf", type: "" }), "document");
assert.equal(mediaKindFromFile({ name: "frame.webp", type: "image/webp" }), "image");
+ assert.equal(mediaKindFromFile({ name: "motion.gif", type: "image/gif" }), "image");
+ assert.equal(normalizeMediaAsset({ id: "gif", kind: "image", mimeType: "image/gif" }).mimeType, "image/gif");
assert.equal(mediaKindFromFile({ name: "archive.bin", type: "application/octet-stream" }), "");
});
diff --git a/test/page-capture-adapter-registry.test.js b/test/page-capture-adapter-registry.test.js
new file mode 100644
index 0000000..cd39d20
--- /dev/null
+++ b/test/page-capture-adapter-registry.test.js
@@ -0,0 +1,88 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ PAGE_CAPTURE_ADAPTERS,
+ pageCaptureSupportMatrix,
+ resolvePageCaptureAdapter
+} from "../page-capture-adapter-registry.js";
+
+test("the capture registry covers the requested public-site families without duplicate adapters", () => {
+ const fixtures = new Map([
+ ["https://www.behance.net/gallery/1/project", "behance"],
+ ["https://dribbble.com/shots/1-project", "dribbble"],
+ ["https://www.deviantart.com/artist/art/work-1", "deviantart"],
+ ["https://www.designspiration.com/save/1", "designspiration"],
+ ["https://huaban.com/pins/1", "huaban"],
+ ["https://www.zcool.com.cn/work/1.html", "zcool"],
+ ["https://500px.com/photo/1/work", "500px"],
+ ["https://www.instagram.com/p/example/", "instagram"],
+ ["https://www.flickr.com/photos/artist/1", "flickr"],
+ ["https://www.pexels.com/photo/example-1/", "pexels"],
+ ["https://imgur.com/gallery/example", "imgur"],
+ ["https://weibo.com/1/example", "weibo"],
+ ["https://web.okjike.com/originalPost/1", "jike"],
+ ["https://user.qzone.qq.com/1/photo/1", "qzone"],
+ ["https://www.douban.com/photos/album/1/", "douban"],
+ ["https://www.poco.cn/works/detail_id1", "poco"],
+ ["https://mp.weixin.qq.com/s/example", "wechat"],
+ ["https://www.liblib.art/imageinfo/example", "liblibai"],
+ ["https://www.krea.ai/feed/example-00000000-0000-0000-0000-000000000000", "krea"],
+ ["https://higgsfield.ai/@creator/projects/example", "higgsfield"],
+ ["https://item.jd.com/1.html", "jd"],
+ ["https://item.taobao.com/item.htm?id=1", "taobao"],
+ ["https://detail.tmall.com/item.htm?id=1", "tmall"],
+ ["https://detail.1688.com/offer/1.html", "1688"],
+ ["https://shop.mogujie.com/detail/1", "mogujie"],
+ ["https://www.architecturaldigest.com/story/example", "architectural-digest"],
+ ["https://www.archiproducts.com/en/products/example", "archiproducts"],
+ ["https://www.houzz.com/photos/example-phvw-vp~1", "houzz"],
+ ["https://www.housebeautiful.com/design-inspiration/a1/example/", "house-beautiful"],
+ ["https://officesnapshots.com/2026/01/01/example/", "officesnapshots"],
+ ["https://www.archilovers.com/projects/1/example.html", "archilovers"],
+ ["https://www.archdaily.com/1/example", "archdaily"],
+ ["https://www.archdaily.cn/cn/1/example", "archdaily-cn"],
+ ["https://www.dezeen.com/2026/01/01/example/", "dezeen"],
+ ["https://interiordesign.net/projects/example/", "interior-design"]
+ ]);
+
+ for (const [url, expected] of fixtures) {
+ assert.equal(resolvePageCaptureAdapter(url).id, expected, url);
+ }
+ assert.equal(new Set(PAGE_CAPTURE_ADAPTERS.map((item) => item.id)).size, PAGE_CAPTURE_ADAPTERS.length);
+ assert.equal(resolvePageCaptureAdapter("https://yesand.ai/prompt/example").id, "generic");
+});
+
+test("platform adapters are detected from public page signals on custom domains", () => {
+ assert.equal(resolvePageCaptureAdapter("https://studio.example/work", {
+ metas: { generator: "WordPress 6.8" }
+ }).id, "wordpress");
+ assert.equal(resolvePageCaptureAdapter("https://portfolio.example/work", {
+ scripts: ["https://static.parastorage.com/services/wix-thunderbolt/dist/main.js"]
+ }).id, "wix");
+ assert.equal(resolvePageCaptureAdapter("https://journal.example/work", {
+ links: ["https://assets.squarespace.com/universal/scripts-compressed/common.js"]
+ }).id, "squarespace");
+ assert.equal(resolvePageCaptureAdapter("https://essay.example/work", {
+ metas: { applicationName: "Medium" }
+ }).id, "medium");
+});
+
+test("support matrix never promotes unverified selectors to dedicated support", () => {
+ const matrix = pageCaptureSupportMatrix();
+ assert.equal(matrix.find((item) => item.id === "jimeng").support, "verified-deep");
+ assert.equal(matrix.find((item) => item.id === "liblibai").support, "verified-deep");
+ assert.equal(matrix.find((item) => item.id === "krea").support, "verified-declarative");
+ assert.equal(matrix.find((item) => item.id === "higgsfield").support, "verified-declarative");
+ assert.equal(matrix.find((item) => item.id === "wechat").support, "verified-declarative");
+ assert.equal(matrix.find((item) => item.id === "behance").support, "verified-declarative");
+ assert.equal(matrix.find((item) => item.id === "pinterest").support, "verified-deep");
+ assert.equal(matrix.find((item) => item.id === "dribbble").support, "generic");
+ assert.equal(matrix.every((item) => ["generic", "verified-declarative", "verified-deep"].includes(item.support)), true);
+});
+
+test("X exposes a truthful status permalink and handle instead of using the first link", () => {
+ const adapter = PAGE_CAPTURE_ADAPTERS.find((item) => item.id === "x");
+ assert.deepEqual(adapter.fields.canonicalUrl, ["a[href*='/status/']"]);
+ assert.deepEqual(adapter.fields.handle, ["[data-testid=User-Name] a[href^='/']"]);
+});
diff --git a/test/page-capture-site-adapters.test.js b/test/page-capture-site-adapters.test.js
new file mode 100644
index 0000000..087cfe5
--- /dev/null
+++ b/test/page-capture-site-adapters.test.js
@@ -0,0 +1,665 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ collectPageCaptureSitePayload,
+ installPageCaptureSiteObserver,
+ isTrustedPageCaptureMediaUrl,
+ normalizePageCaptureSitePayload
+} from "../page-capture-site-adapters.js";
+
+test("Jimeng structured payload restores author, prompt, model, time, metrics and original media", () => {
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "jimeng",
+ workId: "7490123456789012345",
+ modelNames: { jimeng_v40: "即梦 4.0" },
+ item: {
+ common_attr: { id: "7490123456789012345", title: "孟菲斯光线4", create_time: 1786000000 },
+ author: { name: "金戈米良", uid: "creator-7" },
+ aigc_image_params: { text2image_params: { prompt: "平面影像,低饱和度,动态模糊的光线。" } },
+ aigc_draft: { content: JSON.stringify({ component_list: [{ abilities: { generate: { core_param: { model: "jimeng_v40" } } } }] }) },
+ statistic: { favorite_num: 103, usage_num: 12 },
+ image: { large_images: [{ image_url: "https://p3-dreamina-sign.byteimg.com/original.webp?x=1", width: 2160, height: 3840 }] }
+ }
+ }, "https://jimeng.jianying.com/ai-tool/work-detail/7490123456789012345");
+
+ assert.equal(normalized.contentText, "平面影像,低饱和度,动态模糊的光线。");
+ assert.equal(normalized.sourceFacts.author, "金戈米良");
+ assert.equal(normalized.sourceFacts.model, "即梦 4.0");
+ assert.equal(normalized.sourceFacts.itemId, "7490123456789012345");
+ assert.equal(normalized.sourceFacts.dimensions, "2160×3840");
+ assert.deepEqual(normalized.sourceFacts.engagement, { favorites: 103, uses: 12 });
+ assert.equal(normalized.media[0].variants[0].sourceKind, "site-original");
+ assert.equal(normalized.completeness, "complete");
+});
+
+test("Jimeng observer keeps a bounded sanitized feed without request credentials", () => {
+ const injected = (0, eval)(`(${installPageCaptureSiteObserver.toString()})`);
+ const original = {
+ location: globalThis.location,
+ fetch: globalThis.fetch,
+ XMLHttpRequest: globalThis.XMLHttpRequest,
+ __get_explore_result: globalThis.__get_explore_result,
+ __image_generate_model_config__: globalThis.__image_generate_model_config__
+ };
+ globalThis.location = { hostname: "jimeng.jianying.com", href: "https://jimeng.jianying.com/ai-tool/home" };
+ globalThis.fetch = undefined;
+ globalThis.XMLHttpRequest = undefined;
+ globalThis.__get_explore_result = { data: { item_list: [
+ { common_attr: { id: "7490123456789012345" }, private_token: "must-not-survive", image: { large_images: [] } },
+ { common_attr: { id: "7490123456789012346" }, request_headers: { cookie: "must-not-survive" }, image: { large_images: [] } }
+ ] } };
+ try {
+ const result = injected({ maxCandidates: 1, maxMedia: 1 });
+ const state = globalThis.__PROMPTDIRECTOR_JIMENG_CAPTURE__;
+ assert.equal(result.installed, true);
+ assert.equal(state.items.length, 1);
+ assert.equal(state.items[0].common_attr.id, "7490123456789012346");
+ assert.equal("private_token" in state.items[0], false);
+ assert.equal("request_headers" in state.items[0], false);
+ } finally {
+ delete globalThis.__PROMPTDIRECTOR_JIMENG_CAPTURE__;
+ Object.assign(globalThis, original);
+ }
+});
+
+test("Jimeng parser rejects lookalike media hosts and remains explicitly partial when page data is absent", () => {
+ assert.equal(isTrustedPageCaptureMediaUrl("jimeng", "https://p3-dreamina-sign.byteimg.com/a.webp"), true);
+ assert.equal(isTrustedPageCaptureMediaUrl("jimeng", "https://p3-dreamina-sign.byteimg.com.evil.example/a.webp"), false);
+ assert.equal(isTrustedPageCaptureMediaUrl("krea", "https://gen.krea.ai/images/public.png"), true);
+ assert.equal(isTrustedPageCaptureMediaUrl("krea", "https://gen.krea.ai.evil.example/public.png"), false);
+ assert.equal(isTrustedPageCaptureMediaUrl("higgsfield", "https://d2ol7oe51mr4n9.cloudfront.net/public.webp"), true);
+ assert.equal(isTrustedPageCaptureMediaUrl("higgsfield", "https://random.cloudfront.net/public.webp"), false);
+ assert.equal(isTrustedPageCaptureMediaUrl("pinterest", "https://i.pinimg.com/originals/public.gif"), true);
+ assert.equal(isTrustedPageCaptureMediaUrl("pinterest", "https://i.pinimg.com.evil.example/public.gif"), false);
+ const partial = normalizePageCaptureSitePayload({ adapter: "jimeng", workId: "7490123456789012345", status: "partial" }, "https://jimeng.jianying.com/ai-tool/work-detail/7490123456789012345");
+ assert.equal(partial.completeness, "partial");
+ assert.equal(partial.sourceFacts.author, undefined);
+});
+
+test("the main-world Jimeng reader is self-contained and parses assigned JSON without evaluating scripts", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ globalThis.location = { hostname: "jimeng.jianying.com", pathname: "/ai-tool/work-detail/7490123456789012345" };
+ globalThis.document = { scripts: [{ textContent: `window.__get_explore_result=${JSON.stringify({ data: { item_list: [{ common_attr: { id: "7490123456789012345" } }] } })};` }] };
+ try {
+ const result = injected();
+ assert.equal(result.item.common_attr.id, "7490123456789012345");
+ assert.doesNotMatch(collectPageCaptureSitePayload.toString(), /eval\(|new Function/u);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("Jimeng home is a feed, never a fake work named home", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ globalThis.location = { hostname: "jimeng.jianying.com", pathname: "/ai-tool/home" };
+ globalThis.document = {
+ scripts: [{ textContent: `window.__get_explore_result=${JSON.stringify({ data: { item_list: [
+ { common_attr: { id: "7490123456789012345" } },
+ { common_attr: { id: "7490123456789012346" } }
+ ] } })};` }]
+ };
+ try {
+ const result = injected();
+ assert.equal(result.pageKind, "feed");
+ assert.equal(result.workId, "");
+ assert.deepEqual(result.items.map((item) => item.common_attr.id), ["7490123456789012345", "7490123456789012346"]);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("Jimeng feed normalization emits one real candidate per work", () => {
+ const item = (id, author) => ({
+ extra: { template_type: "image" },
+ common_attr: { id, create_time: 1786000000 },
+ author: { name: author, uid: `${id}-author` },
+ aigc_image_params: { text2image_params: { prompt: `${author}的提示词` } },
+ image: { large_images: [{ image_url: `https://p3-dreamina-sign.byteimg.com/${id}.webp`, width: 2048, height: 2048 }] }
+ });
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "jimeng",
+ pageKind: "feed",
+ items: [item("7490123456789012345", "作者甲"), item("7490123456789012346", "作者乙")]
+ }, "https://jimeng.jianying.com/ai-tool/home");
+
+ assert.equal(normalized.pageKind, "feed");
+ assert.equal(normalized.candidates.length, 2);
+ assert.equal(normalized.candidates[0].sourceFacts.itemId, "7490123456789012345");
+ assert.equal(normalized.candidates[0].sourceFacts.author, "作者甲");
+ assert.equal(normalized.candidates[0].media[0].placement, "inline");
+ assert.notEqual(normalized.candidates[0].title, "即梦AI - 一站式AI创作平台");
+});
+
+test("direct Jimeng detail falls back to the visible work panel without inventing site identity", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ globalThis.location = { hostname: "jimeng.jianying.com", pathname: "/ai-tool/work-detail/7490123456789012345" };
+ globalThis.document = {
+ scripts: [],
+ body: {
+ innerText: [
+ "AIGC大叔",
+ "+ 关注",
+ "87",
+ "2026-05-30 | 内容由 AI 生成",
+ "图片提示词",
+ "敦煌文化主题场景,全景,暗黑风。",
+ "图片 4.7 | 9:16 | 更多",
+ "做同款",
+ "用作参考图"
+ ].join("\n")
+ },
+ querySelectorAll: () => []
+ };
+ try {
+ const payload = injected({ maxCandidates: 100, maxMedia: 24, maxTextCharacters: 16 * 1024 * 1024 });
+ const normalized = normalizePageCaptureSitePayload(payload, "https://jimeng.jianying.com/ai-tool/work-detail/7490123456789012345");
+ assert.equal(normalized.sourceFacts.author, "AIGC大叔");
+ assert.equal(normalized.sourceFacts.model, "4.7");
+ assert.equal(normalized.sourceFacts.publishedAt.slice(0, 10), "2026-05-30");
+ assert.equal(normalized.sourceFacts.engagement.favorites, 87);
+ assert.equal(normalized.contentText, "敦煌文化主题场景,全景,暗黑风。");
+ assert.equal(normalized.title, "AIGC大叔 · 2026-05-30");
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("LiblibAI public work state keeps creator, prompts, model stack, metrics and original media", () => {
+ const pageUrl = "https://www.liblib.art/imageinfo/f6c920410dd74d37b6680a1ad90dfd53";
+ const mediaUrl = "https://liblibai-online.liblib.cloud/img/public/original.png";
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "liblibai",
+ canonicalUrl: pageUrl,
+ data: {
+ uuid: "f6c920410dd74d37b6680a1ad90dfd53",
+ title: "公开作品标题",
+ createTime: "2024-10-23T08:47:54.000+00:00",
+ counter: { likeCount: 23, commentCount: 4, hitCount: 208 },
+ images: [{
+ id: 5205767,
+ originalImageUrl: mediaUrl,
+ imageUrl: "https://images-wm.liblib.cloud/img/public/watermark.png",
+ width: 1200,
+ height: 2048,
+ generateInfo: { prompt: "公开正向提示词", negativePrompt: "公开负向提示词" },
+ models: [
+ { modelName: "F.1 基础模型", versionName: "v1" },
+ { modelName: "细节 LoRA", versionName: "v2" }
+ ]
+ }]
+ },
+ author: { nickname: "脱敏作者", uuid: "public-author-id" }
+ }, pageUrl);
+
+ assert.equal(normalized.adapter, "liblibai");
+ assert.equal(normalized.contentText, "公开正向提示词");
+ assert.equal(normalized.sourceFacts.author, "脱敏作者");
+ assert.equal(normalized.sourceFacts.handle, "public-author-id");
+ assert.equal(normalized.sourceFacts.model, "F.1 基础模型 v1 · 细节 LoRA v2");
+ assert.equal(normalized.sourceFacts.dimensions, "1200×2048");
+ assert.deepEqual(normalized.sourceFacts.engagement, { likes: 23, comments: 4, views: 208 });
+ assert.equal(normalized.media[0].url, mediaUrl);
+ assert.equal(normalized.media[0].sourceKind, "site-original");
+ assert.equal(normalized.completeness, "complete");
+});
+
+test("LiblibAI collector reads only bounded public Next data from an image detail", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ const pageData = {
+ props: { pageProps: {
+ data: {
+ uuid: "f6c920410dd74d37b6680a1ad90dfd53",
+ title: "公开作品标题",
+ createTime: "2024-10-23T08:47:54.000+00:00",
+ counter: { likeCount: 23 },
+ images: [{
+ id: 5205767,
+ originalImageUrl: "https://liblibai-online.liblib.cloud/img/public/original.png",
+ imageUrl: "https://images-wm.liblib.cloud/img/public/watermark.png",
+ width: 1200,
+ height: 2048,
+ generateInfo: { prompt: "公开正向提示词", metainformation: "must-not-survive" },
+ models: [{ modelName: "F.1 基础模型", versionName: "v1", privatePath: "must-not-survive" }]
+ }]
+ },
+ authorInfo: { userDetail: { nickname: "脱敏作者", uuid: "public-author-id", mobile: "must-not-survive" } }
+ } }
+ };
+ globalThis.location = {
+ hostname: "www.liblib.art",
+ pathname: "/imageinfo/f6c920410dd74d37b6680a1ad90dfd53",
+ href: "https://www.liblib.art/imageinfo/f6c920410dd74d37b6680a1ad90dfd53"
+ };
+ globalThis.document = {
+ querySelector: (selector) => selector === "#__NEXT_DATA__" ? { textContent: JSON.stringify(pageData) } : null,
+ querySelectorAll: () => [],
+ scripts: []
+ };
+ try {
+ const payload = injected({ maxCandidates: 20, maxMedia: 8, maxTextCharacters: 10000 });
+ assert.equal(payload.adapter, "liblibai");
+ assert.equal(payload.data.images.length, 1);
+ assert.equal(payload.data.images[0].generateInfo.prompt, "公开正向提示词");
+ assert.equal(JSON.stringify(payload).includes("must-not-survive"), false);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("Krea public gallery detail keeps the full prompt, UUID, date, dimensions and original image", () => {
+ const pageUrl = "https://www.krea.ai/feed/vintage-film-portrait-554bfb91-2a06-5e91-8a21-24a162f3b81f";
+ const mediaUrl = "https://gen.krea.ai/images/554bfb91-2a06-5e91-8a21-24a162f3b81f.png";
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "krea",
+ pageKind: "detail",
+ canonicalUrl: pageUrl,
+ prompt: "A close-up vintage film portrait with warm sunlight and heavy grain.",
+ jsonLd: [{
+ "@type": "ImageObject",
+ name: "A close-up vintage film portrait...",
+ url: pageUrl,
+ contentUrl: mediaUrl,
+ datePublished: "2026-05-13T06:47:52.874Z",
+ width: 768,
+ height: 1376
+ }]
+ }, pageUrl);
+
+ assert.equal(normalized.adapter, "krea");
+ assert.equal(normalized.contentText, "A close-up vintage film portrait with warm sunlight and heavy grain.");
+ assert.equal(normalized.sourceFacts.itemId, "554bfb91-2a06-5e91-8a21-24a162f3b81f");
+ assert.equal(normalized.sourceFacts.publishedAt, "2026-05-13T06:47:52.874Z");
+ assert.equal(normalized.sourceFacts.dimensions, "768×1376");
+ assert.equal(normalized.media[0].url, mediaUrl);
+ assert.equal(normalized.completeness, "complete");
+});
+
+test("Krea gallery feed emits bounded real artwork candidates instead of application-shell text", () => {
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "krea",
+ pageKind: "feed",
+ items: [{
+ itemId: "72324387-04f9-526e-ae96-e132f34ab60c",
+ canonicalUrl: "https://www.krea.ai/feed/a-vivid-green-praying-mantis-72324387-04f9-526e-ae96-e132f34ab60c",
+ title: "a vivid green praying mantis",
+ imageUrl: "https://gen.krea.ai/images/72324387-04f9-526e-ae96-e132f34ab60c.png"
+ }]
+ }, "https://www.krea.ai/feed");
+
+ assert.equal(normalized.pageKind, "feed");
+ assert.equal(normalized.candidates.length, 1);
+ assert.equal(normalized.candidates[0].sourceFacts.itemId, "72324387-04f9-526e-ae96-e132f34ab60c");
+ assert.equal(normalized.candidates[0].media[0].sourceKind, "site-original");
+ assert.equal(normalized.candidates[0].completeness, "partial");
+});
+
+test("Krea collector reads a public detail prompt and ImageObject without application state", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ const pageUrl = "https://www.krea.ai/feed/vintage-film-portrait-554bfb91-2a06-5e91-8a21-24a162f3b81f";
+ const imageObject = {
+ "@context": "https://schema.org",
+ "@type": "ImageObject",
+ name: "Vintage film portrait",
+ url: pageUrl,
+ contentUrl: "https://gen.krea.ai/images/554bfb91-2a06-5e91-8a21-24a162f3b81f.png",
+ datePublished: "2026-05-13T06:47:52.874Z",
+ width: 768,
+ height: 1376,
+ privateSession: "must-not-survive"
+ };
+ globalThis.location = { hostname: "www.krea.ai", pathname: new URL(pageUrl).pathname, href: pageUrl };
+ globalThis.document = {
+ querySelector: (selector) => selector === "article h1" ? { textContent: "A complete public image prompt." } : null,
+ querySelectorAll: (selector) => selector === 'script[type="application/ld+json"]'
+ ? [{ textContent: JSON.stringify(imageObject) }]
+ : []
+ };
+ try {
+ const payload = injected({ maxCandidates: 20, maxMedia: 8, maxTextCharacters: 10000 });
+ assert.equal(payload.adapter, "krea");
+ assert.equal(payload.pageKind, "detail");
+ assert.equal(payload.prompt, "A complete public image prompt.");
+ assert.equal(payload.jsonLd[0].contentUrl, imageObject.contentUrl);
+ assert.equal(JSON.stringify(payload).includes("must-not-survive"), false);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("Krea collector converts only observed gallery cards to their verified original URL", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ const itemId = "72324387-04f9-526e-ae96-e132f34ab60c";
+ const href = `/feed/a-vivid-green-praying-mantis-${itemId}`;
+ const imageNode = {
+ style: { backgroundImage: `image-set(url("https://optim-images.krea.ai/https---gen-krea-ai-images-${itemId}-png-512.webp") 1x, url("https://optim-images.krea.ai/https---gen-krea-ai-images-${itemId}-png-1024.webp") 2x)` }
+ };
+ globalThis.location = { hostname: "www.krea.ai", pathname: "/feed", href: "https://www.krea.ai/feed" };
+ globalThis.document = {
+ querySelector: () => null,
+ querySelectorAll: (selector) => selector.startsWith('script[type=')
+ ? []
+ : [{ href, querySelector: () => imageNode, getAttribute: () => href }]
+ };
+ try {
+ const payload = injected({ maxCandidates: 1, maxMedia: 8, maxTextCharacters: 10000 });
+ assert.equal(payload.items.length, 1);
+ assert.equal(payload.items[0].itemId, itemId);
+ assert.equal(payload.items[0].imageUrl, `https://gen.krea.ai/images/${itemId}.png`);
+ assert.equal(payload.items[0].title, "a vivid green praying mantis");
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("Higgsfield project keeps public creator, project brief, date, metrics and artwork", () => {
+ const pageUrl = "https://higgsfield.ai/@public-creator/projects/anime-production";
+ const mediaUrl = "https://d2ol7oe51mr4n9.cloudfront.net/public/project-cover.webp";
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "higgsfield",
+ pageKind: "detail",
+ canonicalUrl: pageUrl,
+ brief: "A cinematic anime production brief with deliberate lighting and motion.",
+ jsonLd: [{
+ "@type": "CreativeWork",
+ name: "Anime Production",
+ description: "Public project description",
+ url: pageUrl,
+ author: { "@type": "Person", name: "Public Creator", alternateName: "@public-creator", identifier: "creator-public-id" },
+ datePublished: "2026-06-18T12:30:00.000Z",
+ image: mediaUrl,
+ interactionStatistic: [
+ { interactionType: { "@type": "ViewAction" }, userInteractionCount: 812 },
+ { interactionType: { "@type": "LikeAction" }, userInteractionCount: 37 }
+ ]
+ }]
+ }, pageUrl);
+
+ assert.equal(normalized.adapter, "higgsfield");
+ assert.equal(normalized.title, "Anime Production");
+ assert.equal(normalized.contentText, "A cinematic anime production brief with deliberate lighting and motion.");
+ assert.equal(normalized.sourceFacts.author, "Public Creator");
+ assert.equal(normalized.sourceFacts.handle, "public-creator");
+ assert.equal(normalized.sourceFacts.itemId, "public-creator/anime-production");
+ assert.equal(normalized.sourceFacts.publishedAt, "2026-06-18T12:30:00.000Z");
+ assert.deepEqual(normalized.sourceFacts.engagement, { likes: 37, views: 812 });
+ assert.equal(normalized.media[0].url, mediaUrl);
+ assert.equal(normalized.completeness, "complete");
+});
+
+test("Higgsfield public community ItemList emits projects without page-shell copy", () => {
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "higgsfield",
+ pageKind: "feed",
+ canonicalUrl: "https://higgsfield.ai/community",
+ jsonLd: [{
+ "@type": "ItemList",
+ itemListElement: [{
+ position: 1,
+ item: {
+ "@type": "CreativeWork",
+ name: "Fashion Motion Study",
+ description: "A public motion project.",
+ url: "https://higgsfield.ai/@public-creator/projects/fashion-motion-study",
+ author: { name: "Public Creator", alternateName: "@public-creator" },
+ image: "https://d2ol7oe51mr4n9.cloudfront.net/public/fashion-cover.webp"
+ }
+ }]
+ }]
+ }, "https://higgsfield.ai/community");
+
+ assert.equal(normalized.pageKind, "feed");
+ assert.equal(normalized.candidates.length, 1);
+ assert.equal(normalized.candidates[0].sourceFacts.author, "Public Creator");
+ assert.equal(normalized.candidates[0].sourceFacts.itemId, "public-creator/fashion-motion-study");
+ assert.equal(normalized.candidates[0].title, "Fashion Motion Study");
+ assert.doesNotMatch(normalized.candidates[0].contentText, /create|sign in|pricing/iu);
+});
+
+test("Higgsfield collector exposes only bounded public CreativeWork JSON-LD and the project brief", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ const pageUrl = "https://higgsfield.ai/@public-creator/projects/anime-production";
+ const creativeWork = {
+ "@context": "https://schema.org",
+ "@type": "CreativeWork",
+ name: "Anime Production",
+ description: "Public project description",
+ url: pageUrl,
+ author: { "@type": "Person", name: "Public Creator", alternateName: "@public-creator", privateToken: "must-not-survive" },
+ datePublished: "2026-06-18T12:30:00.000Z",
+ image: "https://d2ol7oe51mr4n9.cloudfront.net/public/project-cover.webp",
+ interactionStatistic: [{ interactionType: { "@type": "ViewAction" }, userInteractionCount: 812 }],
+ accountSession: "must-not-survive"
+ };
+ globalThis.location = { hostname: "higgsfield.ai", pathname: "/@public-creator/projects/anime-production", href: pageUrl };
+ globalThis.document = {
+ querySelector: (selector) => selector === '[aria-label^="Project brief:"]'
+ ? { innerText: "A cinematic anime production brief." }
+ : null,
+ querySelectorAll: (selector) => selector === 'script[type="application/ld+json"]'
+ ? [{ textContent: JSON.stringify(creativeWork) }]
+ : []
+ };
+ try {
+ const payload = injected({ maxCandidates: 20, maxMedia: 8, maxTextCharacters: 10000 });
+ assert.equal(payload.adapter, "higgsfield");
+ assert.equal(payload.pageKind, "detail");
+ assert.equal(payload.brief, "A cinematic anime production brief.");
+ assert.equal(payload.jsonLd[0].author.name, "Public Creator");
+ assert.equal(JSON.stringify(payload).includes("must-not-survive"), false);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("Behance VisualArtwork keeps project owners, description, identity, metrics and cover media", () => {
+ const pageUrl = "https://www.behance.net/gallery/252610351/Cantor8";
+ const mediaUrl = "https://mir-s3-cdn-cf.behance.net/projects/404/e4dcec252610351.Y3JvcCwxODQwLDE0MzksMCww.jpg";
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "behance",
+ pageKind: "detail",
+ canonicalUrl: pageUrl,
+ jsonLd: [{
+ "@type": "VisualArtwork",
+ name: "Cantor8",
+ description: "A public digital-design project description.",
+ url: pageUrl,
+ identifier: 252610351,
+ image: mediaUrl,
+ creator: [
+ { "@type": "Person", identifier: 173435329, name: "Public Owner One", url: "https://www.behance.net/publicownerone" },
+ { "@type": "Person", identifier: 1443573125, name: "Public Owner Two", url: "https://www.behance.net/publicownertwo" }
+ ],
+ interactionStatistic: [
+ { interactionType: "http://schema.org/LikeAction", userInteractionCount: 766 },
+ { interactionType: "http://schema.org/WatchAction", userInteractionCount: 8565 }
+ ]
+ }]
+ }, pageUrl);
+
+ assert.equal(normalized.adapter, "behance");
+ assert.equal(normalized.sourceFacts.itemId, "252610351");
+ assert.equal(normalized.sourceFacts.author, "Public Owner One, Public Owner Two");
+ assert.equal(normalized.sourceFacts.handle, "publicownerone");
+ assert.deepEqual(normalized.sourceFacts.engagement, { likes: 766, views: 8565 });
+ assert.equal(normalized.media[0].url, mediaUrl);
+ assert.equal(normalized.media[0].sourceKind, "structured");
+ assert.equal(normalized.completeness, "complete");
+});
+
+test("Behance collector reads only the public VisualArtwork schema from a project page", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ const pageUrl = "https://www.behance.net/gallery/252610351/Cantor8";
+ const artwork = {
+ "@context": "http://schema.org",
+ "@type": "VisualArtwork",
+ name: "Cantor8",
+ description: "A public digital-design project description.",
+ url: pageUrl,
+ identifier: 252610351,
+ image: "https://mir-s3-cdn-cf.behance.net/projects/404/e4dcec252610351.Y3JvcCwxODQwLDE0MzksMCww.jpg",
+ creator: [{ "@type": "Person", identifier: 173435329, name: "Public Owner", url: "https://www.behance.net/publicowner", email: "must-not-survive" }],
+ interactionStatistic: [{ "@type": "InteractionCounter", interactionType: "http://schema.org/LikeAction", userInteractionCount: 766 }],
+ privateSession: "must-not-survive"
+ };
+ globalThis.location = { hostname: "www.behance.net", pathname: "/gallery/252610351/Cantor8", href: pageUrl };
+ globalThis.document = {
+ querySelector: () => null,
+ querySelectorAll: (selector) => selector === 'script[type="application/ld+json"]'
+ ? [{ textContent: JSON.stringify(artwork) }]
+ : []
+ };
+ try {
+ const payload = injected({ maxCandidates: 20, maxMedia: 8, maxTextCharacters: 10000 });
+ assert.equal(payload.adapter, "behance");
+ assert.equal(payload.jsonLd[0].creator[0].name, "Public Owner");
+ assert.equal(JSON.stringify(payload).includes("must-not-survive"), false);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("Pinterest Pin keeps the public creator, timestamp, description and original media variants", () => {
+ const pageUrl = "https://www.pinterest.com/pin/579205202062276414/";
+ const originalUrl = "https://i.pinimg.com/originals/0d/d6/0c/public-pin.gif";
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "pinterest",
+ pageKind: "detail",
+ canonicalUrl: pageUrl,
+ pin: {
+ entityId: "579205202062276414",
+ title: "2026 Web Design Trends to Watch For",
+ description: "A public design-inspiration Pin description.",
+ createdAt: "Sat, 21 Dec 2019 21:27:05 +0000",
+ author: { fullName: "Public Pinner", username: "publicpinner" },
+ repins: 14,
+ images: {
+ original: { url: originalUrl },
+ large: { url: "https://i.pinimg.com/1200x/0d/d6/0c/public-pin.jpg", width: 1200, height: 592 },
+ display: { url: "https://i.pinimg.com/736x/0d/d6/0c/public-pin.jpg", width: 600, height: 296 }
+ }
+ }
+ }, pageUrl);
+
+ assert.equal(normalized.adapter, "pinterest");
+ assert.equal(normalized.sourceFacts.itemId, "579205202062276414");
+ assert.equal(normalized.sourceFacts.author, "Public Pinner");
+ assert.equal(normalized.sourceFacts.handle, "publicpinner");
+ assert.equal(normalized.sourceFacts.publishedAt, "2019-12-21T21:27:05.000Z");
+ assert.deepEqual(normalized.sourceFacts.engagement, { repins: 14 });
+ assert.equal(normalized.media[0].url, originalUrl);
+ assert.deepEqual(normalized.media[0].variants.map((variant) => variant.sourceKind), ["site-original", "responsive", "current"]);
+ assert.equal(normalized.completeness, "complete");
+});
+
+test("Pinterest collector sanitizes one public Pin relay payload without retaining request context", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ const pageUrl = "https://www.pinterest.com/pin/579205202062276414/";
+ const response = { data: { v3GetPinQueryv2: { data: {
+ entityId: "579205202062276414",
+ gridTitle: "2026 Web Design Trends to Watch For",
+ gridDescription: "A public design-inspiration Pin description.",
+ createdAt: "Sat, 21 Dec 2019 21:27:05 +0000",
+ nativeCreator: { fullName: "Public Pinner", username: "publicpinner", websiteUrl: "must-not-survive" },
+ images_orig: { url: "https://i.pinimg.com/originals/0d/d6/0c/public-pin.gif" },
+ images_1200x: { url: "https://i.pinimg.com/1200x/0d/d6/0c/public-pin.jpg", width: 1200, height: 592 },
+ images_736x: { url: "https://i.pinimg.com/736x/0d/d6/0c/public-pin.jpg", width: 600, height: 296 },
+ trackingParams: "must-not-survive"
+ } } } };
+ globalThis.location = { hostname: "www.pinterest.com", pathname: "/pin/579205202062276414/", href: pageUrl };
+ globalThis.document = {
+ scripts: [{ textContent: `window.__PWS_RELAY_REGISTER_COMPLETED_REQUEST__("%7B%22pinId%22%3A%22579205202062276414%22%7D", ${JSON.stringify(response)});` }],
+ querySelector: (selector) => selector.includes("pinterestapp:repins") ? { content: "14" } : null,
+ querySelectorAll: () => []
+ };
+ try {
+ const payload = injected({ maxCandidates: 20, maxMedia: 8, maxTextCharacters: 10000 });
+ assert.equal(payload.adapter, "pinterest");
+ assert.equal(payload.pin.author.username, "publicpinner");
+ assert.equal(payload.pin.images.original.url, "https://i.pinimg.com/originals/0d/d6/0c/public-pin.gif");
+ assert.equal(JSON.stringify(payload).includes("must-not-survive"), false);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("WeChat public article fields retain account, publication time, body and delayed originals", () => {
+ const pageUrl = "https://mp.weixin.qq.com/s/example";
+ const normalized = normalizePageCaptureSitePayload({
+ adapter: "wechat",
+ canonicalUrl: pageUrl,
+ title: "视觉案例周刊",
+ author: "AI Art Works",
+ publishedAt: "2026-08-01T08:00:00+08:00",
+ contentText: "第一段公开正文\n\n第二段公开正文",
+ images: [{
+ url: "https://mmbiz.qpic.cn/mmbiz_jpg/example/0?wx_fmt=jpeg",
+ width: 1080,
+ height: 1440,
+ alt: "案例作品"
+ }]
+ }, pageUrl);
+
+ assert.equal(normalized.pageType, "article");
+ assert.equal(normalized.title, "视觉案例周刊");
+ assert.equal(normalized.sourceFacts.author, "AI Art Works");
+ assert.equal(normalized.sourceFacts.publishedAt, "2026-08-01T00:00:00.000Z");
+ assert.equal(normalized.contentText, "第一段公开正文\n\n第二段公开正文");
+ assert.equal(normalized.media[0].variants[0].sourceKind, "site-original");
+});
+
+test("site collectors expose only bounded public DOM and JSON-LD data outside Jimeng", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ const content = {
+ innerText: "公开文章正文",
+ querySelectorAll: () => [{
+ currentSrc: "https://mmbiz.qpic.cn/mmbiz_jpg/example/0?wx_fmt=jpeg",
+ src: "",
+ naturalWidth: 1080,
+ naturalHeight: 1440,
+ alt: "案例作品",
+ getAttribute: (name) => ({ "data-src": "https://mmbiz.qpic.cn/mmbiz_jpg/example/0?wx_fmt=jpeg", "data-w": "1080" })[name] || ""
+ }]
+ };
+ globalThis.location = { hostname: "mp.weixin.qq.com", pathname: "/s/example", href: "https://mp.weixin.qq.com/s/example" };
+ globalThis.document = {
+ scripts: [],
+ querySelector: (selector) => ({
+ "#js_content": content,
+ "#activity-name": { textContent: "视觉案例周刊" },
+ "#js_name": { textContent: "AI Art Works" },
+ "#publish_time": { textContent: "2026-08-01 08:00" }
+ })[selector] || null
+ };
+ try {
+ const payload = injected({ maxCandidates: 100, maxMedia: 24, maxTextCharacters: 16 * 1024 * 1024 });
+ assert.equal(payload.adapter, "wechat");
+ assert.equal(payload.images.length, 1);
+ assert.equal(payload.title, "视觉案例周刊");
+ assert.equal("cookie" in payload, false);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("YesAnd has no dedicated collector and falls through to the generic page engine", () => {
+ const injected = (0, eval)(`(${collectPageCaptureSitePayload.toString()})`);
+ const original = { location: globalThis.location, document: globalThis.document };
+ globalThis.location = { hostname: "yesand.ai", pathname: "/prompt/example", href: "https://yesand.ai/prompt/example" };
+ globalThis.document = { querySelector: () => null, querySelectorAll: () => [], scripts: [] };
+ try {
+ assert.equal(injected({ maxCandidates: 20, maxMedia: 8, maxTextCharacters: 10000 }), null);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
diff --git a/test/page-capture.test.js b/test/page-capture.test.js
index 9acf862..7253ba9 100644
--- a/test/page-capture.test.js
+++ b/test/page-capture.test.js
@@ -1,18 +1,123 @@
import test from "node:test";
import assert from "node:assert/strict";
+import { hasEnglishTranslation } from "../i18n.js";
+import { normalizeMediaAsset } from "../media.js";
import {
PAGE_CAPTURE_ADAPTERS,
applyPageCaptureSelections,
+ combinePageCaptureCandidates,
collectPageCaptureSnapshot,
detectPageCaptureAdapter,
+ mergePageCaptureRegionEdit,
normalizePageCaptureBatch,
normalizePageCaptureCandidate,
normalizePageCaptureSelection,
normalizeSourceFacts,
- pageCapturePermissionOrigins
+ pageCaptureDefaultMediaIds,
+ reconcilePageCaptureArticlePlacement,
+ resolvePageCapturePageType,
+ pageCaptureMediaDecisionsResolved,
+ pageCaptureMediaFetchCandidates,
+ pageCapturePermissionOrigins,
+ pageCaptureStructureMatches,
+ resolvePageCaptureImage
} from "../page-capture.js";
-test("page capture adapter registry recognizes every first-wave public site", () => {
+test("only media proven inside the article is proposed by default", () => {
+ const candidate = normalizePageCaptureCandidate({
+ title: "正文和素材区并存",
+ canonicalUrl: "https://example.com/article",
+ media: [
+ { id: "article-image", kind: "image", url: "https://example.com/article.webp", placement: "inline" },
+ { id: "asset-image", kind: "image", url: "https://example.com/asset.webp", placement: "unplaced" }
+ ]
+ });
+ assert.deepEqual(pageCaptureDefaultMediaIds(candidate), ["article-image"]);
+});
+
+test("a social post keeps its post identity when the page also declares video and article data", () => {
+ assert.equal(resolvePageCapturePageType({
+ adapterPageType: "post",
+ structuredTypes: ["VideoObject", "Article"],
+ articleTextLength: 2_000,
+ cardCount: 1,
+ metadataType: "article"
+ }), "post");
+});
+
+test("article placement only puts DOM-proven media into the reading order", () => {
+ const result = reconcilePageCaptureArticlePlacement({
+ articleDocument: {
+ version: 1,
+ blocks: [
+ { id: "copy-a", kind: "paragraph", text: "第一段正文", sourceOrder: 0 },
+ { id: "copy-b", kind: "paragraph", text: "第二段正文", sourceOrder: 1 }
+ ]
+ },
+ media: [
+ { id: "inline-image", kind: "image", url: "https://cdn.example.com/article.webp" },
+ { id: "asset-image", kind: "image", url: "https://cdn.example.com/asset.webp" }
+ ],
+ contentTargets: [
+ { id: "target-a", kind: "text", path: "main > p:nth-of-type(1)", articleBlockIds: ["copy-a"], mediaIds: [], sourceOrder: 0 },
+ { id: "target-image", kind: "image", path: "main > img:nth-of-type(1)", articleBlockIds: [], mediaIds: ["inline-image"], sourceOrder: 1 },
+ { id: "target-b", kind: "text", path: "main > p:nth-of-type(2)", articleBlockIds: ["copy-b"], mediaIds: [], sourceOrder: 2 }
+ ]
+ });
+
+ assert.deepEqual(result.articleDocument.blocks.map((block) => block.id), ["copy-a", "article:image:inline-image", "copy-b"]);
+ assert.deepEqual(result.articleDocument.blocks.map((block) => block.sourceOrder), [0, 1, 2]);
+ assert.deepEqual(result.media.map((item) => [item.id, item.placement]), [
+ ["inline-image", "inline"],
+ ["asset-image", "unplaced"]
+ ]);
+});
+
+test("candidate normalization preserves transient inline and unplaced media evidence", () => {
+ const candidate = normalizePageCaptureCandidate({
+ title: "有位置证据的文章",
+ canonicalUrl: "https://example.com/article",
+ media: [
+ { id: "inline", kind: "image", url: "https://example.com/inline.webp", placement: "inline" },
+ { id: "unplaced", kind: "image", url: "https://example.com/unplaced.webp", placement: "unplaced" }
+ ]
+ });
+ assert.deepEqual(candidate.media.map((item) => item.placement), ["inline", "unplaced"]);
+});
+
+test("page capture quality evidence is complete in the English interface", () => {
+ const labels = [
+ "原网页选区",
+ "智能正文",
+ "结构化正文",
+ "页面正文",
+ "正文分段",
+ "{count} 段 · 可逐段确认",
+ "第 {count} 段",
+ "候选 {count}px",
+ "候选 {count}x",
+ "picture 响应图",
+ "延迟加载原图",
+ "srcset 响应图",
+ "站点原图",
+ "结构化原图",
+ "页面当前图",
+ "页面可见画面",
+ "CSS 背景图",
+ "公开原图失败时,只会使用当前网页已有登录状态读取已确认主体内的相关媒体;不会读取或保存登录信息。",
+ "预览不可用",
+ "保存案例 · 含 {count} 项媒体",
+ "保存 {cases} 个案例 · 含 {media} 项媒体",
+ "只保存 {count} 个正文案例",
+ "只保存正文",
+ "保存时将确认 {count} 项媒体",
+ "未识别到媒体,可返回网页补选",
+ "可能遗漏媒体({count})"
+ ];
+ assert.deepEqual(labels.filter((label) => !hasEnglishTranslation(label)), []);
+});
+
+test("page capture adapter registry preserves first-wave routes and enables verified tool parsers", () => {
const fixtures = new Map([
["https://jimeng.jianying.com/ai-tool/home", "jimeng"],
["https://www.liblib.art/modelinfo/example", "liblibai"],
@@ -29,7 +134,9 @@ test("page capture adapter registry recognizes every first-wave public site", ()
]);
for (const [url, expected] of fixtures) assert.equal(detectPageCaptureAdapter(url).id, expected, url);
assert.equal(detectPageCaptureAdapter("https://example.com/article").id, "generic");
- assert.equal(PAGE_CAPTURE_ADAPTERS.every((adapter) => adapter.fields && Object.keys(adapter.fields).length), true);
+ assert.equal(detectPageCaptureAdapter("https://mp.weixin.qq.com/s/example").id, "wechat");
+ assert.equal(detectPageCaptureAdapter("https://yesand.ai/prompt/example").id, "generic");
+ assert.equal(PAGE_CAPTURE_ADAPTERS.every((adapter) => adapter.fields && adapter.support), true);
});
test("whole-page scanning accumulates each virtualized viewport before the page restores its scroll", () => {
@@ -38,6 +145,16 @@ test("whole-page scanning accumulates each virtualized viewport before the page
assert.match(scan, /collectVisible\(\)/);
assert.match(scan, /window\.scrollY.*viewport/);
assert.match(source, /accumulated\.set/);
+ assert.match(scan, /waitForVisibleMedia\(\)/);
+ assert.match(source, /image\.decode\(\)/);
+ assert.match(source, /PAGE_CAPTURE_VIEWPORT_FALLBACKS/);
+});
+
+test("page capture ignores ordinary iframes while retaining supported video providers", () => {
+ const source = collectPageCaptureSnapshot.toString();
+ assert.match(source, /element\.matches\("iframe"\) && !isSupportedVideoFrame\(element\)/);
+ assert.match(source, /player\.vimeo\.com/);
+ assert.match(source, /player\.bilibili\.com/);
});
test("page capture keeps source facts searchable without turning volatile metrics into labels", () => {
@@ -69,6 +186,368 @@ test("page capture candidates deduplicate media and preserve partial extraction"
assert.equal(candidate.completeness, "partial");
});
+test("a video poster never becomes an independent article image", () => {
+ const candidate = normalizePageCaptureCandidate({
+ title: "视频文章",
+ canonicalUrl: "https://example.com/video-article",
+ media: [
+ { id: "video", kind: "video", url: "https://video.example.com/watch", posterUrl: "https://cdn.example.com/poster.webp" },
+ { id: "poster-copy", kind: "image", url: "https://cdn.example.com/poster.webp" },
+ { id: "content-image", kind: "image", url: "https://cdn.example.com/content.webp" }
+ ]
+ });
+
+ assert.deepEqual(candidate.media.map((item) => item.id), ["video", "content-image"]);
+});
+
+test("page capture selections preserve one ordered article document", () => {
+ const batch = normalizePageCaptureBatch({
+ candidates: [{
+ id: "article",
+ title: "完整文章",
+ canonicalUrl: "https://example.com/article",
+ textBlocks: [
+ { id: "heading", kind: "section", text: "创作过程", sourceOrder: 0 },
+ { id: "paragraph", kind: "section", text: "正文内容", sourceOrder: 2 }
+ ],
+ media: [{ id: "hero", kind: "image", url: "https://example.com/hero.webp" }],
+ articleDocument: {
+ version: 1,
+ blocks: [
+ { id: "heading", kind: "heading", level: 2, text: "创作过程", sourceOrder: 0 },
+ { id: "hero-block", kind: "image", assetId: "hero", sourceUrl: "https://example.com/hero.webp", sourceOrder: 1 },
+ { id: "paragraph", kind: "paragraph", text: "正文内容", sourceOrder: 2 }
+ ]
+ }
+ }],
+ selections: [{
+ candidateId: "article",
+ selectedTextBlockIds: ["heading", "paragraph"],
+ selectedMediaIds: ["hero"],
+ mediaDecision: "confirmed"
+ }]
+ });
+
+ const [selected] = applyPageCaptureSelections(batch);
+ assert.deepEqual(selected.articleDocument.blocks.map((block) => block.kind), ["heading", "image", "paragraph"]);
+ assert.deepEqual(selected.articleDocument.blocks.map((block) => block.sourceOrder), [0, 1, 2]);
+});
+
+test("unconfirmed media never enters a saved article", () => {
+ const copy = "这是一段已经确认属于创作主体的完整正文,用来验证文字可以正常保存,而图片、GIF、视频和文档仍需要独立确认。".repeat(4);
+ const candidate = normalizePageCaptureCandidate({
+ id: "article",
+ title: "待确认媒体文章",
+ canonicalUrl: "https://example.com/article",
+ textBlocks: [{ id: "copy", kind: "paragraph", text: copy, sourceOrder: 0 }],
+ media: [{ id: "hero", kind: "image", url: "https://example.com/hero.webp" }],
+ articleDocument: {
+ version: 1,
+ blocks: [
+ { id: "copy", kind: "paragraph", text: copy, sourceOrder: 0 },
+ { id: "hero-block", kind: "image", assetId: "hero", sourceUrl: "https://example.com/hero.webp", sourceOrder: 1 }
+ ]
+ }
+ });
+ const batch = normalizePageCaptureBatch({
+ candidates: [candidate],
+ selections: [{
+ candidateId: candidate.id,
+ selectedTextBlockIds: candidate.textBlocks.map((block) => block.id),
+ selectedMediaIds: ["hero"],
+ mediaDecision: "pending"
+ }]
+ });
+
+ assert.equal(batch.selections[0].mediaDecision, "pending");
+ const [pending] = applyPageCaptureSelections(batch);
+ assert.deepEqual(pending.media, []);
+ assert.deepEqual(pending.articleDocument.blocks.map((block) => block.kind), ["paragraph"]);
+
+ const [confirmed] = applyPageCaptureSelections(normalizePageCaptureBatch({
+ ...batch,
+ selections: [{ ...batch.selections[0], mediaDecision: "confirmed" }]
+ }));
+ assert.deepEqual(confirmed.media.map((media) => media.id), ["hero"]);
+ assert.deepEqual(confirmed.articleDocument.blocks.map((block) => block.kind), ["paragraph", "image"]);
+
+ const [withoutMedia] = applyPageCaptureSelections(normalizePageCaptureBatch({
+ ...batch,
+ selections: [{ ...batch.selections[0], mediaDecision: "none" }]
+ }));
+ assert.deepEqual(withoutMedia.media, []);
+});
+
+test("a case cannot be saved until the user resolves its media proposal", () => {
+ const candidate = normalizePageCaptureCandidate({
+ id: "proposal",
+ title: "媒体待确认",
+ canonicalUrl: "https://example.com/proposal",
+ contentText: "已确认正文",
+ media: [{ id: "preview", kind: "image", url: "https://example.com/preview.webp" }]
+ });
+ const selection = {
+ candidateId: candidate.id,
+ includeText: true,
+ selectedMediaIds: ["preview"]
+ };
+
+ assert.equal(pageCaptureMediaDecisionsResolved(normalizePageCaptureBatch({
+ candidates: [candidate], selections: [{ ...selection, mediaDecision: "pending" }]
+ })), false);
+ assert.equal(pageCaptureMediaDecisionsResolved(normalizePageCaptureBatch({
+ candidates: [candidate], selections: [{ ...selection, mediaDecision: "confirmed" }]
+ })), true);
+ assert.equal(pageCaptureMediaDecisionsResolved(normalizePageCaptureBatch({
+ candidates: [candidate], selections: [{ ...selection, mediaDecision: "none" }]
+ })), true);
+});
+
+test("manual DOM correction keeps verified source facts and original media quality", () => {
+ const revised = mergePageCaptureRegionEdit({
+ id: "original",
+ title: "原始标题",
+ canonicalUrl: "https://example.com/article",
+ region: {
+ marker: "region:original",
+ contentTargets: [{ id: "old", kind: "text", path: "body:nth-of-type(1) > main:nth-of-type(1) > p:nth-of-type(1)", articleBlockIds: ["old-text"], sourceOrder: 0 }]
+ },
+ sourceFacts: { provider: "verified-site", author: "作者", status: "complete" },
+ media: [{ id: "verified-image", kind: "image", url: "https://cdn.example.com/image.webp", variants: [{ url: "https://cdn.example.com/image.webp", sourceKind: "site-original", width: 2400 }] }],
+ articleDocument: { version: 1, blocks: [{ id: "image", kind: "image", assetId: "verified-image", sourceUrl: "https://cdn.example.com/image.webp", sourceOrder: 0 }] }
+ }, {
+ title: "临时 DOM 标题",
+ canonicalUrl: "https://example.com/article",
+ region: {
+ marker: "region:revised",
+ edits: [{ mode: "exclude", path: "body:nth-of-type(1) > main:nth-of-type(1) > div:nth-of-type(2)" }],
+ contentTargets: [
+ { id: "copy", kind: "text", path: "body:nth-of-type(1) > main:nth-of-type(1) > div:nth-of-type(1)", articleBlockIds: ["text"], sourceOrder: 0 },
+ { id: "media", kind: "image", path: "body:nth-of-type(1) > main:nth-of-type(1) > div:nth-of-type(3) > img:nth-of-type(1)", mediaIds: ["revised-image"], groupId: "group", sourceOrder: 1 },
+ { id: "group", kind: "group", path: "body:nth-of-type(1) > main:nth-of-type(1) > div:nth-of-type(3)", mediaIds: ["revised-image"], sourceOrder: 1 }
+ ]
+ },
+ contentText: "修正后的正文",
+ textBlocks: [{ id: "text", kind: "section", text: "修正后的正文", sourceOrder: 0 }],
+ media: [{ id: "revised-image", kind: "image", url: "https://cdn.example.com/image.webp", width: 320 }],
+ articleDocument: { version: 1, blocks: [{ id: "image", kind: "image", assetId: "revised-image", sourceUrl: "https://cdn.example.com/image.webp", sourceOrder: 0 }] }
+ });
+
+ assert.equal(revised.id, "original");
+ assert.equal(revised.title, "原始标题");
+ assert.equal(revised.sourceFacts.provider, "verified-site");
+ assert.equal(revised.media[0].id, "verified-image");
+ assert.equal(revised.media[0].url, "https://cdn.example.com/image.webp");
+ assert.equal(revised.articleDocument.blocks[0].assetId, "verified-image");
+ assert.equal(revised.region.marker, "region:original");
+ assert.deepEqual(revised.region.edits, [{ mode: "exclude", path: "body:nth-of-type(1) > main:nth-of-type(1) > div:nth-of-type(2)" }]);
+ assert.deepEqual(revised.region.contentTargets.map((target) => target.kind), ["text", "image", "group"]);
+ assert.deepEqual(revised.region.contentTargets[1].mediaIds, ["verified-image"]);
+});
+
+test("the generic capture exposes meaningful nested blocks without turning every DOM node into a choice", () => {
+ const source = collectPageCaptureSnapshot.toString();
+ const targets = source.slice(source.indexOf("function collectContentTargets"), source.indexOf("function collectTextBlocks"));
+ assert.match(targets, /kind: "group"/);
+ assert.match(targets, /articleBlockIds/);
+ assert.match(targets, /mediaIds/);
+ assert.match(targets, /div,section,figure/);
+ assert.match(targets, /!element\.querySelector\?\.\(semanticSelector\)/);
+ assert.match(source, /playerForCompanionPoster/);
+ assert.match(source, /companionPosterForPlayer/);
+});
+
+test("one stable media selection keeps ranked original, lazy and current variants", () => {
+ const candidate = normalizePageCaptureCandidate({
+ title: "多清晰度作品",
+ canonicalUrl: "https://example.com/work/variants",
+ media: [{
+ id: "hero-image",
+ kind: "image",
+ url: "https://cdn.example.com/thumb.jpg",
+ sourceKind: "current",
+ variants: [
+ { url: "https://cdn.example.com/thumb.jpg", sourceKind: "current", width: 320 },
+ { url: "https://cdn.example.com/lazy.jpg", sourceKind: "deferred-src", width: 1600 },
+ { url: "https://origin.example.com/original.webp", sourceKind: "site-original", width: 2160, height: 3840 }
+ ]
+ }]
+ });
+ const [media] = candidate.media;
+ assert.equal(media.id, "hero-image");
+ assert.equal(media.url, "https://origin.example.com/original.webp");
+ assert.deepEqual(pageCaptureMediaFetchCandidates(media), [
+ "https://origin.example.com/original.webp",
+ "https://cdn.example.com/lazy.jpg",
+ "https://cdn.example.com/thumb.jpg"
+ ]);
+ assert.deepEqual(pageCapturePermissionOrigins([candidate]), ["https://cdn.example.com/*", "https://origin.example.com/*"]);
+});
+
+test("responsive URLs for one image merge without changing the first selection id", () => {
+ const candidate = normalizePageCaptureCandidate({
+ title: "同一作品的两个尺寸",
+ canonicalUrl: "https://example.com/work/one-image",
+ media: [
+ { id: "visible-image", kind: "image", url: "https://cdn.example.com/photo.jpg?width=320&quality=70", sourceKind: "current", width: 320 },
+ { id: "late-copy", kind: "image", url: "https://cdn.example.com/photo.jpg?width=2048&quality=90", sourceKind: "site-original", width: 2048 }
+ ]
+ });
+
+ assert.equal(candidate.media.length, 1);
+ assert.equal(candidate.media[0].id, "visible-image");
+ assert.equal(candidate.media[0].url, "https://cdn.example.com/photo.jpg?width=2048&quality=90");
+ assert.deepEqual(candidate.media[0].variants.map((item) => item.width), [2048, 320]);
+});
+
+test("the generic collector ranks an explicit full-image attribute above the visible thumbnail", async () => {
+ const injected = (0, eval)(`(${collectPageCaptureSnapshot.toString()})`);
+ const original = {
+ window: globalThis.window,
+ document: globalThis.document,
+ location: globalThis.location,
+ chrome: globalThis.chrome,
+ Readability: globalThis.Readability,
+ HTMLElement: globalThis.HTMLElement,
+ HTMLCanvasElement: globalThis.HTMLCanvasElement,
+ getComputedStyle: globalThis.getComputedStyle
+ };
+ class Element {}
+ class Canvas extends Element {}
+ const attributes = new Map([
+ ["data-full-image", "https://cdn.example.com/work.jpg?width=2400"],
+ ["src", "https://cdn.example.com/work.jpg?width=320"]
+ ]);
+ const image = new Element();
+ Object.assign(image, {
+ alt: "作品原图",
+ src: attributes.get("src"),
+ currentSrc: attributes.get("src"),
+ srcset: "",
+ naturalWidth: 320,
+ naturalHeight: 480,
+ complete: false,
+ width: 320,
+ height: 480,
+ className: "work-image",
+ matches: (selector) => selector === "img",
+ closest: () => null,
+ getAttribute: (name) => attributes.get(name) || "",
+ getBoundingClientRect: () => ({ x: 0, y: 0, width: 320, height: 480, top: 0, bottom: 480 })
+ });
+ const body = new Element();
+ Object.assign(body, {
+ innerText: "一张可以保存的公开作品。",
+ scrollHeight: 800,
+ querySelector: () => null,
+ querySelectorAll: (selector) => selector === "img,video,iframe,canvas" ? [image] : []
+ });
+ globalThis.HTMLElement = Element;
+ globalThis.HTMLCanvasElement = Canvas;
+ globalThis.window = { scrollX: 0, scrollY: 0, innerWidth: 1200, innerHeight: 800, scrollTo: () => undefined };
+ globalThis.document = {
+ title: "Generic image fixture",
+ body,
+ documentElement: { scrollHeight: 800, clientWidth: 1200, clientHeight: 800 },
+ baseURI: "https://example.com/work",
+ images: [image],
+ querySelector: () => null,
+ querySelectorAll: () => [],
+ cloneNode: () => ({}),
+ createElement: () => ({ width: 0, height: 0, getContext: () => null, toDataURL: () => "" })
+ };
+ globalThis.location = { hostname: "example.com", href: "https://example.com/work" };
+ globalThis.getComputedStyle = () => ({ backgroundImage: "none" });
+ globalThis.chrome = undefined;
+ globalThis.Readability = undefined;
+ try {
+ const result = await injected({ adapters: PAGE_CAPTURE_ADAPTERS, maxCandidates: 10, maxMedia: 10 });
+ assert.equal(result.candidates[0].media[0].url, "https://cdn.example.com/work.jpg?width=2400");
+ assert.equal(result.candidates[0].media[0].sourceKind, "site-original");
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("page capture retries media variants and uses visible pixels only after every remote source fails", async () => {
+ const attempts = [];
+ const media = normalizePageCaptureCandidate({
+ title: "回退作品",
+ canonicalUrl: "https://example.com/work/fallback",
+ media: [{
+ id: "hero",
+ dataUrl: "data:image/webp;base64,AAAA",
+ variants: [
+ { url: "https://origin.example.com/broken.webp", sourceKind: "site-original" },
+ { url: "https://cdn.example.com/working.webp", sourceKind: "deferred-src" }
+ ]
+ }]
+ }).media[0];
+ const remote = await resolvePageCaptureImage(media, {
+ fetchMedia: async (url) => {
+ attempts.push(url);
+ if (url.includes("broken")) throw new Error("HTTP 403");
+ return new Blob(["remote"], { type: "image/webp" });
+ },
+ decodeDataUrl: async () => new Blob(["pixels"], { type: "image/webp" })
+ });
+ assert.deepEqual(attempts, ["https://origin.example.com/broken.webp", "https://cdn.example.com/working.webp"]);
+ assert.equal(remote.usedPixelFallback, false);
+ const pixels = await resolvePageCaptureImage(media, {
+ fetchMedia: async () => { throw new Error("unavailable"); },
+ decodeDataUrl: async () => new Blob(["pixels"], { type: "image/webp" })
+ });
+ assert.equal(pixels.usedPixelFallback, true);
+ assert.equal(pixels.captureMethod, "pixel-fallback");
+});
+
+test("selected media uses the current page session only after public variants fail", async () => {
+ const calls = [];
+ const media = normalizePageCaptureCandidate({
+ title: "登录后可见作品",
+ canonicalUrl: "https://example.com/work/session",
+ media: [{
+ id: "session-image",
+ dataUrl: "data:image/webp;base64,AAAA",
+ variants: [{ url: "https://media.example.com/original.webp", sourceKind: "site-original" }]
+ }]
+ }).media[0];
+ const resolved = await resolvePageCaptureImage(media, {
+ fetchMedia: async (url) => { calls.push(`public:${url}`); throw new Error("HTTP 403"); },
+ fetchSessionMedia: async (url) => {
+ calls.push(`session:${url}`);
+ return { blob: new Blob(["session"], { type: "image/webp" }), metadata: { width: 2048, height: 3072 } };
+ },
+ decodeDataUrl: async () => { calls.push("pixels"); return new Blob(["pixels"], { type: "image/webp" }); }
+ });
+
+ assert.deepEqual(calls, [
+ "public:https://media.example.com/original.webp",
+ "session:https://media.example.com/original.webp"
+ ]);
+ assert.equal(resolved.captureMethod, "page-session");
+ assert.equal(resolved.usedPixelFallback, false);
+ assert.deepEqual(resolved.metadata, { width: 2048, height: 3072 });
+});
+
+test("denied media-domain access skips the page session and keeps the pixel fallback", async () => {
+ const calls = [];
+ const media = normalizePageCaptureCandidate({
+ title: "拒绝额外权限",
+ canonicalUrl: "https://example.com/work/denied",
+ media: [{ id: "image", url: "https://media.example.com/image.webp", dataUrl: "data:image/webp;base64,AAAA" }]
+ }).media[0];
+ const resolved = await resolvePageCaptureImage(media, {
+ sessionMediaAllowed: false,
+ fetchMedia: async () => { calls.push("public"); throw new Error("denied"); },
+ fetchSessionMedia: async () => { calls.push("session"); return new Blob(["unexpected"]); },
+ decodeDataUrl: async () => { calls.push("pixels"); return new Blob(["pixels"], { type: "image/webp" }); }
+ });
+ assert.deepEqual(calls, ["public", "pixels"]);
+ assert.equal(resolved.captureMethod, "pixel-fallback");
+ assert.equal(normalizePageCaptureBatch({ sessionMediaAllowed: false }).sessionMediaAllowed, false);
+});
+
test("page capture requires explicit component confirmation and requests only chosen media origins", () => {
const batch = normalizePageCaptureBatch({ candidates: [
{ id: "one", title: "一", canonicalUrl: "https://example.com/1", contentText: "正文一", media: [{ id: "one-image", url: "https://img.example.com/a.jpg" }] },
@@ -79,14 +558,31 @@ test("page capture requires explicit component confirmation and requests only ch
...batch,
selections: [{ candidateId: "one", includeText: false, selectedMediaIds: ["one-image"] }]
});
- assert.deepEqual(confirmed.selections, [{ candidateId: "one", includeText: false, selectedMediaIds: ["one-image"] }]);
- const selected = applyPageCaptureSelections(confirmed);
+ assert.deepEqual(confirmed.selections, [{ candidateId: "one", includeText: false, selectedMediaIds: ["one-image"], mediaDecision: "pending" }]);
+ assert.deepEqual(applyPageCaptureSelections(confirmed)[0].media, []);
+ const selected = applyPageCaptureSelections(normalizePageCaptureBatch({
+ ...confirmed,
+ selections: confirmed.selections.map((selection) => ({ ...selection, mediaDecision: "confirmed" }))
+ }));
assert.equal(selected.length, 1);
assert.equal(selected[0].contentText, "");
assert.deepEqual(selected[0].media.map((item) => item.id), ["one-image"]);
assert.deepEqual(pageCapturePermissionOrigins(selected), ["https://img.example.com/*"]);
});
+test("page capture requests download access only for verified safe documents", () => {
+ const candidate = normalizePageCaptureCandidate({
+ id: "downloads",
+ title: "文章下载区",
+ canonicalUrl: "https://example.com/article",
+ media: [
+ { id: "brief", kind: "document", url: "https://files.example.com/brief.pdf", mimeType: "application/pdf" },
+ { id: "archive", kind: "document", url: "https://unsafe.example.com/skill.zip", mimeType: "application/zip" }
+ ]
+ });
+ assert.deepEqual(pageCapturePermissionOrigins([candidate]), ["https://files.example.com/*"]);
+});
+
test("page capture selection ignores unknown candidates and media", () => {
const candidates = [normalizePageCaptureCandidate({
id: "known", title: "作品", canonicalUrl: "https://example.com/work",
@@ -95,7 +591,157 @@ test("page capture selection ignores unknown candidates and media", () => {
assert.equal(normalizePageCaptureSelection({ candidateId: "missing", includeText: true }, candidates), null);
assert.deepEqual(normalizePageCaptureSelection({
candidateId: "known", includeText: true, selectedMediaIds: ["missing", "known-image"]
- }, candidates), { candidateId: "known", includeText: true, selectedMediaIds: ["known-image"] });
+ }, candidates), { candidateId: "known", includeText: true, selectedMediaIds: ["known-image"], mediaDecision: "pending" });
+});
+
+test("page capture saves only the article sections the user explicitly chose", () => {
+ const batch = normalizePageCaptureBatch({
+ candidates: [{
+ id: "article",
+ title: "长文章",
+ canonicalUrl: "https://example.com/article",
+ contentText: "开场段落\n\n需要保留的核心段落\n\n结尾段落",
+ contentHtml: "<p>开场段落</p><p>需要保留的核心段落</p><p>结尾段落</p>",
+ textBlocks: [
+ { id: "intro", text: "开场段落", html: "<p>开场段落</p>" },
+ { id: "core", text: "需要保留的核心段落", html: "<p>需要保留的核心段落</p>" },
+ { id: "outro", text: "结尾段落", html: "<p>结尾段落</p>" }
+ ]
+ }],
+ selections: [{
+ candidateId: "article",
+ selectedTextBlockIds: ["core"],
+ selectedMediaIds: [],
+ mediaDecision: "none"
+ }]
+ });
+
+ assert.deepEqual(batch.selections, [{
+ candidateId: "article",
+ includeText: true,
+ selectedTextBlockIds: ["core"],
+ selectedMediaIds: [],
+ mediaDecision: "none"
+ }]);
+ const [selected] = applyPageCaptureSelections(batch);
+ assert.equal(selected.contentText, "需要保留的核心段落");
+ assert.equal(selected.contentHtml, "<p>需要保留的核心段落</p>");
+});
+
+test("creative sections merge adjacent fragments, hide weak page chrome and restore source order when saving", () => {
+ const candidate = normalizePageCaptureCandidate({
+ id: "creative-brief",
+ title: "Project Aurora",
+ canonicalUrl: "https://example.com/projects/aurora",
+ contentText: "Project Aurora\n\n首页\n\nBrief\n\n一部关于三名水下清理员的动作喜剧。\n\n他们试图证明自己,却意外卷入一场远超预期的深海危机。\n\n评论",
+ textBlocks: [
+ { id: "title", text: "Project Aurora", html: "<h1>Project Aurora</h1>", kind: "heading", sourceOrder: 0 },
+ { id: "nav", text: "首页", html: "<p>首页</p>", kind: "noise", sourceOrder: 1 },
+ { id: "brief", text: "Brief", html: "<h2>Brief</h2>", kind: "heading", sourceOrder: 2 },
+ { id: "body-a", text: "一部关于三名水下清理员的动作喜剧。", html: "<p>一部关于三名水下清理员的动作喜剧。</p>", sourceOrder: 3 },
+ { id: "body-b", text: "他们试图证明自己,却意外卷入一场远超预期的深海危机。", html: "<p>他们试图证明自己,却意外卷入一场远超预期的深海危机。</p>", sourceOrder: 4 },
+ { id: "comment", text: "评论", html: "<p>评论</p>", kind: "noise", sourceOrder: 5 }
+ ]
+ });
+
+ assert.equal(candidate.textBlocks.length, 1);
+ assert.match(candidate.textBlocks[0].text, /^Brief\n/u);
+ assert.doesNotMatch(candidate.textBlocks[0].text, /首页|评论|Project Aurora/u);
+ assert.deepEqual(candidate.possibleOmissions.map((item) => item.text), ["首页", "评论"]);
+
+ const [selected] = applyPageCaptureSelections(normalizePageCaptureBatch({
+ candidates: [candidate],
+ selections: [{ candidateId: candidate.id, selectedTextBlockIds: [candidate.textBlocks[0].id], selectedMediaIds: [] }]
+ }));
+ assert.equal(selected.contentText, candidate.textBlocks[0].text);
+});
+
+test("creative-section preview rank never changes the saved page order", () => {
+ const candidate = normalizePageCaptureCandidate({
+ id: "ordered-brief",
+ title: "Ordered brief",
+ canonicalUrl: "https://example.com/ordered",
+ textBlocks: [
+ { text: "Brief", kind: "heading", sourceOrder: 0 },
+ { text: "第一部分很短。", kind: "paragraph", sourceOrder: 1 },
+ { text: "Prompt", kind: "heading", sourceOrder: 2 },
+ { text: "第二部分更长,用于确保预览相关性排序与网页原始顺序不同。", kind: "paragraph", sourceOrder: 3 }
+ ]
+ });
+ assert.match(candidate.textBlocks[0].text, /^Prompt/u);
+
+ const [selected] = applyPageCaptureSelections(normalizePageCaptureBatch({
+ candidates: [candidate],
+ selections: [{
+ candidateId: candidate.id,
+ selectedTextBlockIds: candidate.textBlocks.map((item) => item.id),
+ selectedMediaIds: []
+ }]
+ }));
+ assert.match(selected.contentText, /^Brief/u);
+ assert.match(selected.contentText, /第一部分[\s\S]*Prompt/u);
+});
+
+test("structured site content stays one clean creative section instead of being resegmented from the page shell", async () => {
+ const injected = (0, eval)(`(${collectPageCaptureSnapshot.toString()})`);
+ const original = {
+ window: globalThis.window,
+ document: globalThis.document,
+ location: globalThis.location,
+ chrome: globalThis.chrome,
+ Readability: globalThis.Readability
+ };
+ const body = {
+ innerText: "首页 发现 项目 Brief 评论 推荐 下载 分享 以及大量页面壳文字",
+ scrollHeight: 800,
+ querySelector: () => null,
+ querySelectorAll: () => []
+ };
+ globalThis.window = { scrollX: 0, scrollY: 0, scrollTo: () => undefined };
+ globalThis.document = {
+ title: "Cully Hill Boys",
+ body,
+ documentElement: { scrollHeight: 800 },
+ baseURI: "https://higgsfield.ai/projects/cully-hill-boys",
+ querySelector: () => null,
+ querySelectorAll: () => [],
+ cloneNode: () => ({})
+ };
+ globalThis.location = { hostname: "higgsfield.ai", href: "https://higgsfield.ai/projects/cully-hill-boys" };
+ globalThis.chrome = undefined;
+ globalThis.Readability = undefined;
+ const siteData = {
+ adapter: "higgsfield",
+ pageKind: "detail",
+ completeness: "complete",
+ canonicalUrl: globalThis.location.href,
+ title: "Cully Hill Boys",
+ contentText: "This is the project brief for the Cully Hill Boys, our feature-length AI film.",
+ media: [],
+ sourceFacts: { provider: "higgsfield", extractionMethod: "structured" }
+ };
+ try {
+ const result = normalizePageCaptureBatch(await injected({
+ adapters: PAGE_CAPTURE_ADAPTERS,
+ siteData,
+ maxCandidates: 10,
+ maxMedia: 10
+ }));
+ assert.equal(result.candidates[0].textBlocks.length, 1);
+ assert.equal(result.candidates[0].textBlocks[0].text, siteData.contentText);
+ assert.doesNotMatch(result.candidates[0].contentText, /首页|评论|推荐/u);
+
+ body.innerText = "A complete visible project description remains available when the optional site enhancement is unavailable.";
+ const genericFallback = normalizePageCaptureBatch(await injected({
+ adapters: PAGE_CAPTURE_ADAPTERS,
+ siteData: { ...siteData, contentText: "", completeness: "partial", sourceFacts: {} },
+ maxCandidates: 10,
+ maxMedia: 10
+ }));
+ assert.match(genericFallback.candidates[0].contentText, /complete visible project description/u);
+ } finally {
+ Object.assign(globalThis, original);
+ }
});
test("the actual Chrome injection function is self-contained", async () => {
@@ -135,6 +781,198 @@ test("the actual Chrome injection function is self-contained", async () => {
}
});
+test("Jimeng home uses structured works and never falls back to application-shell text", async () => {
+ const injected = (0, eval)(`(${collectPageCaptureSnapshot.toString()})`);
+ const original = {
+ window: globalThis.window,
+ document: globalThis.document,
+ location: globalThis.location,
+ chrome: globalThis.chrome,
+ Readability: globalThis.Readability
+ };
+ const body = {
+ innerText: "发现 技能 上传参考图 输入文字 图片生成 二维码",
+ scrollHeight: 800,
+ querySelector: () => null,
+ querySelectorAll: () => []
+ };
+ globalThis.window = { scrollX: 0, scrollY: 0, scrollTo: () => undefined };
+ globalThis.document = {
+ title: "即梦AI - 一站式AI创作平台",
+ body,
+ documentElement: { scrollHeight: 800 },
+ baseURI: "https://jimeng.jianying.com/ai-tool/home",
+ querySelector: () => null,
+ querySelectorAll: () => [],
+ cloneNode: () => ({})
+ };
+ globalThis.location = { hostname: "jimeng.jianying.com", href: "https://jimeng.jianying.com/ai-tool/home" };
+ globalThis.chrome = undefined;
+ globalThis.Readability = undefined;
+ const siteData = {
+ adapter: "jimeng",
+ pageKind: "feed",
+ completeness: "complete",
+ candidates: [{
+ id: "jimeng:7490123456789012345",
+ pageType: "artwork",
+ title: "AIGC大叔 · 2026-05-30",
+ canonicalUrl: "https://jimeng.jianying.com/ai-tool/work-detail/7490123456789012345",
+ contentText: "真实作品提示词",
+ media: [{
+ id: "jimeng:7490123456789012345:1",
+ kind: "image",
+ placement: "inline",
+ url: "https://p3-dreamina-sign.byteimg.com/7490123456789012345.webp"
+ }],
+ sourceFacts: { provider: "jimeng", itemId: "7490123456789012345", author: "AIGC大叔" },
+ extraction: { scope: "document", method: "structured" }
+ }]
+ };
+ try {
+ const result = await injected({ adapters: PAGE_CAPTURE_ADAPTERS, siteData, maxCandidates: 10, maxMedia: 10 });
+ assert.equal(result.candidates.length, 1);
+ assert.equal(result.candidates[0].contentText, "真实作品提示词");
+ assert.doesNotMatch(result.candidates[0].contentText, /上传参考图|二维码/u);
+ assert.deepEqual(pageCaptureDefaultMediaIds(result.candidates[0]), ["jimeng:7490123456789012345:1"]);
+
+ const missing = await injected({
+ adapters: PAGE_CAPTURE_ADAPTERS,
+ siteData: { ...siteData, completeness: "partial", candidates: [] },
+ maxCandidates: 10,
+ maxMedia: 10
+ });
+ assert.deepEqual(missing.candidates, []);
+
+ const krea = await injected({
+ adapters: PAGE_CAPTURE_ADAPTERS,
+ siteData: {
+ ...siteData,
+ adapter: "krea",
+ candidates: [{
+ ...siteData.candidates[0],
+ id: "krea:554bfb91-2a06-5e91-8a21-24a162f3b81f",
+ title: "Krea public artwork",
+ sourceFacts: { provider: "krea", itemId: "554bfb91-2a06-5e91-8a21-24a162f3b81f" }
+ }]
+ },
+ maxCandidates: 10,
+ maxMedia: 10
+ });
+ assert.equal(krea.candidates[0].title, "Krea public artwork");
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("generic JSON-LD provides author, identity, publication time, engagement and structured original media", async () => {
+ const injected = (0, eval)(`(${collectPageCaptureSnapshot.toString()})`);
+ const original = {
+ window: globalThis.window,
+ document: globalThis.document,
+ location: globalThis.location,
+ chrome: globalThis.chrome,
+ Readability: globalThis.Readability
+ };
+ const structured = {
+ "@type": "ImageObject",
+ name: "Structured artwork",
+ identifier: "work-77",
+ author: [{ "@type": "Person", name: "Structured Author" }],
+ datePublished: "2026-08-01T12:00:00Z",
+ image: { contentUrl: "https://cdn.example.com/original.webp", width: 2048, height: 3072 },
+ interactionStatistic: [{ interactionType: { "@type": "LikeAction" }, userInteractionCount: 91 }]
+ };
+ const body = {
+ innerText: "Structured prompt body",
+ scrollHeight: 800,
+ querySelector: () => null,
+ querySelectorAll: () => []
+ };
+ globalThis.window = { scrollX: 0, scrollY: 0, scrollTo: () => undefined };
+ globalThis.document = {
+ title: "Fallback title",
+ body,
+ documentElement: { scrollHeight: 800 },
+ baseURI: "https://example.com/work/77",
+ querySelector: () => null,
+ querySelectorAll: (selector) => selector === 'script[type="application/ld+json"]' ? [{ textContent: JSON.stringify(structured) }] : [],
+ cloneNode: () => ({})
+ };
+ globalThis.location = { hostname: "example.com", href: "https://example.com/work/77" };
+ globalThis.chrome = undefined;
+ globalThis.Readability = undefined;
+ try {
+ const result = await injected({ adapters: [], maxCandidates: 10, maxMedia: 10 });
+ const [candidate] = result.candidates;
+ assert.equal(candidate.sourceFacts.author, "Structured Author");
+ assert.equal(candidate.sourceFacts.itemId, "work-77");
+ assert.equal(candidate.sourceFacts.publishedAt, "2026-08-01T12:00:00Z");
+ assert.deepEqual(candidate.sourceFacts.engagement, { likes: 91 });
+ assert.equal(candidate.media[0].url, "https://cdn.example.com/original.webp");
+ assert.equal(candidate.media[0].sourceKind, "structured");
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+test("page capture prefers the user's live page selection and preserves its HTML", async () => {
+ const injected = (0, eval)(`(${collectPageCaptureSnapshot.toString()})`);
+ const original = {
+ window: globalThis.window,
+ document: globalThis.document,
+ location: globalThis.location,
+ chrome: globalThis.chrome,
+ Readability: globalThis.Readability
+ };
+ const selectedText = "只保存用户选中的这一段";
+ const selectionContainer = {
+ innerHTML: "",
+ appendChild: () => { selectionContainer.innerHTML = `<p>${selectedText}</p>`; }
+ };
+ const body = {
+ innerText: "页面上还有很多用户没有选择的正文内容。",
+ scrollHeight: 800,
+ querySelector: () => null,
+ querySelectorAll: () => []
+ };
+ globalThis.window = {
+ scrollX: 0,
+ scrollY: 0,
+ scrollTo: () => undefined,
+ getSelection: () => ({
+ isCollapsed: false,
+ rangeCount: 1,
+ toString: () => selectedText,
+ getRangeAt: () => ({ cloneContents: () => ({}) })
+ })
+ };
+ globalThis.document = {
+ title: "Selection fixture",
+ body,
+ documentElement: { scrollHeight: 800 },
+ baseURI: "https://example.com/article",
+ querySelector: () => null,
+ querySelectorAll: () => [],
+ cloneNode: () => ({}),
+ createElement: () => selectionContainer
+ };
+ globalThis.location = { hostname: "example.com", href: "https://example.com/article" };
+ globalThis.chrome = undefined;
+ globalThis.Readability = undefined;
+ try {
+ const result = await injected({ adapters: [], maxCandidates: 10, maxMedia: 10 });
+ assert.equal(result.candidates[0].contentText, selectedText);
+ assert.equal(result.candidates[0].contentHtml, `<p>${selectedText}</p>`);
+ assert.equal(result.candidates[0].extraction.scope, "selection");
+ const wholePage = await injected({ adapters: [], mode: "whole", maxScrollSteps: 1, maxCandidates: 10, maxMedia: 10 });
+ assert.equal(wholePage.candidates[0].contentText, body.innerText);
+ assert.equal(wholePage.candidates[0].extraction.scope, "document");
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
test("visible canvas pixels stay local to the capture payload and do not request a fake host permission", () => {
const candidate = normalizePageCaptureCandidate({
id: "canvas-work", title: "Canvas 作品", canonicalUrl: "https://example.com/work",
@@ -144,3 +982,77 @@ test("visible canvas pixels stay local to the capture payload and do not request
assert.equal(candidate.media[0].dataUrl, "data:image/webp;base64,AAAA");
assert.deepEqual(pageCapturePermissionOrigins([candidate]), []);
});
+
+test("list capture can combine cases without losing per-media provenance", () => {
+ const batch = normalizePageCaptureBatch({
+ captureMode: "list",
+ saveMode: "combined",
+ targetCount: 2,
+ stopReason: "target-reached",
+ candidates: [
+ {
+ id: "work-a", title: "作品 A", canonicalUrl: "https://example.com/work/a", contentText: "Prompt A",
+ sourceFacts: { author: "作者 A" },
+ media: [{ id: "media-a", url: "https://cdn.example.com/a.jpg" }]
+ },
+ {
+ id: "work-b", title: "作品 B", canonicalUrl: "https://example.com/work/b", contentText: "Prompt B",
+ sourceFacts: { author: "作者 B" },
+ media: [{ id: "media-b", url: "https://cdn.example.com/b.jpg" }]
+ }
+ ]
+ });
+ assert.equal(batch.captureMode, "list");
+ assert.equal(batch.targetCount, 2);
+ assert.equal(batch.saveMode, "combined");
+
+ const combined = combinePageCaptureCandidates(batch.candidates, {
+ title: "本次列表灵感",
+ canonicalUrl: "https://example.com/gallery"
+ });
+ assert.equal(combined.title, "本次列表灵感");
+ assert.match(combined.contentText, /作品 A[\s\S]*Prompt A[\s\S]*作品 B[\s\S]*Prompt B/u);
+ assert.deepEqual(combined.media.map((item) => ({ title: item.sourceTitle, author: item.sourceAuthor, url: item.originalWorkUrl })), [
+ { title: "作品 A", author: "作者 A", url: "https://example.com/work/a" },
+ { title: "作品 B", author: "作者 B", url: "https://example.com/work/b" }
+ ]);
+ const stored = normalizeMediaAsset({
+ id: "stored-media", kind: "image", sourceUrl: combined.media[0].url,
+ sourceTitle: combined.media[0].sourceTitle,
+ sourceAuthor: combined.media[0].sourceAuthor,
+ originalWorkUrl: combined.media[0].originalWorkUrl
+ });
+ assert.deepEqual({ title: stored.sourceTitle, author: stored.sourceAuthor, url: stored.originalWorkUrl }, {
+ title: "作品 A", author: "作者 A", url: "https://example.com/work/a"
+ });
+});
+
+test("list capture inherits a representative structure without auto-accepting a different content shape", () => {
+ const reference = {
+ title: "作品一",
+ canonicalUrl: "https://example.com/1",
+ textBlocks: [{ id: "prompt", kind: "section", text: "创作提示" }],
+ media: [{ id: "image", kind: "image", url: "https://example.com/1.webp" }],
+ articleDocument: { version: 1, blocks: [
+ { id: "prompt", kind: "paragraph", text: "创作提示", sourceOrder: 0 },
+ { id: "image-block", kind: "image", assetId: "image", sourceOrder: 1 }
+ ] }
+ };
+ assert.equal(pageCaptureStructureMatches(reference, {
+ ...reference,
+ title: "作品二",
+ canonicalUrl: "https://example.com/2",
+ media: [{ id: "other", kind: "image", url: "https://example.com/2.webp" }],
+ articleDocument: { version: 1, blocks: [
+ { id: "prompt-2", kind: "paragraph", text: "另一条创作提示", sourceOrder: 0 },
+ { id: "image-block-2", kind: "image", assetId: "other", sourceOrder: 1 }
+ ] }
+ }), true);
+ assert.equal(pageCaptureStructureMatches(reference, {
+ ...reference,
+ title: "混入的视频模块",
+ canonicalUrl: "https://example.com/3",
+ media: [{ id: "video", kind: "video", url: "https://example.com/3.mp4" }],
+ articleDocument: { version: 1, blocks: [{ id: "video-block", kind: "video", assetId: "video", sourceOrder: 0 }] }
+ }), false);
+});
diff --git a/test/page-session-media.test.js b/test/page-session-media.test.js
new file mode 100644
index 0000000..2e36b01
--- /dev/null
+++ b/test/page-session-media.test.js
@@ -0,0 +1,48 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ discardPageSessionMedia,
+ preparePageSessionMedia,
+ readPageSessionMediaChunk
+} from "../page-session-media.js";
+
+test("page-session media reads only the exact selected HTTPS URL with browser credentials", async () => {
+ const injected = (0, eval)(`(${preparePageSessionMedia.toString()})`);
+ const original = { location: globalThis.location, fetch: globalThis.fetch };
+ const calls = [];
+ globalThis.location = { href: "https://example.com/work/1", origin: "https://example.com" };
+ globalThis.fetch = async (url, options) => {
+ calls.push({ url, options });
+ return new Response(Uint8Array.from([0x89, 0x50, 0x4e, 0x47]), { headers: { "content-type": "image/png" } });
+ };
+ try {
+ await assert.rejects(() => injected({
+ token: "token-a", url: "https://evil.example/image.png", allowedUrls: ["https://media.example/image.png"], maxBytes: 32, chunkBytes: 4
+ }), /不在本次选择范围/);
+ const prepared = await injected({
+ token: "token-b", url: "https://media.example/image.png", allowedUrls: ["https://media.example/image.png"], maxBytes: 32, chunkBytes: 4
+ });
+ assert.equal(prepared.chunkCount, 1);
+ assert.equal(calls[0].options.credentials, "include");
+ assert.equal(calls[0].options.redirect, "error");
+ assert.equal(calls[0].options.referrerPolicy, "no-referrer");
+ } finally {
+ delete globalThis.__PROMPTDIRECTOR_PAGE_SESSION_MEDIA__;
+ Object.assign(globalThis, original);
+ }
+});
+
+test("page-session chunks are one-time bounded state and can be explicitly discarded", async () => {
+ const read = (0, eval)(`(${readPageSessionMediaChunk.toString()})`);
+ const discard = (0, eval)(`(${discardPageSessionMedia.toString()})`);
+ globalThis.__PROMPTDIRECTOR_PAGE_SESSION_MEDIA__ = new Map([["token", { chunks: ["AAAA", "BBBB"] }]]);
+ try {
+ assert.equal(read({ token: "token", index: 0 }), "AAAA");
+ assert.equal(read({ token: "token", index: 2 }), "");
+ assert.equal(discard({ token: "token" }), true);
+ assert.equal(read({ token: "token", index: 0 }), "");
+ } finally {
+ delete globalThis.__PROMPTDIRECTOR_PAGE_SESSION_MEDIA__;
+ }
+});
diff --git a/test/page_capture_e2e.py b/test/page_capture_e2e.py
index bbe5ce7..2377dbb 100644
--- a/test/page_capture_e2e.py
+++ b/test/page_capture_e2e.py
@@ -9,15 +9,22 @@ ARTICLE = b"""<!doctype html><html><head>
<title>Controllable capture fixture</title>
<meta property="og:title" content="Controllable capture fixture">
<meta name="author" content="Fixture Author">
+<script type="application/ld+json">{"@type":"Article","headline":"Controllable capture fixture","image":{"contentUrl":"/asset-area-preview.png","width":1200,"height":800}}</script>
</head><body>
<header><img class="site-logo" src="/logo.png" style="width:40px;height:40px"><button><img class="button-icon" src="/icon.png" style="width:24px;height:24px"></button></header>
<main><article>
<h1>Controllable capture fixture</h1>
<p>This article contains enough deliberate editorial text to exercise the real injected page capture path. The scanner must produce a preview before anything is stored, and the reader must remain in control of the article text and every media item.</p>
-<p>A second paragraph makes the article boundary unambiguous while keeping navigation, logos, avatars, buttons and advertising outside the saved content.</p>
-<img alt="Primary artwork" src="/hero.png" style="display:block;width:720px;height:480px">
-<img alt="Secondary artwork" src="/secondary.png" style="display:block;width:640px;height:420px">
+<p>A second paragraph includes <a href="/evidence">evidence</a> and makes the article boundary unambiguous while keeping navigation, logos, avatars, buttons and advertising outside the saved content.</p>
+<picture><source media="(min-width: 1px)" srcset="/hero-picture-800.png 800w, /hero-picture-2000.png 2000w" sizes="400px">
+<img alt="Primary artwork" src="/hero-400.png" srcset="/hero-400.png 400w, /hero-1600.png 1600w" sizes="400px" style="display:block;width:720px;height:480px"></picture>
+<img alt="Secondary artwork" src="/secondary-640.png" srcset="/secondary-640.png 640w, /secondary-1280.png 1280w" sizes="400px" style="display:block;width:640px;height:420px">
+<img alt="Deferred artwork" src="/placeholder.png" data-src="/deferred-original.png" style="display:block;width:600px;height:400px">
+<img alt="Animated process" src="/animation.gif" style="display:block;width:480px;height:320px">
+<video aria-label="Process film" controls poster="/video-poster.png" src="/film.mp4" style="display:block;width:640px;height:360px"></video>
+<iframe src="/ordinary-resource-frame" title="Not a video"></iframe>
</article></main>
+<section id="appendix"><h2>Production appendix</h2><p>This deliberately separate appendix contains the downloadable production notes that the reader may choose to add to the captured article.</p><a download href="/production-brief.pdf">Production brief PDF</a><a download href="/unsafe-package.zip">Packaged Skill archive</a></section>
<aside aria-label="advertisement"><img class="advert" src="/ad.png" style="width:500px;height:300px"></aside>
</body></html>"""
@@ -26,18 +33,52 @@ PNG = bytes.fromhex(
"0000000d49444154789c6360f8cfc000000301010018dd8db10000000049454e44ae426082"
)
+GIF = bytes.fromhex(
+ "47494638396101000100800000000000ffffff21f90401000000002c00000000010001000002024401003b"
+)
+
+PDF = b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n%%EOF"
+
+
+def list_page(page: int) -> bytes:
+ first = 1 if page == 1 else 3
+ cards = "".join(
+ f'''<div class="work-card"><a href="/work/{index}"><h2>List Work {index}</h2></a>
+ <h3>Prompt</h3><p>Creative prompt for list work {index}.</p>
+ <img alt="List artwork {index}" src="/list-image-{index}.png" style="display:block;width:320px;height:320px"></div>'''
+ for index in range(first, first + 2)
+ )
+ next_link = '<a rel="next" href="/promptdirector-list?page=2">Next</a>' if page == 1 else ""
+ return f"<!doctype html><html><head><title>Prompt list</title></head><body><main>{cards}</main><nav aria-label=\"pagination\">{next_link}</nav></body></html>".encode()
+
def main() -> None:
with extension_session("prompt-director-page-capture-") as run:
fixture_url = "https://api.deepseek.com/promptdirector-capture-fixture"
- run.context.route(
- "https://api.deepseek.com/**",
- lambda route: route.fulfill(
+ def route_fixture(route) -> None:
+ request_url = route.request.url
+ if request_url.endswith("/deferred-original.png"):
+ route.fulfill(status=403, body=b"expired", content_type="text/plain")
+ return
+ if request_url.endswith("/animation.gif"):
+ route.fulfill(status=200, body=GIF, content_type="image/gif")
+ return
+ if request_url.endswith("/production-brief.pdf"):
+ route.fulfill(status=200, body=PDF, content_type="application/pdf")
+ return
+ if request_url.endswith("/unsafe-package.zip"):
+ route.fulfill(status=200, body=b"PK\x03\x04unsafe", content_type="application/zip")
+ return
+ if "/promptdirector-list" in request_url:
+ route.fulfill(status=200, body=list_page(2 if "page=2" in request_url else 1), content_type="text/html; charset=utf-8")
+ return
+ route.fulfill(
status=200,
- body=ARTICLE if route.request.url == fixture_url else PNG,
- content_type="text/html; charset=utf-8" if route.request.url == fixture_url else "image/png",
- ),
- )
+ body=ARTICLE if request_url == fixture_url else PNG,
+ content_type="text/html; charset=utf-8" if request_url == fixture_url else "image/png",
+ )
+
+ run.context.route("https://api.deepseek.com/**", route_fixture)
collector = run.open_page("collector.html", wait_until="networkidle")
run.seed_storage(collector, {"schemaVersion": 24, "entries": []})
fixture = run.context.new_page()
@@ -46,30 +87,166 @@ def main() -> None:
collector.evaluate("() => document.querySelector('#start-page-capture').click()")
expect(collector.locator("#page-capture")).to_be_visible(timeout=8000)
- expect(collector.locator(".page-capture-item")).to_have_count(1)
- media_labels = collector.locator(".page-capture-media").all_text_contents()
- media_sources = collector.locator(".page-capture-media img").evaluate_all("nodes => nodes.map(node => node.src)")
- assert len(media_labels) == 2, {"labels": media_labels, "sources": media_sources}
- expect(collector.locator(".page-capture-component input:checked")).to_have_count(0)
+ expect(collector.locator(".page-capture-item")).to_have_count(2)
+ media_labels = collector.locator(".page-capture-article-media").all_text_contents()
+ media_sources = collector.locator(".page-capture-article-media img").evaluate_all("nodes => nodes.map(node => node.src)")
+ assert len(media_labels) == 5, {"labels": media_labels, "sources": media_sources}
+ assert media_sources[0].endswith("/hero-picture-2000.png"), {"labels": media_labels, "sources": media_sources}
+ assert "候选 2000px" in media_labels[0] and "picture 响应图" in media_labels[0], media_labels
+ assert media_sources[1].endswith("/secondary-1280.png"), {"labels": media_labels, "sources": media_sources}
+ assert "候选 1280px" in media_labels[1], media_labels
+ assert "延迟加载原图" in media_labels[2], media_labels
+ expect(collector.locator(".page-capture-article-media").nth(2).locator(".page-capture-media-preview")).to_contain_text("预览不可用")
+ assert any(source.endswith("/animation.gif") for source in media_sources), media_sources
+ assert "视频引用" in " ".join(media_labels), media_labels
+ assert not any(source.endswith("/video-poster.png") for source in media_sources[:-1]), media_sources
+ expect(collector.locator(".page-capture-item.confirmed")).to_have_count(0)
assert collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries.length)") == 0
expect(collector.locator("#page-capture-save")).to_be_disabled()
- collector.locator(".page-capture-text input").check()
+ collector.locator(".page-capture-article-media").first.click()
+ expect(collector.locator("#page-capture-media-viewer")).to_be_visible()
+ expect(collector.locator("#page-capture-media-stage img")).to_be_visible()
+ expect(collector.locator("#page-capture-media-position")).to_have_text("媒体 2 / 6")
+ collector.locator("#page-capture-media-next").click()
+ expect(collector.locator("#page-capture-media-position")).to_have_text("媒体 3 / 6")
+ collector.locator("#page-capture-media-close").click()
+
+ collector.locator(".page-capture-inspect").first.click()
+ expect(fixture.locator("#promptdirector-page-capture-region-preview")).to_be_visible(timeout=8000)
+ collector.locator(".page-capture-confirm").first.click()
+ expect(collector.locator(".page-capture-item.confirmed")).to_have_count(1)
+ expect(collector.locator("#page-capture-media-review")).to_be_visible()
+ expect(collector.locator("#page-capture-media-review-list .page-capture-media-review-item")).to_have_count(6)
+ expect(collector.locator(".page-capture-media-review-group")).to_contain_text("可能遗漏媒体(1)")
+ expect(collector.locator("#page-capture-save")).to_have_text("保存案例 · 含 5 项媒体")
expect(collector.locator("#page-capture-save")).to_be_enabled()
- collector.locator(".page-capture-media input").first.check()
- collector.locator("#page-capture-clear").click()
- expect(collector.locator(".page-capture-component input:checked")).to_have_count(0)
- collector.locator("#page-capture-select-text").click()
- expect(collector.locator(".page-capture-text input")).to_be_checked()
- expect(collector.locator(".page-capture-media input:checked")).to_have_count(0)
+ collector.locator("#page-capture-add-region").click()
+ fixture.bring_to_front()
+ expect(fixture.locator("#promptdirector-page-capture-region-editor")).to_be_visible(timeout=8000)
+ fixture.locator("#appendix").evaluate("element => element.click()")
+ fixture.get_by_role("button", name="完成").click()
+ confirmed_article = collector.locator(".page-capture-item.confirmed .page-capture-article")
+ expect(confirmed_article).to_contain_text("downloadable production notes", timeout=8000)
+ collector.locator("#page-capture-exclude-region").click()
+ fixture.bring_to_front()
+ fixture.locator("article p").nth(1).click()
+ fixture.get_by_role("button", name="完成").click()
+ expect(confirmed_article).not_to_contain_text("A second paragraph", timeout=8000)
+ collector.locator("#page-capture-undo-region").click()
+ expect(confirmed_article).to_contain_text("A second paragraph")
+ collector.locator("#page-capture-exclude-region").click()
+ fixture.bring_to_front()
+ fixture.locator("article p").nth(1).click()
+ fixture.get_by_role("button", name="完成").click()
+ expect(confirmed_article).not_to_contain_text("A second paragraph", timeout=8000)
+ expect(collector.locator("#page-capture-media-review-list .page-capture-media-review-item")).to_have_count(7)
+ expect(collector.locator("#page-capture-save")).to_have_text("保存案例 · 含 6 项媒体")
+ expect(collector.locator("#page-capture-save")).to_be_enabled()
+ collector.locator("#page-capture-save").click()
+ expect(collector.locator("#page-capture")).to_be_hidden(timeout=8000)
+ expect(fixture.locator("#promptdirector-page-capture-region-preview")).to_have_count(0)
+ expect(fixture.locator("[data-promptdirector-capture-region]")).to_have_count(0)
+ media_saved = collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries)")
+ assert len(media_saved) == 1 and len(media_saved[0].get("mediaAssets", [])) == 6, media_saved
+ assert "real injected page capture path" in media_saved[0]["text"], media_saved[0]
+ assert "A second paragraph" not in media_saved[0]["text"], media_saved[0]
+ assert "downloadable production notes" in media_saved[0]["text"], media_saved[0]
+ block_kinds = [block["kind"] for block in media_saved[0]["articleDocument"]["blocks"]]
+ assert block_kinds.count("image") == 4, media_saved[0]
+ assert block_kinds.count("video") == 1, media_saved[0]
+ assert block_kinds.count("document") == 1, media_saved[0]
+ assert block_kinds.count("link") == 1, media_saved[0]
+ assert any(asset["sourceUrl"].endswith("/placeholder.png") for asset in media_saved[0]["mediaAssets"]), media_saved[0]
+ assert any(asset.get("mimeType") == "image/gif" and asset["sourceUrl"].endswith("/animation.gif") for asset in media_saved[0]["mediaAssets"]), media_saved[0]
+ assert any(asset.get("kind") == "video" and asset["sourceUrl"].endswith("/film.mp4") for asset in media_saved[0]["mediaAssets"]), media_saved[0]
+ assert any(asset.get("kind") == "document" and asset.get("mimeType") == "application/pdf" for asset in media_saved[0]["mediaAssets"]), media_saved[0]
+ assert not any(asset.get("sourceUrl", "").endswith("/unsafe-package.zip") for asset in media_saved[0]["mediaAssets"]), media_saved[0]
+ assert media_saved[0]["sourceFacts"]["captureScope"] == "document", media_saved[0]
+ assert media_saved[0]["sourceFacts"]["extractionMethod"] == "page", media_saved[0]
+ library = run.open_page("library.html", wait_until="networkidle")
+ expect(library.locator(".case-card")).to_have_count(1, timeout=8000)
+ library.locator(".case-card").click()
+ expect(library.locator(".article-document-reader")).to_be_visible(timeout=8000)
+ expect(library.locator(".article-document-reader")).to_contain_text("downloadable production notes")
+ expect(library.locator(".article-document-reader")).not_to_contain_text("A second paragraph")
+ expect(library.locator(".article-document-reader .article-document-image")).to_have_count(4)
+ expect(library.locator(".unplaced-media-section")).to_have_count(0)
+ expect(library.get_by_text("单独查看文章媒体")).to_have_count(0)
+ expect(library.locator(".article-document-reader")).to_contain_text("本地副本已保存在案例媒体中")
+ expect(library.locator(".article-document-reader")).to_contain_text("Packaged Skill archive")
+ library.close()
+ collector.evaluate("() => chrome.storage.local.set({entries: []})")
+ fixture.evaluate("""() => {
+ const paragraph = document.querySelector('article p');
+ const range = document.createRange();
+ range.selectNodeContents(paragraph);
+ const selection = window.getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ }""")
+ fixture.bring_to_front()
+ collector.evaluate("() => document.querySelector('#start-page-capture').click()")
+ expect(collector.locator("#page-capture")).to_be_visible(timeout=8000)
+ expect(collector.locator(".page-capture-item > header small")).to_contain_text("原网页选区")
+ expect(collector.locator(".page-capture-article p")).to_have_count(1)
+ collector.locator(".page-capture-confirm").click()
+ expect(collector.locator("#page-capture-save")).to_have_text("只保存正文")
collector.locator("#page-capture-save").click()
expect(collector.locator("#page-capture")).to_be_hidden(timeout=8000)
- saved = collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries)")
- assert len(saved) == 1, saved
- assert "real injected page capture path" in saved[0]["text"], saved[0]
- assert not saved[0].get("mediaAssets"), saved[0]
- print({"previewCandidates": 1, "selectableImages": 2, "savedAfterConfirmation": 1})
+ selected_saved = collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries)")
+ assert len(selected_saved) == 1, selected_saved
+ assert "real injected page capture path" in selected_saved[0]["text"], selected_saved[0]
+ assert "A second paragraph" not in selected_saved[0]["text"], selected_saved[0]
+ assert len(selected_saved[0].get("mediaAssets", [])) == 0, selected_saved[0]
+ assert selected_saved[0]["sourceFacts"]["captureScope"] == "selection", selected_saved[0]
+
+ collector.evaluate("() => chrome.storage.local.set({entries: []})")
+ list_url = "https://api.deepseek.com/promptdirector-list?page=1"
+ fixture.goto(list_url, wait_until="networkidle")
+ fixture.bring_to_front()
+ collector.evaluate("() => document.querySelector('#start-page-capture').click()")
+ expect(collector.locator("#page-capture")).to_be_visible(timeout=8000)
+ expect(collector.locator(".page-capture-item")).to_have_count(2)
+ collector.locator(".page-capture-confirm").first.click()
+ collector.locator("#page-capture-scan").click()
+ collector.locator("#page-capture-target-count").fill("3")
+ collector.locator("#page-capture-list-run").click()
+ expect(collector.locator("#page-capture-list-result")).to_be_visible(timeout=15000)
+ expect(collector.locator(".page-capture-item")).to_have_count(3)
+ expect(collector.locator(".page-capture-item.confirmed")).to_have_count(3)
+ expect(collector.locator("#page-capture-save")).to_be_disabled()
+ collector.locator("#page-capture-save-mode").select_option("multiple")
+ expect(collector.locator("#page-capture-save")).to_be_enabled()
+ collector.locator("#page-capture-save").click()
+ expect(collector.locator("#page-capture")).to_be_hidden(timeout=10000)
+ multiple_saved = collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries)")
+ assert len(multiple_saved) == 3, multiple_saved
+ assert fixture.url == list_url, fixture.url
+
+ collector.evaluate("() => chrome.storage.local.set({entries: []})")
+ fixture.bring_to_front()
+ collector.evaluate("() => document.querySelector('#start-page-capture').click()")
+ expect(collector.locator(".page-capture-item")).to_have_count(2)
+ collector.locator(".page-capture-confirm").first.click()
+ collector.locator("#page-capture-scan").click()
+ collector.locator("#page-capture-target-count").fill("3")
+ collector.locator("#page-capture-list-run").click()
+ expect(collector.locator("#page-capture-list-result")).to_be_visible(timeout=15000)
+ collector.locator("#page-capture-save-mode").select_option("combined")
+ collector.locator("#page-capture-combined-title").fill("Combined list inspiration")
+ collector.locator("#page-capture-combined-title").press("Tab")
+ collector.locator("#page-capture-save").click()
+ expect(collector.locator("#page-capture")).to_be_hidden(timeout=10000)
+ combined_saved = collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries)")
+ assert len(combined_saved) == 1, combined_saved
+ assert combined_saved[0]["title"] == "Combined list inspiration", combined_saved[0]
+ assert len(combined_saved[0].get("mediaAssets", [])) == 3, combined_saved[0]
+ assert {asset.get("originalWorkUrl") for asset in combined_saved[0]["mediaAssets"]} == {
+ "https://api.deepseek.com/work/1", "https://api.deepseek.com/work/2", "https://api.deepseek.com/work/3"
+ }, combined_saved[0]
+ print({"previewCandidates": 2, "mediaViewerItems": 5, "confirmedSubjects": 1, "savedWholeCaseMedia": 6, "savedLiveSelectionMedia": 0, "paginatedCases": 3, "combinedCases": 1, "clearedPageMarkers": 1})
if __name__ == "__main__":
diff --git a/test/privacy-policy.test.js b/test/privacy-policy.test.js
index 49772fe..bc6ce61 100644
--- a/test/privacy-policy.test.js
+++ b/test/privacy-policy.test.js
@@ -27,6 +27,13 @@ test("privacy policy makes the two independent execution confirmations explicit"
assert.match(policy, /两者不能互相替代/);
});
+test("privacy policy discloses that composer text-only mode reads and sends zero images", async () => {
+ const policy = await privacyPolicy();
+ assert.match(policy, /全程只用案例\/分析文字/);
+ assert.match(policy, /不会读取、分析或发送图片/);
+ assert.match(policy, /图片载荷为零/);
+});
+
test("privacy policy accurately declares local-first handling and manifest permissions", async () => {
const [policy, manifestSource] = await Promise.all([
privacyPolicy(),
@@ -42,3 +49,18 @@ test("privacy policy accurately declares local-first handling and manifest permi
assert.match(policy, /`https:\/\/api\.deepseek\.com\/\*`/);
assert.match(policy, /`<all_urls>`/);
});
+
+test("privacy policy explains corrected article regions and safe download handling", async () => {
+ const policy = await privacyPolicy();
+ assert.match(policy, /添加遗漏内容、排除错误内容、整组修正、撤销或恢复自动识别/);
+ assert.match(policy, /正文在主体确认后默认纳入/);
+ assert.match(policy, /正文内已定位媒体默认进入保存方案/);
+ assert.match(policy, /无法确认文章位置的媒体默认不选/);
+ assert.match(policy, /“保存案例”按钮是当前媒体方案的最终授权/);
+ assert.match(policy, /“只保存正文”/);
+ assert.match(policy, /PDF、Markdown、SKILL\.md、TXT、HTML 和 RTF/);
+ assert.match(policy, /只有属于用户最终保存方案时/);
+ assert.match(policy, /真实文件类型和容量限制/);
+ assert.match(policy, /压缩包、程序和未知类型文件不会自动下载/);
+ assert.match(policy, /失败时只保留原始来源链接/);
+});
diff --git a/test/run_e2e.py b/test/run_e2e.py
index de919d4..bd799ba 100644
--- a/test/run_e2e.py
+++ b/test/run_e2e.py
@@ -35,8 +35,10 @@ SCRIPTS = [
"region_and_smart_picker_e2e.py",
"smart_visual_picker_e2e.py",
"page_capture_e2e.py",
+ "jimeng_capture_e2e.py",
"ai_provider_registry_e2e.py",
"creative_skills_e2e.py",
+ "skill_source_density_e2e.py",
"manager_regression_e2e.py",
"library_gallery_recovery_e2e.py",
"library_132_e2e.py",
diff --git a/test/sharing_and_data_safety_e2e.py b/test/sharing_and_data_safety_e2e.py
index 4fe11cf..be10934 100644
--- a/test/sharing_and_data_safety_e2e.py
+++ b/test/sharing_and_data_safety_e2e.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import io
import json
import tempfile
import zipfile
@@ -29,6 +30,8 @@ def main() -> None:
{"id": "share-image-two", "kind": "image", "storageMode": "managed", "mimeType": "image/png", "width": 1, "height": 1, "palette": {"colors": ["#123456", "#345678"]}}
]
entries[1]["primaryMediaId"] = "share-image-two"
+ entries[1]["note"] = "不应公开的私人笔记"
+ entries[1]["metadataLabels"] = ["作者:测试作者", "权利:本人原创", "秘密:sk-private"]
with extension_session("prompt-director-share-") as session:
setup = session.open_page("collector.html")
current_schema = setup.evaluate("async () => (await import(chrome.runtime.getURL('taxonomy.js'))).SCHEMA_VERSION")
@@ -58,8 +61,11 @@ def main() -> None:
library.locator(".case-card").nth(1).click()
expect(library.locator("#share-count")).to_have_text("已选择 2 个案例")
library.locator("#share-export").click()
+ expect(library.locator("#share-dialog")).to_be_visible()
+ expect(library.locator("#share-dialog-submit")).to_be_disabled()
+ library.locator("#share-dialog-export").click()
expect(library.locator("#feedback")).to_contain_text("分享包已导出")
- archive_path, _ = wait_for_download(library)
+ archive_path, download_id = wait_for_download(library)
with zipfile.ZipFile(archive_path) as archive:
shared = json.loads(archive.read("library.json"))
assert len(shared["entries"]) == 2
@@ -113,12 +119,48 @@ def main() -> None:
offline.screenshot(path=str(screenshots / "share-preview-detail-mobile.png"), full_page=True)
offline.close()
+ library.locator("#select-cases").click()
+ library.locator('.case-card[data-entry-id="share-two"]').click()
+ library.locator("#share-export").click()
+ expect(library.locator("#share-dialog")).to_be_visible()
+ expect(library.locator("#share-dialog-disclosure")).not_to_be_checked()
+ library.locator("#share-dialog-disclosure").check()
+ expect(library.locator("#share-dialog-submit")).to_be_enabled()
+ library.locator("#share-dialog-submit").click()
+ expect(library.locator("#share-dialog-result")).to_be_visible(timeout=15_000)
+ expect(library.locator("#share-dialog-result")).to_contain_text("投稿包已生成")
+ expect(library.locator("#share-dialog-show-files")).to_be_visible()
+ expect(library.locator("#share-dialog-open-form")).to_be_visible()
+ submission_path, _ = wait_for_download(library, after_id=download_id)
+ with zipfile.ZipFile(submission_path) as transport:
+ assert sorted(transport.namelist()) == ["payload.zip", "submission.json"]
+ manifest = json.loads(transport.read("submission.json"))
+ payload_bytes = transport.read("payload.zip")
+ assert manifest["format"] == "prompt-director-curated-submission"
+ assert manifest["version"] == 1
+ assert manifest["caseCount"] == 1
+ assert manifest["mediaCount"] == 1
+ assert manifest["payloadBytes"] == len(payload_bytes)
+ import hashlib
+ assert manifest["submissionId"] == hashlib.sha256(payload_bytes).hexdigest()
+ with zipfile.ZipFile(io.BytesIO(payload_bytes)) as payload:
+ submission_library = json.loads(payload.read("library.json"))
+ assert len(submission_library["entries"]) == 1
+ assert submission_library["entries"][0]["title"] == "分享案例二"
+ serialized = json.dumps(submission_library, ensure_ascii=False)
+ assert "不应公开的私人笔记" not in serialized
+ assert "sk-private" not in serialized
+ assert "作者:测试作者" in serialized
+ assert "权利:本人原创" in serialized
+ assert payload.testzip() is None
+ library.locator("#share-dialog-close").click()
+
library.locator("#open-settings").click()
library.locator('[data-settings-tab="general"]').click()
expect(library.locator("#create-folder-backup")).to_be_visible()
expect(library.locator("#restore-folder-backup")).to_be_visible()
assert library.locator("#create-portable-backup").count() == 0
- print({"shared_entries": 2, "private_drafts_removed": True, "data_safety": True, "offline_preview": True, "mobile_width": 390, "screenshots": str(screenshots)})
+ print({"shared_entries": 2, "curated_submission": True, "private_drafts_removed": True, "data_safety": True, "offline_preview": True, "mobile_width": 390, "screenshots": str(screenshots)})
if __name__ == "__main__":
diff --git a/test/skill-contact-sheet.test.js b/test/skill-contact-sheet.test.js
index 970a1dd..09fbc15 100644
--- a/test/skill-contact-sheet.test.js
+++ b/test/skill-contact-sheet.test.js
@@ -21,6 +21,30 @@ test("one image stays direct while larger selections use at most nine images per
assert.equal(plan.every((item) => item.kind === "contact-sheet"), true);
});
+test("compound Skill sources include only explicitly selected assets", () => {
+ const entries = [{
+ id: "compound",
+ text: "共享案例文字",
+ mediaAssets: [
+ { id: "chosen", kind: "image", usage: "content", visionAnalysis: { description: "保留的构图" } },
+ { id: "hidden", kind: "image", usage: "content", visionAnalysis: { description: "不应发送的构图" } },
+ { id: "doc", kind: "document", usage: "content" }
+ ],
+ mediaPrompts: [
+ { assetId: "chosen", text: "选中图片提示词" },
+ { assetId: "hidden", text: "未选图片提示词" }
+ ]
+ }];
+ const selections = [{ entryId: "compound", includeEntryText: false, assetIds: ["chosen", "doc"] }];
+ const images = selectedSkillContentImages(entries, selections);
+ assert.deepEqual(images.map((item) => item.visualId), ["chosen"]);
+ const sources = anonymousSkillSources(entries, selections, { documentTextByAsset: new Map([["doc", "所选文档正文"]]) });
+ assert.equal(sources.length, 1);
+ assert.match(sources[0].prompt, /选中图片提示词[\s\S]*所选文档正文/);
+ assert.match(sources[0].analysis, /保留的构图/);
+ assert.doesNotMatch(JSON.stringify(sources), /共享案例文字|未选图片提示词|不应发送的构图|compound|chosen|doc/);
+});
+
test("extraction payload contains anonymous selected text and no local identity fields", () => {
const entries = [{ id: "local:secret", title: "Secret Project", url: "https://private.example", text: "original prompt", mediaAssets: [{ usage: "content", visionAnalysis: { description: "visible composition" } }] }];
const request = buildSkillExtractionRequest({ goal: "提炼构图", sources: anonymousSkillSources(entries, ["local:secret"]), locale: "zh-CN" });
diff --git a/test/skill-source-picker.test.js b/test/skill-source-picker.test.js
new file mode 100644
index 0000000..3b8311a
--- /dev/null
+++ b/test/skill-source-picker.test.js
@@ -0,0 +1,82 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ SKILL_SOURCE_BATCH_SIZE,
+ availableSkillSourceAssets,
+ cloneSkillSourceSelection,
+ filterSkillSourceEntries,
+ pageSkillSourceEntries,
+ skillSourceSelectionSummary
+} from "../skill-source-picker.js";
+
+function entry(id, kinds = ["image"], text = "") {
+ const mediaAssets = kinds.map((kind, index) => ({
+ id: `${id}:${kind}:${index}`,
+ kind,
+ usage: "content",
+ mimeType: kind === "image" ? "image/png" : kind === "video" ? "video/mp4" : "application/pdf"
+ }));
+ return { id, title: `案例 ${id}`, text, primaryMediaId: mediaAssets[0]?.id ?? "", mediaAssets };
+}
+
+test("Skill source picker renders large libraries in the shared 24-case batches", () => {
+ const entries = Array.from({ length: 60 }, (_, index) => entry(String(index + 1)));
+ const filtered = filterSkillSourceEntries(entries, { query: "案例" });
+
+ assert.equal(SKILL_SOURCE_BATCH_SIZE, 24);
+ assert.equal(pageSkillSourceEntries(filtered, SKILL_SOURCE_BATCH_SIZE).length, 24);
+ assert.equal(pageSkillSourceEntries(filtered, SKILL_SOURCE_BATCH_SIZE * 2).length, 48);
+ assert.equal(pageSkillSourceEntries(filtered, 100).length, 60);
+});
+
+test("Skill source picker filters by project and text without changing the source entries", () => {
+ const entries = [entry("one"), entry("two"), entry("three")];
+ entries[1].title = "目标案例";
+ const result = filterSkillSourceEntries(entries, {
+ projectEntryIds: new Set(["one", "two"]),
+ query: "目标"
+ });
+
+ assert.deepEqual(result.map((item) => item.id), ["two"]);
+ assert.equal(entries.length, 3);
+});
+
+test("Skill source summary separates images videos documents and case text", () => {
+ const entries = [
+ entry("compound", ["image", "image", "video", "document"], "案例正文"),
+ entry("text", [], "只有文字")
+ ];
+ const selections = new Map([
+ ["compound", { entryId: "compound", includeEntryText: true, assetIds: new Set([
+ "compound:image:0", "compound:video:2", "compound:document:3"
+ ]) }],
+ ["text", { entryId: "text", includeEntryText: true, assetIds: new Set() }]
+ ]);
+
+ assert.deepEqual(skillSourceSelectionSummary(entries, selections), {
+ cases: 2,
+ images: 1,
+ videos: 1,
+ documents: 1,
+ texts: 2
+ });
+});
+
+test("Skill source inspector edits an isolated draft until the user applies it", () => {
+ const source = { entryId: "compound", includeEntryText: true, assetIds: new Set(["compound:image:0"]) };
+ const draft = cloneSkillSourceSelection(source);
+ draft.assetIds.add("compound:video:2");
+ draft.includeEntryText = false;
+
+ assert.deepEqual([...source.assetIds], ["compound:image:0"]);
+ assert.equal(source.includeEntryText, true);
+ assert.deepEqual([...draft.assetIds], ["compound:image:0", "compound:video:2"]);
+ assert.equal(draft.includeEntryText, false);
+});
+
+test("poster assets never enter precise Skill source selection", () => {
+ const item = entry("video", ["video"]);
+ item.mediaAssets.push({ id: "poster", kind: "image", usage: "poster", mimeType: "image/jpeg" });
+ assert.deepEqual(availableSkillSourceAssets(item).map((asset) => asset.id), ["video:video:0"]);
+});
diff --git a/test/skill_source_density_e2e.py b/test/skill_source_density_e2e.py
new file mode 100644
index 0000000..68d4196
--- /dev/null
+++ b/test/skill_source_density_e2e.py
@@ -0,0 +1,205 @@
+from __future__ import annotations
+
+from playwright.sync_api import expect
+
+from e2e_support import base_entry, extension_session
+
+
+def dense_entries() -> list[dict]:
+ entries: list[dict] = []
+ for index in range(1, 61):
+ title = f"真实密度案例 {index:02d} · 带有较长名称用于检查标题和内容按钮是否发生遮挡"
+ item = base_entry(f"dense-skill-{index:02d}", title, f"案例文字 {index}:主体、空间、色彩与动作节奏。", "content:prompt:image", index % 60)
+ assets: list[dict] = []
+ if index % 12 == 0:
+ title = f"复合案例 {index:02d} · 图片、视频、文档和文字组合"
+ item["title"] = title
+ assets = [
+ media_asset(item["id"], "image", 0, "image/png"),
+ media_asset(item["id"], "video", 1, "video/mp4"),
+ media_asset(item["id"], "document", 2, "application/pdf"),
+ ]
+ elif index % 10 == 0:
+ assets = [media_asset(item["id"], "document", 0, "application/pdf")]
+ elif index % 9 == 0:
+ assets = [media_asset(item["id"], "video", 0, "video/mp4")]
+ elif index % 15 != 0:
+ assets = [media_asset(item["id"], "image", 0, "image/png")]
+ item["mediaAssets"] = assets
+ item["primaryMediaId"] = assets[0]["id"] if assets else ""
+ entries.append(item)
+ return entries
+
+
+def media_asset(entry_id: str, kind: str, index: int, mime_type: str) -> dict:
+ return {
+ "id": f"{entry_id}:{kind}:{index}",
+ "kind": kind,
+ "usage": "content",
+ "storageMode": "managed",
+ "mimeType": mime_type,
+ "capturedAt": "2026-08-12T08:00:00.000Z",
+ "reviewStatus": "verified",
+ }
+
+
+def main() -> None:
+ entries = dense_entries()
+ with extension_session("prompt-director-skill-density-", viewport={"width": 1840, "height": 733}) as session:
+ setup = session.open_page("collector.html")
+ session.seed_storage(setup, {
+ "schemaVersion": 24,
+ "entries": entries,
+ "organizerState": {
+ "version": 6,
+ "collections": [{
+ "id": "collection:dense-skill",
+ "name": "真实案例测试项目",
+ "order": 0,
+ "entryIds": [item["id"] for item in entries[12:48]],
+ }],
+ },
+ "uiPreferences": {"locale": "zh-CN", "theme": "dark", "motion": "none"},
+ })
+ setup.evaluate(
+ """async (entries) => {
+ const {saveMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
+ for (const [index, entry] of entries.entries()) {
+ const image = entry.mediaAssets.find((asset) => asset.kind === 'image');
+ if (!image) continue;
+ const canvas = document.createElement('canvas');
+ canvas.width = 480;
+ canvas.height = 360;
+ const context = canvas.getContext('2d');
+ context.fillStyle = `hsl(${(index * 37) % 360} 32% 24%)`;
+ context.fillRect(0, 0, canvas.width, canvas.height);
+ context.fillStyle = 'rgba(255,255,255,.92)';
+ context.font = '700 26px sans-serif';
+ context.fillText(`CASE ${String(index + 1).padStart(2, '0')}`, 28, 58);
+ context.font = '18px sans-serif';
+ context.fillText('IMAGE TEXT MUST STAY VISIBLE', 28, 318);
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'));
+ await saveMediaBlob(image.id, blob, {checkCapacity: false});
+ }
+ }""",
+ entries,
+ )
+
+ skills = session.open_page("skills.html")
+ skills.locator("#skill-create").click()
+ wait_for_theme(skills, "dark")
+ skills.wait_for_function("""() => [...document.querySelectorAll('.skill-case-visual img')].some((image) => image.complete && image.naturalWidth > 0)""")
+ expect(skills.locator(".skill-case")).to_have_count(24)
+ expect(skills.locator("#skill-case-load-more")).to_be_visible()
+ expect(skills.locator("#skill-case-grid")).not_to_contain_text("0/1")
+ expect(skills.locator("#skill-project-picker")).not_to_have_attribute("open", "")
+
+ desktop = layout_metrics(skills)
+ assert desktop["columns"] == 4, desktop
+ assert desktop["minCardWidth"] >= 240, desktop
+ assert desktop["pageWidth"] <= desktop["viewportWidth"], desktop
+ assert desktop["gridScrollWidth"] <= desktop["gridClientWidth"] + 1, desktop
+ assert desktop["titleClearance"] >= 4, desktop
+ skills.screenshot(path="/tmp/promptdirector-skills-density-1840-dark.png")
+
+ skills.locator(".skill-case-toggle").first.click()
+ expect(skills.locator(".skill-case-state:not([hidden])")).to_have_count(1)
+ expect(skills.locator("#skill-selection-summary")).to_contain_text("图片 1")
+ first_content = skills.locator(".skill-case-detail").first
+ first_content.click()
+ skills.locator("#skill-source-clear").click()
+ skills.locator("#skill-source-cancel").click()
+ expect(skills.locator("#skill-selected-count")).to_have_text("1")
+
+ compound = skills.locator(".skill-case", has_text="复合案例 12")
+ compound.locator(".skill-case-detail").click()
+ skills.locator("#skill-source-select-all").click()
+ skills.locator("#skill-source-apply").click()
+ expect(skills.locator("#skill-selection-summary")).to_contain_text("图片 2")
+ expect(skills.locator("#skill-selection-summary")).to_contain_text("视频 1")
+ expect(skills.locator("#skill-selection-summary")).to_contain_text("文档 1")
+ expect(skills.locator("#skill-selection-summary")).to_contain_text("案例文字 2")
+
+ skills.locator("#skill-case-load-more").click()
+ expect(skills.locator(".skill-case")).to_have_count(48)
+ skills.locator("#skill-case-search").fill("真实密度案例 58")
+ expect(skills.locator(".skill-case")).to_have_count(1)
+ expect(skills.locator("#skill-selected-count")).to_have_text("2")
+ skills.locator("#skill-case-search").fill("")
+ expect(skills.locator(".skill-case")).to_have_count(24)
+ expect(skills.locator("#skill-selected-count")).to_have_text("2")
+
+ skills.set_viewport_size({"width": 1440, "height": 900})
+ skills.evaluate("async () => chrome.storage.local.set({uiPreferences: {locale: 'zh-CN', theme: 'light', motion: 'none'}})")
+ skills.reload(wait_until="domcontentloaded")
+ expect(skills.locator("#skill-source-step")).to_be_visible()
+ wait_for_theme(skills, "light")
+ skills.wait_for_function("""() => [...document.querySelectorAll('.skill-case-visual img')].some((image) => image.complete && image.naturalWidth > 0)""")
+ light = layout_metrics(skills)
+ assert light["columns"] == 4, light
+ assert light["minCardWidth"] >= 240, light
+ assert light["pageWidth"] <= light["viewportWidth"], light
+ assert light["headingColor"] == light["bodyColor"], light
+ assert light["brandColor"] == light["bodyColor"], light
+ skills.screenshot(path="/tmp/promptdirector-skills-density-1440-light.png")
+
+ skills.set_viewport_size({"width": 1200, "height": 900})
+ narrow = layout_metrics(skills)
+ assert narrow["columns"] == 3, narrow
+ assert narrow["minCardWidth"] >= 240, narrow
+ assert narrow["pageWidth"] <= narrow["viewportWidth"], narrow
+
+ skills.set_viewport_size({"width": 390, "height": 844})
+ skills.evaluate("async () => chrome.storage.local.set({uiPreferences: {locale: 'en', theme: 'dark', motion: 'none'}})")
+ skills.reload(wait_until="domcontentloaded")
+ expect(skills.locator("#skill-source-step")).to_be_visible()
+ wait_for_theme(skills, "dark")
+ skills.wait_for_function("""() => [...document.querySelectorAll('.skill-case-visual img')].some((image) => image.complete && image.naturalWidth > 0)""")
+ mobile = layout_metrics(skills)
+ assert mobile["columns"] == 2, mobile
+ assert mobile["pageWidth"] <= mobile["viewportWidth"], mobile
+ assert mobile["sectionHeadingColor"] == mobile["headingColor"], mobile
+ skills.screenshot(path="/tmp/promptdirector-skills-density-390-dark-en.png", full_page=False)
+
+ print({"dense_cases": 60, "desktop_columns": 4, "mobile_columns": 2, "staged_inspector": True})
+
+
+def layout_metrics(page) -> dict:
+ return page.evaluate(
+ """() => {
+ const grid = document.querySelector('#skill-case-grid');
+ const cards = [...document.querySelectorAll('.skill-case')];
+ const first = cards[0];
+ const title = first.querySelector('.skill-case-copy strong').getBoundingClientRect();
+ const detail = first.querySelector('.skill-case-detail')?.getBoundingClientRect();
+ return {
+ columns: getComputedStyle(grid).gridTemplateColumns.split(' ').length,
+ minCardWidth: Math.min(...cards.map((card) => card.getBoundingClientRect().width)),
+ viewportWidth: innerWidth,
+ pageWidth: document.documentElement.scrollWidth,
+ gridClientWidth: grid.clientWidth,
+ gridScrollWidth: grid.scrollWidth,
+ titleClearance: detail ? detail.left - title.right : 99,
+ bodyColor: getComputedStyle(document.body).color,
+ headingColor: getComputedStyle(document.querySelector('.skill-workspace-header h1')).color,
+ brandColor: getComputedStyle(document.querySelector('.skills-brand strong')).color,
+ sectionHeadingColor: getComputedStyle(document.querySelector('.skill-section-heading strong')).color
+ };
+ }"""
+ )
+
+
+def wait_for_theme(page, theme: str) -> None:
+ page.wait_for_function(
+ """(theme) => {
+ if (document.documentElement.dataset.theme !== theme) return false;
+ const channels = getComputedStyle(document.body).backgroundColor.match(/[0-9]+/g)?.map(Number) || [];
+ if (channels.length < 3) return false;
+ return theme === 'dark' ? Math.max(...channels.slice(0, 3)) < 60 : Math.min(...channels.slice(0, 3)) > 200;
+ }""",
+ arg=theme,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/ui-foundation.test.js b/test/ui-foundation.test.js
index 14b4ce9..ff4d6c6 100644
--- a/test/ui-foundation.test.js
+++ b/test/ui-foundation.test.js
@@ -17,6 +17,7 @@ test("shared visual foundation owns the locked dark theme and control scale", ()
assert.match(foundation, /--ui-compact-height:\s*30px/);
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/);
});
test("page styles keep domain layout without redefining shared theme roles", async () => {
diff --git a/test/video-analysis.test.js b/test/video-analysis.test.js
index 4b270c1..d6b20cc 100644
--- a/test/video-analysis.test.js
+++ b/test/video-analysis.test.js
@@ -1,6 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
+ analyzeVideoWithChatCompletions,
analyzeVideoWithGemini,
analyzeVideoWithOpenRouter,
publicYouTubeUrl,
@@ -76,3 +77,54 @@ test("OpenRouter sends local video as video_url without changing the selected mo
assert.equal(result.cost, 0.012);
assert.deepEqual(result.routing, { provider: "declared-provider" });
});
+
+test("Kimi uses its configured Chat Completions endpoint and exposes provider-specific results", async () => {
+ const calls = [];
+ const result = await analyzeVideoWithChatCompletions({
+ apiKey: "kimi-key",
+ endpoint: "https://api.moonshot.cn/v1/chat/completions",
+ providerLabel: "Kimi",
+ model: "moonshot-account-video",
+ mode: "ad-review",
+ videoBlob: new Blob([new Uint8Array([4, 5, 6])], { type: "video/mp4" })
+ }, {
+ fetchImpl: async (url, options) => {
+ calls.push({ url, headers: options.headers, body: JSON.parse(options.body) });
+ return new Response(JSON.stringify({
+ model: "moonshot-account-video-202608",
+ choices: [{ message: { content: [{ type: "text", text: "00:03 钩子" }] } }],
+ usage: { prompt_tokens: 9, completion_tokens: 5, total_tokens: 14 }
+ }), { status: 200, headers: { "content-type": "application/json" } });
+ }
+ });
+
+ assert.equal(calls[0].url, "https://api.moonshot.cn/v1/chat/completions");
+ assert.equal(calls[0].body.model, "moonshot-account-video");
+ assert.equal(calls[0].body.messages[0].content[1].type, "video_url");
+ assert.match(calls[0].body.messages[0].content[1].video_url.url, /^data:video\/mp4;base64,/);
+ assert.equal(result.provider, "Kimi");
+ assert.equal(result.model, "moonshot-account-video-202608");
+ assert.equal(result.usage.totalTokens, 14);
+});
+
+test("generic Chat Completions video errors name the selected provider without exposing its key", async () => {
+ await assert.rejects(analyzeVideoWithChatCompletions({
+ apiKey: "never-print-this-key",
+ endpoint: "https://compatible.example/v1",
+ providerLabel: "兼容视频服务",
+ model: "account-video",
+ mode: "content-summary",
+ youtubeUrl: "https://video.example/watch/1"
+ }, {
+ fetchImpl: async () => new Response(JSON.stringify({
+ error: { message: "quota unavailable for never-print-this-key" }
+ }), {
+ status: 429,
+ headers: { "content-type": "application/json" }
+ })
+ }), (error) => {
+ assert.match(error.message, /兼容视频服务.*quota unavailable/);
+ assert.doesNotMatch(error.message, /never-print-this-key/);
+ return true;
+ });
+});
diff --git a/test/visual-interaction.test.js b/test/visual-interaction.test.js
index 7d9e213..574295d 100644
--- a/test/visual-interaction.test.js
+++ b/test/visual-interaction.test.js
@@ -39,7 +39,8 @@ test("composer and Skill selections avoid oversized green outer rings", async ()
assert.match(rule(composer, '.composer-case-option[data-selected="true"]'), /background:\s*var\(--selection\)/);
assert.match(rule(composer, ".composer-project-card .composer-project-active"), /box-shadow:\s*inset 2px 0 var\(--selection-indicator\)/);
assert.doesNotMatch(composer, /0 0 0 (?:2px|3px) color-mix\(in srgb, var\(--accent\)/);
- assert.match(rule(skills, '.skill-case[data-selected="true"]::after'), /border-color:\s*var\(--accent/);
+ assert.match(rule(skills, '.skill-case[data-selected="true"]'), /border-color:\s*var\(--selection-indicator\)/);
+ assert.match(rule(skills, '.skill-case[data-selected="true"] .skill-case-state'), /background:\s*var\(--accent\)/);
assert.doesNotMatch(skills, /box-shadow:\s*0 0 0 (?:2px|3px) color-mix\(in srgb, var\(--accent\)/);
});
@@ -54,6 +55,27 @@ test("collector highlights use the shared restrained interaction language", asyn
assert.doesNotMatch(source, /box-shadow:\s*0 0 0 3px var\(--accent-soft\)/);
});
+test("capture notifications use the shared neutral toast instead of legacy green text", async () => {
+ const [foundation, collector, collectorHtml, libraryHtml] = await Promise.all([
+ readFile(new URL("../ui-foundation.css", import.meta.url), "utf8"),
+ readFile(new URL("../collector.css", import.meta.url), "utf8"),
+ readFile(new URL("../collector.html", import.meta.url), "utf8"),
+ readFile(new URL("../library.html", import.meta.url), "utf8")
+ ]);
+ const toast = rule(foundation, ".ui-feedback-toast");
+
+ assert.match(collectorHtml, /id="feedback"[^>]*class="ui-feedback-toast"/);
+ assert.match(libraryHtml, /id="feedback"[^>]*class="ui-feedback-toast"/);
+ assert.match(toast, /position:\s*fixed/);
+ assert.match(toast, /color:\s*var\(--ui-text\)/);
+ assert.match(toast, /background:\s*var\(--ui-surface\)/);
+ assert.match(toast, /border:\s*1px solid var\(--ui-border-strong\)/);
+ assert.match(rule(foundation, ".ui-feedback-toast.error"), /color:\s*var\(--ui-danger\)/);
+ assert.doesNotMatch(rule(collector, "#feedback"), /color:\s*var\(--accent\)/);
+ assert.match(rule(collector, ".smart-selection"), /box-shadow:\s*inset 2px 0 var\(--selection-indicator\)/);
+ assert.match(rule(collector, ".smart-selection small"), /color:\s*var\(--muted\)/);
+});
+
test("smart visual picker uses a fine neutral edge with a small branded check", async () => {
const source = await readFile(new URL("../capture-region.css", import.meta.url), "utf8");
const candidate = rule(source, "#__prompt_case_visual_picker__ .prompt-case-visual-candidate");
diff --git a/test/x_post_capture_e2e.py b/test/x_post_capture_e2e.py
new file mode 100644
index 0000000..ddcbe84
--- /dev/null
+++ b/test/x_post_capture_e2e.py
@@ -0,0 +1,109 @@
+from __future__ import annotations
+
+from playwright.sync_api import expect
+
+from e2e_support import base_entry, extension_session
+
+
+PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+
+
+def main() -> None:
+ entry = base_entry(
+ "captured-x-post",
+ "Director Name · A practical lighting breakdown",
+ "A practical lighting breakdown for a midnight chase: keep the street cyan, reserve warm light for the character, and let the wet road carry the contrast.",
+ "content:prompt:image",
+ 1,
+ )
+ entry.update({
+ "url": "https://x.com/director/status/123",
+ "sourceFacts": {
+ "provider": "x",
+ "pageType": "post",
+ "itemId": "123",
+ "author": "Director Name",
+ "handle": "director",
+ "publishedAt": "2026-08-16T09:30:00.000Z",
+ "capturedAt": "2026-08-16T09:31:00.000Z",
+ "engagement": {"likes": 42, "reposts": 7},
+ "captureScope": "document",
+ "extractionMethod": "page",
+ "status": "complete",
+ },
+ "mediaAssets": [
+ {
+ "id": "post-image",
+ "kind": "image",
+ "usage": "content",
+ "storageMode": "managed",
+ "mimeType": "image/png",
+ "width": 1600,
+ "height": 1067,
+ "capturedAt": "2026-08-16T09:31:00.000Z",
+ "reviewStatus": "verified",
+ },
+ {
+ "id": "post-video",
+ "kind": "video",
+ "usage": "content",
+ "storageMode": "reference",
+ "sourceUrl": "https://x.com/director/status/123/video/1",
+ "sourceTitle": "Attached clip",
+ "originalWorkUrl": "https://x.com/director/status/123",
+ "reference": {
+ "url": "https://x.com/director/status/123/video/1",
+ "provider": "x",
+ "playbackMode": "embed",
+ },
+ "reviewStatus": "verified",
+ },
+ ],
+ "primaryMediaId": "post-image",
+ "articleDocument": {
+ "version": 1,
+ "blocks": [
+ {"id": "post-copy", "kind": "paragraph", "text": "A practical lighting breakdown for a midnight chase: keep the street cyan, reserve warm light for the character, and let the wet road carry the contrast.", "sourceOrder": 0},
+ {"id": "post-image-block", "kind": "image", "assetId": "post-image", "sourceUrl": "https://x.com/post-image.png", "sourceOrder": 1},
+ {"id": "post-video-block", "kind": "video", "assetId": "post-video", "sourceUrl": "https://x.com/director/status/123/video/1", "sourceOrder": 2},
+ ],
+ },
+ })
+
+ with extension_session("prompt-director-x-post-") as run:
+ setup = run.open_page("collector.html")
+ setup.evaluate(
+ """async ({entry, png}) => {
+ const {saveMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
+ const bytes = Uint8Array.from(atob(png), value => value.charCodeAt(0));
+ await saveMediaBlob('post-image', new Blob([bytes], {type: 'image/png'}), {checkCapacity: false});
+ await chrome.storage.local.clear();
+ await chrome.storage.local.set({schemaVersion: 24, entries: [entry]});
+ }""",
+ {"entry": entry, "png": PNG_BASE64},
+ )
+
+ library = run.open_page("library.html", wait_until="networkidle")
+ expect(library.locator(".case-card")).to_have_count(1)
+ library.locator(".case-card").click()
+ expect(library.locator(".captured-post-view")).to_be_visible(timeout=8000)
+ expect(library.locator(".captured-post-text")).to_contain_text("practical lighting breakdown")
+ expect(library.locator(".captured-post-heading")).to_contain_text("Director Name")
+ expect(library.locator(".captured-post-heading")).to_contain_text("@director")
+ expect(library.locator(".compact-captured-image img")).to_have_count(1)
+ expect(library.get_by_text("打开原帖观看视频")).to_have_count(1)
+ expect(library.locator(".article-document-reader")).to_have_count(0)
+ expect(library.locator(".detail-video, iframe")).to_have_count(0)
+ expect(library.get_by_text("单独查看文章媒体")).to_have_count(0)
+
+ print({
+ "page_type": "post",
+ "author": "Director Name",
+ "saved_media": 2,
+ "compact_post": True,
+ "black_video_embed": False,
+ })
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/zip.test.js b/test/zip.test.js
index af7bd83..ca3f598 100644
--- a/test/zip.test.js
+++ b/test/zip.test.js
@@ -2,7 +2,7 @@ import test from "node:test";
import assert from "node:assert/strict";
import { deflateRawSync } from "node:zlib";
-import { createZipBlob, readZipBlob } from "../zip.js";
+import { createZipBlob, openZipBlob, readZipBlob } from "../zip.js";
test("createZipBlob produces a UTF-8 ZIP containing markdown and image paths", async () => {
const archive = await createZipBlob([
@@ -51,6 +51,38 @@ test("readZipBlob restores MP4 assets with their video MIME type", async () => {
assert.equal(files.get("videos/case-1.mp4").type, "video/mp4");
});
+test("readZipBlob reports each verified file while large packages are being opened", async () => {
+ const archive = await createZipBlob([
+ { name: "library.json", data: "{}" },
+ { name: "videos/case-1.mp4", data: new Uint8Array(64) },
+ { name: "images/case-1.webp", data: new Uint8Array(32) }
+ ]);
+ const progress = [];
+
+ await readZipBlob(archive, {}, { onProgress: (value) => progress.push(value) });
+
+ assert.deepEqual(progress.map(({ completed, total, name }) => ({ completed, total, name })), [
+ { completed: 1, total: 3, name: "library.json" },
+ { completed: 2, total: 3, name: "videos/case-1.mp4" },
+ { completed: 3, total: 3, name: "images/case-1.webp" }
+ ]);
+});
+
+test("openZipBlob validates the whole directory but materializes only requested files", async () => {
+ const archive = await createZipBlob([
+ { name: "library.json", data: "{}" },
+ { name: "videos/selected.mp4", data: new Uint8Array([1, 2, 3]) },
+ { name: "videos/unselected.mp4", data: new Uint8Array([4, 5, 6]) }
+ ]);
+ const reader = await openZipBlob(archive);
+
+ const files = await reader.read(["library.json", "videos/selected.mp4"]);
+
+ assert.deepEqual(reader.names, ["library.json", "videos/selected.mp4", "videos/unselected.mp4"]);
+ assert.deepEqual([...files.keys()], ["library.json", "videos/selected.mp4"]);
+ await assert.rejects(() => reader.read(["videos/missing.mp4"]), /ZIP 内缺少文件/);
+});
+
test("readZipBlob rejects unsupported or damaged archives", async () => {
await assert.rejects(() => readZipBlob(new Blob(["not a zip"])), /不是有效的 ZIP/);
const archive = await createZipBlob([{ name: "library.json", data: "valid" }]);
diff --git a/tools/package-extension.mjs b/tools/package-extension.mjs
index e83c875..dd78792 100644
--- a/tools/package-extension.mjs
+++ b/tools/package-extension.mjs
@@ -73,7 +73,7 @@ function validateManifest(value, paths) {
if (value.manifest_version !== 3) throw new Error("只允许打包 Manifest V3 扩展");
if (!/^\d+\.\d+\.\d+$/.test(value.version ?? "")) throw new Error("manifest 版本号无效");
if (!/^__MSG_[A-Za-z0-9_]+__$/.test(String(value.name ?? ""))) throw new Error("manifest 品牌名未使用本地化消息");
- for (const required of ["manifest.json", "LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md", "ui-foundation.css", "ui-icons.js", "assets/ui-icons.svg", "collector.html", "collector.js", "collector-view.js", "collector.css", "capture-draft.js", "compound-cases.js", "media.js", "media-store.js", "visuals.js", "composer.html", "composer-page.js", "composer-page.css", "composer-diagnostics.js", "creative-skills.js", "creative-skill-package.js", "creative-skill-service.js", "skill-contact-sheet.js", "skills.html", "skills-page.js", "skills-page.css", "curated.html", "curated-page.js", "curated.css", "curated-catalog.js", "curated-config.js", "background.js", "image-transaction.js", "assets/icons/icon-128.png", "_locales/zh_CN/messages.json", "_locales/en/messages.json"]) {
+ for (const required of ["manifest.json", "LICENSE", "NOTICE", "THIRD_PARTY_NOTICES.md", "ui-foundation.css", "ui-icons.js", "assets/ui-icons.svg", "collector.html", "collector.js", "collector-view.js", "collector.css", "capture-draft.js", "compound-cases.js", "media.js", "media-store.js", "visuals.js", "composer.html", "composer-page.js", "composer-page.css", "composer-diagnostics.js", "creative-skills.js", "creative-skill-package.js", "creative-skill-service.js", "skill-contact-sheet.js", "skills.html", "skills-page.js", "skills-page.css", "curated.html", "curated-page.js", "curated.css", "curated-catalog.js", "curated-import.js", "curated-config.js", "background.js", "image-transaction.js", "assets/icons/icon-128.png", "_locales/zh_CN/messages.json", "_locales/en/messages.json"]) {
if (!paths.includes(required)) throw new Error(`发布包缺少 ${required}`);
}
if (!paths.includes("ui-dialogs.js")) throw new Error("发布包缺少 ui-dialogs.js");
@@ -81,8 +81,11 @@ function validateManifest(value, paths) {
if (!paths.includes("page-capture.js") || !paths.includes("vendor/document-ingestion/Readability.js")) {
throw new Error("发布包缺少网页采集运行时");
}
- if (!paths.includes("ai-task-routing.js") || !paths.includes("video-analysis.js")) {
- throw new Error("发布包缺少 AI 任务分工或视频分析运行时");
+ if (!paths.includes("page-capture-adapter-registry.js") || !paths.includes("page-capture-site-adapters.js") || !paths.includes("page-session-media.js")) {
+ throw new Error("发布包缺少网页站点适配或页面会话媒体运行时");
+ }
+ if (!paths.includes("ai-provider-registry.js") || !paths.includes("ai-model-capabilities.js") || !paths.includes("ai-runtime.js") || !paths.includes("video-analysis.js")) {
+ throw new Error("发布包缺少 AI 配置或视频分析运行时");
}
if (paths.some((path) => /(?:^|\/)(?:test|tools|store|dist)(?:\/|$)/.test(path))) {
throw new Error("发布包混入了测试、工具或商店素材");
diff --git a/ui-foundation.css b/ui-foundation.css
index 5bfebaa..f70ce3c 100644
--- a/ui-foundation.css
+++ b/ui-foundation.css
@@ -157,7 +157,7 @@ button,
}
button:hover:not(:disabled),
.button-primary:hover:not(:disabled) { background: var(--ui-accent-hover); }
-button:active:not(:disabled) { transform: translateY(1px); }
+button:active:not(:disabled) { transform: none; }
button:disabled { cursor: not-allowed; opacity: .48; }
button[aria-busy="true"] { cursor: progress; }
@@ -239,6 +239,31 @@ summary:focus-visible,
white-space: nowrap;
}
+.ui-feedback-toast {
+ position: fixed;
+ z-index: 90;
+ right: 18px;
+ bottom: var(--ui-feedback-bottom, 18px);
+ max-width: min(360px, calc(100vw - 36px));
+ margin: 0;
+ border: 1px solid var(--ui-border-strong);
+ border-radius: var(--ui-container-radius);
+ padding: 9px 12px;
+ color: var(--ui-text);
+ background: var(--ui-surface);
+ box-shadow: var(--ui-shadow);
+ font-size: var(--ui-meta-size);
+ font-weight: 650;
+ line-height: 1.45;
+ text-align: left;
+ pointer-events: none;
+}
+.ui-feedback-toast:empty { display: none; }
+.ui-feedback-toast.error {
+ color: var(--ui-danger);
+ border-color: color-mix(in srgb, var(--ui-danger) 38%, var(--ui-border));
+}
+
.app-dialog { width: min(520px, calc(100vw - 28px)); max-height: min(760px, calc(100dvh - 28px)); overflow: hidden; border: 1px solid var(--ui-border-strong); border-radius: var(--ui-container-radius); padding: 0; color: var(--ui-text); background: var(--ui-surface); box-shadow: var(--ui-shadow); }
.app-dialog::backdrop { background: rgba(7, 9, 11, .72); backdrop-filter: blur(3px); }
.app-dialog-form { display: grid; max-height: min(760px, calc(100dvh - 28px)); grid-template-rows: auto minmax(0, 1fr) auto; }
diff --git a/video-analysis.js b/video-analysis.js
index 8862b22..ec63960 100644
--- a/video-analysis.js
+++ b/video-analysis.js
@@ -10,7 +10,7 @@ export const GEMINI_VIDEO_API_ROOT = "https://generativelanguage.googleapis.com/
export const GEMINI_FILE_POLL_INTERVAL_MS = 2_000;
export const GEMINI_FILE_POLL_LIMIT = 150;
const GEMINI_VIDEO_MIME_TYPES = new Set(["video/mp4", "video/mpeg", "video/quicktime", "video/avi", "video/x-flv", "video/mpg", "video/webm", "video/wmv", "video/3gpp"]);
-const OPENROUTER_VIDEO_MIME_TYPES = new Set(["video/mp4", "video/mpeg", "video/quicktime", "video/webm"]);
+const CHAT_COMPLETIONS_VIDEO_MIME_TYPES = new Set(["video/mp4", "video/mpeg", "video/quicktime", "video/webm"]);
export function requireVideoAnalysisConfirmation(value) {
if (value !== true) throw new Error("请从视频分析确认框开始本次付费媒体分析");
@@ -74,28 +74,36 @@ export async function analyzeVideoWithGemini(input = {}, dependencies = {}) {
}
export async function analyzeVideoWithOpenRouter(input = {}, dependencies = {}) {
+ return analyzeVideoWithChatCompletions({
+ ...input,
+ providerLabel: clean(input.providerLabel) || "OpenRouter"
+ }, dependencies);
+}
+
+export async function analyzeVideoWithChatCompletions(input = {}, dependencies = {}) {
const fetchImpl = dependencies.fetchImpl ?? fetch;
const apiKey = clean(input.apiKey);
const model = clean(input.model);
- if (!apiKey || !model) throw new Error("OpenRouter 视频分析尚未完成配置");
+ const providerLabel = clean(input.providerLabel) || "兼容视频服务";
+ if (!apiKey || !model) throw new Error(`${providerLabel} 视频分析尚未完成配置`);
const prompt = videoAnalysisPrompt(input.mode, input.customQuestion);
const onStage = typeof input.onStage === "function" ? input.onStage : () => {};
let videoUrl;
let sourceKind;
if (input.videoBlob instanceof Blob) {
- if (!OPENROUTER_VIDEO_MIME_TYPES.has(input.videoBlob.type)) {
- throw new Error(`OpenRouter 当前不支持 ${input.videoBlob.type || "未知格式"} 视频;请先转换为 MP4、WebM、MOV 或 MPEG`);
+ if (!CHAT_COMPLETIONS_VIDEO_MIME_TYPES.has(input.videoBlob.type)) {
+ throw new Error(`${providerLabel} 当前不支持 ${input.videoBlob.type || "未知格式"} 视频;请先转换为 MP4、WebM、MOV 或 MPEG`);
}
sourceKind = "local-video";
onStage("encoding");
videoUrl = await blobDataUrl(input.videoBlob);
} else {
videoUrl = safeHttpsUrl(input.youtubeUrl);
- if (!videoUrl) throw new Error("该视频链接不能安全发送给 OpenRouter,请改用 HTTPS 地址或附加本地视频文件");
+ if (!videoUrl) throw new Error(`该视频链接不能安全发送给 ${providerLabel},请改用 HTTPS 地址或附加本地视频文件`);
sourceKind = "public-video-url";
}
onStage("analyzing");
- const endpoint = openRouterChatEndpoint(input.endpoint);
+ const endpoint = chatCompletionsEndpoint(input.endpoint, providerLabel);
const response = await fetchImpl(endpoint, {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
@@ -113,17 +121,22 @@ export async function analyzeVideoWithOpenRouter(input = {}, dependencies = {})
}]
})
});
- const payload = await readJsonResponse(response, "OpenRouter 视频分析");
- const text = openRouterMessageText(payload?.choices?.[0]?.message?.content);
- if (!text) throw new Error("OpenRouter 没有返回可保存的视频分析文字");
+ let payload;
+ try {
+ payload = await readJsonResponse(response, `${providerLabel} 视频分析`);
+ } catch (error) {
+ throw new Error(`${providerLabel} 视频分析失败:${redactSecret(error?.message, apiKey)}`, { cause: error });
+ }
+ const text = chatCompletionsMessageText(payload?.choices?.[0]?.message?.content);
+ if (!text) throw new Error(`${providerLabel} 没有返回可保存的视频分析文字`);
onStage("completed");
return {
text,
- provider: "OpenRouter",
+ provider: providerLabel,
model: clean(payload.model) || model,
sourceKind,
prompt,
- usage: normalizeOpenRouterUsage(payload.usage),
+ usage: normalizeChatCompletionsUsage(payload.usage),
cost: Number.isFinite(Number(payload.usage?.cost)) ? Number(payload.usage.cost) : null,
routing: clean(payload.provider) ? { provider: clean(payload.provider) } : null
};
@@ -200,9 +213,9 @@ function safeGoogleUploadUrl(value) {
}
}
-function openRouterChatEndpoint(value) {
- const endpoint = safeHttpsUrl(value || "https://openrouter.ai/api/v1");
- if (!endpoint) throw new Error("OpenRouter 接口地址无效");
+function chatCompletionsEndpoint(value, providerLabel) {
+ const endpoint = safeHttpsUrl(value);
+ if (!endpoint) throw new Error(`${providerLabel} 接口地址无效`);
const url = new URL(endpoint);
url.pathname = `${url.pathname.replace(/\/$/, "").replace(/\/chat\/completions$/, "")}/chat/completions`;
url.search = "";
@@ -227,7 +240,7 @@ async function blobDataUrl(blob) {
return `data:${blob.type};base64,${btoa(binary)}`;
}
-function openRouterMessageText(value) {
+function chatCompletionsMessageText(value) {
if (typeof value === "string") return clean(value);
return (Array.isArray(value) ? value : [])
.map((part) => clean(part?.text ?? part?.content))
@@ -235,7 +248,7 @@ function openRouterMessageText(value) {
.join("\n\n");
}
-function normalizeOpenRouterUsage(value = {}) {
+function normalizeChatCompletionsUsage(value = {}) {
return {
inputTokens: Math.max(0, Number(value.prompt_tokens ?? value.input_tokens) || 0),
outputTokens: Math.max(0, Number(value.completion_tokens ?? value.output_tokens) || 0),
@@ -243,6 +256,12 @@ function normalizeOpenRouterUsage(value = {}) {
};
}
+function redactSecret(value, secretValue) {
+ const message = clean(value);
+ const secret = clean(secretValue);
+ return secret ? message.split(secret).join("[已隐藏 API Key]") : message;
+}
+
async function readJsonResponse(response, label) {
let payload = {};
try { payload = await response.json(); } catch {}
diff --git a/zip.js b/zip.js
index 0ee2e0b..6f43492 100644
--- a/zip.js
+++ b/zip.js
@@ -54,7 +54,12 @@ export async function createZipBlob(files) {
);
}
-export async function readZipBlob(archive, limitsValue = {}) {
+export async function readZipBlob(archive, limitsValue = {}, options = {}) {
+ const reader = await openZipBlob(archive, limitsValue);
+ return reader.read(null, options);
+}
+
+export async function openZipBlob(archive, limitsValue = {}) {
const limits = portableLibraryLimits(limitsValue);
if (!(archive instanceof Blob) || archive.size < 22) throw invalidZip();
if (archive.size > limits.maxArchiveBytes) {
@@ -79,8 +84,9 @@ export async function readZipBlob(archive, limitsValue = {}) {
}
if (directoryOffset + directorySize !== endOffset) throw invalidZip();
- const files = new Map();
- let extractedBytes = 0;
+ const records = [];
+ const names = new Set();
+ let declaredBytes = 0;
let cursor = directoryOffset;
for (let index = 0; index < fileCount; index += 1) {
if (cursor + 46 > endOffset || view.getUint32(cursor, true) !== 0x02014b50) throw invalidZip();
@@ -114,7 +120,7 @@ export async function readZipBlob(archive, limitsValue = {}) {
continue;
}
const name = normalizeArchivePath(decodedName);
- if (name !== decodedName || files.has(name)) throw new Error("ZIP 内包含不安全或重复的文件路径");
+ if (name !== decodedName || names.has(name)) throw new Error("ZIP 内包含不安全或重复的文件路径");
if (localOffset + 30 > directoryOffset || view.getUint32(localOffset, true) !== 0x04034b50) throw invalidZip();
const localFlags = view.getUint16(localOffset + 6, true);
@@ -136,17 +142,45 @@ export async function readZipBlob(archive, limitsValue = {}) {
const dataOffset = localOffset + 30 + localNameLength + localExtraLength;
const dataEnd = dataOffset + compressedSize;
if (dataEnd > directoryOffset) throw invalidZip();
- const compressed = bytes.subarray(dataOffset, dataEnd);
- const data = method === STORE_METHOD ? compressed : await inflateRaw(compressed, size, name);
- if (data.byteLength !== size) throw new Error(`ZIP 内的文件解压大小不符:${name}`);
- extractedBytes += data.byteLength;
- if (extractedBytes > limits.maxArchiveBytes) throw new Error("ZIP 解压内容超过安全上限");
- if (crc32(data) !== checksum) throw new Error(`ZIP 内的文件已损坏:${name}`);
- files.set(name, new Blob([data], { type: mimeTypeForPath(name) }));
+ declaredBytes += size;
+ if (declaredBytes > limits.maxArchiveBytes) throw new Error("ZIP 解压内容超过安全上限");
+ names.add(name);
+ records.push({ name, method, checksum, compressedSize, size, dataOffset, dataEnd });
cursor = nameEnd + extraLength + entryCommentLength;
}
if (cursor !== endOffset) throw invalidZip();
- return files;
+ return {
+ names: Object.freeze([...names]),
+ async read(selectedNames = null, options = {}) {
+ const requested = selectedNames == null
+ ? null
+ : new Set((Array.isArray(selectedNames) ? selectedNames : [...selectedNames]).map(normalizeArchivePath));
+ if (requested) {
+ for (const name of requested) {
+ if (!names.has(name)) throw new Error(`ZIP 内缺少文件:${name}`);
+ }
+ }
+ const targets = requested ? records.filter((record) => requested.has(record.name)) : records;
+ const onProgress = typeof options.onProgress === "function" ? options.onProgress : () => undefined;
+ const files = new Map();
+ let extractedBytes = 0;
+ for (let index = 0; index < targets.length; index += 1) {
+ const record = targets[index];
+ const compressed = bytes.subarray(record.dataOffset, record.dataEnd);
+ const data = record.method === STORE_METHOD
+ ? compressed
+ : await inflateRaw(compressed, record.size, record.name);
+ if (data.byteLength !== record.size) throw new Error(`ZIP 内的文件解压大小不符:${record.name}`);
+ extractedBytes += data.byteLength;
+ if (extractedBytes > limits.maxArchiveBytes) throw new Error("ZIP 解压内容超过安全上限");
+ if (crc32(data) !== record.checksum) throw new Error(`ZIP 内的文件已损坏:${record.name}`);
+ files.set(record.name, new Blob([data], { type: mimeTypeForPath(record.name) }));
+ onProgress({ completed: index + 1, total: targets.length, name: record.name, extractedBytes });
+ if ((index + 1) % 8 === 0 && index + 1 < targets.length) await yieldToMain();
+ }
+ return files;
+ }
+ };
}
async function inflateRaw(bytes, expectedSize, name) {
@@ -285,12 +319,16 @@ function ensureUint32(value, message) {
function crc32(bytes) {
let checksum = 0xffffffff;
- for (const byte of bytes) {
- checksum = CRC_TABLE[(checksum ^ byte) & 0xff] ^ (checksum >>> 8);
+ for (let index = 0; index < bytes.length; index += 1) {
+ checksum = CRC_TABLE[(checksum ^ bytes[index]) & 0xff] ^ (checksum >>> 8);
}
return (checksum ^ 0xffffffff) >>> 0;
}
+function yieldToMain() {
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
const CRC_TABLE = new Uint32Array(256);
for (let index = 0; index < CRC_TABLE.length; index += 1) {
let value = index;