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

修复 AI 分析数据完整性与批量任务体验

MigenAIa0da6bc61f69
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 24c6dbc..94534b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## 1.19.1
+
+- 修复项目侧栏与案例管理两处批量画面分析入口:选择范围、开始按钮、运行中进度、暂停与失败数量都会即时显示,旧任务也不会再用过期模型覆盖当前设置。
+- 画面分析改为原子保存:只有同时得到详细反推提示词与有效 AI 标签才算成功;缺字段、空标签和旧版半成品统一明确失败,不再写入不完整案例。
+- 反推提示词继续覆盖构图、主体、空间、镜头、光线、色彩、材质、风格、文字与画面关系等复刻维度;对兼容视觉服务默认关闭思考,并收敛为“提示词 + 标签”的结构化输出。
+- 分析任务使用统一的受控并发与后台恢复机制,区分网络、限流、服务端和格式错误;每张图的网络重试与格式纠正共享最多 3 次真实请求预算,界面提供可重试的中文结果。
+- 文字批量分析改为以实际保存的检索标签判定成功,并与案例当前主图提示词使用同一份分析输入,避免显示成功却在详情页看不到标签。
+- 分享包与完整资料库导入会校验并重建 AI 标签引用;即使图片 ID 冲突并被重命名,视觉标签也会跟随对应图片迁移,缺失词表则停止导入并说明问题。
+- 案例详情页移除重复的下方反推提示词模块,只保留一处可编辑提示词入口;本地索引维护也不再使用容易与 AI 失败混淆的“待补全”文案。
+
## 1.19.0
- 项目升级为可嵌套的树形结构:支持空父项目、跨层级拖动、键盘管理、子树去重统计,并无损迁移原有项目、案例归属与顺序。
diff --git a/analysis-batch.js b/analysis-batch.js
index 65607ea..ccbb8ca 100644
--- a/analysis-batch.js
+++ b/analysis-batch.js
@@ -1,5 +1,6 @@
import { ANALYSIS_PROMPT_VERSION, DEFAULT_ANALYSIS_MODEL } from "./deepseek.js";
import { applyTextAnalysisTags } from "./analysis-candidates.js";
+import { canonicalTextAnalysisInput } from "./analysis-input.js";
import {
analysisRevisionMeta,
entryTextRevision,
@@ -19,13 +20,14 @@ export async function previewAnalysisBatch(entries = [], options = {}) {
const mode = ["reanalyze", "rebuild"].includes(options.mode) ? "rebuild" : "incremental";
const profileFingerprint = String(options.profileFingerprint ?? "").trim();
for (const entry of Array.isArray(entries) ? entries : []) {
- const text = String(entry?.text ?? "").trim();
+ const { text, assetId, textRevision } = canonicalTextAnalysisInput(entry);
if (!entry?.id || !text) continue;
const reason = mode === "rebuild" ? "explicit_reanalysis" : textAnalysisReason(entry);
if (!reason) continue;
eligible.push({
entryId: entry.id,
- textRevision: entryTextRevision(entry),
+ textRevision,
+ ...(assetId ? { assetId } : {}),
characterCount: text.length,
title: String(entry.title ?? ""),
reason
@@ -53,7 +55,7 @@ export async function backfillLegacyAnalysisMeta(entries = []) {
let updatedCount = 0;
const next = [];
for (const entry of Array.isArray(entries) ? entries : []) {
- const text = String(entry?.text ?? "").trim();
+ const { text } = canonicalTextAnalysisInput(entry);
if (!entry?.id || !text || entry.analysisMeta || !hasPriorTextAnalysis(entry)) {
next.push(entry);
continue;
@@ -61,7 +63,7 @@ export async function backfillLegacyAnalysisMeta(entries = []) {
next.push({
...entry,
analysisMeta: {
- textRevision: entryTextRevision(entry),
+ ...analysisRevisionMeta(entry),
promptVersion: ANALYSIS_PROMPT_VERSION,
model: "previous-analysis",
analyzedAt: String(entry.analyzedAt ?? ""),
@@ -102,6 +104,7 @@ export async function createAnalysisBatchJob(entries, options = {}) {
items: preview.entries.map((item) => ({
entryId: item.entryId,
textRevision: item.textRevision,
+ ...(item.assetId ? { assetId: item.assetId } : {}),
fingerprint: "",
status: "pending",
attempts: 0,
@@ -127,7 +130,7 @@ export function previewVisionBatch(entries = [], options = {}) {
: [primaryImageAsset(entry)].filter(Boolean);
for (const visual of candidates) {
if (!visual?.id) continue;
- const hasCompleteAnalysis = Boolean(visual.visionAnalysis?.description) && visual.visionAnalysis?.quality !== "partial";
+ const hasCompleteAnalysis = hasReusableVisionAnalysis(visual);
if (!reanalyze && hasCompleteAnalysis) {
skippedAnalyzedCount += 1;
continue;
@@ -153,6 +156,14 @@ export function previewVisionBatch(entries = [], options = {}) {
};
}
+function hasReusableVisionAnalysis(visual = {}) {
+ const analysis = visual?.visionAnalysis;
+ if (!analysis || analysis.quality === "partial") return false;
+ if (!String(analysis.reconstructionPrompt ?? "").trim()) return false;
+ return Array.isArray(analysis.tags)
+ && analysis.tags.some((tag) => String(tag?.g ?? "").trim() && String(tag?.t ?? "").trim());
+}
+
export function createVisionBatchJob(entries = [], options = {}) {
const preview = previewVisionBatch(entries, options);
if (!preview.requestCount) throw new Error("没有需要批量分析的图片");
@@ -191,7 +202,7 @@ export function createVisionBatchJob(entries = [], options = {}) {
export function normalizeAnalysisBatchJob(value) {
if (!value || ![1, ANALYSIS_BATCH_VERSION].includes(value.version) || !value.id || !Array.isArray(value.items)) return null;
- const statuses = new Set(["pending", "running", "succeeded", "partial", "failed"]);
+ const statuses = new Set(["pending", "running", "succeeded", "failed"]);
const jobStatuses = new Set(["running", "paused", "completed", "partial", "failed", "canceled"]);
return {
version: ANALYSIS_BATCH_VERSION,
@@ -224,12 +235,17 @@ export function normalizeAnalysisBatchJob(value) {
items: value.items.flatMap((item) => item?.entryId ? [{
entryId: String(item.entryId),
...(String(item.visualId ?? "").trim() ? { visualId: String(item.visualId).trim() } : {}),
+ ...(String(item.assetId ?? "").trim() ? { assetId: String(item.assetId).trim() } : {}),
fingerprint: String(item.fingerprint ?? ""),
textRevision: Math.max(1, Math.floor(Number(item.textRevision) || 1)),
- status: statuses.has(item.status) ? item.status : "pending",
+ status: item.status === "partial"
+ ? "failed"
+ : statuses.has(item.status) ? item.status : "pending",
attempts: Math.max(0, Number(item.attempts) || 0),
claimId: String(item.claimId ?? ""),
- error: String(item.error ?? ""),
+ error: item.status === "partial"
+ ? value.kind === "vision" ? "旧版图片分析结果不完整,请重试" : "旧版分析结果不完整,请重试"
+ : String(item.error ?? ""),
statusCode: Math.max(0, Number(item.statusCode) || 0),
serviceRequests: Math.max(0, Number(item.serviceRequests) || 0),
outputCorrectionRequests: Math.max(0, Number(item.outputCorrectionRequests) || 0),
@@ -256,6 +272,7 @@ export function claimAnalysisItems(value, limit, idFactory = () => globalThis.cr
claims.push({
entryId: item.entryId,
...(item.visualId ? { visualId: item.visualId } : {}),
+ ...(item.assetId ? { assetId: item.assetId } : {}),
fingerprint: item.fingerprint,
textRevision: item.textRevision,
claimId: item.claimId,
@@ -281,21 +298,6 @@ export function succeedAnalysisItem(value, entryId, claimId, usage, catalogRevis
return job;
}
-export function partiallySucceedAnalysisItem(value, entryId, claimId, usage, catalogRevision, metadata = {}) {
- const job = requireJob(value);
- const item = claimedItem(job, entryId, claimId);
- item.status = "partial";
- item.claimId = "";
- item.error = "分析结果待补全";
- item.statusCode = 0;
- recordItemExecution(item, metadata);
- job.usage = addUsage(job.usage, usage);
- job.resultCatalogRevision = Number.isInteger(catalogRevision) ? catalogRevision : job.resultCatalogRevision;
- finishIfSettled(job);
- touch(job);
- return job;
-}
-
export function failAnalysisItem(value, entryId, claimId, error = {}) {
const job = requireJob(value);
const item = claimedItem(job, entryId, claimId);
@@ -311,6 +313,22 @@ export function failAnalysisItem(value, entryId, claimId, error = {}) {
return job;
}
+export function failUnfinishedAnalysisItems(value, error = {}) {
+ const job = requireJob(value);
+ const message = String(error.message ?? "批量任务启动失败");
+ const statusCode = Math.max(0, Number(error.status) || 0);
+ for (const item of job.items) {
+ if (!["pending", "running"].includes(item.status)) continue;
+ item.status = "failed";
+ item.claimId = "";
+ item.error = message;
+ item.statusCode = statusCode;
+ }
+ finishIfSettled(job);
+ touch(job);
+ return job;
+}
+
export function stageAnalysisRebuildResults(jobValue, stagingValue, state, results = []) {
let job = requireJob(jobValue);
if (job.mode !== "rebuild") throw new Error("当前任务不是标签系统重建");
@@ -324,7 +342,7 @@ export function stageAnalysisRebuildResults(jobValue, stagingValue, state, resul
continue;
}
const entry = state.entries?.find((item) => item.id === result.entryId);
- if (!entry || entryTextRevision(entry) !== Math.max(1, Number(result.textRevision) || 1)) {
+ if (!entry || canonicalTextAnalysisInput(entry, result.assetId).textRevision !== Math.max(1, Number(result.textRevision) || 1)) {
job = failAnalysisItem(job, result.entryId, result.claimId, {
message: "提示词原文已变化,请重新预览",
status: 409
@@ -342,6 +360,7 @@ export function stageAnalysisRebuildResults(jobValue, stagingValue, state, resul
tags,
fingerprint: String(result.fingerprint ?? ""),
textRevision: Math.max(1, Number(result.textRevision) || 1),
+ ...(String(result.assetId ?? "").trim() ? { assetId: String(result.assetId).trim() } : {}),
model: String(result.model ?? ""),
normalizationDiagnostics: structuredClone(Array.isArray(result.normalizationDiagnostics) ? result.normalizationDiagnostics : []),
attempts: {
@@ -463,8 +482,11 @@ export function reconcileVisionBatchResults(value, entries = []) {
for (const item of job.items) {
if (!["pending", "running"].includes(item.status)) continue;
const analysis = visuals.get(`${item.entryId}:${item.visualId}`)?.visionAnalysis;
- if (!analysis?.description || analysis.batchJobId !== job.id) continue;
- item.status = analysis.quality === "partial" ? "partial" : "succeeded";
+ const hasPrompt = Boolean(String(analysis?.reconstructionPrompt ?? "").trim());
+ const hasTags = Array.isArray(analysis?.tags)
+ && analysis.tags.some((tag) => String(tag?.g ?? "").trim() && String(tag?.t ?? "").trim());
+ if (!hasPrompt || !hasTags || analysis.batchJobId !== job.id) continue;
+ item.status = "succeeded";
item.claimId = "";
item.error = "";
item.statusCode = 0;
@@ -589,6 +611,7 @@ function normalizeRetryPolicy(value) {
return {
serviceRetries: Number(value?.serviceRetries) === 2 ? 2 : ANALYSIS_RETRY_POLICY.serviceRetries,
outputCorrectionRequests: Number(value?.outputCorrectionRequests) === 1 ? 1 : ANALYSIS_RETRY_POLICY.outputCorrectionRequests,
+ maxProviderCallsPerItem: ANALYSIS_RETRY_POLICY.maxProviderCallsPerItem,
backoffMs: [...ANALYSIS_RETRY_POLICY.backoffMs],
obeyRetryAfter: true
};
@@ -642,7 +665,8 @@ function normalizeUsage(value = {}) {
function rebuildAnalysisMeta(staged, job, entry, analyzedAt) {
return {
...(staged.fingerprint ? { textFingerprint: staged.fingerprint } : {}),
- ...analysisRevisionMeta(entry),
+ textRevision: Math.max(1, Math.floor(Number(staged.textRevision) || analysisRevisionMeta(entry).textRevision)),
+ ...(String(staged.assetId ?? "").trim() ? { assetId: String(staged.assetId).trim() } : {}),
promptVersion: job.promptVersion || ANALYSIS_PROMPT_VERSION,
model: staged.model,
analyzedAt,
diff --git a/analysis-candidates.js b/analysis-candidates.js
index 425ce9b..6f99686 100644
--- a/analysis-candidates.js
+++ b/analysis-candidates.js
@@ -72,8 +72,8 @@ export function applyVisionAnalysis(state = {}, entryId, result = {}, metadata =
next.facetCatalog = normalizeFacetCatalog(next.facetCatalog);
let entry = next.entries?.find((item) => item.id === entryId);
if (!entry) throw new Error("没有找到需要分析的案例");
- const description = String(result.description ?? "").trim();
- if (!description) throw new Error("视觉模型没有返回画面描述,本次没有写入");
+ const reconstructionPrompt = String(result.reconstructionPrompt ?? "").trim();
+ if (!reconstructionPrompt) throw new Error("视觉模型没有返回可独立使用的反推提示词,本次没有写入");
const visualId = String(metadata.visualId ?? "").trim();
const matchesVisual = (item) => item.source === "vision_model" && (!visualId || item.visualId === visualId);
@@ -88,7 +88,6 @@ export function applyVisionAnalysis(state = {}, entryId, result = {}, metadata =
const assignmentStart = entry.facetAssignments.length;
const tagged = applyFixedAnalysisTags(next, entryId, result.tags ?? [], {
source: "vision_model",
- allowEmpty: true,
maxTags: 6,
replaceExisting: false
});
@@ -101,9 +100,8 @@ export function applyVisionAnalysis(state = {}, entryId, result = {}, metadata =
}
entry.visionAnalysis = {
version: Math.max(1, Number(metadata.version) || 1),
- description,
- quality: result.quality === "partial" ? "partial" : "complete",
- missingFields: Array.isArray(result.missingFields) ? [...new Set(result.missingFields.map(String).filter(Boolean))] : [],
+ reconstructionPrompt,
+ quality: "complete",
normalizationDiagnostics: Array.isArray(result.normalizationDiagnostics)
? result.normalizationDiagnostics.map((item) => ({
field: String(item?.field ?? ""),
@@ -112,13 +110,6 @@ export function applyVisionAnalysis(state = {}, entryId, result = {}, metadata =
...(Number(item?.count) > 0 ? { count: Number(item.count) } : {})
})).filter((item) => item.field)
: [],
- ...(result.canvas ? { canvas: structuredClone(result.canvas) } : {}),
- ...(Array.isArray(result.elements) ? { elements: structuredClone(result.elements) } : {}),
- ...(Array.isArray(result.dimensions) ? { dimensions: structuredClone(result.dimensions) } : {}),
- ...(Array.isArray(result.ocr) ? { ocr: structuredClone(result.ocr) } : {}),
- ...(String(result.reconstructionPrompt ?? "").trim() ? { reconstructionPrompt: String(result.reconstructionPrompt).trim() } : {}),
- ...(Array.isArray(result.limitations) ? { limitations: structuredClone(result.limitations) } : {}),
- ...(result.completeness ? { completeness: structuredClone(result.completeness) } : {}),
tags: Array.isArray(result.tags) ? structuredClone(result.tags) : [],
locale: metadata.locale === "en" ? "en" : "zh-CN",
imageFingerprint: String(metadata.imageFingerprint ?? "").trim(),
@@ -169,11 +160,18 @@ export function undoVisionAnalysis(state = {}, undo = {}) {
return next;
}
-export function editVisionDescription(entry = {}, description) {
- if (!entry.visionAnalysis || entry.visionAnalysis.invalidated) throw new Error("这条案例还没有可编辑的画面描述");
- const value = String(description ?? "").trim();
- if (!value) throw new Error("画面描述不能为空");
- return { ...entry, visionAnalysis: { ...entry.visionAnalysis, description: value, userEdited: true } };
+export function editVisionReconstructionPrompt(entry = {}, prompt) {
+ if (!entry.visionAnalysis || entry.visionAnalysis.invalidated) throw new Error("这条案例还没有可编辑的反推提示词");
+ const value = String(prompt ?? "").trim();
+ if (!value) throw new Error("反推提示词不能为空");
+ return {
+ ...entry,
+ visionAnalysis: {
+ ...entry.visionAnalysis,
+ reconstructionPrompt: value,
+ userEdited: true
+ }
+ };
}
export function invalidateVisionForScreenshot(entry = {}) {
diff --git a/analysis-input.js b/analysis-input.js
new file mode 100644
index 0000000..2147342
--- /dev/null
+++ b/analysis-input.js
@@ -0,0 +1,53 @@
+import { primaryImageAsset } from "./media.js";
+
+function clean(value) {
+ return String(value ?? "").trim();
+}
+
+function revisionFromValue(value, fallback = 1) {
+ const numeric = Math.floor(Number(value) || 0);
+ return numeric > 0 ? numeric : fallback;
+}
+
+function revisionFromUpdatedAt(value, fallback = 1) {
+ const timestamp = Date.parse(String(value ?? ""));
+ return Number.isFinite(timestamp) && timestamp > 0
+ ? Math.floor(timestamp)
+ : fallback;
+}
+
+export function canonicalTextAnalysisInput(entryValue = {}, assetIdValue = "") {
+ const entry = entryValue && typeof entryValue === "object" ? entryValue : {};
+ const primaryImage = primaryImageAsset(entry);
+ const requestedAssetId = clean(assetIdValue);
+ const selectedImage = requestedAssetId
+ ? (Array.isArray(entry.mediaAssets) ? entry.mediaAssets : [])
+ .find((item) => item?.id === requestedAssetId && item?.kind === "image" && item?.usage !== "poster")
+ : primaryImage;
+ const selectedAssetId = clean(selectedImage?.id);
+ const mediaPrompt = selectedAssetId
+ ? (Array.isArray(entry.mediaPrompts) ? entry.mediaPrompts : [])
+ .find((item) => String(item?.assetId ?? "").trim() === selectedAssetId)
+ : null;
+ const mediaText = clean(mediaPrompt?.text);
+ if (mediaText) {
+ return {
+ text: mediaText,
+ textRevision: revisionFromUpdatedAt(mediaPrompt?.updatedAt, revisionFromValue(mediaPrompt?.textRevision, 1)),
+ source: "media_prompt",
+ assetId: selectedAssetId
+ };
+ }
+ const sharedText = clean(entry.text);
+ return {
+ text: sharedText,
+ textRevision: revisionFromValue(entry.textRevision, 1),
+ source: sharedText ? "entry_text" : "",
+ assetId: selectedAssetId
+ };
+}
+
+export function hasCommittedTextAnalysisTags(entryValue = {}) {
+ return (Array.isArray(entryValue?.facetAssignments) ? entryValue.facetAssignments : [])
+ .some((item) => item?.source === "deepseek_text");
+}
diff --git a/analysis-retry-policy.js b/analysis-retry-policy.js
index 64d6496..89d8a8f 100644
--- a/analysis-retry-policy.js
+++ b/analysis-retry-policy.js
@@ -1,6 +1,9 @@
+const SERVICE_RETRIES = 2;
+
export const ANALYSIS_RETRY_POLICY = Object.freeze({
- serviceRetries: 2,
+ serviceRetries: SERVICE_RETRIES,
outputCorrectionRequests: 1,
+ maxProviderCallsPerItem: SERVICE_RETRIES + 1,
backoffMs: Object.freeze([1000, 3000]),
obeyRetryAfter: true
});
diff --git a/analysis-revision.js b/analysis-revision.js
index 912ed77..c9c3fb5 100644
--- a/analysis-revision.js
+++ b/analysis-revision.js
@@ -1,18 +1,24 @@
+import { canonicalTextAnalysisInput, hasCommittedTextAnalysisTags } from "./analysis-input.js";
+
export function entryTextRevision(entry = {}) {
return Math.max(1, Math.floor(Number(entry.textRevision) || 1));
}
+export function analysisInputRevision(entry = {}, assetId = "") {
+ return canonicalTextAnalysisInput(entry, assetId).textRevision;
+}
+
export function analyzedTextRevision(entry = {}) {
if (!hasPriorTextAnalysis(entry)) return 0;
return Math.max(1, Math.floor(Number(entry.analysisMeta?.textRevision) || 1));
}
export function textAnalysisReason(entry = {}) {
- const text = String(entry.text ?? "").trim();
+ const { text } = canonicalTextAnalysisInput(entry);
if (!entry.id || !text) return "";
const analyzedRevision = analyzedTextRevision(entry);
if (!analyzedRevision) return "missing_analysis";
- return analyzedRevision === entryTextRevision(entry) ? "" : "text_changed";
+ return analyzedRevision === analysisInputRevision(entry) ? "" : "text_changed";
}
export function markEntryTextChanged(entryValue = {}, nextTextValue) {
@@ -40,12 +46,9 @@ export function updateEntryText(entryValue = {}, nextTextValue, expectedRevision
}
export function analysisRevisionMeta(entry = {}) {
- return { textRevision: entryTextRevision(entry) };
+ return { textRevision: analysisInputRevision(entry) };
}
export function hasPriorTextAnalysis(entry = {}) {
- if (entry.analysisMeta && typeof entry.analysisMeta === "object") return true;
- if (String(entry.analyzedAt ?? "").trim()) return true;
- return [...(entry.facetAssignments ?? []), ...(entry.analysisCandidates ?? [])]
- .some((item) => item?.source === "deepseek_text");
+ return hasCommittedTextAnalysisTags(entry);
}
diff --git a/background.js b/background.js
index defbf76..ed59485 100644
--- a/background.js
+++ b/background.js
@@ -36,7 +36,7 @@ import {
applyAnalysisImport,
applyTextAnalysisTags,
applyVisionAnalysis,
- editVisionDescription,
+ editVisionReconstructionPrompt,
rejectAnalysisCandidate,
undoVisionAnalysis,
setManualAssignment
@@ -65,11 +65,11 @@ import {
createAnalysisBatchJob,
createVisionBatchJob,
failAnalysisItem,
+ failUnfinishedAnalysisItems,
finalizeAnalysisRebuild,
finalizePartialAnalysisRebuild,
normalizeAnalysisBatchJob,
pauseAnalysisBatch,
- partiallySucceedAnalysisItem,
previewAnalysisBatch,
previewVisionBatch,
reconcileVisionBatchResults,
@@ -81,6 +81,7 @@ import {
succeedAnalysisItem,
textFingerprint
} from "./analysis-batch.js";
+import { canonicalTextAnalysisInput } from "./analysis-input.js";
import { buildAutomaticVisionJob } from "./automatic-vision.js";
import { coalesceAnalysisRequest, runScheduledAnalysisWithRetries } from "./analysis-scheduler.js";
import { findPersistedVisionAnalysis } from "./vision-analysis-cache.js";
@@ -312,6 +313,7 @@ import {
evaluateCreativeOutputWithVision,
analyzeImageWithVision,
blobToDataUrl,
+ createVisionRequestBudget,
imageFingerprint,
publicVisionSettings,
visionAnalysisProfileFingerprint
@@ -497,7 +499,7 @@ scheduleLibraryMaintenanceRunner();
scheduleAutomaticVisionRunner();
scheduleAnalysisBatchRunner();
recoverCreativeJobs().catch((error) => console.error("PromptDirector creative job recovery failed", error));
-recoverImportJobs().catch((error) => console.error("PromptDirector local import recovery failed", error));
+enqueue(recoverImportJobs).catch((error) => console.error("PromptDirector local import recovery failed", error));
chrome.contextMenus.onClicked.addListener((info, tab) => {
handleContextMenuCapture(info, tab, {
@@ -837,8 +839,8 @@ async function handleMessage(message, interaction = {}) {
return analyzeEntryVisualSet(message);
case "ANALYZE_ENTRY_VIDEO":
return analyzeEntryVideo(message);
- case "UPDATE_VISION_DESCRIPTION":
- return enqueue(async () => updateVisionDescription(message.entryId, message.visualId, message.description));
+ case "UPDATE_VISION_RECONSTRUCTION_PROMPT":
+ return enqueue(async () => updateVisionReconstructionPrompt(message.entryId, message.visualId, message.reconstructionPrompt));
case "UPDATE_ENTRY_TEXT":
return enqueue(async () => updateCaseText(message));
case "UPDATE_ENTRY_MEDIA_PROMPT":
@@ -3449,7 +3451,8 @@ async function undoImportJobAction(jobId) {
async function recoverImportJobs() {
const stored = await chrome.storage.local.get(STORAGE_KEYS.importJobs);
const recovered = normalizeImportJobsState(stored[STORAGE_KEYS.importJobs], { recoverRunning: true });
- if (JSON.stringify(stored[STORAGE_KEYS.importJobs] ?? {}) !== JSON.stringify(recovered)) {
+ if (stored[STORAGE_KEYS.importJobs]
+ && JSON.stringify(stored[STORAGE_KEYS.importJobs]) !== JSON.stringify(recovered)) {
await commitLocalChanges({ [STORAGE_KEYS.importJobs]: recovered });
}
if (recovered.items.some((job) => ["queued", "running"].includes(job.status) && job.items.some((item) => item.status === "queued"))) {
@@ -4753,17 +4756,14 @@ async function analyzeEntryImage(entryId, visualIdValue, outputLocale, batchJobI
});
return {
ok: true,
- message: result.quality === "partial"
- ? `画面分析已保存可用部分,仍有 ${result.missingFields.length} 项待补全`
- : result.tagDiagnostics?.rejectedCount
+ message: result.tagDiagnostics?.rejectedCount
? `画面分析已保存,并写入 ${applied.appliedCount} 个检索标签;另有 ${result.tagDiagnostics.rejectedCount} 个不符合当前分类体系的可选标签未采用`
: `画面分析已保存,并写入 ${applied.appliedCount} 个检索标签`,
entry: applied.state.entries.find((item) => item.id === current.id),
usage: result.usage,
cacheHit: result.cacheHit,
attempts: result.attempts,
- quality: result.quality,
- missingFields: result.missingFields,
+ quality: "complete",
...publicDomainState(applied.state),
visionUndoEntryIds: Object.keys(undoStore)
};
@@ -4809,9 +4809,9 @@ async function analyzeVisionBlobWithScheduler({ blob, catalog, locale, measuredC
}
};
const schedulerKey = `${assignment.providerId}:${assignment.model}:imageAnalysis`;
- const requestMode = bypassCache ? "reanalyze" : (previousAnalysis?.quality === "partial" || cached?.quality === "partial") ? "complete" : "analyze";
+ const requestMode = bypassCache ? "reanalyze" : "analyze";
const requestKey = `${schedulerKey}:${fingerprint}:${profileFingerprint}:${locale}:${catalog?.revision ?? 0}:${requestMode}`;
- let serviceRequests = 0;
+ const requestBudget = createVisionRequestBudget();
let coalesced = false;
let result;
try {
@@ -4819,21 +4819,21 @@ async function analyzeVisionBlobWithScheduler({ blob, catalog, locale, measuredC
key: schedulerKey,
concurrency: assignment.concurrency,
task: async () => {
- serviceRequests += 1;
return analyzeImageWithVision({
imageDataUrl: await blobToDataUrl(blob),
catalog,
locale,
measuredCanvas,
- previousAnalysis: !bypassCache && previousAnalysis?.quality === "partial" ? previousAnalysis : !bypassCache ? cached : null,
- settings
+ previousAnalysis: null,
+ settings,
+ requestBudget
});
}
}), { onCoalesced: () => { coalesced = true; } });
} catch (error) {
error.attempts = {
- serviceRequests,
- outputCorrectionRequests: Math.max(0, Number(error?.attempts?.outputCorrectionRequests) || 0)
+ serviceRequests: coalesced ? 0 : visionPrimaryRequestCount(requestBudget),
+ outputCorrectionRequests: coalesced ? 0 : requestBudget.outputCorrectionRequests
};
throw error;
}
@@ -4842,14 +4842,21 @@ async function analyzeVisionBlobWithScheduler({ blob, catalog, locale, measuredC
...result,
cacheHit: result.cacheHit === true || coalesced,
attempts: {
- serviceRequests,
- outputCorrectionRequests: Number(result.attempts?.outputCorrectionRequests) || 0
+ serviceRequests: coalesced ? 0 : visionPrimaryRequestCount(requestBudget),
+ outputCorrectionRequests: coalesced ? 0 : requestBudget.outputCorrectionRequests
}
},
fingerprint
};
}
+function visionPrimaryRequestCount(requestBudget) {
+ return Math.max(
+ 0,
+ (Number(requestBudget?.providerCalls) || 0) - (Number(requestBudget?.outputCorrectionRequests) || 0)
+ );
+}
+
async function analyzeEntryVisualSet(message) {
const state = await readState();
const current = normalizeEntryMedia(findEntry(state, message.entryId));
@@ -4946,17 +4953,17 @@ async function analyzeEntryVideo(message) {
});
}
-async function updateVisionDescription(entryId, visualIdValue, description) {
+async function updateVisionReconstructionPrompt(entryId, visualIdValue, reconstructionPrompt) {
const state = await readState();
const current = findEntry(state, entryId);
const visualId = String(visualIdValue ?? "").trim() || primaryVisual(current)?.id;
const visual = normalizeEntryVisuals(current).visuals.find((item) => item.id === visualId);
- if (!visual?.visionAnalysis) throw new Error("这张截图还没有可编辑的画面描述");
- const temporary = editVisionDescription({ visionAnalysis: visual.visionAnalysis }, description);
+ if (!visual?.visionAnalysis) throw new Error("这张截图还没有可编辑的反推提示词");
+ const temporary = editVisionReconstructionPrompt({ visionAnalysis: visual.visionAnalysis }, reconstructionPrompt);
const updated = updateEntryVisual(current, visual.id, (item) => ({ ...item, visionAnalysis: temporary.visionAnalysis }));
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
- return { ok: true, message: "画面描述已保存", entry: updated, entries };
+ return { ok: true, message: "反推提示词已保存", entry: updated, entries };
}
async function updateEntryMediaPromptAction(message) {
@@ -5215,10 +5222,15 @@ async function decideAnalysisCandidate(message, accepted) {
async function applyEntryAnalysisResult(message) {
const state = await readState();
const entry = findEntry(state, message.entryId);
- if (message.textRevision && message.textRevision !== entryTextRevision(entry)) {
+ const input = canonicalTextAnalysisInput(entry, message.assetId);
+ if (message.textRevision && message.textRevision !== input.textRevision) {
+ return { ok: false, message: "提示词原文已变化,本次分析结果没有写入" };
+ }
+ const currentFingerprint = await textFingerprint(input.text);
+ if (message.fingerprint && message.fingerprint !== currentFingerprint) {
return { ok: false, message: "提示词原文已变化,本次分析结果没有写入" };
}
- const fingerprint = message.fingerprint || await textFingerprint(entry.text);
+ const fingerprint = currentFingerprint;
const applied = applyTextAnalysisTags(domainState(state), entry.id, message.tags);
const updated = applied.state.entries.find((item) => item.id === entry.id);
updated.analysisPending = false;
@@ -5351,7 +5363,7 @@ async function commitDeepSeekBatchItem(message) {
}
const state = await readState();
const entry = findEntry(state, message.entryId);
- if (entryTextRevision(entry) !== Math.max(1, Number(message.textRevision) || 1)) {
+ if (canonicalTextAnalysisInput(entry, message.assetId).textRevision !== Math.max(1, Number(message.textRevision) || 1)) {
return failDeepSeekBatchItem({
...message,
error: { message: "提示词原文已变化,请重新预览", status: 409 }
@@ -5420,7 +5432,7 @@ async function commitDeepSeekBatchItems(message) {
continue;
}
const entry = working.entries.find((item) => item.id === result.entryId);
- if (!entry || entryTextRevision(entry) !== Math.max(1, Number(result.textRevision) || 1)) {
+ if (!entry || canonicalTextAnalysisInput(entry, result.assetId).textRevision !== Math.max(1, Number(result.textRevision) || 1)) {
job = failAnalysisItem(job, result.entryId, result.claimId, {
message: "提示词原文已变化,请重新预览",
status: 409
@@ -5546,7 +5558,7 @@ async function applyStagedAnalysisRebuild(jobId) {
const staleCount = job.items.filter((item) => {
if (item.status !== "succeeded") return false;
const entry = state.entries.find((candidate) => candidate.id === item.entryId);
- return !entry || entryTextRevision(entry) !== item.textRevision;
+ return !entry || canonicalTextAnalysisInput(entry, item.assetId).textRevision !== item.textRevision;
}).length;
if (staleCount) {
return { ok: false, message: `${staleCount} 条成功案例的原文已变化,不能安全应用旧缓存` };
@@ -5682,6 +5694,14 @@ async function claimVisionBatchItem(jobId) {
const loadedConfiguration = await loadAiConfiguration();
const configuration = configurationForAssignment(loadedConfiguration, "imageAnalysis", job);
const settings = resolveVisionTaskSettings("imageAnalysis", configuration, { requireConfigured: false });
+ const currentSettings = resolveVisionTaskSettings("imageAnalysis", loadedConfiguration, { requireConfigured: false });
+ const currentModel = currentSettings.activeProvider === "openai" ? currentSettings.openai.model : currentSettings.compatible.model;
+ const snapshotModel = settings.activeProvider === "openai" ? settings.openai.model : settings.compatible.model;
+ if (job.providerType !== currentSettings.activeProvider || job.model !== currentModel || job.providerType !== settings.activeProvider || job.model !== snapshotModel) {
+ const canceled = cancelAnalysisBatch(job);
+ await commitLocalChanges({ [STORAGE_KEYS.batchJob]: canceled });
+ return { ok: false, message: "图片分析设置已变化,旧批量任务已取消,请重新开始" };
+ }
const snapshotReady = publicVisionSettings(settings)[settings.activeProvider]?.configured === true;
if (!snapshotReady || !settings.consent) {
const paused = pauseAnalysisBatch(job);
@@ -5710,9 +5730,7 @@ async function completeVisionBatchItem(message) {
totalTokens: Math.max(0, Number(message.usage?.totalTokens) || 0),
cacheHits: message.cacheHit === true ? 1 : 0
};
- const next = message.quality === "partial"
- ? partiallySucceedAnalysisItem(job, message.entryId, message.claimId, usage, undefined, message)
- : succeedAnalysisItem(job, message.entryId, message.claimId, usage, undefined, message);
+ const next = succeedAnalysisItem(job, message.entryId, message.claimId, usage, undefined, message);
await commitLocalChanges({ [STORAGE_KEYS.batchJob]: next });
return { ok: true, visionBatchJob: analysisBatchSummary(next) };
}
@@ -5778,8 +5796,16 @@ async function runPersistedAnalysisBatch() {
} catch (error) {
console.error("PromptDirector persisted analysis batch failed", error);
const stored = await chrome.storage.local.get(STORAGE_KEYS.batchJob).catch(() => ({}));
- const stillRunning = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob])?.status === "running";
- await ensureAnalysisBatchAlarm(stillRunning);
+ const current = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
+ if (current?.status === "running") {
+ const taskLabel = current.kind === "vision" ? "图片服务" : "文字服务";
+ const failed = failUnfinishedAnalysisItems(current, {
+ message: `任务启动失败:${taskLabel}配置或后台运行状态无效,请检查 AI 服务后重试`,
+ status: 500
+ });
+ await commitLocalChanges({ [STORAGE_KEYS.batchJob]: failed });
+ }
+ await ensureAnalysisBatchAlarm(false);
continueRunning = false;
} finally {
analysisBatchRunnerActive = false;
@@ -5830,6 +5856,7 @@ async function runPersistedTextBatchSlice(jobId) {
async function analyzePersistedTextClaim(job, claim, entry, catalog, settings) {
if (!entry) return persistedTextFailure(claim, "案例已不存在", 404);
+ const analysisInput = canonicalTextAnalysisInput(entry, claim.assetId);
let serviceRequests = 0;
try {
const result = await runScheduledAnalysisWithRetries({
@@ -5840,14 +5867,15 @@ async function analyzePersistedTextClaim(job, claim, entry, catalog, settings) {
return analyzeTextDetailedWithDeepSeek(entry, catalog, {
...settings,
outputLocale: job.outputLocale
- });
+ }, fetch, { analysisInput });
}
});
return {
entryId: claim.entryId,
claimId: claim.claimId,
- fingerprint: await textFingerprint(entry.text),
+ fingerprint: await textFingerprint(analysisInput.text),
textRevision: claim.textRevision,
+ assetId: analysisInput.assetId,
tags: result.tags,
normalizationDiagnostics: result.normalizationDiagnostics,
attempts: {
@@ -5890,6 +5918,14 @@ async function runPersistedVisionBatchSlice(jobId) {
job = reconcileVisionBatchResults(recoverInterruptedAnalysisBatch(job), state.entries).job;
const snapshotConfiguration = configurationForAssignment(configuration, "imageAnalysis", job);
const settings = resolveVisionTaskSettings("imageAnalysis", snapshotConfiguration, { requireConfigured: false });
+ const currentSettings = resolveVisionTaskSettings("imageAnalysis", configuration, { requireConfigured: false });
+ const currentModel = currentSettings.activeProvider === "openai" ? currentSettings.openai.model : currentSettings.compatible.model;
+ const snapshotModel = settings.activeProvider === "openai" ? settings.openai.model : settings.compatible.model;
+ if (job.providerType !== currentSettings.activeProvider || job.model !== currentModel || job.providerType !== settings.activeProvider || job.model !== snapshotModel) {
+ job = cancelAnalysisBatch(job);
+ await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job });
+ return { job, claims: [] };
+ }
const snapshotReady = publicVisionSettings(settings)[settings.activeProvider]?.configured === true;
if (!snapshotReady || !settings.consent) {
job = pauseAnalysisBatch(job);
@@ -6035,7 +6071,7 @@ async function runAutomaticVisionItem() {
const latest = requireAnalysisBatch(latestStored[STORAGE_KEYS.automaticVisionBatchJob], job.id, "vision");
requireClaim(latest, claim.entryId, claim.claimId, claim.visualId);
const next = result.ok
- ? (result.quality === "partial" ? partiallySucceedAnalysisItem : succeedAnalysisItem)(latest, claim.entryId, claim.claimId, {
+ ? succeedAnalysisItem(latest, claim.entryId, claim.claimId, {
promptTokens: result.usage?.inputTokens,
completionTokens: result.usage?.outputTokens,
totalTokens: result.usage?.totalTokens,
@@ -6475,7 +6511,8 @@ function requireClaim(job, entryId, claimId, visualId = "") {
function analysisMeta(message, fingerprint, analyzedAt, entry = {}) {
return {
...(fingerprint ? { textFingerprint: fingerprint } : {}),
- ...analysisRevisionMeta(entry),
+ textRevision: Math.max(1, Math.floor(Number(message.textRevision) || analysisRevisionMeta(entry).textRevision)),
+ ...(String(message.assetId ?? "").trim() ? { assetId: String(message.assetId).trim() } : {}),
promptVersion: ANALYSIS_PROMPT_VERSION,
model: String(message.model ?? ""),
analyzedAt,
@@ -6794,6 +6831,7 @@ function previewLibraryImport(state, library, options = {}) {
skillIdMap: result.skillIdMap,
packageAssetIdMap: result.packageAssetIdMap,
importedCount: result.importedCount,
+ remappedCount: result.remappedCount,
skippedCount: result.skippedCount,
importedRunCount: result.importedRunCount,
importedOutputCount: result.importedOutputCount,
@@ -6833,10 +6871,11 @@ async function applyLibraryImport(state, message) {
return {
ok: true,
message: result.importedCount || result.importedRunCount || result.importedSkillCount
- ? `已导入 ${result.importedCount} 个案例、${result.importedRunCount} 次创作运行和 ${result.importedSkillCount} 个 Skill${result.skippedCount || result.skippedSkillCount ? `,跳过 ${result.skippedCount} 个已有案例和 ${result.skippedSkillCount} 个已有 Skill` : ""}`
+ ? `已导入 ${result.importedCount} 个案例、${result.importedRunCount} 次创作运行和 ${result.importedSkillCount} 个 Skill${result.remappedCount ? `;其中 ${result.remappedCount} 个同源案例作为新副本导入,未覆盖旧数据` : ""}${result.skippedCount || result.skippedSkillCount ? `,跳过 ${result.skippedCount} 个已有案例和 ${result.skippedSkillCount} 个已有 Skill` : ""}`
: `没有新增内容,${result.skippedCount} 个案例已经存在`,
count: result.state.entries.length,
importedCount: result.importedCount,
+ remappedCount: result.remappedCount,
skippedCount: result.skippedCount,
importedRunCount: result.importedRunCount,
importedOutputCount: result.importedOutputCount,
diff --git a/creative-skill-service.js b/creative-skill-service.js
index 3a52a54..24758c6 100644
--- a/creative-skill-service.js
+++ b/creative-skill-service.js
@@ -188,7 +188,7 @@ export function anonymousSkillSources(entriesValue = [], selectionsValue = [], o
const selectedIds = new Set(selectedAssets.map((asset) => String(asset.id)));
const analysis = [
...selectedAssets.filter((asset) => !asset?.visionAnalysis?.invalidated)
- .map((asset) => multiline(asset?.visionAnalysis?.description)),
+ .map((asset) => multiline(asset?.visionAnalysis?.reconstructionPrompt || 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 : [])
diff --git a/curated-import.js b/curated-import.js
index a9f4714..ae6432a 100644
--- a/curated-import.js
+++ b/curated-import.js
@@ -50,6 +50,7 @@ export function mergeCuratedLibraryPackage(currentValue = {}, libraryValue = {},
sessionIdMap: options.sessionIdMap,
runIdMap: options.runIdMap,
preserveLibraryConfiguration: true,
+ skipExistingEntryIds: true,
now: projectCreatedAt
});
diff --git a/deepseek.js b/deepseek.js
index 1666fb4..299ffa3 100644
--- a/deepseek.js
+++ b/deepseek.js
@@ -17,6 +17,7 @@ import {
compileAgentExecutionPrompt,
compileAgentPlanningPrompt
} from "./composer-agent.js";
+import { canonicalTextAnalysisInput } from "./analysis-input.js";
export const DEEPSEEK_ENDPOINT = "https://api.deepseek.com/chat/completions";
export const DEFAULT_ANALYSIS_MODEL = "deepseek-v4-flash";
@@ -50,6 +51,9 @@ export function deepSeekErrorDetails(error) {
if (error instanceof DeepSeekApiError) {
return { kind: error.kind, message: error.message, retryable: error.retryable };
}
+ if (error instanceof TypeError && /fetch|network|load/i.test(String(error.message ?? ""))) {
+ return { kind: "network", message: "网络连接失败,请检查服务地址、权限或网络后重试", retryable: true };
+ }
return { kind: "unknown", message: error?.message || "DeepSeek 处理失败", retryable: false };
}
@@ -128,13 +132,14 @@ export async function analyzeTextWithDeepSeek(entry, catalogValue, settingsValue
export async function analyzeTextDetailedWithDeepSeek(entry, catalogValue, settingsValue, fetchImpl = fetch, requestOptions = {}) {
const settings = requireAiSettings(settingsValue, "分析");
const outputLocale = settingsValue?.outputLocale === "en" ? "en" : "zh-CN";
- if (!String(entry?.text ?? "").trim()) throw new Error("这条案例没有文字,DeepSeek 文字分析会跳过");
+ const input = requestOptions.analysisInput || canonicalTextAnalysisInput(entry);
+ if (!input.text) throw new Error("这条案例没有文字,DeepSeek 文字分析会跳过");
const systemMessages = [
{ role: "system", content: analysisSystemInstruction(outputLocale) },
{ role: "system", content: analysisTaxonomyPrompt(catalogValue, outputLocale) },
{ role: "system", content: settings.analysisInstructionsByLocale[outputLocale].slice(0, 1200) }
];
- const userMessage = { role: "user", content: analysisEntryInput(entry) };
+ const userMessage = { role: "user", content: analysisEntryInput(entry, input.text) };
let usage = normalizeUsage();
for (let outputAttempt = 0; outputAttempt < 2; outputAttempt += 1) {
const attempt = outputAttempt ? "correction" : "initial";
@@ -665,11 +670,11 @@ export function analysisTaxonomyPrompt(catalogValue, outputLocale = "zh-CN") {
return `fixedPaths=${analysisTaxonomyPayload(catalogValue, outputLocale)}`;
}
-function analysisEntryInput(entry) {
+function analysisEntryInput(entry, textValue = entry?.text) {
return JSON.stringify({
contentType: String(entry.contentTypeName ?? "").trim() || "unknown",
title: String(entry.title ?? ""),
- text: String(entry.text ?? "")
+ text: String(textValue ?? "")
});
}
diff --git a/i18n.js b/i18n.js
index ae13efe..e452969 100644
--- a/i18n.js
+++ b/i18n.js
@@ -393,6 +393,7 @@ const EN = Object.freeze({
"{message} · 输入 {input} / 输出 {output} tokens": "{message} · input {input} / output {output} tokens",
"正在检查本机资料…": "Checking local library…",
"资料索引已完整": "Library index is complete",
+ "需要更新索引:{types} 条内容类型,{palettes} 张图片色卡。": "Index update needed: {types} content types and {palettes} image palettes.",
"{status} · 已处理 {processed}/{total} · 成功 {succeeded} · 失败 {failed}": "{status} · processed {processed}/{total} · {succeeded} succeeded · {failed} failed",
"永久删除": "Delete permanently",
"正在撤销权限…": "Revoking permission…",
@@ -912,7 +913,7 @@ const EN = Object.freeze({
"批量分析画面": "Analyze visuals in batch",
"关闭批量画面分析": "Close batch visual analysis",
"分析所选案例中的全部未分析图片": "Analyze every unanalysed image in the selected cases",
- "重新分析已有画面描述": "Reanalyse existing visual descriptions",
+ "重新分析已有反推提示词": "Reanalyze existing reconstruction prompts",
"每次分析一张图片;失败项需手动重试。": "Images are analyzed one at a time. Retry failed items manually.",
"取消任务": "Cancel task",
"分享项目": "Share project",
@@ -1368,6 +1369,7 @@ const EN = Object.freeze({
"图片提示词": "Image prompt",
"视频提示词": "Video prompt",
"画面描述": "Visual description",
+ "反推提示词": "Reconstruction prompt",
"参考资料已更新": "References updated",
"无法读取创作资料": "Could not load creation data",
"无法打开创作台": "Could not open the prompt studio",
@@ -1613,10 +1615,10 @@ const EN = Object.freeze({
"画面描述": "Visual description",
"提示词原文": "Prompt original",
"画面描述已复制": "Visual description copied",
- "浏览器未允许复制,请选中描述后复制": "Copy was blocked. Select the description and copy it manually.",
- "编辑画面描述": "Edit visual description",
- "保存画面描述": "Save visual description",
- "画面描述已保存": "Visual description saved",
+ "浏览器未允许复制,请选中提示词后复制": "Copy was blocked. Select the prompt and copy it manually.",
+ "编辑画面描述": "Edit reconstruction prompt",
+ "保存画面描述": "Save reconstruction prompt",
+ "画面描述已保存": "Reconstruction prompt saved",
"请先完成图片视觉设置并确认截图发送范围": "Complete image vision settings and confirm the screenshot-sharing scope first.",
"选择内容类型": "Choose content type",
"保存分类": "Save classification",
@@ -1852,6 +1854,9 @@ const EN = Object.freeze({
"批量分析已停止": "Batch analysis stopped",
"分析结果提交失败": "The analysis result could not be saved",
"分析失败": "Analysis failed",
+ "有失败项": "Some items failed",
+ "将创建为根项目": "Will be created as a top-level project.",
+ "将创建在“{project}”下面": "Will be created under “{project}”.",
"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.",
diff --git a/lib.js b/lib.js
index ad9f648..93d4e62 100644
--- a/lib.js
+++ b/lib.js
@@ -261,8 +261,8 @@ function renderEntry(entry, index, taxonomy, facetCatalog, locale) {
? `[${escapeLinkText(entry.title)}](${escapeLinkUrl(sourceUrl.href)})`
: escapeLinkText(entry.title);
const fence = codeFenceFor(entry.text);
- const visionDescription = primaryVisionDescription(entry);
- const visionFence = codeFenceFor(visionDescription);
+ const reconstructionPrompt = primaryVisionDescription(entry);
+ const visionFence = codeFenceFor(reconstructionPrompt);
const screenshot = entry.visuals.flatMap((visual, visualIndex) => isSafeScreenshotPath(visual.screenshotPath)
? [`- ${english ? `Visual ${visualIndex + 1}${visual.id === entry.primaryVisualId ? " (primary)" : ""}: ` : `截图 ${visualIndex + 1}${visual.id === entry.primaryVisualId ? "(主图)" : ""}:`}![${english ? "Matching visual" : "对应画面"}](${visual.screenshotPath})`]
: []);
@@ -305,7 +305,7 @@ function renderEntry(entry, index, taxonomy, facetCatalog, locale) {
...screenshot,
"",
...(attributeLines.length ? ["### Creative attributes", "", ...attributeLines, ""] : []),
- ...(visionDescription ? ["### Visual description", "", `${visionFence}text`, visionDescription, visionFence, ""] : []),
+ ...(reconstructionPrompt ? ["### Reconstruction prompt", "", `${visionFence}text`, reconstructionPrompt, visionFence, ""] : []),
...(entry.text ? ["### Original prompt", "", `${fence}text`, entry.text, fence] : ["### Case note", "", "This visual reference contains a screenshot and creative attributes without prompt text."]),
...(suggestionLines.length ? ["", "### Suggestions awaiting review", "", ...suggestionLines] : [])
].join("\n") : [
@@ -321,7 +321,7 @@ function renderEntry(entry, index, taxonomy, facetCatalog, locale) {
...screenshot,
"",
...(attributeLines.length ? ["### AI 标签", "", ...attributeLines, ""] : []),
- ...(visionDescription ? ["### 画面描述", "", `${visionFence}text`, visionDescription, visionFence, ""] : []),
+ ...(reconstructionPrompt ? ["### 反推提示词", "", `${visionFence}text`, reconstructionPrompt, visionFence, ""] : []),
...(entry.text ? ["### 原始提示词", "", `${fence}text`, entry.text, fence] : ["### 案例说明", "", "这是一条仅包含截图和 AI 标签的图片案例。"]),
...(suggestionLines.length ? ["", "### 待确认建议", "", ...suggestionLines] : [])
].join("\n");
diff --git a/library-package.js b/library-package.js
index 1cb834e..f743528 100644
--- a/library-package.js
+++ b/library-package.js
@@ -59,6 +59,15 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
data.taxonomy = normalizeTaxonomy(data.taxonomy);
data.facetCatalog = normalizeFacetCatalog(data.facetCatalog);
data.classificationRules = Array.isArray(data.classificationRules) ? data.classificationRules : [];
+ const packageFacetIds = new Set(data.facetCatalog.facets.map((item) => item.id));
+ const packageNodeIds = new Set(data.facetCatalog.nodes.map((item) => item.id));
+ for (const entry of data.entries) {
+ const missingAssignment = (Array.isArray(entry?.facetAssignments) ? entry.facetAssignments : [])
+ .find((item) => !packageFacetIds.has(String(item?.facetId ?? "")) || !packageNodeIds.has(String(item?.nodeId ?? "")));
+ if (missingAssignment) {
+ throw new Error(`分享包中的案例“${clean(entry?.title) || clean(entry?.id) || "未命名案例"}”引用了缺失的 AI 标签词表,导入已取消`);
+ }
+ }
const ids = new Set();
const visualIds = new Set();
const assets = new Map();
@@ -373,6 +382,7 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
importedRunCount: imported.creativeRuns.length,
importedOutputCount: imported.creativeRuns.reduce((sum, run) => sum + run.outputs.length, 0),
importedCount: imported.entries.length,
+ remappedCount: 0,
skippedCount: 0
};
}
@@ -397,15 +407,22 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
const visualIdMap = { ...(options.visualIdMap ?? {}) };
const organizerEntryIdMap = {};
let importedCount = 0;
+ let remappedCount = 0;
let skippedCount = 0;
for (const source of imported.entries) {
- if (usedEntryIds.has(source.id)) {
+ const idCollision = usedEntryIds.has(source.id);
+ if (idCollision && options.skipExistingEntryIds === true) {
skippedCount += 1;
organizerEntryIdMap[source.id] = source.id;
continue;
}
const preferred = clean(options.entryIdMap?.[source.id]);
- const targetId = preferred && !usedEntryIds.has(preferred) ? preferred : source.id;
+ const targetId = preferred && !usedEntryIds.has(preferred)
+ ? preferred
+ : usedEntryIds.has(source.id)
+ ? uniqueId("entry", usedEntryIds)
+ : source.id;
+ if (idCollision) remappedCount += 1;
if (usedEntryIds.has(targetId)) throw new Error("导入期间案例库发生变化,请重试");
const entry = withoutArchivePath(structuredClone(source));
Object.assign(entry, importMetadata);
@@ -440,10 +457,18 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
assetId: visualIdMap[note.assetId] ?? note.assetId,
...(note.frameAssetId ? { frameAssetId: visualIdMap[note.frameAssetId] ?? note.frameAssetId } : {})
}));
- entry.facetAssignments = (entry.facetAssignments ?? []).flatMap((item) => {
+ entry.facetAssignments = (entry.facetAssignments ?? []).map((item) => {
const facetId = facetIds.get(item.facetId);
const nodeId = nodeIds.get(item.nodeId);
- return facetId && nodeId ? [{ ...item, facetId, nodeId }] : [];
+ if (!facetId || !nodeId) {
+ throw new Error(`分享包中的案例“${clean(entry.title) || source.id}”引用了缺失的 AI 标签词表,导入已取消且没有写入案例`);
+ }
+ return {
+ ...item,
+ facetId,
+ nodeId,
+ ...(item.visualId ? { visualId: visualIdMap[item.visualId] ?? item.visualId } : {})
+ };
});
next.entries.push(entry);
usedEntryIds.add(targetId);
@@ -529,6 +554,7 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
importedRunCount: imported.creativeRuns.length,
importedOutputCount: imported.creativeRuns.reduce((sum, run) => sum + run.outputs.length, 0),
importedCount,
+ remappedCount,
skippedCount
};
}
diff --git a/library.css b/library.css
index eb6484a..2c0857c 100644
--- a/library.css
+++ b/library.css
@@ -850,11 +850,6 @@ details:not([open]) > .selection-menu-panel { display: none; }
.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); }
.task-option input { width: auto; min-height: auto; margin-top: 2px; accent-color: var(--accent-emphasis); }
.privacy-note { margin: 0; color: var(--muted); font-size: 11px; line-height: 1.6; }
-.vision-description { display: grid; gap: 10px; }
-.vision-description-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
-.vision-description-heading h3 { margin: 0; }
-.vision-description-actions { display: flex; flex-wrap: wrap; gap: 8px; }
-.vision-description p { margin: 0; white-space: pre-wrap; color: var(--prompt-ink); font-size: 12px; line-height: 1.7; }
.vision-analysis-status { margin: 7px 0 0; color: var(--muted); font-size: 11px; font-weight: 700; line-height: 1.5; }
.vision-analysis-status.success { color: var(--accent-ink); }
.vision-analysis-status.error { color: var(--danger); }
diff --git a/library.html b/library.html
index 03074ad..dd985d5 100644
--- a/library.html
+++ b/library.html
@@ -465,8 +465,9 @@
<span id="vision-batch-service"></span>
</section>
<label class="task-option"><input id="vision-batch-all-images" type="checkbox" /><span data-i18n="分析所选案例中的全部未分析图片">分析所选案例中的全部未分析图片</span></label>
- <label class="task-option"><input id="vision-batch-reanalyze" type="checkbox" /><span data-i18n="重新分析已有画面描述">重新分析已有画面描述</span></label>
+ <label class="task-option"><input id="vision-batch-reanalyze" type="checkbox" /><span data-i18n="重新分析已有反推提示词">重新分析已有反推提示词</span></label>
<p class="data-safety-note" data-i18n="每次分析一张图片;失败项需手动重试。">每次分析一张图片;失败项需手动重试。</p>
+ <div id="vision-batch-progress" class="maintenance-progress" hidden><progress id="vision-batch-progress-bar" max="1" value="0"></progress></div>
<div class="data-safety-primary-actions">
<button id="vision-batch-start" type="button" data-i18n="确认并开始">确认并开始</button>
<button id="vision-batch-pause" class="button-secondary" type="button" hidden data-i18n="暂停">暂停</button>
diff --git a/library.js b/library.js
index f0d8e04..bba4a23 100644
--- a/library.js
+++ b/library.js
@@ -53,6 +53,7 @@ import {
normalizeComposerSettings
} from "./composer.js";
import { textFingerprint } from "./analysis-batch.js";
+import { canonicalTextAnalysisInput } from "./analysis-input.js";
import { entryTextRevision, textAnalysisReason } from "./analysis-revision.js";
import { createSimilarityIndex, rankSimilarEntries } from "./local-similarity.js";
import {
@@ -193,7 +194,7 @@ const elements = Object.fromEntries([
"open-curated", "open-skills", "open-trash", "trash-count", "trash-dialog", "trash-close", "trash-list", "trash-feedback", "trash-restore-all", "trash-empty", "data-safety-dialog", "data-safety-count", "data-safety-status", "data-safety-feedback",
"sync-settings", "data-safety-password", "sync-password", "connect-sync-folder", "unlock-sync-vault", "sync-now", "cancel-sync", "create-folder-backup", "restore-folder-backup", "import-library-package", "library-package-file", "disconnect-sync-folder", "capture-web-permission-status", "capture-clipboard-permission-status", "revoke-capture-web-permission", "revoke-capture-clipboard-permission", "capture-permission-settings-feedback",
"vision-batch-dialog", "vision-batch-close", "vision-batch-summary", "vision-batch-service", "vision-batch-all-images", "vision-batch-reanalyze",
- "vision-batch-start", "vision-batch-pause", "vision-batch-resume", "vision-batch-retry", "vision-batch-cancel", "vision-batch-feedback",
+ "vision-batch-progress", "vision-batch-progress-bar", "vision-batch-start", "vision-batch-pause", "vision-batch-resume", "vision-batch-retry", "vision-batch-cancel", "vision-batch-feedback",
"library-drop-target", "import-dialog", "import-dialog-title", "import-close", "import-source", "import-choose-files", "import-last-job", "import-actions", "import-preparing", "import-confirmation", "import-supported-count", "import-skipped-count", "import-duplicate-count", "import-byte-size", "import-project", "import-project-hint", "import-auto-analyze", "import-label-editor", "import-file-list", "import-feedback", "import-job-panel", "import-job-title", "import-job-count", "import-job-progress", "import-job-feedback", "import-cancel", "import-retry", "import-undo", "import-view-project", "import-start"
].map((id) => [camel(id), document.querySelector(`#${id}`)]));
@@ -256,7 +257,6 @@ let aiProviderRegistry = { version: 1, providers: {} };
let aiTaskAssignments = {};
let aiModelCatalogRefreshStarted = false;
let creativeExperimentSettings = { enabled: false, autoAnalyze: false };
-let visionUndoEntryIds = new Set();
let visibleEntries = [];
let renderedCount = 0;
let selectedContentId = "";
@@ -476,19 +476,19 @@ function renderAnalysisBatch() {
elements.batchStatusBadge.textContent = t("尚未开始");
elements.analysisBatchSummary.textContent = t("先生成预览,不会直接产生 API 请求。");
} else {
- const statusNames = { running: "分析中", paused: "已暂停", completed: unfinishedRebuild ? "重建待完成" : partialRebuildApplied ? "成功结果已应用" : "已完成", partial: "部分完成", failed: "分析失败", canceled: "上次已取消" };
+ const statusNames = { running: "分析中", paused: "已暂停", completed: unfinishedRebuild ? "重建待完成" : partialRebuildApplied ? "成功结果已应用" : "已完成", partial: "有失败项", failed: "分析失败", canceled: "上次已取消" };
elements.batchStatusBadge.textContent = t(statusNames[job.status] || job.status);
const progress = currentLocale() === "en"
- ? [`${job.counts.succeeded}/${job.total} completed`, `${job.counts.partial || 0} partial`, `${job.counts.running} active`, `${job.counts.pending} queued`, `${job.counts.failed} failed`, `${job.requestAttempts || 0} actual requests`, `${job.outputCorrectionRequests || 0} output corrections`, `input ${job.usage.promptTokens} / output ${job.usage.completionTokens} tokens`, `${job.cacheHitCount || 0} result cache hits`, `prompt cache ${job.usage.cacheHitTokens} tokens`, analysisFailureCategorySummary(job, "en")].filter(Boolean).join(" · ")
- : [`${job.counts.succeeded}/${job.total} 已完成`, `${job.counts.partial || 0} 待补全`, `${job.counts.running} 处理中`, `${job.counts.pending} 等待中`, `${job.counts.failed} 失败`, `真实请求 ${job.requestAttempts || 0} 次`, `结构补全 ${job.outputCorrectionRequests || 0} 次`, `输入 ${job.usage.promptTokens} / 输出 ${job.usage.completionTokens} tokens`, `结果缓存命中 ${job.cacheHitCount || 0} 次`, `提示缓存命中 ${job.usage.cacheHitTokens} tokens`, analysisFailureCategorySummary(job, "zh-CN")].filter(Boolean).join(" · ");
+ ? [`${job.counts.succeeded}/${job.total} completed`, `${job.counts.running} active`, `${job.counts.pending} queued`, `${job.counts.failed} failed`, `${job.requestAttempts || 0} actual requests`, `${job.outputCorrectionRequests || 0} output corrections`, `input ${job.usage.promptTokens} / output ${job.usage.completionTokens} tokens`, `${job.cacheHitCount || 0} result cache hits`, `prompt cache ${job.usage.cacheHitTokens} tokens`, analysisFailureCategorySummary(job, "en")].filter(Boolean).join(" · ")
+ : [`${job.counts.succeeded}/${job.total} 已完成`, `${job.counts.running} 处理中`, `${job.counts.pending} 等待中`, `${job.counts.failed} 失败`, `真实请求 ${job.requestAttempts || 0} 次`, `结构补全 ${job.outputCorrectionRequests || 0} 次`, `输入 ${job.usage.promptTokens} / 输出 ${job.usage.completionTokens} tokens`, `结果缓存命中 ${job.cacheHitCount || 0} 次`, `提示缓存命中 ${job.usage.cacheHitTokens} tokens`, analysisFailureCategorySummary(job, "zh-CN")].filter(Boolean).join(" · ");
const recovery = unfinishedRebuild
? (currentLocale() === "en"
? `${job.stagedResultCount ?? job.counts.succeeded} successful results are safely staged. ${analysisFailureSummary(job, "en")}`
: `${job.stagedResultCount ?? job.counts.succeeded} 条成功结果已安全暂存。${analysisFailureSummary(job, "zh-CN")}`)
: partialRebuildApplied
? (currentLocale() === "en"
- ? `Successful results are active. ${job.counts.failed} cases remain pending analysis.`
- : `成功结果已经生效,${job.counts.failed} 条失败案例已转为待分析。`)
+ ? `Complete successful results are active. ${job.counts.failed} failed cases were not written and can be retried.`
+ : `完整成功结果已经生效,${job.counts.failed} 条失败案例未写入,可单独重试。`)
: "";
elements.analysisBatchSummary.textContent = [progress, recovery].filter(Boolean).join(" · ");
}
@@ -505,19 +505,19 @@ function renderAnalysisBatch() {
elements.retryAnalysisFailures.textContent = unfinishedRebuild
? (currentLocale() === "en" ? `Finish rebuild (${job.counts.failed})` : `继续完成重建(${job.counts.failed} 条)`)
: currentLocale() === "en"
- ? `Retry failed/incomplete (${(job?.counts.failed || 0) + (job?.counts.partial || 0)} expected items)`
- : `重试失败/待补全(预计新增 ${(job?.counts.failed || 0) + (job?.counts.partial || 0)} 项)`;
- elements.retryAnalysisFailures.hidden = !(job?.counts.failed || job?.counts.partial) || running || partialRebuildApplied || (unfinishedRebuild && job.stagingValid !== true);
+ ? `Retry failed (${job?.counts.failed || 0})`
+ : `重试失败(${job?.counts.failed || 0} 条)`;
+ elements.retryAnalysisFailures.hidden = !job?.counts.failed || running || partialRebuildApplied || (unfinishedRebuild && job.stagingValid !== true);
elements.applyStagedAnalysisRebuild.textContent = unfinishedRebuild
? (currentLocale() === "en"
- ? `Apply ${job.stagedResultCount ?? job.counts.succeeded} successful results (${job.counts.failed} pending)`
- : `应用已成功结果(${job.counts.failed} 条待补)`)
+ ? `Apply ${job.stagedResultCount ?? job.counts.succeeded} complete results (${job.counts.failed} failed)`
+ : `应用完整成功结果(${job.counts.failed} 条失败不写入)`)
: t("应用已成功结果");
elements.applyStagedAnalysisRebuild.hidden = !unfinishedRebuild || job.stagingValid !== true;
elements.undoAnalysisBatch.hidden = !job || !canUndoAnalysisBatch || running || paused;
elements.analysisProgress.hidden = !active;
elements.analysisProgressBar.max = Math.max(1, job?.total || 1);
- elements.analysisProgressBar.value = Math.min((job?.counts?.succeeded || 0) + (job?.counts?.partial || 0) + (job?.counts?.failed || 0), job?.total || 0);
+ elements.analysisProgressBar.value = Math.min((job?.counts?.succeeded || 0) + (job?.counts?.failed || 0), job?.total || 0);
}
function analysisFailureSummary(job, locale) {
@@ -902,7 +902,6 @@ async function refreshLibrary() {
composerSettings = normalizeComposerSettings(response.composerSettings);
creativeExperimentSettings = response.creativeExperimentSettings ?? creativeExperimentSettings;
syncStatus = response.syncStatus ?? {};
- visionUndoEntryIds = new Set(response.visionUndoEntryIds ?? []);
canUndoFacetUpdate = Boolean(response.canUndoFacetUpdate);
analysisBatchJob = response.analysisBatchJob ?? null;
maintenanceJob = response.maintenanceJob ?? maintenanceJob;
@@ -940,6 +939,7 @@ async function refreshLibrary() {
if (elements.searchInput.value.trim()) scheduleSearchRender();
}).catch(() => undefined);
if (elements.managerDialog.open) renderManager();
+ if (elements.visionBatchDialog.open) renderVisionBatchDialog();
if (elements.settingsDialog.open && activeSettingsTab === "tasks") renderBatchManager();
if (currentDetailId && logicalCases.some((entry) => entry.id === currentDetailId) && !promptEditState?.dirty) await renderDetail();
scheduleMaintenanceStatusPoll();
@@ -1903,7 +1903,9 @@ async function createProjectCollection(button) {
const parent = organizerState.collections.find((item) => item.id === selectedCollectionId);
const name = await promptAppText({
title: t("新建项目"),
- description: parent ? `将创建在“${collectionPathLabel(organizerState, parent.id)}”下面` : "将创建为根项目",
+ description: parent
+ ? t("将创建在“{project}”下面", { project: collectionPathLabel(organizerState, parent.id) })
+ : t("将创建为根项目"),
label: t("项目名称"),
confirmLabel: t("新建")
});
@@ -1987,12 +1989,11 @@ async function enterVisionSelection(collection) {
caseOrderManagementActive = false;
projectOrderManagementActive = false;
selectedCollectionId = collection.id;
- selectedCaseIds.clear();
+ replaceSelectedCaseIds(getVisionSelectableEntries("all").map((entry) => entry.id));
selectedContentId = "";
selectedFacets.clear();
elements.pendingFilter.checked = false;
elements.searchInput.value = "";
- updateSelectionBar();
renderGallery();
}
@@ -2622,6 +2623,18 @@ async function openVisionBatchConfirmation() {
async function previewSelectedVisionBatch() {
if (visionBatchJob && ["running", "paused"].includes(visionBatchJob.status)) {
+ const currentModel = visionSettings.activeProvider === "openai" ? visionSettings.openai.model : visionSettings.compatible.model;
+ if (visionBatchJob.providerType !== visionSettings.activeProvider || visionBatchJob.model !== currentModel) {
+ try {
+ const response = await chrome.runtime.sendMessage({ type: "CANCEL_VISION_BATCH", jobId: visionBatchJob.id });
+ if (!response?.ok) throw new Error(response?.message || "无法取消旧批量任务");
+ visionBatchJob = response.visionBatchJob;
+ } catch (error) {
+ showVisionBatchFeedback(error.message || "无法取消旧批量任务", true);
+ return;
+ }
+ return previewSelectedVisionBatch();
+ }
renderVisionBatchDialog();
return;
}
@@ -2636,38 +2649,51 @@ async function previewSelectedVisionBatch() {
}
function renderVisionBatchDialog(preview = null) {
- const job = visionBatchJob;
- const active = job && ["running", "paused"].includes(job.status);
- const source = job ?? preview ?? {};
+ const activeJob = visionBatchJob && ["running", "paused"].includes(visionBatchJob.status) ? visionBatchJob : null;
+ const job = activeJob ?? (preview ? null : visionBatchJob);
+ const active = Boolean(activeJob);
+ const source = activeJob ?? preview ?? visionBatchJob ?? {};
const counts = job?.counts ?? {};
const requestCount = job?.requestCount ?? preview?.requestCount ?? 0;
const caseCount = preview?.caseCount ?? new Set(job?.items?.map((item) => item.entryId) ?? []).size;
+ const processedCount = Math.min(
+ requestCount,
+ (counts.succeeded ?? 0) + (counts.failed ?? 0)
+ );
elements.visionBatchSummary.textContent = job
- ? currentLocale() === "en"
- ? `${counts.succeeded ?? 0}/${requestCount} completed · ${counts.partial ?? 0} partial · ${counts.failed ?? 0} failed · ${job.requestAttempts || 0} actual requests · ${job.outputCorrectionRequests || 0} output corrections · ${job.cacheHitCount || 0} cache hits${analysisFailureCategorySummary(job, "en") ? ` · ${analysisFailureCategorySummary(job, "en")}` : ""}`
- : `${counts.succeeded ?? 0}/${requestCount} 已完成 · ${counts.partial ?? 0} 待补全 · ${counts.failed ?? 0} 失败 · 真实请求 ${job.requestAttempts || 0} 次 · 结构补全 ${job.outputCorrectionRequests || 0} 次 · 缓存命中 ${job.cacheHitCount || 0} 次${analysisFailureCategorySummary(job, "zh-CN") ? ` · ${analysisFailureCategorySummary(job, "zh-CN")}` : ""}`
+ ? active
+ ? currentLocale() === "en"
+ ? `${counts.succeeded ?? 0}/${requestCount} completed · ${counts.running ?? 0} processing · ${counts.pending ?? 0} waiting · ${counts.failed ?? 0} failed`
+ : `${counts.succeeded ?? 0}/${requestCount} 已完成 · ${counts.running ?? 0} 处理中 · ${counts.pending ?? 0} 等待中 · ${counts.failed ?? 0} 失败`
+ : currentLocale() === "en"
+ ? `${counts.succeeded ?? 0}/${requestCount} completed · ${counts.failed ?? 0} failed · ${job.requestAttempts || 0} requests · ${job.cacheHitCount || 0} cache hits${analysisFailureCategorySummary(job, "en") ? ` · ${analysisFailureCategorySummary(job, "en")}` : ""}`
+ : `${counts.succeeded ?? 0}/${requestCount} 已完成 · ${counts.failed ?? 0} 失败 · 请求 ${job.requestAttempts || 0} 次 · 缓存 ${job.cacheHitCount || 0} 次${analysisFailureCategorySummary(job, "zh-CN") ? ` · ${analysisFailureCategorySummary(job, "zh-CN")}` : ""}`
: currentLocale() === "en"
? `${caseCount} cases · ${requestCount} image requests`
: `${caseCount} 个案例 · ${requestCount} 次图片请求`;
elements.visionBatchService.textContent = [source.providerType, source.model].filter(Boolean).join(" · ");
elements.visionBatchAllImages.disabled = Boolean(active);
elements.visionBatchReanalyze.disabled = Boolean(active);
- elements.visionBatchStart.hidden = Boolean(job);
+ elements.visionBatchProgress.hidden = !job;
+ elements.visionBatchProgressBar.max = Math.max(1, requestCount || job?.requestCount || 1);
+ elements.visionBatchProgressBar.value = Math.min(processedCount, elements.visionBatchProgressBar.max);
+ elements.visionBatchStart.hidden = Boolean(activeJob);
elements.visionBatchStart.disabled = !requestCount;
- elements.visionBatchPause.hidden = !job || job.status !== "running";
- elements.visionBatchResume.hidden = !job || job.status !== "paused";
- elements.visionBatchRetry.hidden = !job || !(counts.failed || counts.partial) || job.status === "running";
+ elements.visionBatchPause.hidden = !activeJob || activeJob.status !== "running";
+ elements.visionBatchResume.hidden = !activeJob || activeJob.status !== "paused";
+ elements.visionBatchRetry.hidden = !job || !counts.failed || job.status === "running";
elements.visionBatchRetry.textContent = currentLocale() === "en"
- ? `Retry failed/incomplete (${(counts.failed || 0) + (counts.partial || 0)} expected items)`
- : `重试失败/待补全(预计新增 ${(counts.failed || 0) + (counts.partial || 0)} 项)`;
+ ? `Retry failed (${counts.failed || 0} expected items)`
+ : `重试失败项(预计新增 ${counts.failed || 0} 项)`;
elements.visionBatchCancel.hidden = !active;
if (job && !active) {
const total = job.usage?.totalTokens ?? 0;
+ const failureMessage = job.items?.find((item) => item.status === "failed")?.error || "";
const label = job.status === "completed" ? (currentLocale() === "en" ? "Completed" : "全部完成")
: job.status === "failed" ? (currentLocale() === "en" ? "Failed" : "全部失败")
: job.status === "canceled" ? (currentLocale() === "en" ? "Canceled" : "已取消")
- : (currentLocale() === "en" ? "Partially completed" : "部分完成,可重试失败或待补全项");
- showVisionBatchFeedback(`${label} · ${total} tokens` , job.status === "failed");
+ : (currentLocale() === "en" ? "Completed with failures" : "已完成,可重试失败项");
+ showVisionBatchFeedback(`${label}${failureMessage ? ` · ${failureMessage}` : ""} · ${total} tokens` , job.status === "failed");
}
}
@@ -2699,8 +2725,10 @@ async function updateVisionBatchAction(type) {
visionBatchJob = response.visionBatchJob;
showVisionBatchFeedback(response.message);
renderVisionBatchDialog();
+ return response;
} catch (error) {
showVisionBatchFeedback(error.message, true);
+ return null;
}
}
@@ -3042,7 +3070,7 @@ async function restoreCompleteFolderBackup() {
if (!preview?.ok) throw new Error(preview?.message || "无法检查资料夹备份");
const approved = await confirmAppAction({
title: "恢复资料库备份?",
- description: `将恢复 ${preview.importedCount || 0} 个新案例、${preview.importedSkillCount || 0} 个 Skill 和 ${parsed.assets.size + parsed.skillAssets.size} 项本地文件(${formatBytes(totalBytes)})。已有内容不会被覆盖。`,
+ description: `将恢复 ${preview.importedCount || 0} 个新案例、${preview.importedSkillCount || 0} 个 Skill 和 ${parsed.assets.size + parsed.skillAssets.size} 项本地文件(${formatBytes(totalBytes)})。${preview.remappedCount ? `其中 ${preview.remappedCount} 个同源案例会作为新副本导入。` : ""}已有内容不会被覆盖。`,
confirmLabel: "开始恢复"
});
if (!approved) {
@@ -3127,6 +3155,7 @@ async function importSharedLibraryPackage() {
const approved = await confirmAppAction({
title: "导入分享包?",
description: `将导入 ${preview.importedCount || 0} 个新案例和 ${parsed.assets.size} 项本地媒体` +
+ `${preview.remappedCount ? `;其中 ${preview.remappedCount} 个同源案例会作为新副本导入` : ""}` +
`${preview.skippedCount ? `,跳过 ${preview.skippedCount} 个已有案例` : ""}。现有资料不会被覆盖。`,
confirmLabel: "开始导入"
});
@@ -3773,8 +3802,6 @@ async function renderDetail({ resetScroll = false } = {}) {
if (isEntryPending(entry)) body.append(createPendingReviewPanel(entry));
const prompt = capturedPost ? null : createPromptSection(entry);
if (prompt) body.append(prompt);
- const visionDescription = createVisionDescription(entry);
- if (visionDescription) body.append(visionDescription);
const visualSetAnalyses = createVisualSetAnalyses(entry);
if (visualSetAnalyses) body.append(visualSetAnalyses);
const attributes = createDetailAttributes(entry);
@@ -3929,8 +3956,6 @@ async function renderCompoundDetail(entry, content, body) {
if (isEntryPending(member)) section.append(createPendingReviewPanel(member));
const prompt = createPromptSection(member, { compoundMember: true });
if (prompt) section.append(prompt);
- const vision = createVisionDescription(member);
- if (vision) section.append(vision);
const attributes = createDetailAttributes(member);
if (attributes) section.append(attributes);
const metadata = createDetailMetadata(member);
@@ -4385,11 +4410,6 @@ function refreshActiveDetailAssetSections(entry) {
else if (prompt) body.querySelector(":scope > .detail-header")?.after(prompt);
else currentPrompt?.remove();
- const vision = createVisionDescription(entry);
- const currentVision = body.querySelector(":scope > .vision-description");
- if (vision && currentVision) currentVision.replaceWith(vision);
- else if (vision) (body.querySelector(":scope > .prompt-section") || body.querySelector(":scope > .detail-header"))?.after(vision);
- else currentVision?.remove();
}
function handleVideoAnalysisProgress(message) {
@@ -5328,34 +5348,6 @@ async function openSingleCaseComposer(entry, targetType, assetId = "") {
}
}
-function createVisionDescription(entry) {
- const activeAssetId = activeDetailMediaIdByEntry.get(entry.id) || entry.primaryMediaId;
- const activeAsset = entryMediaAssets(entry).find((asset) => asset.id === activeAssetId && asset.kind === "image" && asset.usage !== "poster");
- const vision = activeAsset ? activeAsset.visionAnalysis : primaryVisionAnalysis(entry);
- if (!vision?.description?.trim()) return null;
- const section = el("section", "detail-section vision-description");
- const heading = el("div", "vision-description-heading");
- heading.append(textEl("h3", "", "画面描述"));
- if (vision.quality === "partial") heading.append(textEl("span", "batch-status-badge", `部分完成 · ${vision.missingFields?.length || 0} 项待补全`));
- const actions = el("div", "vision-description-actions");
- const copy = textEl("button", "button-secondary", "复制");
- copy.addEventListener("click", () => copyTextWithFeedback(
- copy,
- vision.description,
- "画面描述已复制",
- "浏览器未允许复制,请选中描述后复制"
- ));
- actions.append(copy);
- if (visionUndoEntryIds.has(entry.id)) {
- const undo = textEl("button", "button-secondary", "撤回本次分析");
- undo.addEventListener("click", () => perform(undo, { type: "UNDO_VISION_ANALYSIS", entryId: entry.id }));
- actions.append(undo);
- }
- heading.append(actions);
- section.append(heading, rawTextEl("p", "", vision.description));
- return section;
-}
-
async function analyzeEntryVision(entry, button) {
const provider = visionSettings.activeProvider === "compatible" ? visionSettings.compatible : visionSettings.openai;
if (!provider?.configured || !visionSettings.consent) {
@@ -5368,9 +5360,9 @@ async function analyzeEntryVision(entry, button) {
if (!visual) return;
if (vision) {
const message = currentLocale() === "en"
- ? `Reanalyzing will replace the ${vision.userEdited ? "manually revised description" : "previous model description"} and vision-model tags. Manual tags and DeepSeek text tags remain unchanged. Continue?`
- : `重新分析会替换${vision.userEdited ? "手动修订过的描述" : "旧模型描述"}和视觉模型标签;人工标签与 DeepSeek 文字标签不会改变。继续吗?`;
- if (!await confirmAppAction({ title: "重新分析当前画面?", description: message, confirmLabel: "重新分析" })) return;
+ ? `Reanalyzing will replace the ${vision.userEdited ? "manually revised reconstruction prompt" : "previous model reconstruction prompt"} and vision-model tags. Manual tags and DeepSeek text tags remain unchanged. Continue?`
+ : `重新分析会替换${vision.userEdited ? "手动修订过的反推提示词" : "旧模型反推提示词"}和视觉模型标签;人工标签与 DeepSeek 文字标签不会改变。继续吗?`;
+ if (!await confirmAppAction({ title: "重新分析主图?", description: message, confirmLabel: "重新分析主图" })) return;
}
const originalLabel = button.textContent;
button.disabled = true;
@@ -5382,10 +5374,9 @@ async function analyzeEntryVision(entry, button) {
entryId: entry.id,
visualId: visual.id,
outputLocale: currentLocale(),
- bypassCache: Boolean(vision && vision.quality !== "partial")
+ bypassCache: Boolean(vision)
});
if (!response?.ok) throw new Error(response?.message || "图片分析失败");
- if (response.canUndoVisionAnalysis) visionUndoEntryIds.add(entry.id);
const replacement = visualAnalysisPromptReplacement(response.entry, visual.id);
if (replacement) await reviewVisualAnalysisPromptReplacements(entry.id, [{ ...replacement, index: 1 }]);
setVisionAnalysisStatus(entry.id, "success", response.message || "画面分析已保存");
@@ -6655,6 +6646,7 @@ function createPromptSection(entry, options = {}) {
const separatesCurrentAndShared = Boolean(activeImage && (imageAssets.length > 1 || options.compoundMember));
const mediaPrompt = activeImage ? (entry.mediaPrompts || []).find((item) => item.assetId === activeImage.id) : null;
const displayedPrompt = activeImage ? promptForEntryImage(entry, activeImage.id) : String(entry.text ?? "").trim();
+ const analysisInput = canonicalTextAnalysisInput(entry, activeImage?.id || "");
if (promptEditState?.entryId === entry.id) {
const textarea = document.createElement("textarea");
textarea.className = "prompt-text prompt-editor";
@@ -6708,7 +6700,7 @@ function createPromptSection(entry, options = {}) {
const vision = primaryVisionAnalysis(entry);
const primary = primaryVisual(entry);
const analyzeVisual = primary?.kind === "image" && !entry.compoundCase
- ? textEl("button", "button-secondary", vision?.quality === "partial" ? "补全主图分析" : vision ? "重新分析主图" : "分析主图")
+ ? textEl("button", "button-secondary", vision ? "重新分析主图" : "分析主图")
: null;
const analyze = textEl("button", "button-secondary", "分析检索标签");
const edit = textEl("button", "button-secondary", separatesCurrentAndShared ? "编辑当前图片" : "编辑");
@@ -6716,7 +6708,7 @@ function createPromptSection(entry, options = {}) {
const promptReplacement = activeImage ? visualAnalysisPromptReplacement(entry, activeImage.id) : null;
const replaceAnalyzedPrompt = promptReplacement ? textEl("button", "button-secondary", "更新为 V2 提示词") : null;
copy.disabled = !displayedPrompt;
- analyze.disabled = !entry.text;
+ analyze.disabled = !analysisInput.text;
copy.addEventListener("click", () => copyTextWithFeedback(
copy,
displayedPrompt,
@@ -6724,7 +6716,7 @@ function createPromptSection(entry, options = {}) {
"浏览器未允许复制,请选中文本后复制"
));
analyzeVisual?.addEventListener("click", () => analyzeEntryVision(entry, analyzeVisual));
- analyze.addEventListener("click", () => analyzeSingleEntry(entry, analyze));
+ analyze.addEventListener("click", () => analyzeSingleEntry(entry, analyze, analysisInput));
edit.addEventListener("click", () => {
promptEditState = { entryId: entry.id, assetId: separatesCurrentAndShared ? activeImage?.id || "" : "", originalText: displayedPrompt, draftText: displayedPrompt, dirty: false };
renderDetail();
@@ -6791,7 +6783,7 @@ async function analyzeEntryVisualSet(entry, button) {
&& currentFingerprint === analysis.imageFingerprint);
if (analysis?.invalidated || !fingerprintMatches) return { valid: false, label: "分析已过期" };
if (Number(analysis?.version) === 2 && analysis?.quality !== "partial" && analysis?.reconstructionPrompt) return { valid: true, label: "有效 V2,可直接复用" };
- if (analysis?.quality === "partial") return { valid: false, label: "部分完成,待补全" };
+ if (analysis?.quality === "partial") return { valid: false, label: "分析失败,请重试" };
return { valid: false, label: "未分析" };
};
const missingAssets = assets.filter((asset) => !stateFor(asset).valid);
@@ -6887,7 +6879,6 @@ async function analyzeEntryVisualSet(entry, button) {
}
const promptSuggestions = [];
const failures = [];
- const partials = [];
await Promise.allSettled(selectedAssets.map(async (asset) => {
const imageIndex = assets.findIndex((item) => item.id === asset.id);
const card = cardByAssetId.get(asset.id);
@@ -6904,17 +6895,15 @@ async function analyzeEntryVisualSet(entry, button) {
});
if (!response?.ok) throw new Error(response?.message || "逐图分析失败");
const partial = response.quality === "partial";
- if (partial) partials.push({ index: imageIndex + 1, missingFields: response.missingFields ?? [] });
- else completedAssetIds.add(asset.id);
+ if (partial) throw new Error("图片分析结果不完整,请重试");
+ completedAssetIds.add(asset.id);
const input = dialogControls?.get(`asset_${imageIndex}`);
- if (input && !partial) {
+ if (input) {
input.checked = false;
input.disabled = true;
}
- if (card) card.dataset.state = partial ? "partial" : "completed";
- if (statusLabel) statusLabel.textContent = partial
- ? t("待补全 · 已保存有效结果")
- : t("本次已完成");
+ if (card) card.dataset.state = "completed";
+ if (statusLabel) statusLabel.textContent = t("本次已完成");
updateSelectionSummary();
const replacement = visualAnalysisPromptReplacement(response.entry, asset.id);
if (replacement) savedPromptSuggestions.set(asset.id, { ...replacement, index: imageIndex + 1 });
@@ -6925,12 +6914,11 @@ async function analyzeEntryVisualSet(entry, button) {
if (statusLabel) statusLabel.textContent = t("失败 · {message}", { message });
}
}));
- if (failures.length || partials.length) {
+ if (failures.length) {
const statusLine = status();
statusLine.classList.add("error");
- statusLine.textContent = t("{failed} 张失败,{partial} 张待补全,已成功 {completed} 张且不会重复请求。可直接重试失败或待补全项。", {
+ statusLine.textContent = t("{failed} 张失败,已成功 {completed} 张且不会重复请求。可直接重试失败项。", {
failed: failures.length,
- partial: partials.length,
completed: completedAssetIds.size
});
await refreshLibrary();
@@ -6988,19 +6976,6 @@ function createEntryEditor(entry, options = {}) {
});
body.append(textEl("h4", "", "内容类型"), classification);
}
- const vision = primaryVisionAnalysis(entry);
- const visual = primaryVisual(entry);
- if (vision && visual) {
- const field = el("label", "vision-edit-field");
- const textarea = document.createElement("textarea");
- textarea.value = vision.description;
- field.append(textEl("span", "sr-only", "画面描述"), textarea);
- const saveDescription = textEl("button", "button-secondary", "保存");
- saveDescription.addEventListener("click", () => perform(saveDescription, {
- type: "UPDATE_VISION_DESCRIPTION", entryId: entry.id, visualId: visual.id, description: textarea.value
- }));
- body.append(textEl("h4", "", "画面描述"), field, saveDescription);
- }
const grouped = groupEntryAssignments(entry, facetCatalog, "confirmed");
const selected = el("div", "selected-edit-tags");
for (const facet of facetCatalog.facets.filter((item) => item.status === "active").sort((a, b) => a.order - b.order)) {
@@ -8214,7 +8189,7 @@ async function applyStagedAnalysisRebuild() {
}
}
-async function analyzeEntryWithRetry(entry, catalog, settingsValue, outputLocale = currentLocale(), signal, onDiagnostic) {
+async function analyzeEntryWithRetry(entry, catalog, settingsValue, outputLocale = currentLocale(), signal, onDiagnostic, analysisInput) {
const reportDiagnostic = typeof onDiagnostic === "function"
? (event) => onDiagnostic(event.stage, event)
: undefined;
@@ -8228,7 +8203,8 @@ async function analyzeEntryWithRetry(entry, catalog, settingsValue, outputLocale
serviceRequests += 1;
return analyzeTextDetailedWithDeepSeek(entry, catalog, { ...settingsValue, outputLocale }, fetch, {
signal,
- onDiagnostic: reportDiagnostic
+ onDiagnostic: reportDiagnostic,
+ analysisInput
});
}
});
@@ -8248,18 +8224,19 @@ async function analyzeEntryWithRetry(entry, catalog, settingsValue, outputLocale
}
}
-async function analyzeSingleEntry(entry, button) {
+async function analyzeSingleEntry(entry, button, analysisInput = canonicalTextAnalysisInput(entry)) {
button.disabled = true;
try {
const settingsValue = await privateAiSettings();
- const fingerprint = await textFingerprint(entry.text);
- const result = await analyzeEntryWithRetry(entry, facetCatalog, settingsValue, currentLocale());
+ const fingerprint = await textFingerprint(analysisInput.text);
+ const result = await analyzeEntryWithRetry(entry, facetCatalog, settingsValue, currentLocale(), undefined, undefined, analysisInput);
const profileFingerprint = await analysisProfileFingerprint(settingsValue, currentLocale());
const response = await chrome.runtime.sendMessage({
type: "APPLY_ENTRY_ANALYSIS_RESULT",
entryId: entry.id,
fingerprint,
- textRevision: entryTextRevision(entry),
+ textRevision: analysisInput.textRevision,
+ assetId: analysisInput.assetId,
tags: result.tags,
normalizationDiagnostics: result.normalizationDiagnostics,
attempts: result.attempts,
@@ -8403,8 +8380,11 @@ function renderReanalysisPreview() {
const wrapper = el("div", "");
const nothingMissing = !reanalysisPreview.confirmed && !reanalysisPreview.suggested && !reanalysisPreview.paletteCount;
wrapper.append(textEl("strong", "", nothingMissing
- ? "资料索引已完整"
- : `待补全:${reanalysisPreview.confirmed} 条内容类型,${reanalysisPreview.paletteCount} 张图片色卡。`));
+ ? t("资料索引已完整")
+ : t("需要更新索引:{types} 条内容类型,{palettes} 张图片色卡。", {
+ types: reanalysisPreview.confirmed,
+ palettes: reanalysisPreview.paletteCount
+ })));
const list = el("div", "reanalyze-case-list");
reanalysisPreview.cases.forEach((item) => list.append(rawTextEl("p", "", `${item.title}:${t("确认")} ${item.confirmed},${currentLocale() === "en" ? "suggestions" : "建议"} ${item.suggested}`)));
wrapper.append(list);
diff --git a/manifest.json b/manifest.json
index 4c5b712..4519e4c 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.19.0",
+ "version": "1.19.1",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq2m8W9ACXJTkJqPAd36sPrtzonmHhOYU34uS7c+D7DXX6ggWNMwB4xZapGFJ4ScBQJv71PeG9KfsEnhcXFZ9RoX/X3wY+57evL19hf6woNX1xxhKOe1rtx5QmzWCEYIr99TzW50k/N9U6tS9Ri+2DHKYA85ssXTC8B2yRQ5zUXhsAWZe/HDU18UFuvUKXYt3ZdIUi31c2vIlgFFBfsyKbIUMny9LlxL/smb4vJzU/+A3LwJDjjvOtS/lmQ2vHoQGjHJItO18bYI6h67fIEvmWk+HJKtO08Ca+5RLS8TYhI+K7l7S0RyDVNujyVWtvhAULot1H0BvteYL87fKu3SNywIDAQAB",
"homepage_url": "https://github.com/wchao6891/PromptDirector",
"default_locale": "zh_CN",
diff --git a/media.js b/media.js
index 4ea90b1..e428df0 100644
--- a/media.js
+++ b/media.js
@@ -94,7 +94,9 @@ export function normalizeMediaAsset(value = {}) {
...(kind === "video" && storageMode === "reference" && reference.url ? { reference } : {}),
...(localAssetReference ?? {}),
...(value.palette?.colors?.length ? { palette: structuredClone(value.palette) } : {}),
- ...(value.visionAnalysis?.description?.trim() ? { visionAnalysis: structuredClone(value.visionAnalysis) } : {}),
+ ...(String(value.visionAnalysis?.reconstructionPrompt ?? value.visionAnalysis?.description ?? "").trim()
+ ? { visionAnalysis: structuredClone(value.visionAnalysis) }
+ : {}),
reviewStatus: value.reviewStatus === "verified" ? "verified" : "unverified"
};
}
@@ -331,7 +333,9 @@ export function setEntryMediaPrompt(entryValue, assetIdValue, textValue, source
export function mediaDescriptions(entryValue = {}) {
return entryMediaAssets(entryValue)
- .map((asset) => asset.visionAnalysis?.invalidated ? "" : clean(asset.visionAnalysis?.description))
+ .map((asset) => asset.visionAnalysis?.invalidated || asset.visionAnalysis?.quality === "partial"
+ ? ""
+ : clean(asset.visionAnalysis?.reconstructionPrompt || asset.visionAnalysis?.description))
.filter(Boolean);
}
diff --git a/package-lock.json b/package-lock.json
index d25a6ee..e93910c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "prompt-case-collector",
- "version": "1.19.0",
+ "version": "1.19.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.19.0",
+ "version": "1.19.1",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
diff --git a/package.json b/package.json
index d0a3bcf..ec0e9a2 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.19.0",
+ "version": "1.19.1",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
diff --git a/share-preview.js b/share-preview.js
index 21e8486..2166c0f 100644
--- a/share-preview.js
+++ b/share-preview.js
@@ -2,7 +2,7 @@ import { libraryTitleForLocale, normalizeSettings } from "./lib.js";
import { entryAttributeSummary } from "./library-model.js";
import { normalizeTaxonomy } from "./taxonomy.js";
import { normalizeFacetCatalog } from "./facets.js";
-import { entryPalette, normalizeEntryVisuals, primaryVisionDescription } from "./visuals.js";
+import { entryPalette, normalizeEntryVisuals } from "./visuals.js";
import { posterAssetForVideo, primaryMediaAsset } from "./media.js";
import { createSimilarityIndex, rankSimilarEntries } from "./local-similarity.js";
import { promptForEntryImage } from "./image-prompt.js";
@@ -318,7 +318,6 @@ function renderDetail(entry, index, taxonomy, facetCatalog, relatedEntries) {
const sourceUrl = safeWebUrl(entry.url);
const primary = primaryMediaAsset(entry);
const prompt = primary?.kind === "image" ? promptForEntryImage(entry, primary.id) : clean(entry.text);
- const visionDescription = primaryVisionDescription(entry);
const metadataRows = renderMetadataRows(entry.metadataLabels);
const timeNotes = renderTimeNotes(entry, media);
const related = relatedEntries.length
@@ -331,7 +330,6 @@ function renderDetail(entry, index, taxonomy, facetCatalog, relatedEntries) {
<section class="detail-section detail-heading"><p class="eyebrow">PROMPTDIRECTOR</p><h2>${escapeHtml(title)}</h2><div class="detail-meta"><span data-zh="${escapeAttribute(contentZh)}" data-en="${escapeAttribute(contentEn)}">${escapeHtml(contentZh)}</span>${dateZh ? `<span data-zh="${escapeAttribute(dateZh)}" data-en="${escapeAttribute(dateEn)}">${escapeHtml(dateZh)}</span>` : ""}<span>${media.length} <span data-zh="项媒体" data-en="media items">项媒体</span></span></div>${palette.length ? `<div class="palette">${palette.map((color) => `<i style="background:${color}" title="${color}"></i>`).join("")}</div>` : ""}</section>
${attributes.length ? `<section class="detail-section"><h3 data-zh="AI 标签" data-en="AI tags">AI 标签</h3><div class="detail-tags">${attributes.map((item) => `<span title="${escapeAttribute(item.label)}">${escapeHtml(item.leafLabel)}</span>`).join("")}</div></section>` : ""}
${prompt ? `<section class="detail-section prompt-section"><div class="section-heading"><h3 data-zh="提示词" data-en="Prompt">提示词</h3><button class="button-secondary compact" type="button" data-copy-prompt="${escapeAttribute(prompt)}"><span data-zh="复制提示词" data-en="Copy prompt">复制提示词</span></button></div><pre class="prompt-text">${escapeHtml(prompt)}</pre><p class="compose-guide" data-zh="导入 PromptDirector 后可将当前图片作为具体参考继续创作。" data-en="Import this package into PromptDirector to continue creating with the current image as a specific reference.">导入 PromptDirector 后可将当前图片作为具体参考继续创作。</p></section>` : ""}
- ${visionDescription ? `<section class="detail-section"><h3 data-zh="画面描述" data-en="Visual description">画面描述</h3><p class="visual-description">${escapeHtml(visionDescription)}</p></section>` : ""}
${metadataRows || sourceUrl ? `<section class="detail-section"><div class="section-heading"><h3 data-zh="来源" data-en="Source">来源</h3>${sourceUrl ? `<a class="source-open-action" href="${escapeAttribute(sourceUrl)}" target="_blank" rel="noreferrer"><span data-zh="打开来源" data-en="Open source">打开来源</span></a>` : ""}</div>${metadataRows}</section>` : ""}
${timeNotes}
</aside>
@@ -349,7 +347,6 @@ function renderDetailMedia(entry, media, title) {
function renderMediaAsset(entry, asset, title) {
const prompt = clean(entry.mediaPrompts?.find((item) => item.assetId === asset.id)?.text);
- const description = clean(asset.visionAnalysis?.description);
let content;
if (asset.kind === "image") {
const path = safeArchiveMediaPath(asset.assetPath, asset);
@@ -373,7 +370,7 @@ function renderMediaAsset(entry, asset, title) {
? `<div class="document-panel"><strong>${escapeHtml(assetFormatLabel(asset))}</strong><span>${escapeHtml(asset.sourceTitle || title)}</span><small>${escapeHtml(assetFileSummary(asset))}</small><a class="button-primary" href="${escapeAttribute(path)}" download><span data-zh="下载源文件" data-en="Download source file">下载源文件</span></a></div>`
: renderExternalMedia(asset, label);
}
- const caption = prompt || description ? `<div class="media-caption">${prompt ? `<p><strong data-zh="本图提示词" data-en="Media prompt">本图提示词</strong>${escapeHtml(prompt)}</p>` : ""}${description ? `<p><strong data-zh="画面描述" data-en="Visual description">画面描述</strong>${escapeHtml(description)}</p>` : ""}</div>` : "";
+ const caption = prompt ? `<div class="media-caption"><p><strong data-zh="本图提示词" data-en="Media prompt">本图提示词</strong>${escapeHtml(prompt)}</p></div>` : "";
return `${content}${caption}`;
}
diff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/CHROME_WEB_STORE_SUBMISSION.md
index b765ea7..19c9c04 100644
--- a/store/CHROME_WEB_STORE_SUBMISSION.md
+++ b/store/CHROME_WEB_STORE_SUBMISSION.md
@@ -6,9 +6,9 @@ This file is the source-of-truth worksheet for the current PromptDirector manife
- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.
- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.
-- Current release candidate: `dist/PromptDirector-1.19.0.zip`.
-- Candidate size: `8,616,920` bytes.
-- Candidate SHA-256: `03620a885fcc7eb6590d8d08d1f41da24307367207f0eb42a63f31e3961207d8`.
+- Current release candidate: `dist/PromptDirector-1.19.1.zip`.
+- Candidate size: `8,628,576` bytes.
+- Candidate SHA-256: `75ac89066fa94aa2b21876796de9986173b6f3f8020bda9ef07d27e610ec12dd`.
- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest.
## Store listing
diff --git a/temp-references.js b/temp-references.js
index dc111ee..3f47918 100644
--- a/temp-references.js
+++ b/temp-references.js
@@ -100,7 +100,12 @@ export function imageTempReferenceBlock(referenceSnapshots, service) {
export function unreadReferenceImageAssets(reference) {
const analyzedAssets = new Map((Array.isArray(reference?.assets) ? reference.assets : [])
.map((item) => [String(item?.assetId ?? "").trim(), item]));
- if (String(reference?.referenceText ?? "").trim() && !analyzedAssets.size) return [];
+ const promptBacked = Boolean(
+ String(reference?.originalText ?? "").trim()
+ || (["prompt", "prompt_vision"].includes(reference?.referenceKind)
+ && String(reference?.referenceText ?? "").trim())
+ );
+ if (promptBacked || (String(reference?.referenceText ?? "").trim() && !analyzedAssets.size)) return [];
const assets = [];
const seen = new Set();
for (const asset of Array.isArray(reference?.assetRefs) ? reference.assetRefs : []) {
diff --git a/test/ai-background-v4.test.js b/test/ai-background-v4.test.js
index 89f5a88..88d9909 100644
--- a/test/ai-background-v4.test.js
+++ b/test/ai-background-v4.test.js
@@ -38,7 +38,7 @@ test("background keeps service profiles for job execution but stops publishing o
assert.doesNotMatch(source, /aiTaskRoutes:/);
});
-test("persisted batch recovery wakes the runner while runner exceptions wait for the alarm", () => {
+test("persisted batch recovery wakes the runner while runner exceptions become visible failures", () => {
const recovery = source.slice(
source.indexOf("async function recoverDeepSeekBatch"),
source.indexOf("async function undoDeepSeekBatch")
@@ -50,5 +50,32 @@ test("persisted batch recovery wakes the runner while runner exceptions wait for
source.indexOf("async function runPersistedAnalysisBatch"),
source.indexOf("async function runPersistedTextBatchSlice")
);
- assert.match(runner, /catch \(error\)[\s\S]*ensureAnalysisBatchAlarm\(stillRunning\)[\s\S]*continueRunning = false/);
+ assert.match(runner, /catch \(error\)[\s\S]*failUnfinishedAnalysisItems\(current,[\s\S]*commitLocalChanges\(\{ \[STORAGE_KEYS\.batchJob\]: failed \}\)/);
+ assert.match(runner, /ensureAnalysisBatchAlarm\(false\)[\s\S]*continueRunning = false/);
+});
+
+test("vision batch runner cancels stale model snapshots instead of blocking new settings", () => {
+ const claim = source.slice(
+ source.indexOf("async function claimVisionBatchItem"),
+ source.indexOf("async function completeVisionBatchItem")
+ );
+ const runner = source.slice(
+ source.indexOf("async function runPersistedVisionBatchSlice"),
+ source.indexOf("async function finalizeVisionBatchResults")
+ );
+ assert.match(claim, /const currentSettings = resolveVisionTaskSettings\("imageAnalysis", loadedConfiguration, \{ requireConfigured: false \}\);/);
+ assert.match(claim, /job\.providerType !== currentSettings\.activeProvider \|\| job\.model !== currentModel/);
+ assert.match(claim, /const canceled = cancelAnalysisBatch\(job\)/);
+ assert.match(runner, /const currentSettings = resolveVisionTaskSettings\("imageAnalysis", configuration, \{ requireConfigured: false \}\);/);
+ assert.match(runner, /job\.providerType !== currentSettings\.activeProvider \|\| job\.model !== currentModel/);
+ assert.match(runner, /job = cancelAnalysisBatch\(job\)/);
+});
+
+test("vision retries and structured-output correction share one per-image provider-call budget", () => {
+ const scheduled = source.slice(
+ source.indexOf("async function analyzeVisionBlobWithScheduler"),
+ source.indexOf("async function analyzeEntryVideo")
+ );
+ assert.match(scheduled, /const requestBudget = createVisionRequestBudget\(\)/);
+ assert.match(scheduled, /runScheduledAnalysisWithRetries\([\s\S]*analyzeImageWithVision\([\s\S]*requestBudget/);
});
diff --git a/test/ai_provider_registry_e2e.py b/test/ai_provider_registry_e2e.py
index 592e65f..5b2997b 100644
--- a/test/ai_provider_registry_e2e.py
+++ b/test/ai_provider_registry_e2e.py
@@ -64,7 +64,7 @@ def complete_visual_analysis() -> dict:
"reconstructionPrompt": "深色背景中的中央主体,保持清晰轮廓和居中构图。",
"limitations": ["无法确认画外信息"],
"completeness": {"checkedRegions": ["四角", "主体", "背景", "文字"], "omittedVisibleElements": []},
- "tags": [],
+ "tags": [{"g": "camera.composition", "t": "居中构图"}],
}
@@ -192,7 +192,7 @@ def assert_deepseek_dynamic_image_analysis() -> None:
expect(model_select).to_have_value(model_id)
expect(model_select.locator("option")).to_have_text(model_id)
expect(dialog.locator(".model-capability-help")).to_have_count(1)
- expect(dialog.locator(".model-capability-help")).to_have_text("当前模型未声明这项能力;是否可用以真实执行结果为准")
+ expect(dialog.locator(".model-capability-help")).to_contain_text("当前模型未声明这项能力;是否可用以真实执行结果为准")
expect(dialog).not_to_contain_text("实验")
dialog.get_by_role("button", name="保存任务默认").click()
expect(dialog).to_be_hidden()
@@ -205,6 +205,7 @@ def assert_deepseek_dynamic_image_analysis() -> None:
"providerId": "deepseek",
"model": model_id,
"evidence": "manual_unverified",
+ "concurrency": 10,
}, stored_assignment
runtime = library.evaluate(
"() => chrome.runtime.sendMessage({type: 'GET_AI_TASK_RUNTIME', taskId: 'imageAnalysis'})"
@@ -229,7 +230,8 @@ def assert_deepseek_dynamic_image_analysis() -> None:
content = request["messages"][0]["content"]
assert [item["type"] for item in content] == ["text", "image_url"], content
assert "JSON property names are case-sensitive" in content[0]["text"], content[0]
- assert '\"ocr\":{\"type\":\"array\"' in content[0]["text"], content[0]
+ assert '\"required\":[\"reconstructionPrompt\",\"tags\"]' in content[0]["text"], content[0]
+ assert '\"ocr\"' not in content[0]["text"], content[0]
assert content[1]["image_url"]["url"].startswith("data:image/png;base64,"), content
assert not openai_paid_requests, openai_paid_requests
@@ -297,8 +299,20 @@ def assert_new_install_defaults() -> None:
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
+ assert all(value["providerId"] == "" and value["model"] == "" for value in stored["aiTaskAssignments"].values()), stored
+ assert {
+ task_id: value["concurrency"]
+ for task_id, value in stored["aiTaskAssignments"].items()
+ } == {
+ "textTags": 20,
+ "skillExtraction": 20,
+ "creativePlanning": 20,
+ "imageAnalysis": 10,
+ "videoAnalysis": 10,
+ "imageGeneration": 10,
+ "videoGeneration": 10,
+ }, stored
+ assert stored["aiProviderRegistry"]["version"] == 5, stored
execution_state = library.evaluate(
"() => chrome.runtime.sendMessage({type: 'GET_CREATIVE_JOB_EXECUTION_STATE'})"
@@ -664,7 +678,9 @@ def main() -> None:
task_dialog = library.locator("#promptdirector-app-dialog")
expect(task_dialog.locator('[data-field-id="providerId"]')).to_be_visible()
expect(task_dialog.locator('[data-field-id="model"]')).to_be_visible()
- expect(task_dialog.locator('[data-field-id]')).to_have_count(2)
+ expect(task_dialog.locator('[data-field-id="concurrency"]')).to_be_visible()
+ expect(task_dialog.locator('[data-field-id="concurrency"] input')).to_have_value("10")
+ expect(task_dialog.locator('[data-field-id="highConcurrencyConfirmed"]')).to_be_hidden()
task_dialog.locator(".app-dialog-close").click()
stored = library.evaluate("() => chrome.storage.local.get(['aiProviderRegistry', 'aiTaskAssignments'])")
@@ -709,7 +725,7 @@ def main() -> None:
nano_saved = library.evaluate("() => chrome.storage.local.get(['aiProviderRegistry', 'aiTaskAssignments'])")
assert nano_saved["aiTaskAssignments"]["imageGeneration"] == {
- "providerId": "gemini", "model": "gemini-3.1-flash-image"
+ "providerId": "gemini", "model": "gemini-3.1-flash-image", "concurrency": 10
}
assert assignment_routes({
task: value for task, value in nano_saved["aiTaskAssignments"].items() if task != "imageGeneration"
diff --git a/test/analysis-batch.test.js b/test/analysis-batch.test.js
index 69ebf82..0361970 100644
--- a/test/analysis-batch.test.js
+++ b/test/analysis-batch.test.js
@@ -12,7 +12,6 @@ import {
finalizeAnalysisRebuild,
failAnalysisItem,
pauseAnalysisBatch,
- partiallySucceedAnalysisItem,
previewAnalysisBatch,
finalizePartialAnalysisRebuild,
resumeAnalysisBatch,
@@ -24,6 +23,7 @@ import {
textFingerprint,
previewVisionBatch,
createVisionBatchJob,
+ normalizeAnalysisBatchJob,
reconcileVisionBatchResults,
recoverInterruptedAnalysisBatch
} from "../analysis-batch.js";
@@ -56,8 +56,19 @@ test("manual text and vision batches run from the persistent background queue",
test("batch preview selects only text cases that are new or changed", async () => {
const unchanged = await textFingerprint("same prompt");
const preview = await previewAnalysisBatch([
- { id: "same", text: "same prompt", analysisMeta: { textFingerprint: unchanged, promptVersion: ANALYSIS_PROMPT_VERSION } },
- { id: "changed", text: "new prompt", textRevision: 2, analysisMeta: { textRevision: 1, textFingerprint: "old", promptVersion: ANALYSIS_PROMPT_VERSION } },
+ {
+ id: "same",
+ text: "same prompt",
+ analysisMeta: { textFingerprint: unchanged, promptVersion: ANALYSIS_PROMPT_VERSION },
+ facetAssignments: [{ source: "deepseek_text", nodeId: "node:same" }]
+ },
+ {
+ id: "changed",
+ text: "new prompt",
+ textRevision: 2,
+ analysisMeta: { textRevision: 1, textFingerprint: "old", promptVersion: ANALYSIS_PROMPT_VERSION },
+ facetAssignments: [{ source: "deepseek_text", nodeId: "node:changed" }]
+ },
{ id: "new", text: "first analysis" },
{ id: "image", text: "" }
]);
@@ -66,12 +77,42 @@ test("batch preview selects only text cases that are new or changed", async () =
assert.deepEqual(preview.reasonCounts, { missing_analysis: 1, text_changed: 1, explicit_reanalysis: 0 });
});
+test("batch preview uses the same canonical primary-image prompt and revision as detail analysis", async () => {
+ const entry = {
+ id: "media-prompt",
+ title: "带逐图提示词",
+ text: "",
+ primaryMediaId: "image-b",
+ mediaAssets: [
+ { id: "image-a", kind: "image" },
+ { id: "image-b", kind: "image" }
+ ],
+ mediaPrompts: [
+ { assetId: "image-b", text: "当前图片提示词", updatedAt: "2026-08-21T09:30:00.000Z" }
+ ],
+ facetAssignments: []
+ };
+ const preview = await previewAnalysisBatch([entry]);
+ assert.deepEqual(preview.entries.map((item) => ({
+ entryId: item.entryId,
+ textRevision: item.textRevision,
+ characterCount: item.characterCount,
+ reason: item.reason
+ })), [{
+ entryId: "media-prompt",
+ textRevision: Date.parse("2026-08-21T09:30:00.000Z"),
+ characterCount: "当前图片提示词".length,
+ reason: "missing_analysis"
+ }]);
+});
+
test("analysis profile changes never queue unchanged text in the default incremental preview", async () => {
const unchanged = await textFingerprint("same prompt");
const preview = await previewAnalysisBatch([{
id: "same",
text: "same prompt",
- analysisMeta: { textFingerprint: unchanged, promptVersion: ANALYSIS_PROMPT_VERSION, profileFingerprint: "old-profile" }
+ analysisMeta: { textFingerprint: unchanged, promptVersion: ANALYSIS_PROMPT_VERSION, profileFingerprint: "old-profile" },
+ facetAssignments: [{ source: "deepseek_text", nodeId: "node:same" }]
}], { profileFingerprint: "new-profile" });
assert.equal(preview.mode, "incremental");
assert.equal(preview.caseCount, 0);
@@ -168,7 +209,8 @@ test("matching text and analysis profile do not queue a paid request", async ()
const preview = await previewAnalysisBatch([{
id: "same",
text: "same prompt",
- analysisMeta: { textFingerprint: unchanged, profileFingerprint: "same-profile" }
+ analysisMeta: { textFingerprint: unchanged, profileFingerprint: "same-profile" },
+ facetAssignments: [{ source: "deepseek_text", nodeId: "node:same" }]
}], { profileFingerprint: "same-profile" });
assert.equal(preview.caseCount, 0);
});
@@ -188,6 +230,68 @@ test("legacy DeepSeek results receive a text baseline instead of being sent agai
assert.equal(baseline.entries[0].analysisMeta.textFingerprint, undefined);
});
+test("dangling text analysis metadata is still queued until committed deepseek tags exist", async () => {
+ const preview = await previewAnalysisBatch([{
+ id: "dangling",
+ text: "共享提示词",
+ textRevision: 4,
+ analysisMeta: { textRevision: 4, model: "old" },
+ analyzedAt: "2026-08-21T00:00:00.000Z",
+ facetAssignments: []
+ }]);
+ assert.deepEqual(preview.entries.map((item) => item.entryId), ["dangling"]);
+ assert.deepEqual(preview.reasonCounts, { missing_analysis: 1, text_changed: 0, explicit_reanalysis: 0 });
+});
+
+test("vision preview skips only analyses with a reusable reconstruction prompt and tags", () => {
+ const preview = previewVisionBatch([{
+ id: "case",
+ title: "视觉案例",
+ primaryMediaId: "image-a",
+ mediaAssets: [
+ {
+ id: "image-a",
+ kind: "image",
+ visionAnalysis: {
+ version: 2,
+ description: "只有描述",
+ reconstructionPrompt: "只有反推提示词但没有本图标签",
+ quality: "complete"
+ }
+ },
+ {
+ id: "image-b",
+ kind: "image",
+ visionAnalysis: {
+ version: 2,
+ description: "完整分析",
+ reconstructionPrompt: "可复用提示词",
+ tags: [{ g: "style.render", t: "赛璐珞" }],
+ quality: "complete"
+ }
+ },
+ {
+ id: "image-c",
+ kind: "image",
+ visionAnalysis: {
+ version: 2,
+ description: "partial",
+ reconstructionPrompt: "不应视为完成",
+ tags: [{ g: "style.render", t: "赛璐珞" }],
+ quality: "partial"
+ }
+ }
+ ],
+ facetAssignments: [{ source: "vision_model", visualId: "image-b", nodeId: "style.render" }]
+ }], {
+ entryIds: ["case"],
+ includeAllImages: true,
+ reanalyze: false
+ });
+ assert.equal(preview.skippedAnalyzedCount, 1);
+ assert.deepEqual(preview.items.map((item) => item.visualId), ["image-a", "image-c"]);
+});
+
test("pausing and immediately resuming preserves active claims to prevent duplicate paid requests", async () => {
let job = await createAnalysisBatchJob([{ id: "a", text: "one" }, { id: "b", text: "two" }], { id: "job", now: "2026-07-18T00:00:00Z", outputLocale: "en" });
assert.equal(job.outputLocale, "en");
@@ -364,13 +468,19 @@ test("settled batch status distinguishes complete, partial, and failed outcomes"
assert.equal(complete.status, "completed");
});
-test("a saved partial item remains retryable and only the incomplete item is requeued", async () => {
- let job = await createAnalysisBatchJob([{ id: "a", text: "one" }, { id: "b", text: "two" }], { id: "saved-partial" });
- const claims = claimAnalysisItems(job, 2, (() => { let index = 0; return () => `partial-${++index}`; })());
- job = succeedAnalysisItem(claims.job, "a", "partial-1", { totalTokens: 5 });
- job = partiallySucceedAnalysisItem(job, "b", "partial-2", { totalTokens: 7 });
- assert.equal(job.status, "partial");
- assert.deepEqual(analysisBatchSummary(job).counts, { pending: 0, running: 0, succeeded: 1, partial: 1, failed: 0 });
+test("legacy incomplete text items migrate to failures and retry without a partial state", () => {
+ let job = normalizeAnalysisBatchJob({
+ version: 2,
+ kind: "text_tags",
+ id: "saved-partial",
+ status: "partial",
+ items: [
+ { entryId: "a", status: "succeeded", attempts: 1 },
+ { entryId: "b", status: "partial", attempts: 1, error: "分析结果待补全" }
+ ]
+ });
+ assert.deepEqual(analysisBatchSummary(job).counts, { pending: 0, running: 0, succeeded: 1, partial: 0, failed: 1 });
+ assert.match(job.items[1].error, /不完整.*重试/);
job = retryFailedAnalysisItems(job);
assert.equal(job.items[0].status, "succeeded");
@@ -426,6 +536,7 @@ test("batch jobs snapshot configured concurrency and vision claims use it", () =
assert.deepEqual(job.retryPolicy, {
serviceRetries: 2,
outputCorrectionRequests: 1,
+ maxProviderCallsPerItem: 3,
backoffMs: [1000, 3000],
obeyRetryAfter: true
});
@@ -439,7 +550,17 @@ test("vision batch defaults to one primary image per selected case and can inclu
primaryMediaId: "one-a",
mediaAssets: [
{ id: "one-a", kind: "image", usage: "content" },
- { id: "one-b", kind: "image", usage: "content", visionAnalysis: { description: "already analysed", quality: "complete" } },
+ {
+ id: "one-b",
+ kind: "image",
+ usage: "content",
+ visionAnalysis: {
+ description: "already analysed",
+ reconstructionPrompt: "可复用提示词",
+ tags: [{ g: "style.render", t: "赛璐珞" }],
+ quality: "complete"
+ }
+ },
{ id: "one-c", kind: "image", usage: "content", visionAnalysis: { description: "usable partial", quality: "partial", missingFields: ["canvas"] } },
{ id: "one-poster", kind: "image", usage: "poster" }
]
@@ -501,7 +622,8 @@ test("vision batch resumes after a saved result without paying for the same imag
kind: "image",
usage: "content",
visionAnalysis: {
- description: "云端白龙与少女",
+ reconstructionPrompt: "云端白龙盘旋在少女身后,电影级逆光与冷暖对比",
+ tags: [{ g: "style.render", t: "电影感" }],
batchJobId: "vision-job",
usage: { inputTokens: 40, outputTokens: 20, totalTokens: 60 }
}
@@ -514,3 +636,28 @@ test("vision batch resumes after a saved result without paying for the same imag
assert.equal(reconciled.job.usage.totalTokens, 60);
assert.deepEqual(claimAnalysisItems(reconciled.job, 1).claims, []);
});
+
+test("legacy partial vision items migrate to failed so the UI can retry them", () => {
+ const normalized = normalizeAnalysisBatchJob({
+ version: 2,
+ kind: "vision",
+ id: "legacy-vision",
+ status: "partial",
+ items: [{
+ entryId: "one",
+ visualId: "one-a",
+ status: "partial",
+ error: "分析结果待补全"
+ }]
+ });
+
+ assert.equal(normalized.items[0].status, "failed");
+ assert.equal(normalized.items[0].error, "旧版图片分析结果不完整,请重试");
+ assert.deepEqual(analysisBatchSummary(normalized).counts, {
+ pending: 0,
+ running: 0,
+ succeeded: 0,
+ partial: 0,
+ failed: 1
+ });
+});
diff --git a/test/analysis-candidates.test.js b/test/analysis-candidates.test.js
index 46e125a..99628a9 100644
--- a/test/analysis-candidates.test.js
+++ b/test/analysis-candidates.test.js
@@ -7,6 +7,7 @@ import {
applyAnalysisImport,
applyTextAnalysisTags,
applyVisionAnalysis,
+ editVisionReconstructionPrompt,
extractStructureCandidates,
invalidateVisionForScreenshot,
mergeAnalysisCandidates,
@@ -466,24 +467,26 @@ test("vision analysis replaces only vision tags and can be undone once", () => {
state = applyFixedAnalysisTags(state, "image", [{ g: "style.render", t: "人工风格" }], { source: "manual" }).state;
state = applyFixedAnalysisTags(state, "image", [{ g: "style.render", t: "文字标签" }], { source: "deepseek_text", replaceExisting: false }).state;
state = applyFixedAnalysisTags(state, "image", [{ g: "style.render", t: "旧视觉标签" }], { source: "vision_model", replaceExisting: false }).state;
- state.entries[0].visionAnalysis = { description: "旧描述", imageFingerprint: "old", userEdited: true };
+ state.entries[0].visionAnalysis = { reconstructionPrompt: "旧反推提示词", imageFingerprint: "old", userEdited: true };
const beforeNodeIds = state.entries[0].facetAssignments.map((item) => item.nodeId);
const applied = applyVisionAnalysis(state, "image", {
- description: "新描述",
+ reconstructionPrompt: "新反推提示词:逆光人物站在潮湿街道中央,电影写实风格。",
tags: [
{ g: "style.render", t: "人工风格" },
{ g: "light.direction", t: "逆光" }
]
}, { imageFingerprint: "new", locale: "zh-CN", providerType: "openai", model: "gpt-5-mini" });
const entry = applied.state.entries[0];
- assert.equal(entry.visionAnalysis.description, "新描述");
+ assert.equal(entry.visionAnalysis.reconstructionPrompt, "新反推提示词:逆光人物站在潮湿街道中央,电影写实风格。");
+ assert.equal(Object.hasOwn(entry.visionAnalysis, "description"), false);
+ assert.equal(entry.visionAnalysis.quality, "complete");
assert.equal(entry.visionAnalysis.tags.length, 2);
assert.deepEqual(entry.facetAssignments.map((item) => item.source).sort(), ["deepseek_text", "manual", "vision_model"]);
assert.equal(entry.facetAssignments.find((item) => item.nodeId === beforeNodeIds[0]).source, "manual");
assert.equal(applied.appliedCount, 2);
const undone = undoVisionAnalysis(applied.state, applied.undo);
- assert.equal(undone.entries[0].visionAnalysis.description, "旧描述");
+ assert.equal(undone.entries[0].visionAnalysis.reconstructionPrompt, "旧反推提示词");
assert.deepEqual(undone.entries[0].facetAssignments.map((item) => item.nodeId).sort(), beforeNodeIds.sort());
assert.equal(undone.facetCatalog.nodes.some((item) => item.name === "逆光" && item.parentId === "light.direction"), false);
});
@@ -506,13 +509,34 @@ test("screenshot replacement invalidates vision references and undo restores the
assert.deepEqual(restored.facetAssignments.map((item) => item.source).sort(), ["manual", "vision_model"]);
});
-test("vision analysis stores zero to six tags and safely caps an over-limit result", () => {
- for (const returned of [0, 3, 6]) {
+test("vision analysis atomically requires a reconstruction prompt and at least one valid search tag", () => {
+ const original = {
+ facetCatalog: createDefaultFacetCatalog(),
+ entries: [{
+ id: "atomic",
+ facetAssignments: [{ facetId: "style", nodeId: "style.render", status: "confirmed", source: "manual" }],
+ visionAnalysis: { reconstructionPrompt: "上一版完整提示词", quality: "complete" }
+ }]
+ };
+ assert.throws(() => applyVisionAnalysis(original, "atomic", {
+ reconstructionPrompt: "只有提示词,没有标签",
+ tags: []
+ }), /至少.*标签|1–6|标签/);
+ assert.throws(() => applyVisionAnalysis(original, "atomic", {
+ reconstructionPrompt: "",
+ tags: [{ g: "style.render", t: "电影写实" }]
+ }), /反推提示词|重建提示词/);
+ assert.equal(original.entries[0].visionAnalysis.reconstructionPrompt, "上一版完整提示词");
+ assert.equal(original.entries[0].facetAssignments.length, 1);
+});
+
+test("vision analysis stores one to six tags and safely caps an over-limit result", () => {
+ for (const returned of [1, 3, 6]) {
const applied = applyVisionAnalysis({
facetCatalog: createDefaultFacetCatalog(),
entries: [{ id: `image-${returned}`, facetAssignments: [] }]
}, `image-${returned}`, {
- description: `description ${returned}`,
+ reconstructionPrompt: `prompt ${returned}`,
tags: Array.from({ length: returned }, (_, index) => ({ g: "style.render", t: `标签${index + 1}` }))
}, { imageFingerprint: "image" });
assert.equal(applied.appliedCount, returned);
@@ -521,12 +545,27 @@ test("vision analysis stores zero to six tags and safely caps an over-limit resu
const capped = applyVisionAnalysis({
facetCatalog: createDefaultFacetCatalog(), entries: [{ id: "too-many", facetAssignments: [] }]
}, "too-many", {
- description: "description", tags: Array.from({ length: 7 }, (_, index) => ({ g: "style.render", t: `标签${index}` }))
+ reconstructionPrompt: "prompt", tags: Array.from({ length: 7 }, (_, index) => ({ g: "style.render", t: `标签${index}` }))
});
assert.equal(capped.appliedCount, 6);
assert.equal(capped.state.entries[0].facetAssignments.length, 6);
});
+test("manual visual edits update only the reconstruction prompt", () => {
+ const original = {
+ visionAnalysis: {
+ reconstructionPrompt: "旧反推提示词",
+ tags: [{ tagId: "style.cinematic", label: "电影感" }],
+ quality: "complete"
+ }
+ };
+ const edited = editVisionReconstructionPrompt(original, "新的详细反推提示词");
+ assert.equal(edited.visionAnalysis.reconstructionPrompt, "新的详细反推提示词");
+ assert.equal(edited.visionAnalysis.description, undefined);
+ assert.deepEqual(edited.visionAnalysis.tags, original.visionAnalysis.tags);
+ assert.equal(edited.visionAnalysis.userEdited, true);
+});
+
test("image analysis can retain a reusable breakdown while promoting only six results", () => {
const incoming = Array.from({ length: 10 }, (_, index) => ({
dimensionName: "视觉风格",
diff --git a/test/analysis-input.test.js b/test/analysis-input.test.js
new file mode 100644
index 0000000..e851464
--- /dev/null
+++ b/test/analysis-input.test.js
@@ -0,0 +1,78 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { canonicalTextAnalysisInput, hasCommittedTextAnalysisTags } from "../analysis-input.js";
+
+test("canonical text analysis input prefers the primary image prompt over shared text", () => {
+ const entry = {
+ id: "entry",
+ text: "共享提示词",
+ textRevision: 3,
+ primaryMediaId: "image-b",
+ mediaAssets: [
+ { id: "image-a", kind: "image" },
+ { id: "image-b", kind: "image" }
+ ],
+ mediaPrompts: [
+ { assetId: "image-a", text: "其他图提示词", textRevision: 2, updatedAt: "2026-08-20T10:00:00.000Z" },
+ { assetId: "image-b", text: "当前图片提示词", textRevision: 1, updatedAt: "2026-08-21T09:30:00.000Z" }
+ ]
+ };
+
+ assert.deepEqual(canonicalTextAnalysisInput(entry), {
+ text: "当前图片提示词",
+ textRevision: Date.parse("2026-08-21T09:30:00.000Z"),
+ source: "media_prompt",
+ assetId: "image-b"
+ });
+});
+
+test("canonical text analysis input falls back to shared text when no primary image prompt is present", () => {
+ assert.deepEqual(canonicalTextAnalysisInput({
+ id: "entry",
+ text: "共享提示词",
+ textRevision: 5,
+ mediaAssets: [{ id: "image-a", kind: "image" }],
+ mediaPrompts: [{ assetId: "image-a", text: " " }]
+ }), {
+ text: "共享提示词",
+ textRevision: 5,
+ source: "entry_text",
+ assetId: "image-a"
+ });
+});
+
+test("canonical text analysis input can target the image currently shown in detail", () => {
+ const entry = {
+ id: "entry",
+ text: "共享提示词",
+ textRevision: 5,
+ primaryMediaId: "image-a",
+ mediaAssets: [
+ { id: "image-a", kind: "image" },
+ { id: "image-b", kind: "image" }
+ ],
+ mediaPrompts: [
+ { assetId: "image-a", text: "主图提示词", updatedAt: "2026-08-20T10:00:00.000Z" },
+ { assetId: "image-b", text: "当前查看图片提示词", updatedAt: "2026-08-22T10:00:00.000Z" }
+ ]
+ };
+
+ assert.deepEqual(canonicalTextAnalysisInput(entry, "image-b"), {
+ text: "当前查看图片提示词",
+ textRevision: Date.parse("2026-08-22T10:00:00.000Z"),
+ source: "media_prompt",
+ assetId: "image-b"
+ });
+});
+
+test("only committed deepseek_text facet assignments count as completed text analysis", () => {
+ assert.equal(hasCommittedTextAnalysisTags({
+ analysisMeta: { textRevision: 1 },
+ analyzedAt: "2026-08-20T00:00:00.000Z",
+ facetAssignments: []
+ }), false);
+ assert.equal(hasCommittedTextAnalysisTags({
+ facetAssignments: [{ source: "deepseek_text", nodeId: "node:1" }]
+ }), true);
+});
diff --git a/test/analysis-revision.test.js b/test/analysis-revision.test.js
index 4bed4b0..aab7723 100644
--- a/test/analysis-revision.test.js
+++ b/test/analysis-revision.test.js
@@ -24,7 +24,8 @@ test("only a real text edit advances the revision and becomes incremental work",
id: "entry",
text: "same",
textRevision: 4,
- analysisMeta: { textRevision: 4 }
+ analysisMeta: { textRevision: 4 },
+ facetAssignments: [{ source: "deepseek_text", nodeId: "node:1" }]
};
assert.equal(textAnalysisReason(markEntryTextChanged(original, "same")), "");
const changed = markEntryTextChanged(original, "changed");
@@ -35,6 +36,13 @@ test("only a real text edit advances the revision and becomes incremental work",
test("new text without prior analysis is immediately counted as missing", () => {
assert.equal(textAnalysisReason({ id: "new", text: "first" }), "missing_analysis");
+ assert.equal(textAnalysisReason({
+ id: "image-only",
+ text: "",
+ primaryMediaId: "image-a",
+ mediaAssets: [{ id: "image-a", kind: "image" }],
+ mediaPrompts: [{ assetId: "image-a", text: "当前图片提示词", updatedAt: "2026-08-21T00:00:00.000Z" }]
+ }), "missing_analysis");
assert.equal(textAnalysisReason({ id: "empty", text: "" }), "");
});
@@ -46,3 +54,33 @@ test("prompt edits reject stale revisions and keep media cases valid when text i
assert.equal(cleared.textRevision, 5);
assert.throws(() => updateEntryText({ id: "text-only", text: "old", textRevision: 1 }, "", 1), /不能为空/);
});
+
+test("editing shared text keeps its own revision even when the primary image has a newer prompt", () => {
+ const entry = {
+ id: "mixed",
+ text: "共享提示词",
+ textRevision: 4,
+ primaryMediaId: "image-a",
+ mediaAssets: [{ id: "image-a", kind: "image" }],
+ mediaPrompts: [{
+ assetId: "image-a",
+ text: "图片提示词",
+ updatedAt: "2026-08-22T10:00:00.000Z"
+ }]
+ };
+
+ assert.equal(entryTextRevision(entry), 4);
+ const updated = updateEntryText(entry, "新的共享提示词", 4);
+ assert.equal(updated.textRevision, 5);
+});
+
+test("analysis metadata alone does not suppress missing analysis when deepseek tags are absent", () => {
+ assert.equal(textAnalysisReason({
+ id: "dangling-meta",
+ text: "共享提示词",
+ textRevision: 2,
+ analysisMeta: { textRevision: 2 },
+ analyzedAt: "2026-08-21T00:00:00.000Z",
+ facetAssignments: []
+ }), "missing_analysis");
+});
diff --git a/test/automatic-vision.test.js b/test/automatic-vision.test.js
index 6b34ba6..410ef47 100644
--- a/test/automatic-vision.test.js
+++ b/test/automatic-vision.test.js
@@ -9,7 +9,17 @@ const entries = [{
mediaAssets: [
{ id: "image-one", kind: "image", usage: "content" },
{ id: "image-two", kind: "image", usage: "content" },
- { id: "image-done", kind: "image", usage: "content", visionAnalysis: { description: "already analyzed" } },
+ {
+ id: "image-done",
+ kind: "image",
+ usage: "content",
+ visionAnalysis: {
+ version: 2,
+ quality: "complete",
+ reconstructionPrompt: "already analyzed",
+ tags: [{ g: "light.direction", t: "逆光" }]
+ }
+ },
{ id: "video-poster", kind: "image", usage: "poster" }
]
}];
diff --git a/test/composer.test.js b/test/composer.test.js
index 3f9d112..d16e3bc 100644
--- a/test/composer.test.js
+++ b/test/composer.test.js
@@ -484,6 +484,11 @@ test("DeepSeek failures expose safe retry categories", () => {
assert.equal(deepSeekErrorDetails(new DeepSeekApiError("rate", 429)).kind, "rate_limit");
assert.equal(deepSeekErrorDetails(new DeepSeekApiError("timeout", 408)).kind, "timeout");
assert.equal(deepSeekErrorDetails(new DOMException("Aborted", "AbortError")).kind, "stopped");
+ assert.deepEqual(deepSeekErrorDetails(new TypeError("Failed to fetch")), {
+ kind: "network",
+ message: "网络连接失败,请检查服务地址、权限或网络后重试",
+ retryable: true
+ });
assert.equal(deepSeekErrorDetails(new Error("unexpected response")).kind, "unknown");
});
diff --git a/test/composer_temp_references_e2e.py b/test/composer_temp_references_e2e.py
index fbd9f81..a7ea99b 100644
--- a/test/composer_temp_references_e2e.py
+++ b/test/composer_temp_references_e2e.py
@@ -89,7 +89,7 @@ def main() -> None:
"reconstructionPrompt": "Centered subject with a clear silhouette and controlled contrast.",
"limitations": [],
"completeness": {"checkedRegions": ["full frame"], "omittedVisibleElements": []},
- "tags": [],
+ "tags": [{"g": "camera.composition", "t": "主体居中"}],
}),
"usage": {"input_tokens": 12, "output_tokens": 8, "total_tokens": 20},
}),
@@ -213,7 +213,7 @@ def main() -> None:
}""",
session_id,
)
- assert len(vision_requests) == 2, vision_requests
+ assert len(vision_requests) == 1, vision_requests
assert len(composer_requests) == 2, composer_requests
assert analyzed == [
{"kind": "vision", "text": "Centered subject with a clear silhouette and controlled contrast."},
diff --git a/test/deepseek-analysis-input.test.js b/test/deepseek-analysis-input.test.js
new file mode 100644
index 0000000..9da200c
--- /dev/null
+++ b/test/deepseek-analysis-input.test.js
@@ -0,0 +1,35 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { analyzeTextDetailedWithDeepSeek } from "../deepseek.js";
+import { createFixedFacetCatalog } from "../tag-taxonomy.js";
+
+test("detail text analysis sends the canonical primary-image prompt to DeepSeek", async () => {
+ const requests = [];
+ const result = await analyzeTextDetailedWithDeepSeek({
+ id: "entry",
+ title: "案例",
+ text: "共享提示词",
+ primaryMediaId: "image-a",
+ mediaAssets: [{ id: "image-a", kind: "image" }],
+ mediaPrompts: [{ assetId: "image-a", text: "当前图片提示词", updatedAt: "2026-08-21T09:30:00.000Z" }]
+ }, createFixedFacetCatalog(), {
+ apiKey: "test-key",
+ consent: true,
+ analysisModel: "deepseek-v4-flash"
+ }, async (_url, options) => {
+ requests.push(JSON.parse(options.body));
+ return {
+ ok: true,
+ json: async () => ({
+ choices: [{ finish_reason: "stop", message: { content: JSON.stringify({ tags: [{ g: "subject.character", t: "角色" }] }) } }],
+ usage: { total_tokens: 9 }
+ })
+ };
+ });
+
+ assert.equal(result.tags.length, 1);
+ const userMessage = requests[0].messages.find((item) => item.role === "user");
+ assert.match(userMessage.content, /当前图片提示词/);
+ assert.doesNotMatch(userMessage.content, /共享提示词/);
+});
diff --git a/test/large_library_e2e.py b/test/large_library_e2e.py
index 366f364..ff14334 100644
--- a/test/large_library_e2e.py
+++ b/test/large_library_e2e.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import json
import tempfile
import time
from pathlib import Path
@@ -30,7 +31,7 @@ def main() -> None:
setup.goto(f"chrome-extension://{extension_id}/collector.html")
setup.evaluate(
"""async () => {
- const [{createDefaultTaxonomy}, {createDefaultFacetCatalog}, {createDefaultOrganizerState}] = await Promise.all([
+ const [{createDefaultTaxonomy, SCHEMA_VERSION}, {createDefaultFacetCatalog}, {createDefaultOrganizerState}] = await Promise.all([
import(chrome.runtime.getURL('taxonomy.js')),
import(chrome.runtime.getURL('facets.js')),
import(chrome.runtime.getURL('organizer.js'))
@@ -41,7 +42,7 @@ def main() -> None:
const width = 720 + (index % 5) * 120;
const height = 720 + (index % 7) * 150;
return {
- schemaVersion: 22,
+ schemaVersion: SCHEMA_VERSION,
id: caseId,
text: `Large library prompt ${index}`,
textRevision: index ? 1 : 2,
@@ -63,7 +64,7 @@ def main() -> None:
analysisMeta: {textRevision: 1, promptVersion: 1, model: 'existing'},
facetAssignments: [{
facetId: 'style', nodeId: `large-style-${index % 400}`,
- source: 'manual', status: 'confirmed'
+ source: index ? 'deepseek_text' : 'manual', status: 'confirmed'
}],
analysisCandidates: [],
analysisBreakdown: [],
@@ -78,11 +79,12 @@ def main() -> None:
})));
await chrome.storage.local.clear();
await chrome.storage.local.set({
- schemaVersion: 22,
+ schemaVersion: SCHEMA_VERSION,
entries,
taxonomy: createDefaultTaxonomy(),
facetCatalog,
organizerState: createDefaultOrganizerState(),
+ trashState: {version: 1, items: []},
compoundCases: [],
classificationRules: []
});
@@ -107,8 +109,32 @@ def main() -> None:
ready_ms = round((time.perf_counter() - started) * 1000)
assert ready_ms < 5_000, f"6500-case first usable paint took {ready_ms}ms"
+ analysis_requests = []
+
+ def mock_analysis(route) -> None:
+ analysis_requests.append(route.request.post_data_json)
+ route.fulfill(
+ status=200,
+ content_type="application/json",
+ body=json.dumps({
+ "model": "isolated-e2e",
+ "choices": [{
+ "finish_reason": "stop",
+ "message": {"content": json.dumps({
+ "tags": [{"g": "style.render", "t": "赛璐珞"}],
+ }, ensure_ascii=False)},
+ }],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 4, "total_tokens": 14},
+ }, ensure_ascii=False),
+ )
+
+ context.route("https://api.deepseek.com/**", mock_analysis)
batch = library.evaluate(
"""async () => {
+ const {createAnalysisBatchJob, claimAnalysisItems} = await import(chrome.runtime.getURL('analysis-batch.js'));
+ const payloadJob = await createAnalysisBatchJob([{id: 'payload-check', text: 'payload check'}], {concurrency: 20});
+ const payloadClaimed = claimAnalysisItems(payloadJob, 1, () => 'payload-claim');
+ const payloadItem = payloadClaimed.claims[0];
await chrome.runtime.sendMessage({
type: 'UPDATE_AI_PROVIDER_CONFIGURATION',
registry: {providers: {deepseek: {
@@ -119,29 +145,24 @@ def main() -> None:
assignments: {textTags: {providerId: 'deepseek', model: 'isolated-e2e'}}
});
const created = await chrome.runtime.sendMessage({type: 'CREATE_ANALYSIS_BATCH'});
- const claimed = await chrome.runtime.sendMessage({
- type: 'CLAIM_ANALYSIS_ITEMS',
- jobId: created.analysisBatchJob.id
- });
- const item = claimed.claims[0];
- const committed = await chrome.runtime.sendMessage({
- type: 'COMMIT_ANALYSIS_ITEMS',
- jobId: created.analysisBatchJob.id,
- results: [{
- entryId: item.entryId,
- claimId: item.claimId,
- textRevision: item.textRevision,
- tags: [{g: 'style.render', t: '赛璐珞'}],
- usage: {},
- model: 'isolated-e2e'
- }]
- });
+ let completed = created.analysisBatchJob;
+ for (let index = 0; index < 120 && ['running', 'paused'].includes(completed.status); index += 1) {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ completed = (await chrome.runtime.sendMessage({
+ type: 'GET_ANALYSIS_BATCH_STATUS',
+ jobId: created.analysisBatchJob.id
+ })).analysisBatchJob;
+ }
+ const stored = await chrome.storage.local.get(['entries', 'facetCatalog']);
+ const savedEntry = stored.entries.find(item => item.id === 'large-00000');
+ const savedNodeIds = new Set(savedEntry.facetAssignments.filter(item => item.source === 'deepseek_text').map(item => item.nodeId));
return {
createdTotal: created.analysisBatchJob.total,
- claimCount: claimed.claims.length,
- claimHasEntry: Object.hasOwn(item, 'entry'),
- claimHasCatalog: Object.hasOwn(claimed, 'facetCatalog'),
- completedStatus: committed.analysisBatchJob.status
+ claimCount: payloadClaimed.claims.length,
+ claimHasEntry: Object.hasOwn(payloadItem, 'entry'),
+ claimHasCatalog: Object.hasOwn(payloadClaimed, 'facetCatalog'),
+ completedStatus: completed.status,
+ savedTag: stored.facetCatalog.nodes.some(item => savedNodeIds.has(item.id) && item.name === '赛璐珞')
};
}"""
)
@@ -151,7 +172,9 @@ def main() -> None:
"claimHasEntry": False,
"claimHasCatalog": False,
"completedStatus": "completed",
+ "savedTag": True,
}, batch
+ assert len(analysis_requests) == 1, analysis_requests
style_facet = library.locator('.facet-filter[data-facet-id="style"]')
style_facet.locator("summary").click()
diff --git a/test/lib.test.js b/test/lib.test.js
index d1878d3..d893aa2 100644
--- a/test/lib.test.js
+++ b/test/lib.test.js
@@ -193,18 +193,22 @@ test("screenshot-only cases can have no prompt text and export as image referenc
assert.doesNotMatch(markdown, /### 原始提示词/);
});
-test("Markdown backup keeps the current visual description without exposing provider metadata", () => {
+test("Markdown backup keeps the current reconstruction prompt without exposing provider metadata", () => {
const markdown = renderMarkdown([{
id: "vision-case",
title: "Visual case",
text: "",
visuals: [{ id: "vision-1", visionAnalysis: {
- description: "A courtyard surrounded by blue-green mist.", providerType: "compatible", model: "private-model"
+ reconstructionPrompt: "A courtyard surrounded by blue-green mist.",
+ tags: [{ tagId: "style.cinematic", label: "Cinematic" }],
+ providerType: "compatible",
+ model: "private-model"
} }],
primaryVisualId: "vision-1",
classification: { pathIds: [CONTENT_IDS.imageCase], status: "confirmed" }
}]);
- assert.match(markdown, /### 画面描述[\s\S]*A courtyard surrounded by blue-green mist\./);
+ assert.match(markdown, /### 反推提示词[\s\S]*A courtyard surrounded by blue-green mist\./);
+ assert.doesNotMatch(markdown, /### 画面描述/);
assert.doesNotMatch(markdown, /private-model|compatible/);
});
diff --git a/test/library-interaction-regressions.test.js b/test/library-interaction-regressions.test.js
index b9ec732..a12204a 100644
--- a/test/library-interaction-regressions.test.js
+++ b/test/library-interaction-regressions.test.js
@@ -2,13 +2,14 @@ import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
-const [library, html, css, background, composerHtml, composerCss] = await Promise.all([
+const [library, html, css, background, composerHtml, composerCss, i18n] = await Promise.all([
readFile(new URL("../library.js", import.meta.url), "utf8"),
readFile(new URL("../library.html", import.meta.url), "utf8"),
readFile(new URL("../library.css", import.meta.url), "utf8"),
readFile(new URL("../background.js", import.meta.url), "utf8"),
readFile(new URL("../composer.html", import.meta.url), "utf8"),
- readFile(new URL("../composer-page.css", import.meta.url), "utf8")
+ readFile(new URL("../composer-page.css", import.meta.url), "utf8"),
+ readFile(new URL("../i18n.js", import.meta.url), "utf8")
]);
test("project visibility uses the clicked control and updates the wall without a redundant reload", () => {
@@ -54,6 +55,77 @@ test("library refresh waits for detail rebuilding before returning control", ()
assert.match(refreshLibrary, /if \(currentDetailId[\s\S]*await renderDetail\(\)/);
});
+test("vision batch dialog only revives running or paused jobs and otherwise shows the fresh preview", () => {
+ const previewSelectedVisionBatch = library.slice(
+ library.indexOf("async function previewSelectedVisionBatch"),
+ library.indexOf("function renderVisionBatchDialog")
+ );
+ const renderVisionBatchDialog = library.slice(
+ library.indexOf("function renderVisionBatchDialog"),
+ library.indexOf("async function startSelectedVisionBatch")
+ );
+ assert.match(previewSelectedVisionBatch, /visionBatchJob && \["running", "paused"\]\.includes\(visionBatchJob\.status\)/);
+ assert.match(renderVisionBatchDialog, /const activeJob = visionBatchJob && \["running", "paused"\]\.includes\(visionBatchJob\.status\) \? visionBatchJob : null/);
+ assert.match(renderVisionBatchDialog, /const source = activeJob \?\? preview \?\? visionBatchJob \?\? \{\}/);
+ assert.match(renderVisionBatchDialog, /elements\.visionBatchStart\.hidden = Boolean\(activeJob\)/);
+ assert.match(renderVisionBatchDialog, /elements\.visionBatchPause\.hidden = !activeJob \|\| activeJob\.status !== "running"/);
+ assert.match(renderVisionBatchDialog, /elements\.visionBatchResume\.hidden = !activeJob \|\| activeJob\.status !== "paused"/);
+ assert.match(renderVisionBatchDialog, /elements\.visionBatchCancel\.hidden = !active/);
+ assert.match(renderVisionBatchDialog, /elements\.visionBatchProgress\.hidden = !job/);
+ assert.match(renderVisionBatchDialog, /elements\.visionBatchProgressBar\.max = Math\.max\(1, requestCount \|\| job\?\.requestCount \|\| 1\)/);
+ assert.match(renderVisionBatchDialog, /elements\.visionBatchProgressBar\.value = Math\.min\(processedCount, elements\.visionBatchProgressBar\.max\)/);
+ assert.match(previewSelectedVisionBatch, /visionBatchJob\.providerType !== visionSettings\.activeProvider \|\| visionBatchJob\.model !== currentModel/);
+ assert.match(previewSelectedVisionBatch, /chrome\.runtime\.sendMessage\(\{ type: "CANCEL_VISION_BATCH", jobId: visionBatchJob\.id \}\)/);
+});
+
+test("image-analysis UI keeps one prompt surface instead of duplicating the reconstruction prompt", () => {
+ const createPromptSection = library.slice(
+ library.indexOf("function createPromptSection"),
+ library.indexOf("async function analyzeEntryVisualSet")
+ );
+ const createEntryEditor = library.slice(
+ library.indexOf("function createEntryEditor"),
+ library.indexOf("function removeReferenceCard")
+ );
+ assert.match(html, /id="vision-batch-reanalyze"[\s\S]*重新分析已有反推提示词/);
+ assert.doesNotMatch(html, /id="vision-batch-reanalyze"[\s\S]*重新分析已有画面描述/);
+ assert.match(html, /id="vision-batch-progress"[\s\S]*id="vision-batch-progress-bar"/);
+ assert.doesNotMatch(library, /function createVisionDescription|vision-description|撤回本次分析/);
+ assert.match(createPromptSection, /promptForEntryImage/);
+ assert.match(createPromptSection, /复制提示词/);
+ assert.doesNotMatch(createEntryEditor, /UPDATE_VISION_RECONSTRUCTION_PROMPT|vision-edit-field/);
+ assert.doesNotMatch(createEntryEditor, /反推提示词/);
+ assert.doesNotMatch(createEntryEditor, /画面描述/);
+ assert.match(i18n, /"重新分析已有反推提示词": "Reanalyze existing reconstruction prompts"/);
+ assert.match(i18n, /"反推提示词": "Reconstruction prompt"/);
+});
+
+test("analysis progress reports failures without exposing incomplete-result wording", () => {
+ const renderAnalysisBatch = library.slice(
+ library.indexOf("function renderAnalysisBatch"),
+ library.indexOf("function analysisFailureSummary")
+ );
+ assert.doesNotMatch(renderAnalysisBatch, /待补全|重试失败\/待补全|部分完成/);
+ assert.doesNotMatch(renderAnalysisBatch, /\$\{job\.counts\.partial \|\| 0\} partial/);
+});
+
+test("detail text analysis follows the currently displayed image prompt", () => {
+ const createPromptSection = library.slice(
+ library.indexOf("function createPromptSection"),
+ library.indexOf("async function analyzeEntryVisualSet")
+ );
+ const analyzeSingleEntry = library.slice(
+ library.indexOf("async function analyzeSingleEntry"),
+ library.indexOf("async function privateAiSettings")
+ );
+ assert.match(createPromptSection, /canonicalTextAnalysisInput\(entry, activeImage\?\.id \|\| ""\)/);
+ assert.match(createPromptSection, /analyze\.disabled = !analysisInput\.text/);
+ assert.match(createPromptSection, /analyzeSingleEntry\(entry, analyze, analysisInput\)/);
+ assert.match(analyzeSingleEntry, /fingerprint = await textFingerprint\(analysisInput\.text\)/);
+ assert.match(analyzeSingleEntry, /assetId: analysisInput\.assetId/);
+ assert.doesNotMatch(analyzeSingleEntry, /textFingerprint\(entry\.text\)/);
+});
+
test("composer keeps only primary controls exposed and moves secondary choices into one settings menu", () => {
assert.match(composerHtml, /class="composer-options-panel"/);
assert.match(composerHtml, /id="composer-applied-skills"[^>]*hidden/);
diff --git a/test/library-large-e2e.py b/test/library-large-e2e.py
index 2a5e35e..312c7b9 100644
--- a/test/library-large-e2e.py
+++ b/test/library-large-e2e.py
@@ -144,19 +144,17 @@ def main() -> None:
started = time.perf_counter()
project.click()
expect(project).to_have_attribute("aria-pressed", "true")
- expect(library.locator("#active-filter-badge")).to_have_text("筛选 1")
project_switch_ms = (time.perf_counter() - started) * 1000
project_menu = library.locator("#collection-filters details.project-menu")
project_menu.locator("summary").click()
started = time.perf_counter()
- project_menu.get_by_role("button", name="批量分析画面").click()
+ project_menu.get_by_role("button", name="批量分析", exact=True).click()
library.locator("#project-selection-title").filter(has_text="批量分析画面").wait_for(timeout=60_000)
- expect(library.locator("#project-selection-count")).to_contain_text("已选 0")
+ selection_text = library.locator("#project-selection-count").text_content() or ""
+ assert "已选 0" not in selection_text, selection_text
vision_selection_ms = (time.perf_counter() - started) * 1000
- assert library.locator("#project-selection-save").is_disabled()
-
- library.locator(".case-card").first.click()
+ assert not library.locator("#project-selection-save").is_disabled()
started = time.perf_counter()
library.locator("#project-selection-save").click()
diff --git a/test/library-large-safety.test.js b/test/library-large-safety.test.js
index 620006b..05ed6db 100644
--- a/test/library-large-safety.test.js
+++ b/test/library-large-safety.test.js
@@ -11,10 +11,9 @@ test("current libraries bypass whole-library migration and normalization on ever
assert.match(readState, /shouldMigrate \? migrateLibraryState\(stored\) : null/);
});
-test("visual batch selection never preselects an entire project", () => {
+test("visual batch selection preselects analyzable project cases before continuing", () => {
const enterVision = library.slice(library.indexOf("function enterVisionSelection"), library.indexOf("function enterSelectMode"));
- assert.match(enterVision, /selectedCaseIds\.clear\(\)/);
- assert.doesNotMatch(enterVision, /selectedCaseIds\.add/);
+ assert.match(enterVision, /replaceSelectedCaseIds\(getVisionSelectableEntries\("all"\)\.map\(\(entry\) => entry\.id\)\)/);
});
test("visible thumbnails use a bounded queue and a rebuildable persistent cache", () => {
diff --git a/test/library-package.test.js b/test/library-package.test.js
index 2017a5c..aa598bc 100644
--- a/test/library-package.test.js
+++ b/test/library-package.test.js
@@ -336,13 +336,21 @@ test("imports remap visual ids that would overwrite a different local case", ()
{ id: "article-copy", kind: "paragraph", text: "正文" },
{ id: "article-image", kind: "image", assetId: "shared-visual", sourceUrl: "https://example.com/original.webp" }
]
- }
+ },
+ facetAssignments: [
+ { facetId: "facet:mood", nodeId: "tag:epic", status: "confirmed", source: "manual" },
+ { facetId: "facet:mood", nodeId: "tag:dramatic", status: "confirmed", source: "vision_model", visualId: "shared-visual" }
+ ]
}];
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);
+ assert.equal(
+ remote.facetAssignments.find((item) => item.source === "vision_model").visualId,
+ remote.primaryMediaId
+ );
});
test("imports remap both sides of a video poster relationship", () => {
@@ -422,7 +430,7 @@ test("single curated saves preserve an empty user's library configuration", () =
assert.deepEqual(result.state.organizerState.collections.map((item) => item.name), ["我的项目"]);
});
-test("existing-library import merges new cases, reuses same-name vocabulary and skips repeated shares", () => {
+test("existing-library import reuses same-name vocabulary and remaps repeated case ids without merging", () => {
const localCatalog = createFacetNode(createDefaultFacetCatalog(), {
id: "tag:local-epic", facetId: "mood", parentId: "mood.emotion", name: "史诗"
});
@@ -432,16 +440,75 @@ test("existing-library import merges new cases, reuses same-name vocabulary and
};
const first = mergeLibraryPackage(current, packageData([entry("one"), entry("two")], catalog()));
- assert.equal(first.importedCount, 1);
- assert.equal(first.skippedCount, 1);
+ assert.equal(first.importedCount, 2);
+ assert.equal(first.skippedCount, 0);
+ assert.equal(first.state.entries.length, 3);
assert.equal(first.state.entries.find((item) => item.id === "two").facetAssignments[0].nodeId, "tag:local-epic");
assert.equal(first.state.facetCatalog.facets.length, 10);
assert.equal(first.state.settings.libraryTitle, "接收者资料库");
assert.equal(first.state.classificationRules.length, 0);
const repeated = mergeLibraryPackage(first.state, packageData([entry("two")], catalog()));
- assert.equal(repeated.importedCount, 0);
- assert.equal(repeated.skippedCount, 1);
+ assert.equal(repeated.importedCount, 1);
+ assert.equal(repeated.skippedCount, 0);
+ assert.equal(repeated.state.entries.length, 4);
+});
+
+test("a colliding case id imports as a new case instead of silently keeping a stale tagless copy", () => {
+ const stale = entry("shared-case");
+ stale.facetAssignments = [];
+ const incoming = entry("shared-case");
+ incoming.facetAssignments = [{
+ facetId: "facet:mood",
+ nodeId: "tag:epic",
+ status: "confirmed",
+ source: "vision_model"
+ }];
+ incoming.visuals = [{
+ id: "shared-case",
+ screenshotPath: "images/shared-case.webp",
+ visionAnalysis: {
+ version: 2,
+ reconstructionPrompt: "保留这份完整反推提示词",
+ quality: "complete",
+ tags: [{ g: "mood.emotion", t: "史诗" }]
+ }
+ }];
+ incoming.primaryVisualId = "shared-case";
+
+ const result = mergeLibraryPackage({
+ entries: [stale],
+ taxonomy: createDefaultTaxonomy(),
+ facetCatalog: catalog(),
+ classificationRules: [],
+ settings: {}
+ }, packageData([incoming], catalog()));
+
+ assert.equal(result.importedCount, 1);
+ assert.equal(result.remappedCount, 1);
+ assert.equal(result.skippedCount, 0);
+ assert.equal(result.state.entries.length, 2);
+ const restored = result.state.entries.find((item) => item.id !== "shared-case");
+ assert.ok(restored);
+ assert.equal(restored.mediaAssets[0].visionAnalysis.reconstructionPrompt, "保留这份完整反推提示词");
+ assert.equal(restored.facetAssignments.some((item) => item.source === "vision_model"), true);
+});
+
+test("import aborts instead of silently dropping an assignment whose vocabulary node is missing", () => {
+ const incoming = entry("broken-label");
+ incoming.facetAssignments = [{
+ facetId: "facet:mood",
+ nodeId: "tag:not-in-package",
+ status: "confirmed",
+ source: "vision_model"
+ }];
+ assert.throws(() => mergeLibraryPackage({
+ entries: [entry("local")],
+ taxonomy: createDefaultTaxonomy(),
+ facetCatalog: catalog(),
+ classificationRules: [],
+ settings: {}
+ }, packageData([incoming], catalog())), /标签|词表|不完整/);
});
test("package import keeps source time but assigns one receiver-local added time and batch", () => {
@@ -618,6 +685,50 @@ test("share package keeps vision description but strips provider metadata", () =
});
});
+test("v2 share packages roundtrip reconstruction prompts, inline vision tags, and persisted vision labels", () => {
+ const source = entry("vision-v2");
+ source.visuals = [{
+ id: "vision-v2",
+ screenshotPath: "images/vision-v2.webp",
+ visionAnalysis: {
+ version: 2,
+ description: "完整画面描述",
+ reconstructionPrompt: "完整反推提示词",
+ quality: "complete",
+ tags: [{ g: "style.render", t: "赛璐珞" }],
+ locale: "zh-CN",
+ analyzedAt: "2026-08-21T10:00:00.000Z"
+ }
+ }];
+ source.primaryVisualId = "vision-v2";
+ source.facetAssignments = [
+ { facetId: "facet:mood", nodeId: "tag:epic", status: "confirmed", source: "manual" },
+ { facetId: "facet:mood", nodeId: "tag:dramatic", status: "confirmed", source: "vision_model" }
+ ];
+ const selected = selectLibraryPackage(
+ { entries: [source], taxonomy: createDefaultTaxonomy(), facetCatalog: catalog(), classificationRules: [] },
+ ["vision-v2"]
+ );
+ const exported = {
+ format: "prompt-case-library",
+ version: 3,
+ settings: { libraryTitle: "我的灵感库", outputPath: "提示词案例库/案例库.zip" },
+ taxonomy: selected.taxonomy,
+ facetCatalog: selected.facetCatalog,
+ classificationRules: selected.classificationRules,
+ organizerState: selected.organizerState,
+ entries: selected.entries
+ };
+ const merged = mergeLibraryPackage({ entries: [] }, exported);
+ const restored = merged.state.entries[0];
+ const restoredVisual = restored.mediaAssets?.[0] ?? restored.visuals?.[0];
+
+ assert.equal(restoredVisual.visionAnalysis.reconstructionPrompt, "完整反推提示词");
+ assert.deepEqual(restoredVisual.visionAnalysis.tags, [{ g: "style.render", t: "赛璐珞" }]);
+ assert.equal(restoredVisual.visionAnalysis.quality, "complete");
+ assert.equal(restored.facetAssignments.some((item) => item.source === "vision_model"), true);
+});
+
test("full imports merge project collections and permanently ignore legacy project methods", () => {
const current = {
entries: [entry("local")], taxonomy: createDefaultTaxonomy(), facetCatalog: catalog(),
diff --git a/test/library_core_e2e.py b/test/library_core_e2e.py
index 03b483f..f0b6a58 100644
--- a/test/library_core_e2e.py
+++ b/test/library_core_e2e.py
@@ -125,13 +125,13 @@ def main() -> None:
expect(library.locator("#analysis-batch-summary")).to_contain_text("1 条成功结果已安全暂存")
expect(library.locator("#analysis-batch-summary")).to_contain_text("AI 返回了未知分类路径")
expect(library.locator("#retry-analysis-failures")).to_have_text("继续完成重建(1 条)")
- expect(library.locator("#apply-staged-analysis-rebuild")).to_have_text("应用已成功结果(1 条待补)")
+ expect(library.locator("#apply-staged-analysis-rebuild")).to_have_text("应用完整成功结果(1 条失败不写入)")
expect(library.locator("#start-analysis-batch")).to_be_hidden()
expect(library.locator("#preview-analysis-batch")).to_be_hidden()
library.locator("#apply-staged-analysis-rebuild").click()
expect(library.locator("#batch-status-badge")).to_contain_text("成功结果已应用")
- expect(library.locator("#analysis-batch-summary")).to_contain_text("1 条失败案例已转为待分析")
+ expect(library.locator("#analysis-batch-summary")).to_contain_text("完整成功结果已经生效,1 条失败案例未写入,可单独重试")
expect(library.locator("#apply-staged-analysis-rebuild")).to_be_hidden()
expect(library.locator("#retry-analysis-failures")).to_be_hidden()
partial_state = library.evaluate(
diff --git a/test/library_import_ui_e2e.py b/test/library_import_ui_e2e.py
index cf37759..fdf9959 100644
--- a/test/library_import_ui_e2e.py
+++ b/test/library_import_ui_e2e.py
@@ -178,7 +178,8 @@ def main() -> None:
assert import_project_menu["clientHeight"] <= import_project_menu["scrollHeight"], import_project_menu
library.locator("#import-project").press("Escape")
expect(library.locator("#import-project")).to_have_attribute("aria-expanded", "false")
- library.locator("#import-project").fill("Import Review")
+ library.locator("#import-project").click()
+ library.locator(".project-combobox-option", has_text="Import Review").click()
duplicate_row.locator("input").check()
expect(duplicate_row).to_contain_text("仍导入")
diff --git a/test/library_media_actions_e2e.py b/test/library_media_actions_e2e.py
index 29907b2..c0d5931 100644
--- a/test/library_media_actions_e2e.py
+++ b/test/library_media_actions_e2e.py
@@ -31,6 +31,19 @@ def action_geometry(page, name: str) -> dict:
def assert_action_is_reachable(page, name: str) -> None:
+ page.wait_for_function(
+ """name => {
+ const button = [...document.querySelectorAll('button')]
+ .find(node => node.textContent.trim().includes(name));
+ if (!button) return false;
+ const rect = button.getBoundingClientRect();
+ const stage = button.closest('.detail-visual-stage')?.getBoundingClientRect();
+ const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
+ return stage && stage.top <= rect.top && rect.bottom <= stage.bottom
+ && (hit === button || button.contains(hit));
+ }""",
+ arg=name,
+ )
geometry = action_geometry(page, name)
assert geometry["stageTop"] <= geometry["buttonTop"], geometry
assert geometry["buttonBottom"] <= geometry["stageBottom"], geometry
diff --git a/test/library_navigation_e2e.py b/test/library_navigation_e2e.py
index 2c8ae3c..baddda0 100644
--- a/test/library_navigation_e2e.py
+++ b/test/library_navigation_e2e.py
@@ -197,6 +197,14 @@ def main() -> None:
expect(library.locator("#selection-trash")).to_be_enabled()
library.locator("#selection-more-menu > summary").press("Escape")
library.set_viewport_size({"width": 700, "height": 900})
+ library.wait_for_function(
+ """() => {
+ const bar = document.querySelector('#share-bar');
+ const rect = bar?.getBoundingClientRect();
+ return innerWidth === 700 && rect && rect.left >= 0 && rect.right <= innerWidth
+ && document.documentElement.scrollWidth <= document.documentElement.clientWidth;
+ }"""
+ )
compact_desktop = library.locator("#share-bar").evaluate(
"node => { const rect = node.getBoundingClientRect(); return {left: rect.left, right: rect.right, height: rect.height, viewport: innerWidth, overflow: document.documentElement.scrollWidth > document.documentElement.clientWidth}; }"
)
diff --git a/test/library_reconstruction_prompt_e2e.py b/test/library_reconstruction_prompt_e2e.py
index d08a71b..1d965a8 100644
--- a/test/library_reconstruction_prompt_e2e.py
+++ b/test/library_reconstruction_prompt_e2e.py
@@ -47,6 +47,7 @@ def main() -> None:
await chrome.storage.local.set({
schemaVersion: 25,
entries: [entry],
+ visionAnalysisUndo: {[entry.id]: {entryId: entry.id}},
uiPreferences: {locale: 'zh-CN', theme: 'dark', motion: 'reduced'}
});
await saveMediaBlob(entry.primaryMediaId, new Blob([bytes], {type: 'image/png'}), {checkCapacity: false});
@@ -66,6 +67,9 @@ def main() -> None:
"actual": copied,
}
expect(library.locator(".prompt-text").first).to_have_text(reconstruction_prompt)
+ expect(library.get_by_text(reconstruction_prompt, exact=True)).to_have_count(1)
+ expect(library.locator(".vision-description")).to_have_count(0)
+ expect(library.get_by_role("button", name="撤回本次分析")).to_have_count(0)
library.get_by_role("button", name="关闭详情").click()
library.evaluate(
diff --git a/test/local-asset-reference-background.test.js b/test/local-asset-reference-background.test.js
index 7366905..8a4f77a 100644
--- a/test/local-asset-reference-background.test.js
+++ b/test/local-asset-reference-background.test.js
@@ -14,6 +14,18 @@ test("background imports inert local references without reading a managed media
const itemEnd = source.indexOf("function importedEntryFromStagedAsset", itemStart);
const item = source.slice(itemStart, itemEnd);
assert.match(item, /staged\.storageMode !== "reference" && !await getMediaBlob/u);
+ assert.match(item, /await commitLocalChanges\(/u);
+ assert.match(item, /await enqueueAutomaticLibraryMaintenance\(\[entry\]\)/u);
+ assert.match(item, /await notifySaved\(entries\.length\)/u);
+ assert.match(item, /await queueImportJobAnalysis\(finished\.job\)/u);
+});
+
+test("startup recovery cannot replace a newly created import job with an empty snapshot", () => {
+ assert.match(source, /enqueue\(recoverImportJobs\)\.catch/u);
+ const start = source.indexOf("async function recoverImportJobs");
+ const end = source.indexOf("function scheduleImportRunner", start);
+ const recovery = source.slice(start, end);
+ assert.match(recovery, /if \(stored\[STORAGE_KEYS\.importJobs\][\s\S]*JSON\.stringify\(stored\[STORAGE_KEYS\.importJobs\]\)/u);
});
test("relink metadata action touches the case and never accepts a file handle", () => {
diff --git a/test/local-index-maintenance-ui.test.js b/test/local-index-maintenance-ui.test.js
index 523e2fe..0661994 100644
--- a/test/local-index-maintenance-ui.test.js
+++ b/test/local-index-maintenance-ui.test.js
@@ -23,7 +23,8 @@ test("local index maintenance exposes checked, running, complete, and failed tex
assert.match(manager, /t\(reanalysisPreview \|\| maintenanceJob \? "重新检查" : "检查缺失项"\)/);
assert.match(manager, /elements\.applyReanalyze\.hidden = maintenanceActive \|\| !maintenanceMissing/);
assert.match(status, /资料索引已完整/);
- assert.match(status, /待补全:\$\{reanalysisPreview\.confirmed\} 条内容类型,\$\{reanalysisPreview\.paletteCount\} 张图片色卡/);
+ assert.match(status, /t\("需要更新索引:\{types\} 条内容类型,\{palettes\} 张图片色卡。"/);
+ assert.doesNotMatch(status, /待补全/);
assert.match(status, /t\("\{status\} · 已处理 \{processed\}\/\{total\} · 成功 \{succeeded\} · 失败 \{failed\}"/);
assert.match(status, /processed: maintenanceJob\.processed/);
assert.match(status, /succeeded: maintenanceJob\.succeeded/);
diff --git a/test/media.test.js b/test/media.test.js
index 2d5fa37..ae387de 100644
--- a/test/media.test.js
+++ b/test/media.test.js
@@ -4,6 +4,7 @@ import assert from "node:assert/strict";
import {
addEntryMedia,
addTimeNote,
+ mediaDescriptions,
mediaKindFromFile,
normalizeEntryMedia,
normalizeMediaAsset,
@@ -14,6 +15,41 @@ import {
} from "../media.js";
import { normalizeEntryVisuals, reorderEntryVisuals } from "../visuals.js";
+test("new visual analysis remains readable through reconstruction prompts without a legacy description", () => {
+ const entry = normalizeEntryMedia({
+ id: "case:analysis",
+ mediaAssets: [{
+ id: "image:analysis",
+ kind: "image",
+ usage: "content",
+ storageMode: "managed",
+ visionAnalysis: {
+ quality: "complete",
+ reconstructionPrompt: "一名披风角色站在雨夜霓虹街道中央,35mm 低机位电影镜头。",
+ tags: [{ g: "style.render", t: "电影写实" }]
+ }
+ }]
+ });
+ assert.deepEqual(mediaDescriptions(entry), ["一名披风角色站在雨夜霓虹街道中央,35mm 低机位电影镜头。"]);
+});
+
+test("legacy partial visual output is not exposed as usable analysis", () => {
+ const entry = {
+ mediaAssets: [{
+ id: "image-partial",
+ kind: "image",
+ usage: "content",
+ visionAnalysis: {
+ reconstructionPrompt: "只有半截的旧结果",
+ quality: "partial",
+ tags: []
+ }
+ }],
+ primaryMediaId: "image-partial"
+ };
+ assert.deepEqual(mediaDescriptions(entry), []);
+});
+
test("media normalization discards empty slots instead of crashing library startup", () => {
assert.equal(normalizeMediaAsset(null), null);
const entry = normalizeEntryMedia({
diff --git a/test/share-preview.test.js b/test/share-preview.test.js
index 2b096f3..5dbad9e 100644
--- a/test/share-preview.test.js
+++ b/test/share-preview.test.js
@@ -143,7 +143,7 @@ test("share preview renders every portable media kind and its time notes", () =>
assert.match(html, /镜头加速/);
});
-test("share preview shows visual descriptions and related cases from the package", () => {
+test("share preview shows reconstruction prompts without a redundant visual-description section", () => {
const entries = ["one", "two"].map((id) => ({
id,
title: `Visual ${id}`,
@@ -157,16 +157,15 @@ test("share preview shows visual descriptions and related cases from the package
palette: { colors: ["#123456", "#345678"] },
visionAnalysis: {
version: 2,
- description: id === "one" ? "青绿色雾气中的古代庭院。" : "青绿色夜色中的庭院。",
reconstructionPrompt: id === "one" ? "青绿色雾气中的古代庭院,完整重建构图与光色。" : "青绿色夜色中的庭院,完整重建构图与光色。",
+ tags: [{ tagId: "facet:style:cinematic", label: "电影感" }],
imageFingerprint: `${id}-fingerprint`
}
}],
primaryMediaId: `image-${id}`
}));
const html = renderSharePreviewHtml(entries, { libraryTitle: "Archive" }, createDefaultTaxonomy(), createDefaultFacetCatalog(), previewOptions);
- assert.match(html, /画面描述/);
- assert.match(html, /青绿色雾气中的古代庭院/);
+ assert.doesNotMatch(html, /画面描述|Visual description/);
assert.match(html, /青绿色雾气中的古代庭院,完整重建构图与光色/);
assert.match(html, /data-copy-prompt="青绿色雾气中的古代庭院,完整重建构图与光色。"/);
assert.match(html, /相关案例/);
diff --git a/test/single_case_visual_batch_e2e.py b/test/single_case_visual_batch_e2e.py
index eab6dcb..b43f6ac 100644
--- a/test/single_case_visual_batch_e2e.py
+++ b/test/single_case_visual_batch_e2e.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import base64
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Thread
@@ -10,6 +11,7 @@ from e2e_support import base_entry, extension_session
PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+FAILURE_TARGET_SUFFIX = b"PromptDirectorFailureTarget"
DIMENSIONS = ["subject", "scene", "action", "style", "camera", "light", "mood", "sound", "output", "workflow"]
@@ -47,14 +49,14 @@ def complete_analysis(description: str, *, model_response: bool = False) -> dict
"reconstructionPrompt": f"{description},主体居中,完整还原构图和光色。",
"limitations": ["无法确认画外信息"],
"completeness": {"checkedRegions": ["四角", "主体", "背景", "文字"], "omittedVisibleElements": []},
- "tags": [],
+ "tags": [{"g": "style.render", "t": "电影感"}],
}
class AiHandler(BaseHTTPRequestHandler):
visual_requests: list[dict] = []
summary_requests: list[dict] = []
- fail_visual_request_once = 2
+ failure_target_attempts = 0
def do_OPTIONS(self) -> None:
self.send_response(204)
@@ -66,7 +68,18 @@ class AiHandler(BaseHTTPRequestHandler):
payload = json.loads(self.rfile.read(length) or b"{}")
if self.path.endswith("/responses"):
self.visual_requests.append(payload)
- if len(self.visual_requests) == self.fail_visual_request_once:
+ encoded_images = [
+ item
+ for item in json.dumps(payload).split('"')
+ if item.startswith("data:image/") and "," in item
+ ]
+ is_failure_target = any(
+ base64.b64decode(item.split(",", 1)[1]).endswith(FAILURE_TARGET_SUFFIX)
+ for item in encoded_images
+ )
+ if is_failure_target:
+ type(self).failure_target_attempts += 1
+ if is_failure_target and type(self).failure_target_attempts <= 3:
return self.reply({"error": {"message": "temporary local fixture failure"}}, status=503)
result = complete_analysis(f"第 {len(self.visual_requests)} 张待补齐图片", model_response=True)
return self.reply({
@@ -168,16 +181,20 @@ def main() -> None:
const {{saveMediaBlob}} = await import(chrome.runtime.getURL('media-store.js'));
const {{imageFingerprint}} = await import(chrome.runtime.getURL('vision.js'));
const bytes = Uint8Array.from(atob('{PNG}'), value => value.charCodeAt(0));
- const blob = new Blob([bytes], {{type: 'image/png'}});
- const fingerprint = await imageFingerprint(blob);
- for (let index = 1; index <= 15; index += 1) await saveMediaBlob(`visual-batch-${{index}}`, blob, {{checkCapacity: false}});
+ const contentHashes = [];
+ for (let index = 1; index <= 15; index += 1) {{
+ const suffix = index === 2 ? `visual-${{index}}-PromptDirectorFailureTarget` : `visual-${{index}}`;
+ const assetBlob = new Blob([bytes, new TextEncoder().encode(suffix)], {{type: 'image/png'}});
+ await saveMediaBlob(`visual-batch-${{index}}`, assetBlob, {{checkCapacity: false}});
+ contentHashes.push(await imageFingerprint(assetBlob));
+ }}
const stored = await chrome.storage.local.get('entries');
const entry = stored.entries[0];
- entry.mediaAssets.forEach(asset => {{ asset.contentHash = fingerprint; }});
+ entry.mediaAssets.forEach((asset, index) => {{ asset.contentHash = contentHashes[index]; }});
entry.mediaAssets[0].visionAnalysis = {{
...{json.dumps(complete_analysis('第一张已有有效分析'), ensure_ascii=False)},
version: 2,
- imageFingerprint: fingerprint,
+ imageFingerprint: contentHashes[0],
profileFingerprint: 'saved-profile',
providerType: 'compatible',
model: 'previous-model',
@@ -220,7 +237,7 @@ def main() -> None:
expect(dialog).to_contain_text("1 张失败,已成功 13 张且不会重复请求", timeout=15_000)
expect(dialog.locator('.visual-analysis-card[data-state="failed"]')).to_have_count(1)
expect(dialog.locator('.visual-analysis-card[data-state="completed"]')).to_have_count(13)
- assert len(AiHandler.visual_requests) == 14
+ assert len(AiHandler.visual_requests) == 16, len(AiHandler.visual_requests)
assert len(AiHandler.summary_requests) == 0
dialog.get_by_role("button", name="开始分析").click()
@@ -245,7 +262,7 @@ def main() -> None:
assert prompts["visual-batch-3"]["text"] == analyses[2]["reconstructionPrompt"]
assert prompts["visual-batch-3"]["source"] == "ai-suggestion"
assert stored["visualSetAnalyses"][0]["version"] == 1
- assert len(AiHandler.visual_requests) == 15
+ assert len(AiHandler.visual_requests) == 17, len(AiHandler.visual_requests)
assert len(AiHandler.summary_requests) == 1
assert "data:image" not in json.dumps(AiHandler.summary_requests[0])
diff --git a/test/skill-contact-sheet.test.js b/test/skill-contact-sheet.test.js
index 09fbc15..59c0c38 100644
--- a/test/skill-contact-sheet.test.js
+++ b/test/skill-contact-sheet.test.js
@@ -26,7 +26,7 @@ test("compound Skill sources include only explicitly selected assets", () => {
id: "compound",
text: "共享案例文字",
mediaAssets: [
- { id: "chosen", kind: "image", usage: "content", visionAnalysis: { description: "保留的构图" } },
+ { id: "chosen", kind: "image", usage: "content", visionAnalysis: { reconstructionPrompt: "保留的构图" } },
{ id: "hidden", kind: "image", usage: "content", visionAnalysis: { description: "不应发送的构图" } },
{ id: "doc", kind: "document", usage: "content" }
],
@@ -46,7 +46,7 @@ test("compound Skill sources include only explicitly selected assets", () => {
});
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 entries = [{ id: "local:secret", title: "Secret Project", url: "https://private.example", text: "original prompt", mediaAssets: [{ usage: "content", visionAnalysis: { reconstructionPrompt: "visible composition" } }] }];
const request = buildSkillExtractionRequest({ goal: "提炼构图", sources: anonymousSkillSources(entries, ["local:secret"]), locale: "zh-CN" });
assert.match(request, /原提示词[\s\S]*original prompt/);
assert.match(request, /已有画面分析[\s\S]*visible composition/);
diff --git a/test/temp-references.test.js b/test/temp-references.test.js
index 5ec429c..18a6b0b 100644
--- a/test/temp-references.test.js
+++ b/test/temp-references.test.js
@@ -129,6 +129,18 @@ test("a text-only service blocks image attachments without choosing another serv
imageCount: 1,
choices: ["chooseVisionService", "analyzeImages", "cancel"]
});
+ assert.deepEqual(imageTempReferenceBlock([{
+ sourceType: "library",
+ referenceKind: "prompt",
+ originalText: "A centered portrait with hard side light.",
+ referenceText: "A centered portrait with hard side light.",
+ imageRefs: [{ visualId: "temp-reference-asset:one", mimeType: "image/png" }],
+ assets: [{ assetId: "temp-reference-asset:one", kind: "image" }]
+ }], { serviceId: "deepseek", vision: false }), {
+ blocked: false,
+ imageCount: 0,
+ choices: []
+ });
});
test("a partial temporary-image analysis remains eligible for completion", () => {
diff --git a/test/vision-analysis-cache.test.js b/test/vision-analysis-cache.test.js
index f44976a..7d9936a 100644
--- a/test/vision-analysis-cache.test.js
+++ b/test/vision-analysis-cache.test.js
@@ -16,7 +16,8 @@ function entryWithAnalysis(id, quality, overrides = {}) {
visionAnalysis: {
version: 2,
quality,
- description: `${quality} result`,
+ reconstructionPrompt: `${quality} result`,
+ tags: [{ g: "style.render", t: "电影写实" }],
imageFingerprint: "same-image",
profileFingerprint: "same-profile",
locale: "zh-CN",
@@ -27,10 +28,10 @@ function entryWithAnalysis(id, quality, overrides = {}) {
};
}
-test("persisted vision cache prefers a complete matching result and can use a partial result as completion input", () => {
+test("persisted vision cache reuses only complete atomic results and ignores legacy partial output", () => {
const options = { fingerprint: "same-image", profileFingerprint: "same-profile", locale: "zh-CN", catalogRevision: 7 };
const partial = findPersistedVisionAnalysis([entryWithAnalysis("partial", "partial")], options);
- assert.equal(partial.quality, "partial");
+ assert.equal(partial, null);
const complete = findPersistedVisionAnalysis([
entryWithAnalysis("partial", "partial"),
@@ -39,6 +40,19 @@ test("persisted vision cache prefers a complete matching result and can use a pa
assert.equal(complete.quality, "complete");
});
+test("persisted vision cache rejects records missing either the reverse prompt or tags", () => {
+ const options = { fingerprint: "same-image", profileFingerprint: "same-profile", locale: "zh-CN", catalogRevision: 7 };
+ assert.equal(findPersistedVisionAnalysis([
+ entryWithAnalysis("no-prompt", "complete", { reconstructionPrompt: "" })
+ ], options), null);
+ assert.equal(findPersistedVisionAnalysis([
+ entryWithAnalysis("no-tags", "complete", { tags: [] })
+ ], options), null);
+ assert.equal(findPersistedVisionAnalysis([
+ entryWithAnalysis("invalid-tags", "complete", { tags: [{ g: "", t: "伪标签" }, {}] })
+ ], options), null);
+});
+
test("persisted vision cache rejects stale model, locale, taxonomy, and protocol matches", () => {
const entry = entryWithAnalysis("stale", "complete");
assert.equal(findPersistedVisionAnalysis([entry], {
diff --git a/test/vision.test.js b/test/vision.test.js
index ee5b1a3..780dc5f 100644
--- a/test/vision.test.js
+++ b/test/vision.test.js
@@ -4,6 +4,7 @@ import assert from "node:assert/strict";
import {
DEFAULT_VISION_MODEL,
analyzeImageWithVision,
+ createVisionRequestBudget,
evaluateCreativeOutputWithVision,
mergeVisionSettings,
normalizeVisionResult,
@@ -25,7 +26,7 @@ function sampleCatalog() {
return catalog;
}
-function completeVisionResult(description = "一名人物站在逆光环境中。", tags = []) {
+function completeVisionResult(description = "一名人物站在逆光环境中。", tags = [{ g: "light.direction", t: "逆光" }]) {
return {
description,
canvas: {
@@ -222,11 +223,45 @@ test("vision result keeps partial paid output visible and keeps at most six opti
const missingDescription = normalizeVisionResult(completeVisionResult(""));
assert.equal(missingDescription.quality, "partial");
assert.ok(missingDescription.missingFields.includes("description"));
- const partial = normalizeVisionResult({ description: "旧版简述", tags: [] });
- assert.equal(partial.quality, "partial");
- assert.equal(partial.description, "旧版简述");
- assert.ok(partial.missingFields.includes("canvas"));
- assert.ok(partial.missingFields.includes("reconstructionPrompt"));
+ assert.throws(
+ () => normalizeVisionResult({ description: "旧版简述", tags: [] }),
+ /至少一个有效检索标签/
+ );
+});
+
+test("vision request schema is minimized to reconstructionPrompt plus tags", async () => {
+ let body;
+ await analyzeImageWithVision({
+ imageDataUrl: "data:image/png;base64,AAAA",
+ catalog: createDefaultFacetCatalog(),
+ settings: {
+ activeProvider: "compatible",
+ consent: true,
+ compatible: {
+ protocol: "chat_completions",
+ endpoint: "https://api.deepseek.com/chat/completions",
+ apiKey: "secret",
+ model: "deepseek-v4-vision"
+ }
+ }
+ }, async (_url, options) => {
+ body = JSON.parse(options.body);
+ return {
+ ok: true,
+ json: async () => ({
+ model: "deepseek-v4-vision",
+ choices: [{ message: { content: JSON.stringify({ reconstructionPrompt: "主体居中", tags: [{ g: "light.direction", t: "逆光" }] }) } }]
+ })
+ };
+ });
+
+ const schema = body.response_format?.json_schema?.schema ?? body.text?.format?.schema ?? body.response_format;
+ assert.deepEqual(Object.keys(schema.properties).sort(), ["reconstructionPrompt", "tags"]);
+ assert.deepEqual(schema.required, ["reconstructionPrompt", "tags"]);
+ const prompt = body.messages[0].content.find((item) => item.type === "text").text;
+ assert.match(prompt, /reconstructionPrompt/);
+ assert.match(prompt, /tags/);
+ assert.doesNotMatch(prompt, /"description"|"canvas"|"elements"|"dimensions"|"ocr"|"completeness"|partial/);
});
test("partial vision normalization accepts root casing and snake-case aliases without inventing fields", () => {
@@ -242,13 +277,10 @@ test("partial vision normalization accepts root casing and snake-case aliases wi
assert.ok(partial.missingFields.includes("elements"));
});
-test("an invalid optional search tag cannot discard an otherwise complete paid visual analysis", () => {
- const result = normalizeVisionResult(completeVisionResult("主体分析完整。", [
+test("an invalid-only tag response fails atomically even when the reconstruction prompt is usable", () => {
+ assert.throws(() => normalizeVisionResult(completeVisionResult("主体分析完整。", [
{ g: "invented.path", t: "模型自造路径" }
- ]), sampleCatalog());
- assert.equal(result.description, "主体分析完整。");
- assert.deepEqual(result.tags, []);
- assert.equal(result.tagDiagnostics.rejectedCount, 1);
+ ]), sampleCatalog()), /至少一个有效检索标签/);
});
test("OpenAI vision request sends the image and fixed paths without dynamic detail vocabulary", async () => {
@@ -279,21 +311,29 @@ test("OpenAI vision request sends the image and fixed paths without dynamic deta
assert.equal(request.store, false);
assert.equal(request.max_output_tokens, 12000);
assert.equal(request.text.format.type, "json_schema");
- assert.ok(request.text.format.schema.properties.elements.items.properties.box_2d);
- assert.equal(request.text.format.schema.properties.elements.items.properties.bbox, undefined);
- assert.ok(request.text.format.schema.properties.tags.items.properties.g.enum.includes("light.direction"));
- assert.equal(request.text.format.schema.properties.tags.items.properties.g.enum.includes("detail:secret"), false);
+ assert.deepEqual(Object.keys(request.text.format.schema.properties).sort(), ["reconstructionPrompt", "tags"]);
+ assert.equal(request.text.format.schema.properties.reconstructionPrompt.type, "string");
+ assert.equal(request.text.format.schema.properties.tags.maxItems, 6);
const content = request.input[0].content;
assert.deepEqual(content.find((item) => item.type === "input_image"), {
type: "input_image", image_url: "data:image/webp;base64,AAAA", detail: "high"
});
const sentText = content.filter((item) => item.type === "input_text").map((item) => item.text).join("\n");
assert.match(sentText, /优先描述空间关系/);
- assert.match(sentText, /light\.direction/);
- assert.doesNotMatch(sentText, /secret-dynamic-tag/);
- assert.doesNotMatch(sentText, /example\.com|原提示词|案例标题/);
- assert.doesNotMatch(sentText, /1280x720|serviceDeclaredGeneration/);
- assert.equal(result.description, "一名人物站在逆光环境中。");
+ assert.match(sentText, /reconstructionPrompt/);
+ assert.match(sentText, /tags/);
+ assert.match(sentText, /主体/);
+ assert.match(sentText, /场景/);
+ assert.match(sentText, /动作/);
+ assert.match(sentText, /风格材质/);
+ assert.match(sentText, /构图镜头/);
+ assert.match(sentText, /光线色彩/);
+ assert.match(sentText, /情绪/);
+ assert.match(sentText, /可见文字图形/);
+ assert.match(sentText, /媒介画质/);
+ assert.match(sentText, /制作表现/);
+ assert.doesNotMatch(sentText, /"description"|"canvas"|"elements"|"dimensions"|"ocr"|"completeness"|partial/);
+ assert.equal(result.reconstructionPrompt, "一名人物站在逆光环境中。 主体居中,逆光。");
assert.equal(result.tags.length, 1);
assert.equal(result.usage.totalTokens, 55);
});
@@ -324,7 +364,7 @@ test("Gemini native vision adapter sends inline image data and preserves the uni
assert.equal(result.usage.totalTokens, 12);
});
-test("compatible request uses Chat Completions image messages and refuses redirects", async () => {
+test("compatible request disables thinking on DeepSeek chat completions and refuses redirects", async () => {
let options;
const fetchStub = async (_url, input) => {
options = input;
@@ -341,7 +381,7 @@ test("compatible request uses Chat Completions image messages and refuses redire
activeProvider: "compatible", consent: true,
compatible: {
protocol: "chat_completions",
- endpoint: "https://vision.example.com/v1/chat/completions",
+ endpoint: "https://api.deepseek.com/v1/chat/completions",
apiKey: "secret",
model: "vision-pro"
}
@@ -349,11 +389,12 @@ test("compatible request uses Chat Completions image messages and refuses redire
}, fetchStub);
const body = JSON.parse(options.body);
assert.equal(options.redirect, "error");
+ assert.deepEqual(body.thinking, { type: "disabled" });
assert.equal(body.messages[0].content.some((item) => item.type === "image_url" && item.image_url.detail === "high"), true);
assert.equal(body.max_tokens, 12000);
});
-test("compatible json_object vision requests keep image input and local full-schema validation", async () => {
+test("compatible json_object vision requests keep image input and local reconstruction validation", async () => {
let body;
const input = {
imageDataUrl: "data:image/png;base64,AAAA",
@@ -384,16 +425,15 @@ test("compatible json_object vision requests keep image input and local full-sch
assert.deepEqual(body.response_format, { type: "json_object" });
assert.equal(body.messages[0].content.some((item) => item.type === "image_url"), true);
const instruction = body.messages[0].content.find((item) => item.type === "text").text;
- assert.match(instruction, /JSON property names are case-sensitive/);
- assert.match(instruction, /"ocr":\{"type":"array"/);
- assert.equal(success.description, "一张完整分析。");
+ assert.match(instruction, /reconstructionPrompt/);
+ assert.match(instruction, /tags/);
+ assert.doesNotMatch(instruction, /"description"|"canvas"|"elements"|"dimensions"|"ocr"|"completeness"|partial/);
+ assert.equal(success.reconstructionPrompt, "一张完整分析。 主体居中,逆光。");
- const partial = await analyzeImageWithVision(input, async () => ({
+ await assert.rejects(() => analyzeImageWithVision(input, async () => ({
ok: true,
- json: async () => ({ choices: [{ message: { content: JSON.stringify({ description: "不完整" }) } }] })
- }));
- assert.equal(partial.quality, "partial");
- assert.ok(partial.missingFields.includes("canvas"));
+ json: async () => ({ choices: [{ message: { content: JSON.stringify({ reconstructionPrompt: "缺少标签", tags: [] }) } }] })
+ })), /至少一个有效检索标签/);
});
test("compatible empty vision results get exactly one structured-output correction request", async () => {
@@ -432,7 +472,54 @@ test("compatible empty vision results get exactly one structured-output correcti
assert.equal(calls, cases.length * 2);
});
-test("compatible Responses request sends the OpenAI image shape and parses structured output", async () => {
+test("vision provider calls share one budget across service retries and output correction", async () => {
+ const input = {
+ imageDataUrl: "data:image/png;base64,AAAA",
+ catalog: createDefaultFacetCatalog(),
+ requestBudget: createVisionRequestBudget(),
+ settings: {
+ activeProvider: "compatible", consent: true,
+ compatible: {
+ protocol: "chat_completions",
+ structuredOutput: "json_object",
+ endpoint: "http://localhost:1234/v1/chat/completions",
+ model: "fixture-model"
+ }
+ }
+ };
+ let providerCalls = 0;
+ const failingFetch = async () => {
+ providerCalls += 1;
+ if (providerCalls === 2) {
+ return {
+ ok: false,
+ status: 503,
+ headers: { get: () => null },
+ json: async () => ({ error: { message: "temporary" } })
+ };
+ }
+ return {
+ ok: true,
+ status: 200,
+ headers: { get: () => null },
+ json: async () => ({ choices: [{ message: { content: "{}" } }] })
+ };
+ };
+
+ await assert.rejects(() => analyzeImageWithVision(input, failingFetch), (error) => error.status === 503);
+ await assert.rejects(
+ () => analyzeImageWithVision(input, failingFetch),
+ (error) => error.code === "vision_request_budget_exhausted"
+ );
+ assert.equal(providerCalls, 3);
+ assert.deepEqual(input.requestBudget, {
+ maxProviderCalls: 3,
+ providerCalls: 3,
+ outputCorrectionRequests: 1
+ });
+});
+
+test("third-party compatible Responses disables reasoning by task policy and parses structured output", async () => {
let captured;
const result = await analyzeImageWithVision({
imageDataUrl: "data:image/png;base64,AAAA",
@@ -444,7 +531,7 @@ test("compatible Responses request sends the OpenAI image shape and parses struc
protocol: "responses",
endpoint: "https://www.micuapi.ai/v1/responses",
apiKey: "secret",
- model: "gpt-5.4-mini"
+ model: "gpt-5.6-terra"
}
}
}, async (url, options) => {
@@ -452,12 +539,12 @@ test("compatible Responses request sends the OpenAI image shape and parses struc
return {
ok: true,
json: async () => ({
- model: "gpt-5.4-mini",
+ model: "gpt-5.6-terra",
output: [{
type: "message",
content: [{
type: "output_text",
- text: JSON.stringify(completeVisionResult("雾中的庭院。", [{ g: "light.direction", t: "逆光" }]))
+ text: JSON.stringify({ reconstructionPrompt: "雾中的庭院。", tags: [{ g: "light.direction", t: "逆光" }] })
}]
}]
})
@@ -466,10 +553,11 @@ test("compatible Responses request sends the OpenAI image shape and parses struc
assert.equal(captured.url, "https://www.micuapi.ai/v1/responses");
assert.equal(captured.options.redirect, "error");
assert.equal(captured.body.store, false);
+ assert.deepEqual(captured.body.reasoning, { effort: "none" });
assert.equal(captured.body.messages, undefined);
assert.equal(captured.body.input[0].content.some((item) => item.type === "input_image" && item.detail === "high"), true);
assert.equal(captured.body.text.format.type, "json_schema");
- assert.equal(result.description, "雾中的庭院。");
+ assert.equal(result.reconstructionPrompt, "雾中的庭院。");
assert.equal(result.tags.length, 1);
});
@@ -578,9 +666,13 @@ test("vision service refusal, invalid JSON, missing description and HTTP errors
}));
assert.equal(partial.quality, "partial");
assert.ok(partial.missingFields.includes("description"));
- await assert.rejects(() => analyzeImageWithVision(input, async () => ({
+ const rateLimited = await analyzeImageWithVision(input, async () => ({
ok: false,
status: 429,
json: async () => ({ error: { message: "rate limited" } })
- })), /rate limited/);
+ })).catch((error) => error);
+ assert.match(rateLimited.message, /请求过于频繁/);
+ assert.equal(rateLimited.status, 429);
+ assert.match(rateLimited.detail, /rate limited/);
+ assert.doesNotMatch(rateLimited.message, /rate limited/);
});
diff --git a/test/vision_batch_entry_e2e.py b/test/vision_batch_entry_e2e.py
new file mode 100644
index 0000000..bd03ca3
--- /dev/null
+++ b/test/vision_batch_entry_e2e.py
@@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from playwright.sync_api import expect
+
+from e2e_support import ai_configuration_fixture, base_entry, extension_session
+
+
+PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+
+
+def image_entry(entry_id: str, title: str, minute: int) -> dict:
+ entry = base_entry(entry_id, title, f"{title} 的共享提示词", "content:prompt:image", minute)
+ asset_id = f"{entry_id}-image"
+ entry["mediaAssets"] = [{
+ "id": asset_id,
+ "kind": "image",
+ "usage": "content",
+ "storageMode": "managed",
+ "mimeType": "image/png",
+ "width": 1,
+ "height": 1,
+ "capturedAt": "2026-08-24T00:00:00.000Z",
+ "reviewStatus": "verified",
+ }]
+ entry["primaryMediaId"] = asset_id
+ return entry
+
+
+def assert_current_preview(dialog, *, expected_model: str, forbidden_model: str) -> None:
+ expect(dialog).to_be_visible()
+ expect(dialog.locator("#vision-batch-summary")).to_contain_text("2 个案例 · 2 次图片请求")
+ expect(dialog.locator("#vision-batch-start")).to_be_visible()
+ expect(dialog.locator("#vision-batch-start")).to_be_enabled()
+ expect(dialog.locator("#vision-batch-service")).to_contain_text(expected_model)
+ service_text = dialog.locator("#vision-batch-service").text_content() or ""
+ assert forbidden_model not in service_text, service_text
+
+
+def main() -> None:
+ entries = [
+ image_entry("vision-entry-a", "批量入口案例 A", 0),
+ image_entry("vision-entry-b", "批量入口案例 B", 1),
+ ]
+
+ providers = {
+ "custom-media": {
+ "endpoint": "https://fixture.invalid/v1/responses",
+ "protocol": "responses",
+ "apiKey": "fixture-key",
+ "consent": True,
+ "models": {"imageAnalysis": "deepseek-v4-vision"},
+ },
+ }
+ assignments = {
+ "imageAnalysis": {"providerId": "custom-media", "model": "deepseek-v4-vision"},
+ }
+
+ with extension_session("prompt-director-vision-batch-entry-", viewport={"width": 1440, "height": 900}) as session:
+ setup = session.open_page("collector.html")
+ setup.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
+ session.seed_storage(setup, {
+ "schemaVersion": 25,
+ "entries": entries,
+ "uiPreferences": {"locale": "zh-CN", "theme": "dark", "motion": "system"},
+ "organizerState": {
+ "version": 5,
+ "collections": [{
+ "id": "collection:vision-batch",
+ "name": "批量入口验收项目",
+ "order": 0,
+ "entryIds": [entry["id"] for entry in entries],
+ "visibility": "library",
+ }],
+ },
+ **ai_configuration_fixture(providers=providers, assignments=assignments),
+ })
+ setup.evaluate(
+ """async ({entries, png}) => {
+ const {saveMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
+ const {createVisionBatchJob} = await import(chrome.runtime.getURL('analysis-batch.js'));
+ const bytes = Uint8Array.from(atob(png), value => value.charCodeAt(0));
+ const blob = new Blob([bytes], {type: 'image/png'});
+ for (const entry of entries) {
+ await saveMediaBlob(entry.primaryMediaId, blob, {checkCapacity: false});
+ }
+ const stored = await chrome.storage.local.get('entries');
+ const job = createVisionBatchJob(stored.entries, {
+ id: 'completed-old-vision-job',
+ entryIds: stored.entries.map(entry => entry.id),
+ includeAllImages: false,
+ reanalyze: false,
+ providerType: 'compatible',
+ providerId: 'custom-media',
+ model: 'gpt-old',
+ now: '2026-08-24T00:00:00.000Z'
+ });
+ job.status = 'completed';
+ job.updatedAt = '2026-08-24T00:05:00.000Z';
+ job.items = job.items.map((item, index) => ({
+ ...item,
+ status: 'succeeded',
+ attempts: 1,
+ claimId: `done-${index + 1}`,
+ }));
+ job.usage = {promptTokens: 8, completionTokens: 4, totalTokens: 12, cacheHitTokens: 0};
+ await chrome.storage.local.set({batchJob: job});
+ }""",
+ {"entries": entries, "png": PNG_BASE64},
+ )
+
+ library = session.open_page("library.html", wait_until="networkidle")
+ expect(library.locator("#case-list > .case-card")).to_have_count(2)
+ project_menu = library.locator("#collection-filters details.project-menu")
+ project_menu.locator(":scope > summary").click()
+ project_menu.get_by_role("button", name="批量分析").click()
+
+ expect(library.locator("#project-selection-title")).to_contain_text("批量分析画面")
+ expect(library.locator("#project-selection-count")).to_have_text("已选 2 / 当前 2 / 全部 2")
+ assert not library.locator("#project-selection-save").is_disabled()
+
+ library.locator("#project-selection-save").click()
+ dialog = library.locator("#vision-batch-dialog")
+ assert_current_preview(dialog, expected_model="deepseek-v4-vision", forbidden_model="gpt-old")
+ dialog.locator("#vision-batch-close").click()
+ expect(dialog).not_to_be_visible()
+ library.locator("#project-selection-cancel").click()
+
+ library.locator("#select-cases").click()
+ library.locator("#selection-select-filtered").click()
+ expect(library.locator("#share-count")).to_have_text("已选 2")
+ library.locator("#selection-more-menu > summary").click()
+ expect(library.locator("#selection-analyze")).to_be_enabled()
+ library.locator("#selection-analyze").click()
+
+ assert_current_preview(dialog, expected_model="deepseek-v4-vision", forbidden_model="gpt-old")
+
+ print({
+ "project_menu_entry_preselected": True,
+ "selection_toolbar_entry_works": True,
+ "stale_completed_job_did_not_override_preview_model": True,
+ })
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/vision_batch_runner_failure_e2e.py b/test/vision_batch_runner_failure_e2e.py
new file mode 100644
index 0000000..a8f0595
--- /dev/null
+++ b/test/vision_batch_runner_failure_e2e.py
@@ -0,0 +1,95 @@
+from __future__ import annotations
+
+from playwright.sync_api import expect
+
+from e2e_support import ai_configuration_fixture, base_entry, extension_session
+
+
+PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+
+
+def main() -> None:
+ entry = base_entry("runner-failure", "启动失败案例", "共享提示词", "content:prompt:image")
+ entry["mediaAssets"] = [{
+ "id": "runner-failure-image",
+ "kind": "image",
+ "usage": "content",
+ "storageMode": "managed",
+ "mimeType": "image/png",
+ "width": 1,
+ "height": 1,
+ }]
+ entry["primaryMediaId"] = "runner-failure-image"
+ providers = {
+ "custom-media": {
+ "endpoint": "https://fixture.invalid/v1/responses",
+ "protocol": "responses",
+ "apiKey": "fixture-key",
+ "consent": True,
+ "models": {"imageAnalysis": "current-model"},
+ },
+ }
+ assignments = {
+ "imageAnalysis": {"providerId": "custom-media", "model": "current-model"},
+ }
+
+ with extension_session("prompt-director-vision-runner-failure-", viewport={"width": 1280, "height": 800}) as session:
+ session.context.route(
+ "https://fixture.invalid/**",
+ lambda route: route.fulfill(
+ status=500,
+ content_type="application/json",
+ body='{"error":{"message":"fixture vision failure"}}',
+ ),
+ )
+ setup = session.open_page("collector.html")
+ setup.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
+ session.seed_storage(setup, {
+ "schemaVersion": 25,
+ "entries": [entry],
+ **ai_configuration_fixture(providers=providers, assignments=assignments),
+ })
+ 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(entry.mediaAssets[0].id, new Blob([bytes], {type: 'image/png'}), {checkCapacity: false});
+ }""",
+ {"entry": entry, "png": PNG_BASE64},
+ )
+ setup.evaluate(
+ """async () => {
+ const {createVisionBatchJob} = await import(chrome.runtime.getURL('analysis-batch.js'));
+ const stored = await chrome.storage.local.get('entries');
+ const job = createVisionBatchJob(stored.entries, {
+ id: 'runner-failure-job',
+ entryIds: ['runner-failure'],
+ providerType: 'compatible',
+ providerId: 'custom-media',
+ model: 'current-model',
+ now: '2026-08-26T00:00:00.000Z'
+ });
+ await chrome.storage.local.set({batchJob: job});
+ }"""
+ )
+
+ library = session.open_page("library.html", wait_until="networkidle")
+ library.locator("#select-cases").click()
+ library.locator("#selection-select-filtered").click()
+ library.locator("#selection-more-menu > summary").click()
+ library.locator("#selection-analyze").click()
+ dialog = library.locator("#vision-batch-dialog")
+ expect(dialog.locator("#vision-batch-summary")).to_contain_text("1 等待中")
+
+ library.evaluate(
+ "() => chrome.alarms.create('prompt-director-analysis-batch', {when: Date.now() + 50})"
+ )
+ expect(dialog.locator("#vision-batch-feedback")).to_contain_text("图片分析服务暂时不可用", timeout=15_000)
+ expect(dialog.locator("#vision-batch-retry")).to_be_visible(timeout=15_000)
+ expect(dialog.locator("#vision-batch-pause")).to_be_hidden(timeout=15_000)
+
+ print({"runner_failure_visible": True, "retry_available": True})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/vision_batch_running_progress_e2e.py b/test/vision_batch_running_progress_e2e.py
new file mode 100644
index 0000000..4c67001
--- /dev/null
+++ b/test/vision_batch_running_progress_e2e.py
@@ -0,0 +1,159 @@
+from __future__ import annotations
+
+import base64
+import json
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from threading import Event, Thread
+
+from playwright.sync_api import expect
+
+from e2e_support import ai_configuration_fixture, base_entry, extension_session
+
+
+PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+
+
+class HangingVisionHandler(BaseHTTPRequestHandler):
+ request_started = Event()
+ release_requests = Event()
+
+ def do_OPTIONS(self) -> None:
+ self.send_response(204)
+ self.cors()
+ self.end_headers()
+
+ def do_POST(self) -> None:
+ length = int(self.headers.get("content-length", "0"))
+ self.rfile.read(length)
+ type(self).request_started.set()
+ if not type(self).release_requests.wait(timeout=10):
+ return self.reply({"error": {"message": "fixture timed out"}}, status=503)
+ return self.reply({
+ "model": "local-progress-vision",
+ "output_text": json.dumps({
+ "reconstructionPrompt": "主体位于画面中央,低饱和电影光线,完整保留构图、景深与材质细节。",
+ "tags": [{"g": "style.render", "t": "电影感"}],
+ }, ensure_ascii=False),
+ "usage": {"input_tokens": 10, "output_tokens": 20, "total_tokens": 30},
+ })
+
+ def cors(self) -> None:
+ self.send_header("access-control-allow-origin", "*")
+ self.send_header("access-control-allow-headers", "authorization, content-type")
+ self.send_header("access-control-allow-methods", "POST, OPTIONS")
+
+ def reply(self, payload: dict, *, status: int = 200) -> None:
+ data = json.dumps(payload, ensure_ascii=False).encode()
+ self.send_response(status)
+ self.cors()
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def log_message(self, _format: str, *_args) -> None:
+ return
+
+
+def image_entry(entry_id: str, minute: int) -> dict:
+ entry = base_entry(entry_id, f"进度案例 {minute + 1}", "共享提示词", "content:prompt:image", minute)
+ asset_id = f"{entry_id}-image"
+ entry["mediaAssets"] = [{
+ "id": asset_id,
+ "kind": "image",
+ "usage": "content",
+ "storageMode": "managed",
+ "mimeType": "image/png",
+ "width": 1,
+ "height": 1,
+ }]
+ entry["primaryMediaId"] = asset_id
+ return entry
+
+
+def main() -> None:
+ server = ThreadingHTTPServer(("127.0.0.1", 0), HangingVisionHandler)
+ Thread(target=server.serve_forever, daemon=True).start()
+ origin = f"http://127.0.0.1:{server.server_port}"
+ entries = [image_entry("progress-a", 0), image_entry("progress-b", 1)]
+
+ providers = {
+ "custom-media": {
+ "endpoint": f"{origin}/v1/responses",
+ "protocol": "responses",
+ "apiKey": "fixture-key",
+ "consent": True,
+ "models": {"imageAnalysis": "local-progress-vision"},
+ },
+ }
+ assignments = {
+ "imageAnalysis": {"providerId": "custom-media", "model": "local-progress-vision"},
+ }
+
+ try:
+ with extension_session("prompt-director-vision-progress-", viewport={"width": 390, "height": 844}) as session:
+ setup = session.open_page("collector.html")
+ setup.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
+ session.seed_storage(setup, {
+ "schemaVersion": 25,
+ "entries": entries,
+ **ai_configuration_fixture(providers=providers, assignments=assignments),
+ })
+ setup.evaluate(
+ """async ({entries, png}) => {
+ const {saveMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
+ const bytes = Uint8Array.from(atob(png), value => value.charCodeAt(0));
+ for (const [index, entry] of entries.entries()) {
+ await saveMediaBlob(entry.primaryMediaId, new Blob([
+ bytes,
+ new TextEncoder().encode(`progress-${index}`)
+ ], {type: 'image/png'}), {checkCapacity: false});
+ }
+ }""",
+ {"entries": entries, "png": PNG_BASE64},
+ )
+
+ library = session.open_page("library.html", wait_until="networkidle")
+ library.locator("#select-cases").click()
+ library.locator("#selection-select-filtered").click()
+ library.locator("#selection-more-menu > summary").click()
+ library.locator("#selection-analyze").click()
+ dialog = library.locator("#vision-batch-dialog")
+ dialog.locator("#vision-batch-start").click()
+
+ assert HangingVisionHandler.request_started.wait(timeout=5), "本地图片服务没有收到请求"
+ expect(dialog.locator("#vision-batch-summary")).to_contain_text("2 处理中", timeout=5_000)
+ expect(dialog.locator("#vision-batch-summary")).to_contain_text("0 等待中")
+ running_progress = dialog.locator("#vision-batch-progress-bar").evaluate(
+ "element => ({value: element.value, max: element.max})"
+ )
+ assert running_progress == {"value": 0, "max": 2}, running_progress
+ layout = library.evaluate(
+ """() => {
+ const dialog = document.querySelector('#vision-batch-dialog');
+ const rect = dialog.getBoundingClientRect();
+ return {
+ viewportWidth: window.innerWidth,
+ documentWidth: document.documentElement.scrollWidth,
+ dialogLeft: rect.left,
+ dialogRight: rect.right,
+ };
+ }"""
+ )
+ assert layout["documentWidth"] <= layout["viewportWidth"], layout
+ assert layout["dialogLeft"] >= 0 and layout["dialogRight"] <= layout["viewportWidth"], layout
+
+ HangingVisionHandler.release_requests.set()
+ expect(dialog.locator("#vision-batch-summary")).to_contain_text("2/2 已完成", timeout=10_000)
+ completed_progress = dialog.locator("#vision-batch-progress-bar").evaluate(
+ "element => ({value: element.value, max: element.max})"
+ )
+ assert completed_progress == {"value": 2, "max": 2}, completed_progress
+ print({"in_flight_progress_visible": True, "completed": 2, "narrowViewport": layout})
+ finally:
+ HangingVisionHandler.release_requests.set()
+ server.shutdown()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/visual-analysis.test.js b/test/visual-analysis.test.js
index ea8bf14..761d008 100644
--- a/test/visual-analysis.test.js
+++ b/test/visual-analysis.test.js
@@ -91,6 +91,13 @@ test("VisualAnalysisV2 rejects incomplete dimensions and out-of-frame coordinate
})), /边界框/);
});
+test("visual model response schema is reduced to reconstructionPrompt plus tags", () => {
+ assert.deepEqual(Object.keys(VISUAL_MODEL_RESPONSE_SCHEMA.properties).sort(), ["reconstructionPrompt", "tags"]);
+ assert.deepEqual(VISUAL_MODEL_RESPONSE_SCHEMA.required, ["reconstructionPrompt", "tags"]);
+ assert.equal(VISUAL_MODEL_RESPONSE_SCHEMA.additionalProperties, false);
+ assert.equal(VISUAL_MODEL_RESPONSE_SCHEMA.properties.tags.minItems, 1);
+});
+
test("model box_2d uses yxyx order and converts once into the persisted V2 bbox", () => {
const result = normalizeVisualModelResponse(completeModelResponse(), createDefaultFacetCatalog());
assert.deepEqual(result.elements[0].bbox, {
@@ -99,8 +106,9 @@ test("model box_2d uses yxyx order and converts once into the persisted V2 bbox"
assert.deepEqual(result.ocr[0].bbox, {
x: 120, y: 70, width: 760, height: 90, source: "estimated"
});
- assert.ok(VISUAL_MODEL_RESPONSE_SCHEMA.properties.elements.items.properties.box_2d);
- assert.equal(VISUAL_MODEL_RESPONSE_SCHEMA.properties.elements.items.properties.bbox, undefined);
+ assert.deepEqual(Object.keys(VISUAL_MODEL_RESPONSE_SCHEMA.properties).sort(), ["reconstructionPrompt", "tags"]);
+ assert.equal(VISUAL_MODEL_RESPONSE_SCHEMA.properties.reconstructionPrompt.type, "string");
+ assert.equal(VISUAL_MODEL_RESPONSE_SCHEMA.properties.tags.maxItems, 6);
});
test("known root field casing is normalized before strict visual validation", () => {
@@ -134,7 +142,7 @@ test("completion merges only missing fields and preserves fields already validat
const previous = normalizeVisualModelResponse({
description: "已经保存的可靠描述",
reconstructionPrompt: "已经保存的可靠重建提示词",
- tags: []
+ tags: [{ g: "light.direction", t: "逆光" }]
});
const incoming = normalizeVisualModelResponse(completeModelResponse({
description: "补全请求中的重复描述",
@@ -159,30 +167,77 @@ test("visual instruction requests quantitative reconstruction in one call and ex
locale: "zh-CN",
customInstruction: "记录所有可见文字。"
});
- assert.match(instruction, /0 to 1000/);
- assert.match(instruction, /\[y_min, x_min, y_max, x_max\]/);
- assert.match(instruction, /programMeasuredCanvasPixels/);
- assert.match(instruction, /单次分析/);
+ assert.match(instruction, /只输出 reconstructionPrompt 和 tags/);
+ assert.match(instruction, /主体/);
+ assert.match(instruction, /场景/);
+ assert.match(instruction, /动作/);
+ assert.match(instruction, /风格材质/);
+ assert.match(instruction, /构图镜头/);
+ assert.match(instruction, /光线色彩/);
+ assert.match(instruction, /情绪/);
+ assert.match(instruction, /可见文字图形/);
+ assert.match(instruction, /媒介画质/);
+ assert.match(instruction, /制作表现/);
+ assert.match(instruction, /四角|four corners/i);
+ assert.match(instruction, /前景|foreground/i);
+ assert.match(instruction, /相对位置|relative position/i);
+ assert.match(instruction, /比例|scale/i);
+ assert.match(instruction, /景深|depth/i);
+ assert.match(instruction, /遮挡|occlusion/i);
+ assert.match(instruction, /字体|typography/i);
+ assert.match(instruction, /逐字|exact legible text/i);
+ assert.match(instruction, /不适用.*省略|omit.*not applicable/i);
+ assert.doesNotMatch(instruction, /box_2d/);
assert.match(instruction, /reconstructionPrompt/);
- assert.match(instruction, /every reconstruction-relevant visible fact/);
- assert.match(instruction, /do not merely summarize the scene/);
- for (const id of VISUAL_ANALYSIS_DIMENSIONS) assert.match(instruction, new RegExp(`\\b${id}\\b`));
+ assert.match(instruction, /tags/);
+ assert.doesNotMatch(instruction, /"description"|"canvas"|"elements"|"dimensions"|"ocr"|"completeness"|partial/);
assert.match(instruction, /light\.direction/);
assert.doesNotMatch(instruction, /secret-dynamic-tag/);
});
-test("visual set summary consumes saved V2 text and reports missing assets without accepting a contact sheet", () => {
+test("visual set summary consumes saved atomic prompts and tags without accepting a contact sheet", () => {
const ready = prepareVisualSetSummary([
- { assetId: "image-a", imageFingerprint: "fingerprint-a", analysis: completeAnalysis({ imageFingerprint: "fingerprint-a" }) },
- { assetId: "image-b", imageFingerprint: "fingerprint-b", analysis: completeAnalysis({ imageFingerprint: "fingerprint-b", description: "第二张图展示同一人物的侧面近景。" }) }
+ {
+ assetId: "image-a",
+ imageFingerprint: "fingerprint-a",
+ analysis: {
+ version: 2,
+ quality: "complete",
+ imageFingerprint: "fingerprint-a",
+ reconstructionPrompt: "第一张图的完整反推提示词",
+ tags: [{ g: "light.direction", t: "逆光" }]
+ }
+ },
+ {
+ assetId: "image-b",
+ imageFingerprint: "fingerprint-b",
+ analysis: {
+ version: 2,
+ quality: "complete",
+ imageFingerprint: "fingerprint-b",
+ reconstructionPrompt: "第二张图的完整反推提示词",
+ tags: [{ g: "composition.shot", t: "近景" }]
+ }
+ }
], "zh-CN");
assert.equal(ready.ready, true);
assert.deepEqual(ready.missingAssetIds, []);
assert.equal(JSON.stringify(ready.input).includes("data:image"), false);
assert.equal(ready.input.assets.length, 2);
+ assert.deepEqual(Object.keys(ready.input.assets[0]).sort(), ["assetId", "reconstructionPrompt", "tags"]);
const missing = prepareVisualSetSummary([
- { assetId: "image-a", imageFingerprint: "fingerprint-a", analysis: completeAnalysis({ imageFingerprint: "fingerprint-a" }) },
+ {
+ assetId: "image-a",
+ imageFingerprint: "fingerprint-a",
+ analysis: {
+ version: 2,
+ quality: "complete",
+ imageFingerprint: "fingerprint-a",
+ reconstructionPrompt: "第一张图的完整反推提示词",
+ tags: [{ g: "light.direction", t: "逆光" }]
+ }
+ },
{ assetId: "image-b", analysis: null }
], "zh-CN");
assert.equal(missing.ready, false);
diff --git a/vision-analysis-cache.js b/vision-analysis-cache.js
index 2ab81c1..a5fb9b3 100644
--- a/vision-analysis-cache.js
+++ b/vision-analysis-cache.js
@@ -7,16 +7,20 @@ export function findPersistedVisionAnalysis(entries, options = {}) {
const locale = options.locale === "en" ? "en" : "zh-CN";
const catalogRevision = Number(options.catalogRevision);
if (!fingerprint || !profileFingerprint || !Number.isFinite(catalogRevision)) return null;
- let partial = null;
for (const entry of Array.isArray(entries) ? entries : []) {
for (const visual of normalizeEntryVisuals(entry).visuals) {
const analysis = visual.visionAnalysis;
if (!analysis || Number(analysis.version) !== VISION_ANALYSIS_VERSION) continue;
if (analysis.imageFingerprint !== fingerprint || analysis.profileFingerprint !== profileFingerprint) continue;
if (analysis.locale !== locale || Number(analysis.catalogRevision) !== catalogRevision) continue;
- if (analysis.quality === "complete") return structuredClone(analysis);
- if (analysis.quality === "partial") partial = structuredClone(analysis);
+ const complete = analysis.quality === "complete"
+ && String(analysis.reconstructionPrompt ?? "").trim()
+ && Array.isArray(analysis.tags)
+ && analysis.tags.some((tag) =>
+ String(tag?.g ?? "").trim() && String(tag?.t ?? "").trim()
+ );
+ if (complete) return structuredClone(analysis);
}
}
- return partial;
+ return null;
}
diff --git a/vision.js b/vision.js
index 4f4d6b5..1727042 100644
--- a/vision.js
+++ b/vision.js
@@ -9,6 +9,7 @@ import {
} from "./visual-analysis.js";
import { parseStructuredObject } from "./structured-output.js";
import { MICU_COMPATIBLE_PROVIDER_PRESET } from "./compatible-provider-presets.js";
+import { ANALYSIS_RETRY_POLICY } from "./analysis-retry-policy.js";
export const VISION_ANALYSIS_VERSION = VISUAL_ANALYSIS_VERSION;
export const DEFAULT_VISION_MODEL = "gpt-5-mini";
@@ -23,12 +24,25 @@ export const MICU_DEFAULT_IMAGE_SIZE = MICU_COMPATIBLE_PROVIDER_PRESET.imageGene
export const MICU_IMAGE_RESULT_PERMISSION = "https://oss.filenest.top/*";
export const MAX_VISION_TAGS = 6;
export const VISION_MAX_OUTPUT_TOKENS = 12000;
+
+export function createVisionRequestBudget(maxProviderCallsValue = ANALYSIS_RETRY_POLICY.maxProviderCallsPerItem) {
+ const maxProviderCalls = Number(maxProviderCallsValue);
+ return {
+ maxProviderCalls: Number.isInteger(maxProviderCalls) && maxProviderCalls > 0
+ ? maxProviderCalls
+ : ANALYSIS_RETRY_POLICY.maxProviderCallsPerItem,
+ providerCalls: 0,
+ outputCorrectionRequests: 0
+ };
+}
+
export class VisionApiError extends Error {
constructor(message, status = 0, options = {}) {
super(message, options);
this.name = "VisionApiError";
this.status = Number(status) || 0;
this.retryAfterMs = Number(options.retryAfterMs) || 0;
+ this.detail = String(options.detail ?? "").trim();
}
}
class VisionOutputError extends Error {
@@ -333,13 +347,20 @@ export async function analyzeImageWithVision(input = {}, fetchImpl = fetch) {
maxOutputTokens: settings.maxOutputTokens,
schema: visualModelResponseSchema(input.catalog)
};
- const request = async (requestInstruction) => settings.nativeProvider?.id === "gemini"
- ? requestGeminiVision(settings.nativeProvider, imageDataUrl, requestInstruction, fetchImpl, requestOptions)
- : settings.activeProvider === "compatible"
- ? requestCompatible(settings, imageDataUrl, requestInstruction, fetchImpl, requestOptions)
- : requestOpenAI(settings, imageDataUrl, requestInstruction, fetchImpl, requestOptions);
- const perform = async (requestInstruction) => {
- const response = await request(requestInstruction);
+ const requestBudget = input.requestBudget && typeof input.requestBudget === "object"
+ ? input.requestBudget
+ : createVisionRequestBudget();
+ const correctionCountAtStart = Math.max(0, Number(requestBudget.outputCorrectionRequests) || 0);
+ const request = async (requestInstruction, requestKind) => {
+ consumeVisionRequestBudget(requestBudget, requestKind);
+ return settings.nativeProvider?.id === "gemini"
+ ? requestGeminiVision(settings.nativeProvider, imageDataUrl, requestInstruction, fetchImpl, requestOptions)
+ : settings.activeProvider === "compatible"
+ ? requestCompatible(settings, imageDataUrl, requestInstruction, fetchImpl, requestOptions)
+ : requestOpenAI(settings, imageDataUrl, requestInstruction, fetchImpl, requestOptions);
+ };
+ const perform = async (requestInstruction, requestKind = "primary") => {
+ const response = await request(requestInstruction, requestKind);
try {
return { response, normalized: normalizeVisionResult(parseJson(response.content), input.catalog) };
} catch (error) {
@@ -347,18 +368,16 @@ export async function analyzeImageWithVision(input = {}, fetchImpl = fetch) {
}
};
let firstUsage;
- let outputCorrectionRequests = 0;
let completed;
try {
completed = await perform(instruction);
} catch (error) {
if (!(error instanceof VisionOutputError)) throw error;
firstUsage = error.usage;
- outputCorrectionRequests = 1;
try {
- completed = await perform(`${instruction}\nThe previous response was empty or structurally unusable. Return one corrected JSON object now; do not add commentary or markdown.`);
+ completed = await perform(`${instruction}\nThe previous response was empty or structurally unusable. Return one corrected JSON object now; do not add commentary or markdown.`, "correction");
} catch (correctionError) {
- correctionError.attempts = { outputCorrectionRequests };
+ correctionError.attempts = { outputCorrectionRequests: visionCorrectionCount(requestBudget, correctionCountAtStart) };
correctionError.usage = addVisionUsage(firstUsage, correctionError.usage);
throw correctionError;
}
@@ -369,11 +388,30 @@ export async function analyzeImageWithVision(input = {}, fetchImpl = fetch) {
profileFingerprint: await visionAnalysisProfileFingerprint(settings, locale),
providerType: settings.nativeProvider?.id || settings.activeProvider,
model: response.model,
- attempts: { outputCorrectionRequests },
+ attempts: { outputCorrectionRequests: visionCorrectionCount(requestBudget, correctionCountAtStart) },
usage: addVisionUsage(firstUsage, response.usage)
};
}
+function consumeVisionRequestBudget(budget, requestKind) {
+ const maxProviderCalls = Math.max(1, Number(budget?.maxProviderCalls) || ANALYSIS_RETRY_POLICY.maxProviderCallsPerItem);
+ const providerCalls = Math.max(0, Number(budget?.providerCalls) || 0);
+ if (providerCalls >= maxProviderCalls) {
+ const error = new Error(`单张图片最多请求 AI 服务 ${maxProviderCalls} 次,本次已停止继续请求`);
+ error.code = "vision_request_budget_exhausted";
+ throw error;
+ }
+ budget.maxProviderCalls = maxProviderCalls;
+ budget.providerCalls = providerCalls + 1;
+ if (requestKind === "correction") {
+ budget.outputCorrectionRequests = Math.max(0, Number(budget.outputCorrectionRequests) || 0) + 1;
+ }
+}
+
+function visionCorrectionCount(budget, start) {
+ return Math.max(0, (Number(budget?.outputCorrectionRequests) || 0) - start);
+}
+
export async function evaluateCreativeOutputWithVision(input = {}, fetchImpl = fetch) {
const settings = requireVisionSettings(input.settings);
const imageDataUrl = requireImageDataUrl(input.imageDataUrl);
@@ -418,8 +456,8 @@ export async function blobToDataUrl(blob) {
export function visionProtocolDescription(locale = "zh-CN") {
return locale === "en"
- ? "Fixed input: the current image, measured canvas when available, fixed taxonomy paths, and these vision rules. Fixed output: one complete VisualAnalysisV2 reconstruction record and 0–6 compact search tags in one call. Existing detail tags, prompt text, title, URL, project, and other cases are never sent."
- : "固定输入:当前图片、可用的程序实测画布、固定分类路径和本页图片规则。固定输出:单次调用完成一份 VisualAnalysisV2 高保真重建记录和 0–6 个紧凑检索标签;不发送已有三级标签、原提示词、标题、网址、项目或其他案例。";
+ ? "Fixed input: the current image, fixed taxonomy paths, and these vision rules. Fixed output: one self-contained reconstructionPrompt and 1–6 compact search tags in one call. The reconstructionPrompt must cover every visibly reconstructable detail that matters for reuse; do not invent hidden facts, sound, or workflow."
+ : "固定输入:当前图片、固定分类路径和本页图片规则。固定输出:单次调用只返回一个可独立使用的 reconstructionPrompt 和 1–6 个紧凑检索标签;reconstructionPrompt 必须覆盖所有适用的可复刻可见细节,不编造不可见事实、声音或工作流。";
}
export async function visionAnalysisProfileFingerprint(settingsValue = {}, localeValue = "zh-CN") {
@@ -452,7 +490,7 @@ async function requestOpenAI(settings, imageDataUrl, instruction, fetchImpl, opt
async function requestResponses(provider, imageDataUrl, instruction, fetchImpl, options = {}) {
const schema = options.schema ?? VISUAL_MODEL_RESPONSE_SCHEMA;
- const schemaName = options.schemaName ?? "vision_analysis_box_2d_v1";
+ const schemaName = options.schemaName ?? "vision_reconstruction_tags_v1";
const body = {
model: provider.model,
store: false,
@@ -466,6 +504,7 @@ async function requestResponses(provider, imageDataUrl, instruction, fetchImpl,
]
}]
};
+ body.reasoning = { effort: "none" };
const payload = await requestJson(provider.endpoint, provider.apiKey, body, fetchImpl);
const refusal = extractOpenAIRefusal(payload);
if (refusal) throw new Error(`${provider.serviceName} 拒绝分析这张图片:${refusal}`);
@@ -476,16 +515,18 @@ async function requestResponses(provider, imageDataUrl, instruction, fetchImpl,
async function requestCompatible(settings, imageDataUrl, instruction, fetchImpl, options = {}) {
const { url } = endpointDetails(settings.compatible.endpoint);
+ const deepseekCompatible = isDeepSeekEndpoint(url);
if (settings.compatible.protocol === "responses") {
return requestResponses({
endpoint: url,
apiKey: settings.compatible.apiKey,
model: settings.compatible.model,
- serviceName: "兼容服务"
+ serviceName: "兼容服务",
+ disableReasoning: deepseekCompatible
}, imageDataUrl, instruction, fetchImpl, options);
}
const schema = options.schema ?? VISUAL_MODEL_RESPONSE_SCHEMA;
- const schemaName = options.schemaName ?? "vision_analysis_box_2d_v1";
+ const schemaName = options.schemaName ?? "vision_reconstruction_tags_v1";
const structuredInstruction = settings.compatible.structuredOutput === "json_object"
? `${instruction}\nJSON property names are case-sensitive. Return exactly one object matching this JSON Schema: ${JSON.stringify(schema)}`
: instruction;
@@ -503,6 +544,7 @@ async function requestCompatible(settings, imageDataUrl, instruction, fetchImpl,
]
}]
};
+ if (deepseekCompatible) body.thinking = { type: "disabled" };
const payload = await requestJson(url, settings.compatible.apiKey, body, fetchImpl);
const choice = payload?.choices?.[0];
const content = choice?.message?.content;
@@ -522,6 +564,26 @@ function compatibleEmptyResultMessage(finishReason, fallback = "") {
return prefix || "兼容服务响应缺少可用内容,本次没有写入";
}
+function visionHttpErrorMessage(status) {
+ const code = Number(status) || 0;
+ if (code === 401 || code === 403) return "图片分析认证失败,请检查 API Key、模型权限和接口配置";
+ if (code === 408) return "图片分析超时,请稍后重试或降低并发";
+ if (code === 409) return "图片分析请求发生冲突,请稍后重试";
+ if (code === 413) return "图片分析请求过大,请换更小的图片或降低输入体积";
+ if (code === 429) return "图片分析请求过于频繁,请稍后重试";
+ if (code >= 500 && code <= 599) return "图片分析服务暂时不可用,请稍后重试";
+ return "图片分析失败,请检查模型、协议和输出格式";
+}
+
+function isDeepSeekEndpoint(url) {
+ try {
+ const { hostname } = new URL(url);
+ return /(^|\.)deepseek\.com$/i.test(hostname);
+ } catch {
+ return false;
+ }
+}
+
async function requestGeminiVision(provider, imageDataUrl, instruction, fetchImpl, options = {}) {
const match = imageDataUrl.match(/^data:(image\/[^;]+);base64,(.+)$/i);
if (!match) throw new Error("Gemini 图片输入格式无效");
@@ -556,9 +618,12 @@ async function requestGeminiVision(provider, imageDataUrl, instruction, fetchImp
}
const payload = await response.json().catch(() => ({}));
if (!response.ok) throw new VisionApiError(
- `Gemini 图片分析失败:${String(payload?.error?.message ?? `HTTP ${response.status}`)}`,
+ visionHttpErrorMessage(response.status),
response.status,
- { retryAfterMs: retryAfterMilliseconds(response.headers?.get?.("retry-after")) }
+ {
+ retryAfterMs: retryAfterMilliseconds(response.headers?.get?.("retry-after")),
+ detail: String(payload?.error?.message ?? payload?.message ?? "").trim()
+ }
);
const content = (payload?.candidates?.[0]?.content?.parts ?? []).map((part) => part?.text || "").join("").trim();
if (!content) throw new VisionOutputError(options.emptyResultMessage || "Gemini 没有返回可用的画面描述");
@@ -594,8 +659,9 @@ async function requestJson(url, apiKey, body, fetchImpl) {
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
const detail = String(payload?.error?.message ?? payload?.message ?? "").trim();
- throw new VisionApiError(`图片分析失败${detail ? `:${detail}` : `(HTTP ${response.status})`}`, response.status, {
- retryAfterMs: retryAfterMilliseconds(response.headers?.get?.("retry-after"))
+ throw new VisionApiError(visionHttpErrorMessage(response.status), response.status, {
+ retryAfterMs: retryAfterMilliseconds(response.headers?.get?.("retry-after")),
+ detail
});
}
return payload;
diff --git a/visual-analysis.js b/visual-analysis.js
index b5822f9..eb4332f 100644
--- a/visual-analysis.js
+++ b/visual-analysis.js
@@ -2,7 +2,7 @@ import { analysisTaxonomyPayload, validateAnalysisTagResponse } from "./tag-taxo
export const VISUAL_ANALYSIS_VERSION = 2;
export const VISUAL_SET_SUMMARY_VERSION = 1;
-export const VISUAL_MODEL_PROTOCOL_VERSION = "box_2d-yxyx-v1";
+export const VISUAL_MODEL_PROTOCOL_VERSION = "reconstruction-tags-v1";
export const VISUAL_ANALYSIS_DIMENSIONS = Object.freeze([
"subject",
"scene",
@@ -175,20 +175,25 @@ export function compileVisualAnalysisInstruction({ catalog, customInstruction =
? "Write all descriptions, facts, labels, limitations, and the reconstruction prompt in English. Preserve exact visible spelling."
: "所有描述、事实、标签、限制项和重建提示词使用简体中文;画面中的文字保留原始拼写。";
const measured = measuredCanvas?.width && measuredCanvas?.height
- ? `programMeasuredCanvasPixels=${JSON.stringify({ width: measuredCanvas.width, height: measuredCanvas.height })}; these pixel dimensions describe only the source file and must never be copied into box_2d.`
- : "programMeasuredCanvasPixels=unavailable; estimate the canvas size, but never use estimated pixel dimensions inside box_2d.";
+ ? `sourceCanvasPixels=${JSON.stringify({ width: measuredCanvas.width, height: measuredCanvas.height })}; use this only to determine the visible aspect ratio and relative composition.`
+ : "sourceCanvasPixels=unavailable; infer only the visible aspect ratio and relative composition.";
+ const reconstructionChecklist = locale === "en"
+ ? "Build reconstructionPrompt from this internal ten-dimension checklist: (1) subjects and count, appearance, pose and relative scale; (2) scene, time, environment and foreground/midground/background; (3) actions, interactions and physical state; (4) visual style, medium, rendering, materials and textures; (5) framing, camera angle, lens feel, composition, focus and depth; (6) light sources, direction, contrast, palette and grading; (7) mood and narrative atmosphere; (8) visible text, typography, graphic marks and overlays; (9) aspect ratio, medium and image-quality traits; (10) reliably visible production or post-processing traits only. This checklist guides one continuous prompt; do not return ten separate sections."
+ : "用十维度在内部检查后写成一段连续的 reconstructionPrompt,不要输出十个独立分区。十维度是:主体、场景、动作、风格材质、构图镜头、光线色彩、情绪、可见文字图形、媒介画质、制作表现。具体检查:(1)主体数量、外观、姿态、朝向、相对位置与比例;(2)场景、时间环境、前景/中景/背景;(3)动作、交互与物理状态;(4)视觉风格、媒介、渲染、材质与纹理;(5)画幅、机位视角、镜头感、构图、焦点与景深;(6)光源、方向、明暗、色彩方案与调色;(7)情绪与叙事氛围;(8)可见文字、字体观感、图形标记与叠加层;(9)画幅比例、媒介与画质特征;(10)只有可靠可见时才写制作与后期表现。";
+ const completenessCheck = locale === "en"
+ ? "Before returning, check all four corners, foreground, main subject area, background, overlays, borders, and visible text. Include exact legible text and its typography or placement when useful for reconstruction. Omit uncertain or not applicable details instead of naming them as missing; especially do not invent sound, workflow, authors, brands, hidden objects, or AI probability."
+ : "返回前检查画面四角、前景、主体区、背景、叠加层、边缘和所有可见文字;对复刻有用且能辨认的文字要逐字保留,并写明字体观感与位置。不确定或不适用的内容直接省略,不要写成缺失项;尤其不要编造声音、工作流、作者、品牌、隐藏物体或 AI 概率。";
return [
"Analyze only the attached image in one single visual-analysis call.",
locale === "en" ? "Complete the full analysis in this single call; no second visual audit is allowed." : "必须在这一次单次分析中完成全部拆解与自检,不进行第二次视觉复审。",
language,
String(customInstruction ?? "").trim().slice(0, 1200),
measured,
- "Produce a reconstruction-grade inventory of every visible subject, background object, decoration, text block, mark, edge detail, and occlusion. Do not infer off-image facts, authors, brands, or hidden objects.",
- "For every visible element and OCR region, return box_2d exactly as [y_min, x_min, y_max, x_max] using relative integers from 0 to 1000. These are frame-relative edges, never pixel dimensions: 0 <= y_min < y_max <= 1000 and 0 <= x_min < x_max <= 1000. Do not return x/y/width/height.",
- "Record coverage percentage, depth, occlusion, relationships, material, texture, color, lighting, pose, orientation, and typography wherever visible.",
- `Return each of these ten visual dimensions exactly once and in this order: ${VISUAL_ANALYSIS_DIMENSIONS.join(", ")}. Mark a dimension applicable=false with empty facts when it is not visibly applicable; never invent content to fill it.`,
- "Mark quantitative sources as measured, estimated, or not_observable. OCR must distinguish exact, partial, and unreadable text. reconstructionPrompt must be self-contained and usable without the image. It must synthesize every reconstruction-relevant visible fact recorded in canvas, elements, dimensions, and OCR, including aspect ratio, subject count, relative position and scale, depth and occlusion, materials, colors, lighting, focus, typography, and exact legible text; do not merely summarize the scene.",
- "Before returning, inspect all four corners, foreground, subject area, background, overlays, and text. Put any still-visible omission in completeness.omittedVisibleElements; an empty array asserts that the single-call completeness check found none.",
+ "只输出 reconstructionPrompt 和 tags。",
+ reconstructionChecklist,
+ completenessCheck,
+ "reconstructionPrompt must be self-contained, detailed enough to recreate the image without seeing it, and limited to visible evidence. Preserve spatial relationships, relative scale, depth, occlusion, exact legible text, and distinctive visual traits; do not merely summarize the scene.",
+ "tags must contain one to six valid, compact, search-oriented labels from the fixed taxonomy paths; prefer the highest-value visible cues.",
`fixedPaths=${analysisTaxonomyPayload(catalog, locale)}`,
"Return exactly one JSON object matching the supplied visual-model response schema. Do not output commentary, markdown, scores, hidden reasoning, or additional fields."
].filter(Boolean).join("\n");
@@ -200,6 +205,24 @@ export function normalizeVisualModelResponse(value, catalogValue) {
}
const source = normalizeKnownRootFieldCasing(value);
const tagDiagnostics = partitionModelTags(source.tags, catalogValue);
+ if (!tagDiagnostics.accepted.length) {
+ throw new Error("视觉模型没有返回至少一个有效检索标签,本次没有写入");
+ }
+ const legacyFieldsPresent = ["description", "canvas", "elements", "dimensions", "ocr", "limitations", "completeness"]
+ .some((field) => Object.hasOwn(source, field));
+ if (!legacyFieldsPresent && Object.hasOwn(source, "reconstructionPrompt")) {
+ const reconstructionPrompt = requiredText(source.reconstructionPrompt, "视觉模型没有返回可独立使用的重建提示词");
+ return {
+ reconstructionPrompt,
+ description: reconstructionPrompt,
+ tags: tagDiagnostics.accepted,
+ version: VISUAL_ANALYSIS_VERSION,
+ quality: "complete",
+ missingFields: [],
+ normalizationDiagnostics: tagDiagnostics.rejections,
+ tagDiagnostics: { rejectedCount: tagDiagnostics.rejectedCount, rejections: tagDiagnostics.rejections }
+ };
+ }
const converted = {
...source,
elements: (Array.isArray(source.elements) ? source.elements : []).map(convertModelBoxIfValid),
@@ -389,21 +412,17 @@ export function prepareVisualSetSummary(values, locale = "zh-CN") {
missingAssetIds.push(assetId);
continue;
}
- try {
- const analysis = normalizeVisualAnalysisV2(visualAnalysisPayload(item.analysis));
- assets.push({
- assetId,
- description: analysis.description,
- canvas: analysis.canvas,
- elements: analysis.elements,
- dimensions: analysis.dimensions,
- ocr: analysis.ocr,
- reconstructionPrompt: analysis.reconstructionPrompt,
- limitations: analysis.limitations
- });
- } catch {
+ const reconstructionPrompt = String(item.analysis.reconstructionPrompt ?? "").trim();
+ const tags = (Array.isArray(item.analysis.tags) ? item.analysis.tags : []).flatMap((tag) => {
+ const g = String(tag?.g ?? "").trim();
+ const t = String(tag?.t ?? "").trim();
+ return g && t ? [{ g, t }] : [];
+ }).slice(0, 6);
+ if (!reconstructionPrompt || !tags.length) {
missingAssetIds.push(assetId);
+ continue;
}
+ assets.push({ assetId, reconstructionPrompt, tags });
}
return {
ready: missingAssetIds.length === 0 && assets.length > 0,
@@ -417,8 +436,8 @@ export function prepareVisualSetSummary(values, locale = "zh-CN") {
export function compileVisualSetSummaryInstruction(locale = "zh-CN") {
return locale === "en"
- ? "Summarize the saved per-image VisualAnalysisV2 records as one creative set. Do not request or infer from source images. Return strict JSON with imageRoles, sharedVisualSystem, differences, continuity, compositionRules, and reusablePrompt. Cover every assetId exactly once in imageRoles."
- : "仅汇总已保存的逐图 VisualAnalysisV2 记录,不请求原图,也不把主图或拼图当作缺失图片的替代。严格返回 JSON:imageRoles(每个 assetId 恰好一次)、sharedVisualSystem(共同视觉系统)、differences(差异)、continuity(连续关系)、compositionRules(组合规律)、reusablePrompt(不依赖原图的可复用创作提示词)。";
+ ? "Summarize only the saved per-image reconstruction prompts and search tags as one creative set. Do not request or infer from source images. Return strict JSON with imageRoles, sharedVisualSystem, differences, continuity, compositionRules, and reusablePrompt. Cover every assetId exactly once in imageRoles."
+ : "仅汇总已保存的逐图反推提示词与检索标签,不请求原图,也不把主图或拼图当作缺失图片的替代。严格返回 JSON:imageRoles(每个 assetId 恰好一次)、sharedVisualSystem(共同视觉系统)、differences(差异)、continuity(连续关系)、compositionRules(组合规律)、reusablePrompt(不依赖原图的可复用创作提示词)。";
}
export function normalizeVisualSetSummaryV1(value, assetIds = []) {
@@ -531,14 +550,28 @@ function normalizeBbox(value) {
}
function createVisualModelResponseSchema() {
- const schema = structuredClone(VISUAL_ANALYSIS_SCHEMA);
- for (const collection of ["elements", "ocr"]) {
- const item = schema.properties[collection].items;
- item.required = item.required.map((field) => field === "bbox" ? "box_2d" : field);
- delete item.properties.bbox;
- item.properties.box_2d = MODEL_BOX_SCHEMA;
- }
- return schema;
+ return {
+ type: "object",
+ additionalProperties: false,
+ required: ["reconstructionPrompt", "tags"],
+ properties: {
+ reconstructionPrompt: { type: "string", minLength: 1 },
+ tags: {
+ type: "array",
+ minItems: 1,
+ maxItems: 6,
+ items: {
+ type: "object",
+ additionalProperties: false,
+ required: ["g", "t"],
+ properties: {
+ g: { type: "string" },
+ t: { type: ["string", "null"] }
+ }
+ }
+ }
+ }
+ };
}
function fixedTagGroupIds(catalog) {
diff --git a/visuals.js b/visuals.js
index cbbb92b..68e4445 100644
--- a/visuals.js
+++ b/visuals.js
@@ -73,11 +73,12 @@ export function entryPalette(entryValue = {}) {
export function primaryVisionAnalysis(entryValue = {}) {
const analysis = primaryVisual(entryValue)?.visionAnalysis;
- return analysis && !analysis.invalidated ? analysis : null;
+ return analysis && !analysis.invalidated && analysis.quality !== "partial" ? analysis : null;
}
export function primaryVisionDescription(entryValue = {}) {
- return clean(primaryVisionAnalysis(entryValue)?.description);
+ const analysis = primaryVisionAnalysis(entryValue);
+ return clean(analysis?.reconstructionPrompt || analysis?.description);
}
export function visualDescriptions(entryValue = {}) {