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

Release 1.24.0: library continuity, capture and creative workflow fixes (#28)

wchao6891ec668de4de3c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5927fbf..3b21d57 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,17 @@
了解每个版本带来的功能变化与使用改善。下载请前往 [GitHub Releases](https://github.com/wchao6891/PromptDirector/releases/latest)。
+## 1.24.0
+
+- 项目按文件夹组织案例:拖动移动,显式复制保留独立副本;改善项目树、案例定位与删除恢复。
+- 优化完整备份的摘要复用与阶段进度,保留磁盘回读校验;改进共享原件恢复并识别 Skill 附件类型。
+- 本机批量导入按短批次提交,失败项保留重试,减少逐项整库处理的等待。
+- 改善 Higgsfield 当前作品与项目正文的采集边界;Pinterest 按作品补充标题、作者、来源和可取得的互动信息,避免列表界面文字混入资料。
+- 案例图片支持原生右键操作和原件拖出;统一滚动区域表现,保护弹窗中的未完成输入,视频网址支持补全协议。
+- Skill 选材显示视频封面并支持预览,项目名称完整展开,下滑自动续载;提炼完成直接展示 Markdown,返回选材保留草稿。
+- 创作台参考视频在图片和视频两种创作方向下均可预览、播放,统一播放图标;预览不改变所选参考和模型输入规则。
+- 改善批量分析收尾、设置页稳定性和窄屏布局。
+
## 1.23.0
- 网页采集可直接点选图片与正文,补充评论和剪贴板内容;成功项清理,失败项保留重试,重复采集也应用本次明确选择的分类。
diff --git a/docs/DATA_COMPATIBILITY.md b/docs/DATA_COMPATIBILITY.md
index eac927c..102a63f 100644
--- a/docs/DATA_COMPATIBILITY.md
+++ b/docs/DATA_COMPATIBILITY.md
@@ -2,10 +2,18 @@
应用升级继续保留案例、原始媒体、用户编辑、标签、项目、回收站和创作记录。应用版本与数据格式版本分别管理;更新插件不需要常规导出或重新导入资料。
+## 项目与副本
+
+案例按文件夹整理,移动改变所属项目,复制创建独立案例。旧版本同一案例的多个项目位置会分别保留为独立副本;组合顺序、正文、标签和原件保留。转换前在本机保存恢复快照,与转换结果一起提交;写入失败保持原资料。
+
+副本可共享原件存储,删除或撤回时检查其他引用。导出会为共享媒体分配独立包内编号,保留正文、封面、内嵌媒体和对应原文件。
+
## 分享包
当前版本导出最新格式,同时支持导入已正式发布的历史分享包格式。导入前会检查版本、文件完整性和案例关系,并列出可保留或无法恢复的内容。单个损坏资源不会阻断其他可恢复案例。
+导入含项目结构的资料时,不同项目中的相同内容保留为独立案例;重复判断使用完整项目路径,不能只比较末级项目名称。组合案例的不同成员也不会仅因内容相同被折叠。
+
## 完整资料夹备份
完整备份用于换电脑恢复,包含回收站以及可读取的本机链接原件。安全合并保留现有资料;精确替换需要完整备份,并在提交前建立恢复点。写入失败或可用空间不足时,原资料库保持不变。
@@ -16,6 +24,8 @@
同步保留可见的冲突副本,避免覆盖无法确认相同的内容。原设备的安装目录授权不会作为另一台设备的有效授权;升级安装位置与可迁移的案例资料分开保存。
+同步中的内容去重遵守项目与组合边界,保留跨项目副本及其各自引用。
+
## 中断与重试
导入、恢复或同步中断后,可以继续检查已有结果。无法确定是否成功时会保留相关媒体,避免误删。重复确认不会重复写入相同的案例或再次替换已恢复的资料。
diff --git a/extension/asset-formats.js b/extension/asset-formats.js
index 162acfd..36b3a84 100644
--- a/extension/asset-formats.js
+++ b/extension/asset-formats.js
@@ -49,7 +49,7 @@ const DEFINITIONS = [
format("ass", "document", "subtitle", ["ass", "ssa"], ["text/x-ssa", "text/plain"], { plainText: true }),
format("sbv", "document", "subtitle", ["sbv"], ["text/plain"], { plainText: true }),
format("lrc", "document", "subtitle", ["lrc"], ["text/plain", "application/lrc"], { plainText: true }),
- format("skill", "attachment", "workflow", ["skill"], ["application/zip", "application/x-zip-compressed"], { extensionRequired: true }),
+ format("skill", "attachment", "workflow", ["skill"], ["application/zip", "application/x-zip-compressed", "application/vnd.openai.codex.skill"], { extensionRequired: true }),
format("photoshop", "attachment", "design-source", ["psd", "psb"], ["image/vnd.adobe.photoshop", "application/x-photoshop"]),
format("illustrator", "attachment", "design-source", ["ai"], ["application/postscript", "application/illustrator"]),
diff --git a/extension/assets/ui-icons.svg b/extension/assets/ui-icons.svg
index 3a76d4b..a2da858 100644
--- a/extension/assets/ui-icons.svg
+++ b/extension/assets/ui-icons.svg
@@ -58,6 +58,21 @@
<path d="M16 13H8" />
<path d="M16 17H8" />
</symbol>
+ <symbol id="icon-audio-lines" viewBox="0 0 24 24">
+ <path d="M2 10v3" />
+ <path d="M6 6v11" />
+ <path d="M10 3v18" />
+ <path d="M14 8v7" />
+ <path d="M18 5v13" />
+ <path d="M22 10v3" />
+ </symbol>
+ <symbol id="icon-file-box" viewBox="0 0 24 24">
+ <path d="M14 2v5a1 1 0 001 1h5" />
+ <path d="M14.692 22H18a2 2 0 002-2V8a2.4 2.4 0 00-.706-1.706l-3.588-3.588A2.4 2.4 0 0014 2H6a2 2 0 00-2 2v3.804" />
+ <path d="M2.264 13.752 7 16.5l4.737-2.748" />
+ <path d="M2.995 13.014A2 2 0 002 14.744v3.516a2 2 0 00.996 1.73l3 1.74a2 2 0 002.008 0l3-1.74A2 2 0 0012 18.26v-3.517a2 2 0 00-.995-1.73l-3-1.742a2 2 0 00-1.892-.064z" />
+ <path d="M7 16.5V22" />
+ </symbol>
<symbol id="icon-folder" viewBox="0 0 24 24">
<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" />
</symbol>
@@ -97,6 +112,24 @@
<rect width="18" height="18" x="3" y="3" rx="2" />
<path d="M9 3v18" />
</symbol>
+ <symbol id="icon-panel-left-close" viewBox="0 0 24 24">
+ <rect width="18" height="18" x="3" y="3" rx="2" />
+ <path d="M9 3v18" />
+ <path d="m16 15-3-3 3-3" />
+ </symbol>
+ <symbol id="icon-grip-vertical" viewBox="0 0 24 24">
+ <circle cx="9" cy="12" r="1" />
+ <circle cx="9" cy="5" r="1" />
+ <circle cx="9" cy="19" r="1" />
+ <circle cx="15" cy="12" r="1" />
+ <circle cx="15" cy="5" r="1" />
+ <circle cx="15" cy="19" r="1" />
+ </symbol>
+ <symbol id="icon-layers" viewBox="0 0 24 24">
+ <path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z" />
+ <path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12" />
+ <path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17" />
+ </symbol>
<symbol id="icon-paperclip" viewBox="0 0 24 24">
<path d="m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551" />
</symbol>
diff --git a/extension/background.js b/extension/background.js
index 21f3f3f..7b5fb39 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -29,6 +29,8 @@ import {
createSourceRule
} from "./classifier.js";
import { migrateLibraryState, needsMigration } from "./migration.js";
+import { planCaseCopies } from "./library-folder-ownership.js";
+import { remapEntryMediaIds } from "./library-portable-media.js";
import {
CONTENT_TYPE_VISIBILITY,
CONTENT_ROLES,
@@ -163,7 +165,7 @@ import { deleteLocalAssetHandle } from "./local-asset-store.js";
import {
LOCAL_ASSET_REFERENCE_RECORD_TYPE,
chunkedBlobFingerprint,
- findExactMediaDuplicate,
+ createExactMediaDuplicateIndex,
sha256Blob
} from "./local-media.js";
import { tempReferenceAssetIds, unreadReferenceImageAssets } from "./temp-references.js";
@@ -333,6 +335,7 @@ import {
normalizePageCaptureSitePayload
} from "./page-capture-site-adapters.js";
import { boundedMediaBlobFromResponse, fetchBoundedMedia, isSupportedDocumentMimeType } from "./bounded-media.js";
+import { enrichPinterestCandidates, readPinterestHtml } from "./pinterest-capture.js";
import { downloadPageCaptureVideo } from "./page-capture-video.js";
import { resolveXVideoSources } from "./x-video-capture.js";
import { readPageCaptureSupplement } from "./capture-supplement.js";
@@ -441,6 +444,7 @@ const STORAGE_KEYS = Object.freeze({
facetCatalog: "facetCatalog",
classificationRules: "classificationRules",
migrationBackup: "migrationBackup",
+ folderOwnershipBackup: "folderOwnershipBackup",
classificationResetBackup: "classificationResetBackup",
facetMigrationBackup: "creativeFacetMigrationBackupV5",
facetUndo: "facetUndo",
@@ -491,6 +495,7 @@ const SYNCED_STORAGE_KEYS = new Set([
const OFFSCREEN_DOCUMENT_PATH = "offscreen.html";
let writeQueue = Promise.resolve();
let captureWriteQueue = Promise.resolve();
+let stateMigration = null;
let creatingOffscreenDocument = null;
let visionAnalysisInFlight = false;
const aiProviderModule = createAiProviderModule();
@@ -1420,7 +1425,7 @@ async function collectPageCaptureTab(tab, options) {
if (activePageCapture?.sessionId === options.sessionId && activePageCapture.cancelled) return { candidates: [] };
const adapter = PAGE_CAPTURE_ADAPTERS.find((item) => item.id === siteData?.adapter);
let downloads = { items: [], failures: 0 };
- if (adapter?.fields?.downloadButtons) {
+ if (adapter?.fields?.downloadButtons && siteData?.captureScope !== "asset") {
const [downloadResult] = await chrome.scripting.executeScript({
target: { tabId: tab.id }, world: "MAIN", func: collectPageCaptureDownloads,
args: [{ contentSelector: adapter.fields.content[0], containerSelector: adapter.fields.mediaContainers[0],
@@ -1464,7 +1469,17 @@ async function collectPageCaptureTab(tab, options) {
siteData = await readPageCaptureSiteData(tab, { installObserver: false, maxCandidates: options.maxCandidates }) || siteData;
snapshot = { ...snapshot, candidates: siteData.candidates, siteStatus: siteData.completeness };
}
- snapshot = addDiscoveredVideos(snapshot, await discoveredVideosForTab(tab.id));
+ if (snapshot.adapter === "pinterest") {
+ const session = activePageCapture;
+ if (session && !session.pinterestMetadata) session.pinterestMetadata = new Map();
+ snapshot = await enrichPinterestCandidates(snapshot, {
+ cache: session?.pinterestMetadata, cancelled: () => Boolean(session?.cancelled)
+ });
+ }
+ // Scoped Higgsfield content must not inherit videos played in another Asset.
+ const scopedHiggsfield = siteData?.captureScope === "asset"
+ || snapshot.adapter === "higgsfield" && snapshot.candidates?.some(candidate => candidate.pageType === "article");
+ if (!scopedHiggsfield) snapshot = addDiscoveredVideos(snapshot, await discoveredVideosForTab(tab.id));
snapshot = await resolvePageCaptureVideoFrames(snapshot, tab.id, chrome.scripting);
snapshot = await resolveXVideoSources(snapshot, tab, chrome, { cancelled: () => Boolean(activePageCapture?.cancelled) });
return addVisiblePageCaptureFallbacks(snapshot, tab);
@@ -1536,8 +1551,15 @@ async function readPageCaptureSiteData(tab, { installObserver = true, maxCandida
maxTextCharacters: PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes
}]
});
+ if (/^https:\/\/(?:www\.)?pinterest\.com\/pin\/(?:[^/]*--)?\d+\/?(?:\?.*)?$/u.test(tab.url) && !sitePayloadResult?.result?.pin) {
+ const html = await readPinterestHtml(tab.url);
+ return normalizePageCaptureSitePayload(collectPageCaptureSitePayload({ pinterestUrl: tab.url, pinterestHtml: html,
+ maxCandidates, maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate,
+ maxTextCharacters: PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes }), tab.url);
+ }
return sitePayloadResult?.result?.adapter === "libtv" ? normalizeLibTvPublicPayload(sitePayloadResult.result) : normalizePageCaptureSitePayload(sitePayloadResult?.result, tab.url);
- } catch {
+ } catch (error) {
+ console.warn("Page capture site extraction failed:", error?.message || String(error));
return null;
}
}
@@ -2772,7 +2794,7 @@ async function undoLastSave() {
});
const visualIds = normalizeEntryMedia(removed).mediaAssets.filter((asset) => asset.storageMode === "managed").map((asset) => asset.id);
await chrome.storage.local.remove([STORAGE_KEYS.lastSaveUndo, screenshotStorageKey(removed.id)]);
- await Promise.allSettled(visualIds.map((visualId) => deleteMediaBlob(visualId)));
+ await deleteUnreferencedMedia(visualIds);
return { ok: true, message: "已撤回刚才保存的案例", removed, count: entries.length };
}
@@ -2783,6 +2805,33 @@ async function undoLastSave() {
return { ok: false, message: "原案例已经不存在,撤回记录已清理" };
}
const updated = restoreScreenshotSaveEntry(current, undo);
+ const retainedByOthers = collectRetainedLocalAssetIds({ ...state,
+ entries: state.entries.filter(entry => entry.id !== current.id) });
+ if (retainedByOthers.has(current.id)) {
+ let detached = updated;
+ let restoredId = "";
+ if (undo.hadScreenshot) {
+ const previous = await getScreenshotBlob(undo.backupEntryId);
+ if (!previous) throw new Error("撤回所需的截图备份不存在,未修改案例");
+ restoredId = `restored-image:${globalThis.crypto.randomUUID()}`;
+ await saveScreenshotBlob(restoredId, previous);
+ detached = remapEntryMediaIds(normalizeEntryMedia(updated), new Map([[current.id, restoredId]]));
+ const asset = detached.mediaAssets.find(item => item.id === restoredId);
+ if (asset) Object.assign(asset, { byteSize: previous.size, mimeType: previous.type,
+ contentHash: await sha256Blob(previous),
+ width: undo.previousMetadata.screenshotWidth || asset.width,
+ height: undo.previousMetadata.screenshotHeight || asset.height });
+ } else detached = removeEntryMedia(normalizeEntryMedia(updated), current.id);
+ try {
+ await commitLocalChanges({ [STORAGE_KEYS.entries]: state.entries.map(entry => entry.id === current.id ? detached : entry) });
+ } catch (error) {
+ if (restoredId) await deleteMediaBlob(restoredId).catch(() => undefined);
+ throw error;
+ }
+ await chrome.storage.local.remove(STORAGE_KEYS.lastSaveUndo);
+ await discardSaveUndoBackup(undo).catch(() => undefined);
+ return { ok: true, message: "已恢复原案例更新前的截图与图片分析", entry: detached, count: state.entries.length };
+ }
const replacedScreenshot = await getScreenshotBlob(current.id);
let restoredScreenshot = null;
if (undo.hadScreenshot) {
@@ -3061,6 +3110,10 @@ async function readState() {
stored[STORAGE_KEYS.aiPreferences] = aiConfiguration.preferences;
}
const shouldMigrate = needsMigration(stored);
+ if (stateMigration) {
+ await stateMigration;
+ return readState();
+ }
const migration = shouldMigrate ? migrateLibraryState(stored) : null;
let state = migration?.state ?? {
schemaVersion: SCHEMA_VERSION,
@@ -3075,6 +3128,12 @@ async function readState() {
};
if (shouldMigrate) {
const update = storagePayload(state);
+ if (migration.folderOwnershipMigrated && !stored[STORAGE_KEYS.folderOwnershipBackup]) {
+ update[STORAGE_KEYS.folderOwnershipBackup] = { state: Object.fromEntries(
+ ["entries", "organizerState", "compoundCases", "trashState"].map(key => [key, migration.backup[key]])
+ ) };
+ stored[STORAGE_KEYS.folderOwnershipBackup] = update[STORAGE_KEYS.folderOwnershipBackup];
+ }
if (!stored[STORAGE_KEYS.migrationBackup]) {
update[STORAGE_KEYS.migrationBackup] = migration?.backup;
}
@@ -3084,7 +3143,9 @@ async function readState() {
if (migration.resetPerformed && !stored[STORAGE_KEYS.classificationResetBackup]) {
update[STORAGE_KEYS.classificationResetBackup] = migration.backup;
}
- await commitLocalChanges(update);
+ stateMigration = commitLocalChanges(update);
+ try { await stateMigration; }
+ finally { stateMigration = null; }
await chrome.storage.local.remove("tagCatalog");
}
const recoveredVocabulary = recoverFullyArchivedFacets(state.facetCatalog);
@@ -3157,6 +3218,7 @@ async function readState() {
importStaging,
creativeSkills,
activeCreativeResult,
+ folderOwnershipBackup: stored[STORAGE_KEYS.folderOwnershipBackup],
libraryReplacementRecoveryPoint: normalizeLibraryReplacementRecoveryPoint(
stored[STORAGE_KEYS.libraryReplacementRecoveryPoint]
),
@@ -3605,7 +3667,7 @@ async function startImportJobAction(message) {
const keepById = new Map((Array.isArray(message.items) ? message.items : [])
.map((item) => [String(item?.stagedAssetId ?? "").trim(), item?.keepDuplicate === true]));
const jobItems = [];
- const batchAssets = [];
+ const duplicateIndex = createExactMediaDuplicateIndex(state.entries, { readBlob: getMediaBlob });
for (const value of incoming) {
const assetId = String(value?.assetId ?? "").trim();
const name = String(value?.name ?? "").trim();
@@ -3620,10 +3682,7 @@ async function startImportJobAction(message) {
const blob = assetId ? await getMediaBlob(assetId) : null;
if (!(blob instanceof Blob)) throw new Error(`没有读取到待导入文件:${name || assetId || "未命名"}`);
const file = new File([blob], name, { type: blob.type || value?.mimeType });
- const duplicate = await findExactMediaDuplicate(file, state.entries, {
- readBlob: getMediaBlob,
- candidateAssets: batchAssets
- });
+ const duplicate = await duplicateIndex.find(file);
const staged = addStagedAsset(staging, {
...value,
mimeType: blob.type || value?.mimeType,
@@ -3632,7 +3691,7 @@ async function startImportJobAction(message) {
duplicateAssetId: duplicate.duplicateAssetId
});
staging = staged.state;
- batchAssets.push({
+ duplicateIndex.add({
id: staged.asset.assetId,
byteSize: staged.asset.byteSize,
mimeType: staged.asset.mimeType,
@@ -3773,25 +3832,11 @@ async function runImportJobSlice() {
if (importRunnerActive) return;
importRunnerActive = true;
try {
- const stored = await chrome.storage.local.get([STORAGE_KEYS.importJobs, STORAGE_KEYS.importStaging]);
- let jobs = normalizeImportJobsState(stored[STORAGE_KEYS.importJobs]);
- const active = jobs.items.find((job) => ["queued", "running"].includes(job.status) && job.items.some((item) => item.status === "queued"));
+ const state = await readState();
+ const active = state.importJobs.items.find((job) =>
+ ["queued", "running"].includes(job.status) && job.items.some((item) => item.status === "queued"));
if (!active) return;
- const started = startImportJob(jobs, active.id);
- jobs = started.state;
- await commitLocalChanges({ [STORAGE_KEYS.importJobs]: jobs });
- const item = started.job.items.find((value) => value.status === "queued");
- try {
- await importStagedItem(started.job, item);
- } catch (error) {
- const latest = await chrome.storage.local.get(STORAGE_KEYS.importJobs);
- const failed = finishImportItem(latest[STORAGE_KEYS.importJobs], started.job.id, item.id, {
- status: "failed",
- error: userMessage(error)
- });
- await commitLocalChanges({ [STORAGE_KEYS.importJobs]: failed.state });
- await queueImportJobAnalysis(failed.job);
- }
+ await importStagedItems(state, active);
} finally {
importRunnerActive = false;
const stored = await chrome.storage.local.get(STORAGE_KEYS.importJobs);
@@ -3802,33 +3847,65 @@ async function runImportJobSlice() {
}
}
-async function importStagedItem(job, item) {
- const state = await readState();
- const staged = stagedAssetById(state.importStaging, item.stagedAssetId);
- if (!staged) throw new Error("暂存文件已经丢失,无法继续导入");
- if (staged.storageMode !== "reference" && !await getMediaBlob(staged.assetId)) {
- throw new Error(`本机媒体已经丢失:${staged.name}`);
+// Yield between short batches so queued cancellation and edits can run. This
+// bounds preparation work, not item count; large files still finish individually.
+const IMPORT_SLICE_PREPARE_MS = 100;
+
+async function importStagedItems(state, job) {
+ const started = startImportJob(state.importJobs, job.id);
+ let jobs = started.state;
+ let staging = state.importStaging;
+ let finished = started;
+ const imported = [];
+ const deadline = performance.now() + IMPORT_SLICE_PREPARE_MS;
+ const target = job.collectionId
+ ? state.organizerState.collections.find((collection) => collection.id === job.collectionId)
+ : null;
+ for (const item of started.job.items.filter((value) => value.status === "queued")) {
+ let result;
+ let staged;
+ let entry;
+ try {
+ staged = stagedAssetById(staging, item.stagedAssetId);
+ if (!staged) throw new Error("暂存文件已经丢失,无法继续导入");
+ if (job.collectionId && !target) throw new Error("导入目标项目已经不存在");
+ if (staged.storageMode !== "reference" && !await getMediaBlob(staged.assetId)) {
+ throw new Error(`本机媒体已经丢失:${staged.name}`);
+ }
+ if (staged.posterAssetId && !await getMediaBlob(staged.posterAssetId)) throw new Error(`视频或 GIF 封面已经丢失:${staged.name}`);
+ entry = importedEntryFromStagedAsset(state, staged, job, item);
+ result = { status: "imported", entryId: entry.id };
+ } catch (error) {
+ result = { status: "failed", error: userMessage(error) };
+ }
+ finished = finishImportItem(jobs, job.id, item.id, result);
+ jobs = finished.state;
+ if (entry) {
+ imported.push(entry);
+ staging = removeStagedAsset(staging, staged.id).state;
+ }
+ if (performance.now() >= deadline) break;
}
- if (staged.posterAssetId && !await getMediaBlob(staged.posterAssetId)) throw new Error(`视频或 GIF 封面已经丢失:${staged.name}`);
- const entry = importedEntryFromStagedAsset(state, staged, job, item);
- const entries = [...state.entries, entry];
- let organizerState = normalizeOrganizerState(state.organizerState, entries.map((value) => value.id));
- if (job.collectionId) {
- const target = organizerState.collections.find((collection) => collection.id === job.collectionId);
- if (!target) throw new Error("导入目标项目已经不存在");
- target.entryIds = [...new Set([...target.entryIds, entry.id])];
- organizerState = normalizeOrganizerState(organizerState, entries.map((value) => value.id));
- }
- const finished = finishImportItem(state.importJobs, job.id, item.id, { status: "imported", entryId: entry.id });
- const removed = removeStagedAsset(state.importStaging, staged.id);
+ const entries = [...state.entries, ...imported];
+ const organizerState = normalizeOrganizerState(state.organizerState, entries.map((entry) => entry.id));
+ if (target) {
+ const collection = organizerState.collections.find((value) => value.id === target.id);
+ collection.entryIds = [...new Set([...collection.entryIds, ...imported.map((entry) => entry.id)])];
+ }
+ // Cases, staging removal and job receipts share one durable commit. If it
+ // fails or the worker stops before it, queued items are safe to retry.
await commitLocalChanges({
- [STORAGE_KEYS.entries]: entries,
- [STORAGE_KEYS.organizerState]: organizerState,
- [STORAGE_KEYS.importJobs]: finished.state,
- [STORAGE_KEYS.importStaging]: removed.state
+ ...(imported.length ? {
+ [STORAGE_KEYS.entries]: entries,
+ [STORAGE_KEYS.organizerState]: organizerState
+ } : {}),
+ [STORAGE_KEYS.importJobs]: jobs,
+ [STORAGE_KEYS.importStaging]: staging
});
- await enqueueAutomaticLibraryMaintenance([entry]);
- await notifySaved(entries.length);
+ if (imported.length) {
+ await enqueueAutomaticLibraryMaintenance(imported);
+ await notifySaved(entries.length);
+ }
await queueImportJobAnalysis(finished.job);
}
@@ -4896,16 +4973,14 @@ async function deleteCreativeOutput(message) {
if (!located) return { ok: false, message: "没有找到这张创作结果" };
const run = removeCreativeOutput(located.run, located.output.visual.id);
const creativeRuns = replaceCreativeRun(state.creativeRuns, run);
- const usedByCase = state.entries.some((entry) =>
- entryMediaAssets(entry).some((visual) => visual.id === located.output.visual.id)
- );
+ const retained = collectRetainedLocalAssetIds({ ...state, creativeRuns }).has(located.output.visual.id);
if (located.output.visual.kind === "video") {
await commitLocalChanges({ [STORAGE_KEYS.creativeRuns]: creativeRuns });
- if (!usedByCase) await deleteMediaBlob(located.output.visual.id);
+ if (!retained) await deleteMediaBlob(located.output.visual.id);
return { ok: true, message: "生成结果已移除", creativeRuns };
}
await commitMetadataThenDeleteImages({
- imageIds: usedByCase ? [] : [located.output.visual.id],
+ imageIds: retained ? [] : [located.output.visual.id],
deleteImage: deleteScreenshotBlob,
commitMetadata: () => commitLocalChanges({ [STORAGE_KEYS.creativeRuns]: creativeRuns })
});
@@ -6034,12 +6109,23 @@ async function batchSetClassification(message) {
async function batchSetProject(message) {
const state = await readState();
+ if (message.mode === "copy" || message.mode === "add") {
+ const plan = planCaseCopies(state, uniqueNames(message.entryIds), message.collectionId);
+ await commitLocalChanges({
+ [STORAGE_KEYS.entries]: plan.state.entries,
+ [STORAGE_KEYS.organizerState]: plan.state.organizerState,
+ [STORAGE_KEYS.compoundCases]: plan.state.compoundCases
+ });
+ return { ok: true, message: `已复制 ${plan.copies.length} 个案例`,
+ updatedCount: plan.copies.length, entries: plan.state.entries,
+ organizerState: plan.state.organizerState, compoundCases: plan.state.compoundCases };
+ }
const validIds = new Set(state.entries.map((entry) => entry.id));
const requestedEntryIds = uniqueNames(message.entryIds);
const entryIds = requestedEntryIds.filter((entryId) => validIds.has(entryId));
if (!entryIds.length) return { ok: false, message: "案例不存在,未更新项目关系" };
const missingCount = requestedEntryIds.length - entryIds.length;
- const mode = ["remove", "move"].includes(message.mode) ? message.mode : "add";
+ const mode = message.mode === "remove" ? "remove" : "move";
let organizerState = normalizeOrganizerState(state.organizerState, [...validIds]);
if (!organizerState.collections.some((collection) => collection.id === String(message.collectionId ?? "").trim())) {
return { ok: false, message: "项目不存在" };
@@ -6151,6 +6237,7 @@ async function updateOrganizer(message) {
const validIds = new Set(state.entries.map((entry) => entry.id));
const entryIds = (Array.isArray(message.entryIds) ? message.entryIds : []).filter((id) => validIds.has(id));
organizerState = replaceCollectionEntries(organizerState, message.collectionId, entryIds);
+ organizerState = moveEntriesBetweenCollections(organizerState, null, message.collectionId, entryIds);
} else if (message.type === "SET_COLLECTION_VISIBILITY") {
organizerState = setCollectionVisibility(organizerState, message.collectionId, message.visibility);
}
@@ -7852,6 +7939,7 @@ function publicDomainState(state) {
function publicLibraryState(state) {
const {
+ folderOwnershipBackup: _folderOwnershipBackup,
facetUndo: _facetUndo,
composerSessions: _composerSessions,
lastSaveUndo,
diff --git a/extension/blob-digest.js b/extension/blob-digest.js
index e70345e..ffb202d 100644
--- a/extension/blob-digest.js
+++ b/extension/blob-digest.js
@@ -1,14 +1,17 @@
import { sha256 } from "./vendor/noble-hashes/sha2.js";
-export async function sha256Blob(blob) {
+export async function sha256Blob(blob, { onProgress } = {}) {
if (!(blob instanceof Blob)) throw new Error("无法计算无效媒体的内容摘要");
const hash = sha256.create();
const reader = blob.stream().getReader();
+ let completedBytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
hash.update(value);
+ completedBytes += value.byteLength;
+ if (onProgress) await onProgress({ completedBytes, totalBytes: blob.size });
}
return [...hash.digest()].map((value) => value.toString(16).padStart(2, "0")).join("");
} finally {
@@ -16,3 +19,20 @@ export async function sha256Blob(blob) {
reader.releaseLock();
}
}
+
+// Scope this to one operation. Fresh disk readback must use fresh Blob objects,
+// never a persisted asset id or a caller-supplied contentHash as proof of bytes.
+export function createBlobDigestCache() {
+ const digests = new WeakMap();
+ return async (blob, options) => {
+ if (!(blob instanceof Blob)) throw new Error("无法计算无效媒体的内容摘要");
+ if (!digests.has(blob)) {
+ const pending = sha256Blob(blob, options).catch(error => {
+ digests.delete(blob);
+ throw error;
+ });
+ digests.set(blob, pending);
+ }
+ return digests.get(blob);
+ };
+}
diff --git a/extension/capture-draft.js b/extension/capture-draft.js
index de5566c..21d72b0 100644
--- a/extension/capture-draft.js
+++ b/extension/capture-draft.js
@@ -208,6 +208,11 @@ function normalizeSourceContext(value = {}) {
provider: clean(sourceFactsValue.provider),
pageType: clean(sourceFactsValue.pageType),
itemId: clean(sourceFactsValue.itemId),
+ authorUrl: safeHttpUrl(sourceFactsValue.authorUrl),
+ originalSourceUrl: safeHttpUrl(sourceFactsValue.originalSourceUrl),
+ imageDescription: clean(sourceFactsValue.imageDescription),
+ metadataError: clean(sourceFactsValue.metadataError),
+ engagementObservedAt: validIso(sourceFactsValue.engagementObservedAt),
author: clean(sourceFactsValue.author),
handle: clean(sourceFactsValue.handle),
publishedAt: validIso(sourceFactsValue.publishedAt),
diff --git a/extension/composer-page.css b/extension/composer-page.css
index 0d25b54..9f2ec39 100644
--- a/extension/composer-page.css
+++ b/extension/composer-page.css
@@ -549,3 +549,12 @@
.composer-reference-input-choice:has(input:enabled):hover { background: var(--hover); }
.composer-reference-input-choice input { flex: none; width: 16px; height: 16px; margin: 0; accent-color: var(--ui-accent); }
.composer-reference-input-choice:has(input:disabled) { color: var(--muted); cursor: default; }
+
+.composer-case-select-preview { position: relative; }
+.composer-video-cover { display: grid; place-items: center; width: 100%; height: 180px; overflow: hidden; }
+.composer-video-cover :is(img, video), .composer-case-select-preview > .case-video-preview { width: 100%; height: 100%; object-fit: contain; }
+.composer-case-select-preview > .case-video-preview { position: absolute; inset: 0; pointer-events: none; }
+.composer-reference-preview-dialog > .skill-source-video { height: 100%; align-content: center; }
+.composer-reference-preview-dialog > .skill-source-video :is(video, iframe) { max-height: calc(100dvh - 120px); }
+
+.composer-case-inspect.icon-button { width: 32px; height: 32px; padding: 6px; }
diff --git a/extension/composer-page.js b/extension/composer-page.js
index d39a8df..75a9c9f 100644
--- a/extension/composer-page.js
+++ b/extension/composer-page.js
@@ -1,3 +1,5 @@
+import { createSourceVideoPreview, bindSourceVideoCover } from "./source-video-preview.js";
+import { bindVideoHoverPreview } from "./video-hover-preview.js";
import { sendWithGenerationPromptConfirmation } from "./image-generation-confirmation.js";
import { showSkillCoverImage, clearSkillCoverImage } from "./skill-cover-ui.js";
import { readSkillCover } from "./skill-cover.js";
@@ -162,6 +164,11 @@ let workspaceMode = "references";
let feedbackTimer = 0;
const COMPOSER_TITLE_MAX_CHARACTERS = 36;
const thumbnailUrls = new Map();
+let referenceVideoCleanups = [];
+function releaseReferenceVideos() {
+ referenceVideoCleanups.forEach(release => release());
+ referenceVideoCleanups = [];
+}
const openJudgmentIds = new Set();
const judgmentFeedbackById = new Map();
const imageObserver = new IntersectionObserver((items) => {
@@ -298,6 +305,7 @@ function bindEvents() {
if (event.key === "Escape") closeComposerModelMenu();
});
addEventListener("beforeunload", () => {
+ releaseReferenceVideos();
for (const url of thumbnailUrls.values()) URL.revokeObjectURL(url);
});
chrome.storage.onChanged.addListener((changes, areaName) => {
@@ -2108,6 +2116,7 @@ function setReferenceWorkspaceMode(mode) {
}
function closeReferenceWorkspace() {
+ releaseReferenceVideos();
if (elements.composerReferenceWorkspace.contains(document.activeElement)) {
elements.composerReferenceOpen.focus({ preventScroll: true });
}
@@ -2187,6 +2196,7 @@ function renderSkills() {
}
function renderCasePicker() {
+ releaseReferenceVideos();
const query = elements.composerReferenceSearch.value.trim().toLocaleLowerCase();
const projectId = elements.composerReferenceProjectFilter.value;
const projectIds = projectId
@@ -2211,15 +2221,17 @@ function createCaseOption(entry) {
option.dataset.entryId = entry.id;
const referenceAssets = selectableReferenceAssets(entry, composerSession?.targetType);
const primaryAsset = referenceAssets.find((asset) => asset.id === entry.primaryMediaId) ?? referenceAssets[0];
- const previewAsset = referenceAssets.find((asset) => asset.id === referencePreviewAssetIds.get(entry.id)) ?? primaryAsset;
- if (previewAsset) referencePreviewAssetIds.set(entry.id, previewAsset.id);
+ const selectedPreviewAsset = referenceAssets.find((asset) => asset.id === referencePreviewAssetIds.get(entry.id)) ?? primaryAsset;
+ const previewAsset = selectedPreviewAsset ?? previewReferenceAsset(entry);
+ if (selectedPreviewAsset) referencePreviewAssetIds.set(entry.id, selectedPreviewAsset.id);
+ else referencePreviewAssetIds.delete(entry.id);
option.dataset.selected = String(referenceDraftSelections.has(entry.id));
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.className = "composer-case-preview-checkbox";
checkbox.disabled = !selectable;
checkbox.setAttribute("aria-label", `选择当前预览素材:${entry.title || t("未命名案例")}`);
- checkbox.checked = previewAsset ? referenceDraftSelections.get(entry.id)?.has(previewAsset.id) === true : referenceDraftSelections.has(entry.id);
+ checkbox.checked = selectedPreviewAsset ? referenceDraftSelections.get(entry.id)?.has(selectedPreviewAsset.id) === true : referenceDraftSelections.has(entry.id);
checkbox.addEventListener("change", () => {
const assetId = referencePreviewAssetIds.get(entry.id);
setDraftAssetSelected(entry.id, assetId || "", checkbox.checked);
@@ -2242,11 +2254,17 @@ function createCaseOption(entry) {
else syncCaseOptionSelection(option, entry);
renderReferenceSelection();
});
- const inspect = textEl("button", "composer-case-inspect", previewAsset?.kind === "video" ? "查看封面" : "查看原图");
+ const inspect = textEl("button", "composer-case-inspect", previewAsset?.kind === "video" ? "播放视频" : "查看原图");
inspect.type = "button";
+ if (previewAsset?.kind === "video") {
+ inspect.classList.add("icon-button");
+ inspect.setAttribute("aria-label", t("播放视频"));
+ inspect.title = t("播放视频");
+ setUiIcon(inspect, "play");
+ }
inspect.hidden = !previewAsset;
- inspect.disabled = previewAsset?.kind === "video" && !posterAssetForVideo(entry, previewAsset);
- inspect.addEventListener("click", () => openReferenceAssetPreview(entry, referencePreviewAssetIds.get(entry.id)));
+ inspect.disabled = false;
+ inspect.addEventListener("click", () => openReferenceAssetPreview(entry, referencePreviewAssetIds.get(entry.id) || previewAsset?.id));
visual.append(selectPreview, inspect);
option.append(checkbox, visual);
renderCasePreviewImage(option, entry, previewAsset?.id || "");
@@ -2372,9 +2390,20 @@ function setDraftAssetSelected(entryId, assetId, selected) {
function renderCasePreviewImage(option, entry, assetId) {
const surface = option.querySelector(".composer-case-select-preview");
if (!surface) return;
- const asset = selectableReferenceAssets(entry, composerSession?.targetType).find((item) => item.id === assetId);
+ const asset = previewReferenceAsset(entry, assetId);
if (!asset) return surface.replaceChildren(rawTextEl("span", "", t("文字资料")));
- const displayAsset = asset.kind === "video" ? posterAssetForVideo(entry, asset) : asset;
+ surface.releaseVideo?.();
+ if (asset.kind === "video") {
+ const cover = el("span", "composer-video-cover");
+ surface.replaceChildren(cover);
+ const releaseCover = bindSourceVideoCover(cover, entry, asset, null);
+ const hover = asset.storageMode !== "reference"
+ ? bindVideoHoverPreview(surface, { loadBlob: () => getMediaBlob(asset.id) }) : null;
+ surface.releaseVideo = () => { releaseCover(); hover?.destroy(); };
+ referenceVideoCleanups.push(surface.releaseVideo);
+ return;
+ }
+ const displayAsset = asset;
if (!displayAsset) return surface.replaceChildren(rawTextEl("span", "", t("视频")));
const image = document.createElement("img");
image.className = "composer-case-image";
@@ -2409,8 +2438,22 @@ function syncRenderedReferenceCards() {
async function openReferenceAssetPreview(entry, assetId) {
if (!assetId) return;
try {
- const asset = selectableReferenceAssets(entry, composerSession?.targetType).find((item) => item.id === assetId);
- const displayAsset = asset?.kind === "video" ? posterAssetForVideo(entry, asset) : asset;
+ const asset = previewReferenceAsset(entry, assetId);
+ if (asset?.kind === "video") {
+ const dialog = el("dialog", "composer-reference-preview-dialog");
+ const close = textEl("button", "icon-button", "×");
+ close.type = "button";
+ close.setAttribute("aria-label", t("关闭视频预览"));
+ const player = createSourceVideoPreview(entry, asset);
+ dialog.append(close, player);
+ close.addEventListener("click", () => dialog.close());
+ dialog.addEventListener("close", () => { player.releaseMedia(); dialog.remove(); }, { once: true });
+ document.body.append(dialog);
+ dialog.showModal();
+ player.querySelector("button").click();
+ return;
+ }
+ const displayAsset = asset;
const blob = displayAsset ? await getScreenshotBlob(displayAsset.id) : null;
if (!blob) throw new Error("无法读取原图");
const url = URL.createObjectURL(blob);
@@ -2435,6 +2478,13 @@ async function openReferenceAssetPreview(entry, assetId) {
}
}
+// Viewing a case is independent of which assets the current creative task can use.
+function previewReferenceAsset(entry, assetId = "") {
+ const assets = entryMediaAssets(entry).filter(asset => asset.usage !== "poster" && ["image", "video"].includes(asset.kind));
+ return assets.find(asset => asset.id === assetId)
+ ?? assets.find(asset => asset.id === entry.primaryMediaId) ?? assets[0];
+}
+
function selectableReferenceAssets(entry, targetType = "") {
return entryMediaAssets(entry).filter((asset) => asset.usage !== "poster" &&
(asset.kind === "image" || targetType === "video" && asset.kind === "video"));
diff --git a/extension/composer.html b/extension/composer.html
index 51602b8..d18bff9 100644
--- a/extension/composer.html
+++ b/extension/composer.html
@@ -9,6 +9,7 @@
<link rel="stylesheet" href="library.css" />
<link rel="stylesheet" href="composer-page.css" />
<link rel="stylesheet" href="skill-cover.css" />
+ <link rel="stylesheet" href="source-video-preview.css" />
</head>
<body class="composer-page">
<div id="composer-shell" class="composer-shell">
diff --git a/extension/document-viewer.js b/extension/document-viewer.js
index 93029d3..642ca79 100644
--- a/extension/document-viewer.js
+++ b/extension/document-viewer.js
@@ -58,7 +58,7 @@ export async function createPdfViewer(blob, title = "PDF") {
}
zoom.setAttribute("aria-label", "PDF 缩放");
toolbar.append(previous, pageStatus, next, zoom);
- const viewport = node("div", "pdf-page-viewport");
+ const viewport = node("div", "pdf-page-viewport ui-scrollbar");
const canvas = document.createElement("canvas");
canvas.setAttribute("aria-label", `${title} 页面`);
viewport.append(canvas);
diff --git a/extension/i18n.js b/extension/i18n.js
index c566efa..173aacd 100644
--- a/extension/i18n.js
+++ b/extension/i18n.js
@@ -1,6 +1,28 @@
import { normalizeUiPreferences, resolveLocale } from "./preferences.js";
const EN = Object.freeze({
+ "查看草稿": "View draft",
+ "返回选材": "Back to sources",
+ "重新提炼": "Refine again",
+ "关闭视频预览": "Close video preview",
+ "视频 · 点击播放": "Video · Click to play",
+ "视频预览不可用 · 点击检查": "Preview unavailable · Click to inspect",
+ "视频无法播放,请在案例库检查原件或打开来源": "Unable to play. Check the original in the library or open its source.",
+ "视频暂不可播放,请在案例库检查来源": "Video unavailable. Check its source in the library.",
+ "请先在案例库授权 YouTube 播放器": "Authorize the YouTube player in the library first.",
+ "全部展开": "Expand all",
+ "面板布局": "Panel layout",
+ "恢复默认布局": "Reset layout",
+ "标签筛选": "Tags",
+ "拖动排序,方向键调整位置": "Drag to reorder, or use arrow keys",
+ "仅当前项目、无筛选时可手动排序": "Manual ordering requires a single project without filters",
+ "案例视图": "Case view",
+ "瀑布流": "Masonry",
+ "列表": "List",
+ "项目路径": "Project path",
+ "包含子项目": "Include subprojects",
+ "打开项目": "Open project",
+
"部分内容未保存,已保留供重试": "Some content could not be saved and has been kept for retry.",
"播放视频": "Play video",
"AI 整理输出被截断,正式标签库没有改变": "Tag organization output was truncated; the tag library was not changed.",
@@ -643,6 +665,19 @@ const EN = Object.freeze({
"选择文件": "Choose files",
"选择整个文件夹": "Choose entire folder",
"上次导入 · 查看": "Last import · View",
+ "正在检查媒体": "Checking media",
+ "正在核对备份资料…": "Checking backup records…",
+ "正在检查图片": "Checking images",
+ "正在准备备份清单…": "Preparing backup manifest…",
+ "正在准备备份清单": "Preparing backup manifest",
+ "正在读取已写入的文件…": "Reading written files…",
+ "正在读取已写入的文件": "Reading written files",
+ "正在校验已写入的文件": "Verifying written files",
+ "正在检查已写入的图片": "Checking written images",
+ "正在完成备份…": "Finalizing backup…",
+ "正在读取备份文件…": "Reading backup files…",
+ "正在读取备份文件": "Reading backup files",
+ "正在校验备份文件": "Verifying backup files",
"正在检查文件…": "Checking files…",
"正在导入": "Importing",
"撤销本次导入": "Undo this import",
@@ -1235,6 +1270,7 @@ const EN = Object.freeze({
"加入项目…": "Add to project...",
"选择项目…": "Choose a project...",
"同时加入": "Add as well",
+ "复制到项目": "Copy to project",
"移出当前项目": "Remove from current project",
"移出项目": "Remove from project",
"新建并移动": "Create and move",
diff --git a/extension/lib.js b/extension/lib.js
index b272866..4fbb54f 100644
--- a/extension/lib.js
+++ b/extension/lib.js
@@ -17,6 +17,7 @@ import { entryPalette, normalizeEntryVisuals, primaryVisionDescription } from ".
import { normalizeCompoundCases } from "./compound-cases.js";
import { CURRENT_LIBRARY_PACKAGE_VERSION, LIBRARY_PACKAGE_FORMAT } from "./library-package-format.js";
import { normalizeTrashState } from "./trash.js";
+import { projectPortableMedia } from "./library-portable-media.js";
export const DEFAULT_SETTINGS = Object.freeze({
libraryTitle: "视觉创作灵感库",
@@ -251,7 +252,7 @@ export function renderLibraryJson(
payload.creativeRuns = normalizeCreativeRuns(composerState.creativeRuns);
payload.creativeSkills = normalizeCreativeSkillsState(composerState.creativeSkills);
}
- return `${JSON.stringify(payload, null, 2)}\n`;
+ return `${JSON.stringify(projectPortableMedia(payload), null, 2)}\n`;
}
function renderEntry(entry, index, taxonomy, facetCatalog, locale) {
diff --git a/extension/library-asset-inventory.js b/extension/library-asset-inventory.js
index 5abc72b..d17ac53 100644
--- a/extension/library-asset-inventory.js
+++ b/extension/library-asset-inventory.js
@@ -42,6 +42,7 @@ function durableAssets(state) {
function localOnlyAssets(state) {
const recoveryPoint = state.libraryReplacementRecoveryPoint;
return [
+ ...(state.folderOwnershipBackup?.state ? durableAssets(state.folderOwnershipBackup.state) : []),
...creativeJobAssets(state.creativeJobs?.items),
...importStagingAssets(state.importStaging?.assets),
...(recoveryPoint?.state && typeof recoveryPoint.state === "object"
diff --git a/extension/library-browse-view.js b/extension/library-browse-view.js
new file mode 100644
index 0000000..d14c988
--- /dev/null
+++ b/extension/library-browse-view.js
@@ -0,0 +1,50 @@
+import { createUiIcon } from './ui-icons.js';
+import { caseViewProjection } from './library-view.js';
+
+// Navigation changes the scope; the existing case renderer owns filtering,
+// selection and details in every view.
+export function renderBrowseNavigation({ breadcrumb, path, selectedId, rootLabel, navigate, disabled }) {
+ const button = (label, id, current = false) => {
+ const item = document.createElement('button');
+ item.type = 'button';
+ item.disabled = disabled;
+ item.className = 'browse-project-button';
+ item.textContent = label;
+ item.title = label;
+ item.dataset.projectId = id;
+ if (current) item.setAttribute('aria-current', 'page');
+ item.addEventListener('click', () => navigate(id));
+ return item;
+ };
+ breadcrumb.replaceChildren(button(rootLabel, '', !selectedId));
+ for (const project of path.slice(0, -1)) {
+ breadcrumb.append(createUiIcon('chevron-right'), button(project.name, project.id, project.id === selectedId));
+ }
+}
+
+export function appendCaseRowDetails(card, entry, { typeLabel, locale }) {
+ if (!card.querySelector('img')) {
+ card.classList.add('has-row-placeholder');
+ const placeholder = document.createElement('span');
+ placeholder.className = 'case-row-placeholder';
+ placeholder.append(createUiIcon('file-text'));
+ card.append(placeholder);
+ }
+ const details = document.createElement('div');
+ details.className = 'case-row-details';
+ const title = document.createElement('strong');
+ title.className = 'case-row-title';
+ title.textContent = entry.title;
+ const type = document.createElement('span');
+ type.className = 'case-row-type';
+ type.textContent = typeLabel;
+ const date = document.createElement('time');
+ date.className = 'case-row-date';
+ const saved = caseViewProjection(entry).addedAt;
+ if (saved) {
+ date.dateTime = saved;
+ date.textContent = new Date(saved).toLocaleDateString(locale);
+ }
+ details.append(title, type, date);
+ card.append(details);
+}
diff --git a/extension/library-case-scope.js b/extension/library-case-scope.js
new file mode 100644
index 0000000..7f449a1
--- /dev/null
+++ b/extension/library-case-scope.js
@@ -0,0 +1,36 @@
+// Match the same folder paths as organizer import, without folding independent
+// copies in different folders (or different compound members) into one case.
+export function libraryCaseScopes(state = {}) {
+ const collections = state.organizerState?.collections ?? [];
+ const byId = new Map(collections.map(collection => [collection.id, collection]));
+ const paths = new Map();
+ function pathFor(collection, visiting = new Set()) {
+ if (paths.has(collection.id)) return paths.get(collection.id);
+ if (visiting.has(collection.id)) return ["invalid-cycle", collection.id];
+ visiting.add(collection.id);
+ const parent = byId.get(collection.parentId);
+ const name = String(collection.name ?? "").trim().toLocaleLowerCase().replace(/[\s._-]+/g, "");
+ const path = [...(parent ? pathFor(parent, visiting) : []), name || ["unnamed", collection.id]];
+ visiting.delete(collection.id);
+ paths.set(collection.id, path);
+ return path;
+ }
+ const memberships = new Map();
+ for (const collection of collections) {
+ const path = JSON.stringify(pathFor(collection));
+ for (const id of collection.entryIds ?? []) {
+ if (!memberships.has(id)) memberships.set(id, new Set());
+ memberships.get(id).add(path);
+ }
+ }
+ const compounds = new Map();
+ for (const compound of state.compoundCases ?? []) {
+ for (const [index, id] of (compound.memberEntryIds ?? []).entries()) {
+ compounds.set(id, [compound.id, index]);
+ }
+ }
+ return new Map((state.entries ?? []).map(entry => [entry.id, JSON.stringify([
+ [...(memberships.get(entry.id) ?? [])].sort(),
+ compounds.get(entry.id) ?? null
+ ])]));
+}
diff --git a/extension/library-export-plan.js b/extension/library-export-plan.js
index 81f177f..79589e9 100644
--- a/extension/library-export-plan.js
+++ b/extension/library-export-plan.js
@@ -1,35 +1,42 @@
-import { sha256Blob } from "./blob-digest.js";
+import { createBlobDigestCache } from "./blob-digest.js";
const FOLDER_BACKUP_FORMAT = "prompt-director-folder-backup";
const FOLDER_RESCUE_FORMAT = "prompt-director-folder-rescue";
const BACKUP_MARKER_PATHS = new Set(["complete.json", "rescue.json"]);
-export async function buildFolderBackupCompletion(filesValue, metadata = {}) {
+export async function buildFolderBackupCompletion(filesValue, metadata = {}, options = {}) {
return buildFolderMarker(filesValue, metadata, {
format: FOLDER_BACKUP_FORMAT,
version: 2,
status: "complete"
- });
+ }, options);
}
-export async function buildFolderRescueCompletion(filesValue, metadata = {}) {
+export async function buildFolderRescueCompletion(filesValue, metadata = {}, options = {}) {
return buildFolderMarker(filesValue, metadata, {
format: FOLDER_RESCUE_FORMAT,
version: 1,
status: "rescue",
issues: Array.isArray(metadata.issues) ? structuredClone(metadata.issues) : []
- });
+ }, options);
}
-export async function buildFolderBackupWritePlan({ files: filesValue, report = {}, metadata = {} } = {}) {
+export async function buildFolderBackupWritePlan({ files: filesValue, sourceFiles, report = {}, metadata = {}, digest = createBlobDigestCache(), onProgress } = {}) {
const files = backupFiles(filesValue);
if (!(files.get("library.json") instanceof Blob)) throw new Error("备份写入计划缺少 library.json");
const diagnostics = Array.isArray(report?.diagnostics) ? structuredClone(report.diagnostics) : [];
const rescue = report?.status === "partial" || diagnostics.length > 0;
+ if (rescue && sourceFiles instanceof Map) {
+ const source = backupFiles(sourceFiles);
+ for (const [path, blob] of source) {
+ if (path === "library.json") files.set("recovery/source-library.json", blob);
+ else if (!files.has(path)) files.set(path, blob);
+ }
+ }
const marker = rescue
- ? await buildFolderRescueCompletion(files, { ...metadata, issues: diagnostics })
- : await buildFolderBackupCompletion(files, metadata);
- if (rescue) await verifyFolderRescueCompletion(marker, files);
- else await verifyFolderBackupCompletion(marker, files);
+ ? await buildFolderRescueCompletion(files, { ...metadata, issues: diagnostics }, { digest, onProgress })
+ : await buildFolderBackupCompletion(files, metadata, { digest, onProgress });
+ if (rescue) await verifyFolderRescueCompletion(marker, files, { digest });
+ else await verifyFolderBackupCompletion(marker, files, { digest });
return {
mode: rescue ? "rescue" : "complete",
markerPath: rescue ? "rescue.json" : "complete.json",
@@ -43,11 +50,16 @@ export async function buildFolderBackupWritePlan({ files: filesValue, report = {
};
}
-async function buildFolderMarker(filesValue, metadata, identity) {
+async function buildFolderMarker(filesValue, metadata, identity, { digest = createBlobDigestCache(), onProgress } = {}) {
const files = backupFiles(filesValue);
const manifest = [];
for (const [path, blob] of [...files.entries()].sort(([left], [right]) => left.localeCompare(right))) {
- manifest.push({ path, byteSize: blob.size, sha256: await sha256Blob(blob) });
+ const progress = { path, completed: manifest.length, total: files.size };
+ await onProgress?.(progress);
+ manifest.push({ path, byteSize: blob.size, sha256: await digest(blob, {
+ onProgress: bytes => onProgress?.({ ...progress, ...bytes })
+ }) });
+ await onProgress?.({ ...progress, completed: manifest.length });
}
return {
...identity,
@@ -62,25 +74,25 @@ async function buildFolderMarker(filesValue, metadata, identity) {
};
}
-export async function verifyFolderBackupCompletion(completionValue, filesValue) {
+export async function verifyFolderBackupCompletion(completionValue, filesValue, options = {}) {
return verifyFolderMarker(completionValue, filesValue, {
format: FOLDER_BACKUP_FORMAT,
version: 2,
invalidMessage: "完整备份标记无效",
integrityLabel: "完整备份"
- });
+ }, options);
}
-export async function verifyFolderRescueCompletion(completionValue, filesValue) {
+export async function verifyFolderRescueCompletion(completionValue, filesValue, options = {}) {
return verifyFolderMarker(completionValue, filesValue, {
format: FOLDER_RESCUE_FORMAT,
version: 1,
invalidMessage: "救援备份标记无效",
integrityLabel: "救援备份"
- });
+ }, options);
}
-export async function inspectFolderBackupEnvelope(filesValue) {
+export async function inspectFolderBackupEnvelope(filesValue, options = {}) {
const files = filesValue instanceof Map ? filesValue : new Map();
const libraryFile = files.get("library.json");
if (!(libraryFile instanceof Blob)) throw new Error("资料夹备份缺少 library.json");
@@ -96,7 +108,7 @@ export async function inspectFolderBackupEnvelope(filesValue) {
if (marker?.format === FOLDER_BACKUP_FORMAT && marker.version === 1) {
return folderEnvelope("complete", marker, libraryFile, []);
}
- const verification = await verifyFolderBackupCompletion(marker, files);
+ const verification = await verifyFolderBackupCompletion(marker, files, options);
return folderEnvelope("complete", marker, libraryFile, extraFileDiagnostics(verification.extraPaths));
} catch (error) {
if (error?.code === "BACKUP_MARKER_FUTURE") throw error;
@@ -113,7 +125,7 @@ export async function inspectFolderBackupEnvelope(filesValue) {
if (marker?.format === FOLDER_RESCUE_FORMAT && Number(marker.version) > 1) {
throw updateRequiredError();
}
- const verification = await verifyFolderRescueCompletion(marker, files);
+ const verification = await verifyFolderRescueCompletion(marker, files, options);
const diagnostics = [
...(Array.isArray(marker.issues) ? structuredClone(marker.issues) : []),
...extraFileDiagnostics(verification.extraPaths)
@@ -174,7 +186,7 @@ function updateRequiredError() {
});
}
-async function verifyFolderMarker(completionValue, filesValue, expected) {
+async function verifyFolderMarker(completionValue, filesValue, expected, { digest = createBlobDigestCache(), onProgress } = {}) {
const completion = completionValue && typeof completionValue === "object" ? completionValue : {};
if (completion.format !== expected.format || completion.version !== expected.version || !Array.isArray(completion.files)) {
throw new Error(expected.invalidMessage);
@@ -189,9 +201,12 @@ async function verifyFolderMarker(completionValue, filesValue, expected) {
if (!path || expectedPaths.has(path)) throw new Error(`${expected.integrityLabel}的文件清单完整性校验失败`);
expectedPaths.add(path);
const blob = files.get(path);
- if (!(blob instanceof Blob) || blob.size !== descriptor.byteSize || await sha256Blob(blob) !== descriptor.sha256) {
+ const progress = { path, completed: expectedPaths.size - 1, total: completion.files.length };
+ await onProgress?.(progress);
+ if (!(blob instanceof Blob) || blob.size !== descriptor.byteSize || await digest(blob, { onProgress: bytes => onProgress?.({ ...progress, ...bytes }) }) !== descriptor.sha256) {
throw new Error(`${expected.integrityLabel}文件“${path}”完整性校验失败`);
}
+ await onProgress?.({ ...progress, completed: expectedPaths.size });
}
return {
extraPaths: [...files.keys()].filter((path) => !expectedPaths.has(path)).sort()
diff --git a/extension/library-folder-ownership.js b/extension/library-folder-ownership.js
new file mode 100644
index 0000000..25f63b3
--- /dev/null
+++ b/extension/library-folder-ownership.js
@@ -0,0 +1,151 @@
+// Planning is side-effect free: callers commit the whole result atomically only
+// after their import/upgrade checks pass. Original media bytes remain shared.
+export function needsFolderOwnershipMigration(state = {}) {
+ const logicalId = new Map();
+ for (const compound of state.compoundCases ?? []) {
+ for (const id of compound.memberEntryIds ?? []) logicalId.set(id, compound.id);
+ }
+ const owners = new Map();
+ for (const collection of state.organizerState?.collections ?? []) {
+ for (const id of collection.entryIds ?? []) {
+ const key = logicalId.get(id) ?? id;
+ if (owners.has(key) && owners.get(key) !== collection.id) return true;
+ owners.set(key, collection.id);
+ }
+ }
+ return false;
+}
+
+export function planFolderOwnership(stateValue) {
+ const state = structuredClone(stateValue);
+ const { entries, collections, groups, usedIds } = indexState(state);
+ const copies = [];
+ const locations = new Map();
+ for (const collection of collections) {
+ for (const id of collection.entryIds) {
+ const group = groups.get(id);
+ if (!group) throw new Error("项目包含不存在的案例,未转换资料");
+ if (!locations.has(group)) locations.set(group, []);
+ const list = locations.get(group);
+ if (list.at(-1) !== collection) list.push(collection);
+ }
+ }
+ for (const [group, folders] of locations) {
+ const uniqueFolders = [...new Set(folders)];
+ if (uniqueFolders.length < 2) continue;
+ for (const collection of uniqueFolders.slice(1)) {
+ const mapping = new Map(group.members.map(id => [id, reserveId(freeId(
+ `folder-copy:${encodeURIComponent(id)}:${encodeURIComponent(collection.id)}`, usedIds
+ ), usedIds)]));
+ const copy = copyGroup(state, group, entries, mapping, usedIds,
+ freeId(`folder-copy:${encodeURIComponent(group.id)}:${encodeURIComponent(collection.id)}`, usedIds));
+ const members = new Set(group.members);
+ const first = collection.entryIds.findIndex(id => members.has(id));
+ collection.entryIds = collection.entryIds.filter(id => !members.has(id));
+ collection.entryIds.splice(first, 0, ...copy.entryIds);
+ copies.push({ sourceCaseId: group.id, collectionId: collection.id, ...copy });
+ }
+ // A compound shown through any member represents the whole logical case.
+ const original = uniqueFolders[0];
+ const members = new Set(group.members);
+ const first = original.entryIds.findIndex(id => members.has(id));
+ original.entryIds = original.entryIds.filter(id => !members.has(id));
+ original.entryIds.splice(first, 0, ...group.members);
+ }
+ return { state, copies, changed: copies.length > 0 };
+}
+
+export function planCaseCopies(stateValue, caseIds, collectionId, options = {}) {
+ const state = structuredClone(stateValue);
+ const { entries, collections, groups, usedIds } = indexState(state);
+ const collection = collections.find(item => item.id === collectionId);
+ if (!collection) throw new Error("目标项目不存在");
+ const requested = [...new Set(caseIds.map(id => {
+ const group = groups.get(id);
+ if (!group) throw new Error("案例已不存在,未复制");
+ return group;
+ }))];
+ if (!requested.length) throw new Error("请先选择案例");
+ const idFactory = options.idFactory ?? (() => globalThis.crypto.randomUUID());
+ const copies = [];
+ for (const group of requested) {
+ const mapping = new Map(group.members.map(id => [id, reserveId(idFactory(), usedIds)]));
+ const copy = copyGroup(state, group, entries, mapping, usedIds, idFactory());
+ collection.entryIds.push(...copy.entryIds);
+ copies.push({ sourceCaseId: group.id, collectionId, ...copy });
+ }
+ return { state, copies, changed: true };
+}
+
+function copyGroup(state, group, entries, mapping, usedIds, compoundId) {
+ for (const id of group.members) {
+ const original = entries.get(id);
+ // Stable identity survives package sanitization and protects intentional
+ // copies even when a selection share omits private folder names.
+ original.caseInstanceId ||= `case-instance:${original.id}`;
+ const copy = structuredClone(original);
+ copy.id = mapping.get(id);
+ copy.caseInstanceId = `case-instance:${copy.id}`;
+ state.entries.push(copy);
+ }
+ let caseId = mapping.get(group.members[0]);
+ if (group.compound) {
+ const compound = structuredClone(group.compound);
+ compound.id = reserveId(compoundId, usedIds);
+ compound.memberEntryIds = group.members.map(id => mapping.get(id));
+ state.compoundCases.push(compound);
+ caseId = compound.id;
+ }
+ return { caseId, entryIds: group.members.map(id => mapping.get(id)), entryIdMap: Object.fromEntries(mapping) };
+}
+
+function indexState(state) {
+ if (!Array.isArray(state.entries)) throw new Error("案例资料无效,未转换资料");
+ state.organizerState ??= { collections: [] };
+ state.organizerState.collections ??= [];
+ state.compoundCases ??= [];
+ const entries = new Map();
+ const groups = new Map();
+ const usedIds = new Set();
+ for (const entry of state.entries) {
+ reserveId(entry.id, usedIds);
+ entries.set(entry.id, entry);
+ groups.set(entry.id, { id: entry.id, members: [entry.id] });
+ }
+ const claimed = new Set();
+ for (const compound of state.compoundCases) {
+ reserveId(compound.id, usedIds);
+ if (!Array.isArray(compound.memberEntryIds) || compound.memberEntryIds.length < 2) {
+ throw new Error("组合案例关系无效,未转换资料");
+ }
+ const group = { id: compound.id, members: compound.memberEntryIds, compound };
+ groups.set(compound.id, group);
+ for (const id of group.members) {
+ if (!entries.has(id) || claimed.has(id)) throw new Error("组合案例成员冲突,未转换资料");
+ claimed.add(id);
+ groups.set(id, group);
+ }
+ }
+ const collections = state.organizerState.collections;
+ const collectionIds = new Set();
+ for (const item of collections) {
+ reserveId(item.id, collectionIds);
+ if (!Array.isArray(item.entryIds)) throw new Error("项目关系无效,未转换资料");
+ }
+ return { entries, collections, groups, usedIds };
+}
+
+function reserveId(id, usedIds) {
+ if (typeof id !== "string" || !id.trim() || usedIds.has(id)) {
+ throw new Error("案例编号冲突,未转换资料");
+ }
+ usedIds.add(id);
+ return id;
+}
+
+function freeId(base, usedIds) {
+ let id = base;
+ let suffix = 1;
+ while (usedIds.has(id)) id = `${base}:${suffix++}`;
+ return id;
+}
diff --git a/extension/library-import-media.js b/extension/library-import-media.js
index a54caa8..aa1a84c 100644
--- a/extension/library-import-media.js
+++ b/extension/library-import-media.js
@@ -14,7 +14,7 @@ export async function findInvalidImportedImageIds(images, validateImage, { signa
invalidIds.add(assetId);
}
signal?.throwIfAborted();
- onProgress?.({ completed: ++completed, total: images.size });
+ await onProgress?.({ completed: ++completed, total: images.size });
}
return invalidIds;
}
diff --git a/extension/library-layout.css b/extension/library-layout.css
new file mode 100644
index 0000000..a096f3e
--- /dev/null
+++ b/extension/library-layout.css
@@ -0,0 +1,148 @@
+/* Modular library chrome: one toolbar, a vertical dock, and stable panel widths. */
+.modular-library { --library-topbar-height: 56px; }
+.modular-library .topbar { display: flex; flex-wrap: nowrap; height: 56px; min-height: 56px; padding: 8px 10px; gap: 10px; }
+.modular-library .topbar > * { min-width: 0; }
+.modular-library .topbar > #toggle-filters { flex: 0 0 32px; width: 32px; min-height: 32px; }
+.modular-library .topbar > .brand { flex: 0 0 auto; gap: 7px; }
+.modular-library .brand .brand-mark { width: 28px; height: 28px; }
+.modular-library .brand .brand-wordmark { font-size: 12px; }
+.modular-library .brand .product-brand-tagline { display: none; }
+.modular-library .topbar .gallery-heading { position: relative; inset: auto; display: flex; flex: 1 1 auto; flex-wrap: nowrap; height: 38px; min-height: 38px; gap: 10px; margin: 0; padding: 0; border: 0; background: transparent; z-index: auto; }
+.modular-library .topbar .gallery-heading-copy { flex: 0 1 290px; max-width: 290px; height: 34px; gap: 6px; flex-wrap: nowrap; }
+.modular-library .topbar .gallery-heading-copy h1 { font-size: 12px; }
+.modular-library .topbar #result-count { font-size: 10px; white-space: nowrap; }
+.modular-library .topbar .global-search { flex: 1 1 220px; min-width: 100px; }
+.modular-library .global-search input { height: 32px; min-height: 32px; padding: 6px 10px; font-size: 12px; }
+.modular-library .topbar .gallery-view-controls { flex: 0 0 auto; gap: 5px; height: 34px; min-height: 34px; overflow: visible; }
+.modular-library .topbar #browse-scope { margin: 0 3px 0 0; gap: 4px; font-size: 11px; }
+.modular-library .topbar .gallery-view-switch { gap: 4px; margin: 0; }
+.modular-library .topbar button, .modular-library .topbar summary, .modular-library .topbar select { min-height: 32px; }
+.modular-library .topbar .gallery-view-button, .modular-library .topbar .icon-button { width: 32px; min-width: 32px; padding: 6px; }
+.modular-library .topbar .gallery-select-button { flex-basis: 32px; width: 32px; min-width: 32px; padding: 6px; }
+.modular-library .gallery-select-button > span { display: none; }
+.modular-library .topbar .top-actions { flex: 0 0 auto; gap: 5px; }
+.modular-library .top-actions > button, .modular-library .top-actions .package-menu > summary { padding: 6px 9px; font-size: 12px; }
+.modular-library .top-actions .settings-entry-button { padding: 6px; flex-basis: 32px; }
+.modular-library .topbar .browse-location { max-width: 36%; }
+.modular-library .topbar .selection-mode > .global-search { position: absolute; z-index: 1; left: 0; top: 3px; width: clamp(64px, 12vw, 180px); visibility: visible; }
+.modular-library .topbar .share-bar { inset: 2px 0 2px calc(clamp(64px, 12vw, 180px) + 8px); height: 34px; min-height: 34px; background: var(--bar); }
+.modular-library .topbar .share-bar[hidden] { display: none; }
+.modular-library .topbar .project-selection-mode > .gallery-heading-copy,
+.modular-library .topbar .project-selection-mode > .gallery-view-controls,
+.modular-library .topbar .project-selection-mode > .toolbar-more { display: none !important; }
+.modular-library .topbar .project-selection-actions { flex: 1 1 auto; flex-wrap: nowrap; justify-content: flex-start; min-width: 0; overflow-x: auto; }
+.modular-library .topbar #project-selection-title { flex: 0 1 120px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
+.modular-library .workspace { display: grid; grid-template-columns: var(--sidebar-width, 244px) 6px minmax(0, 1fr); min-height: calc(100dvh - var(--library-topbar-height)); }
+.modular-library .workspace.filters-collapsed { grid-template-columns: 48px 0 minmax(0, 1fr); }
+.modular-library .filter-sidebar { position: sticky; display: flex; flex-direction: column; gap: 0; top: var(--library-topbar-height); width: auto; height: calc(100dvh - var(--library-topbar-height)); padding: 8px 6px; overflow: hidden; transform: none; opacity: 1; pointer-events: auto; transition: none; box-shadow: none; z-index: 26; }
+.modular-library .workspace-navigation { flex: 0 0 auto; margin: 0; padding: 0 0 8px; gap: 1px; }
+.modular-library .workspace-navigation-item { min-height: 34px; font-size: 12px; padding: 6px 8px; }
+.modular-library .sidebar-modules { display: flex; flex-direction: column; flex: 1 1 0; min-height: 0; padding-top: 6px; }
+.modular-library .sidebar-module { display: flex; flex-direction: column; flex: 0 0 auto; min-height: 38px; margin: 0; padding: 0; border: 0; border-bottom: 1px solid var(--line); gap: 0; }
+.modular-library .sidebar-module.module-open { flex: 1 1 0; min-height: 80px; }
+.modular-library .sidebar-module .project-tree-tools { position: static; display: block; padding: 0; }
+.modular-library .sidebar-module .filter-heading { position: relative; display: flex; flex: 0 0 38px; gap: 0; height: 38px; min-height: 38px; padding: 0 28px 0 0; }
+.modular-library .sidebar-module .filter-heading > span { display: flex; gap: 0; }
+.modular-library .sidebar-module .filter-heading > span button { padding: 4px; min-width: 26px; min-height: 28px; }
+.modular-library #create-collection > span { display: none; }
+.modular-library .sidebar-module-toggle { position: static; display: flex; align-items: center; justify-content: flex-start; flex: 1 1 auto; gap: 8px; min-width: 0; min-height: 34px; padding: 5px 6px; border: 0; background: transparent; color: var(--ink); text-align: left; font-size: 12px; font-weight: 600; }
+.modular-library .sidebar-module-toggle .ui-icon { flex: 0 0 16px; width: 16px; height: 16px; }
+.modular-library [data-sidebar-module="projects"] .sidebar-module-toggle > .ui-icon:first-child { color: var(--accent-ink); }
+.modular-library .sidebar-module-toggle .ui-icon:last-child { position: absolute; right: 8px; top: 13px; pointer-events: auto; margin-left: 0; width: 12px; height: 12px; flex-basis: 12px; transform: rotate(-90deg); color: var(--muted); }
+.modular-library .module-open .sidebar-module-toggle .ui-icon:last-child { transform: none; }
+.modular-library .module-grip { flex: 0 0 16px; width: 16px; min-width: 16px; min-height: 28px; padding: 0; border: 0; background: transparent; color: var(--muted); cursor: grab; }
+.modular-library .module-grip .ui-icon { width: 12px; height: 12px; }
+.modular-library .module-drop-target { box-shadow: inset 0 2px var(--accent-ink); }
+.modular-library .sidebar-module-body { flex: 1 1 0; min-height: 0; overflow-y: auto; overflow-x: hidden; overscroll-behavior: contain; padding: 2px 0 8px; }
+.modular-library .sidebar-module-body[hidden] { display: none; }
+.modular-library .module-active-count { color: var(--accent-ink); font-size: 10px; }
+.modular-library .sidebar-trash-section { flex: 0 0 auto; padding: 6px 0 0; margin: 0; border: 0; }
+.modular-library .sidebar-layout-menu { position: absolute; right: 6px; bottom: 9px; z-index: 28; }
+.modular-library .sidebar-layout-menu > summary { width: 28px; min-height: 28px; padding: 5px; background: transparent; border: 0; }
+.modular-library .sidebar-layout-menu .package-menu-panel { top: auto; bottom: 36px; right: 0; width: 160px; }
+.modular-library .sidebar-layout-menu .package-menu-panel button { min-height: 32px; font-size: 12px; }
+.modular-library .sidebar-trash-section #open-trash { width: calc(100% - 32px); }
+.modular-library .filters-collapsed .filter-sidebar { padding: 8px 5px; }
+.modular-library .filters-collapsed .workspace-navigation-item { display: flex; width: 36px; height: 36px; justify-content: center; padding: 8px; }
+.modular-library .filters-collapsed .workspace-navigation-item > span,
+.modular-library .filters-collapsed .workspace-navigation-item > strong,
+.modular-library .filters-collapsed .module-label,
+.modular-library .filters-collapsed .module-grip,
+.modular-library .filters-collapsed .sidebar-module-toggle > .ui-icon:last-child,
+.modular-library .filters-collapsed .filter-heading > span,
+.modular-library .filters-collapsed #manage-facets { display: none; }
+.modular-library .filters-collapsed .sidebar-module { min-height: 38px; border: 0; }
+.modular-library .filters-collapsed .sidebar-module-toggle { position: relative; flex: 0 0 36px; width: 36px; height: 36px; justify-content: center; padding: 8px; }
+.modular-library .filters-collapsed .module-active-count { position: absolute; top: 0; right: 1px; font-size: 9px; }
+.modular-library .filters-collapsed .sidebar-layout-menu { display: none; }
+.modular-library .filters-collapsed .sidebar-trash-section #open-trash { width: 36px; }
+.modular-library .gallery-shell { min-width: 0; padding-top: 8px; }
+.modular-library .sidebar-resizer { display: block; }
+.modular-library .toolbar-more { position: relative; flex: 0 0 32px; }
+.modular-library .toolbar-more > summary { display: grid; place-items: center; width: 32px; height: 32px; padding: 6px; list-style: none; border: 1px solid var(--line); border-radius: var(--ui-control-radius); background: var(--raised); cursor: pointer; }
+.modular-library .toolbar-more > summary::-webkit-details-marker { display: none; }
+.modular-library .toolbar-more-panel { position: absolute; top: 42px; right: 0; display: flex; flex-wrap: wrap; gap: 8px; width: min(390px, calc(100vw - 24px)); padding: 12px; border: 1px solid var(--line); border-radius: var(--ui-container-radius); background: var(--card); box-shadow: var(--shadow); }
+.modular-library .toolbar-more:not([open]) > .toolbar-more-panel { display: none; }
+.modular-library .toolbar-more-panel .gallery-view-controls { flex: 1 1 100%; height: auto; flex-wrap: wrap; }
+.modular-library .toolbar-more-panel .package-menu-panel { right: 0; width: min(290px, calc(100vw - 48px)); }
+.modular-library .selection-mode > .toolbar-more { visibility: hidden; }
+@media (max-width: 1100px) {
+ .modular-library .topbar .gallery-heading-copy { flex-basis: 150px; }
+ .modular-library .brand .product-brand-copy { display: none; }
+ .modular-library .topbar .gallery-view-controls[hidden] { display: none !important; }
+}
+@media (max-width: 640px) {
+ .modular-library .topbar { gap: 6px; padding-inline: 6px; }
+ .modular-library .topbar > .brand { display: none; }
+ .modular-library .topbar .gallery-heading { gap: 6px; }
+ .modular-library .topbar .gallery-heading-copy { flex: 0 1 90px; max-width: 90px; }
+ .modular-library .topbar .global-search { flex-basis: 100px; min-width: 64px; }
+ .modular-library .workspace:not(.filters-collapsed) { grid-template-columns: min(var(--sidebar-width, 244px), 65vw) 0 minmax(0, 1fr); }
+ .modular-library .sidebar-resizer { display: none; }
+ .modular-library .topbar:has(.selection-mode) > .top-actions { visibility: hidden; pointer-events: none; }
+ .modular-library .topbar .selection-mode .share-bar { right: -38px; }
+ .modular-library .topbar .selection-action-label { display: none; }
+ .modular-library .topbar .selection-menu > summary, .modular-library .topbar .selection-compact-action { width: 28px; min-width: 28px; padding: 4px; }
+ .modular-library .topbar .share-bar { gap: 4px; }
+ .modular-library .topbar .selection-selected-actions { gap: 3px; }
+ .modular-library .topbar #share-count { font-size: 10px; }
+ .modular-library .topbar #share-cancel { padding-inline: 5px; }
+ .modular-library .topbar .selection-menu-panel { position: fixed; top: var(--library-topbar-height); left: 8px; right: 8px; width: auto; }
+}
+
+.modular-library .gallery-shell { grid-column: 3; grid-row: 1; }
+.modular-library .filter-sidebar { grid-column: 1; grid-row: 1; }
+.modular-library .sidebar-resizer { grid-column: 2; grid-row: 1; }
+.modular-library .toolbar-context { display: flex; align-items: center; gap: 8px; flex: 1 1 100%; min-width: 0; }
+.modular-library .topbar .toolbar-context .browse-location { display: block !important; max-width: 70%; }
+.modular-library .topbar .toolbar-context .browse-location[hidden] { display: none !important; }
+@media (max-width: 640px) {
+ .modular-library .toolbar-more-panel { position: fixed; top: var(--library-topbar-height); left: 12px; right: 12px; width: auto; }
+}
+
+.modular-library #manage-facets { flex: 0 0 28px; width: 28px; min-width: 28px; padding: 5px; }
+.modular-library .module-label { white-space: nowrap; }
+
+.modular-library .project-selection-actions > * { flex-shrink: 0; }
+
+/* One shared disclosure column; auxiliary controls sit immediately to its left. */
+.modular-library .sidebar-module #create-collection,
+.modular-library .sidebar-module #collapse-projects,
+.modular-library .sidebar-module #manage-facets {
+ display: inline-flex; align-items: center; justify-content: center;
+ flex: 0 0 28px; width: 28px; height: 28px; min-width: 28px; min-height: 28px;
+ padding: 6px; border: 0; background: transparent; color: var(--muted);
+}
+.modular-library .sidebar-module #create-collection:hover,
+.modular-library .sidebar-module #collapse-projects:hover,
+.modular-library .sidebar-module #manage-facets:hover { background: var(--hover); color: var(--ink); }
+.modular-library .sidebar-module .filter-heading > span { flex: 0 0 auto; }
+.modular-library .filters-collapsed .sidebar-module .filter-heading { padding: 0; }
+.modular-library .filters-collapsed .sidebar-module #manage-facets { display: none; }
+
+/* Nested add menus must anchor to the compact panel, not its narrow trigger. */
+.modular-library .toolbar-more-panel .add-menu { position: static; }
+.modular-library .toolbar-more-panel .add-menu .package-menu-panel { left: 0; right: auto; }
+@media (max-width: 640px) {
+ .modular-library #filter-sidebar .project-menu-panel { position: fixed; left: 12px; right: auto; top: auto; }
+}
diff --git a/extension/library-layout.js b/extension/library-layout.js
new file mode 100644
index 0000000..ab18049
--- /dev/null
+++ b/extension/library-layout.js
@@ -0,0 +1,186 @@
+import { normalizeSidebarLayout } from "./preferences.js";
+import { createUiIcon } from "./ui-icons.js";
+import { t } from "./i18n.js";
+
+// Presentation only: move existing controls, never clone IDs or change case data.
+export function createLibraryLayout({ preferences, persist, onToggle }) {
+ const workspace = document.querySelector(".workspace");
+ const sidebar = document.getElementById("filter-sidebar");
+ const dock = document.getElementById("sidebar-modules");
+ const toggle = document.getElementById("toggle-filters");
+ const modules = new Map();
+ let layout = normalizeSidebarLayout(preferences.sidebarLayout);
+ const mobile = matchMedia("(max-width: 640px)");
+ if (mobile.matches) layout.collapsed = true;
+ const names = { projects: "项目", types: "内容类型", tags: "标签筛选" };
+ const icons = { projects: "folder", types: "layers", tags: "tag" };
+ let saving = Promise.resolve();
+ function save() {
+ const snapshot = structuredClone(layout);
+ saving = saving.catch(() => {}).then(() => persist(snapshot));
+ return saving;
+ }
+ function apply() {
+ workspace.classList.toggle("filters-collapsed", layout.collapsed);
+ toggle.setAttribute("aria-expanded", String(!layout.collapsed));
+ toggle.replaceChildren(createUiIcon(layout.collapsed ? "panel-left" : "panel-left-close"));
+ for (const key of layout.order) dock.append(modules.get(key).section);
+ for (const [key, item] of modules) {
+ const open = !layout.collapsed && layout.open.includes(key);
+ item.section.classList.toggle("module-open", open);
+ item.button.setAttribute("aria-expanded", String(open));
+ item.body.hidden = !open;
+ }
+ onToggle();
+ }
+ function openModule(key) {
+ if (layout.collapsed) layout.open = [key];
+ else if (!layout.open.includes(key)) layout.open.push(key);
+ layout.collapsed = false;
+ apply();
+ void save();
+ }
+ for (const section of dock.querySelectorAll("[data-sidebar-module]")) {
+ const key = section.dataset.sidebarModule;
+ const heading = section.querySelector(".filter-heading");
+ const title = heading.querySelector("strong");
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "sidebar-module-toggle button-secondary";
+ button.title = t(names[key]);
+ button.setAttribute("aria-label", t(names[key]));
+ button.setAttribute("aria-controls", `sidebar-${key}-body`);
+ const label = document.createElement("span");
+ label.className = "module-label";
+ label.textContent = t(names[key]);
+ const count = document.createElement("small");
+ count.className = "module-active-count";
+ count.hidden = true;
+ button.append(createUiIcon(icons[key]), label, count, createUiIcon("chevron-down", { className: "module-chevron" }));
+ title.replaceWith(button);
+ button.addEventListener("click", () => {
+ if (layout.collapsed || !layout.open.includes(key)) openModule(key);
+ else { layout.open = layout.open.filter(id => id !== key); apply(); void save(); }
+ });
+ const grip = document.createElement("button");
+ grip.type = "button";
+ grip.className = "module-grip icon-button";
+ grip.draggable = true;
+ grip.title = t("拖动排序,方向键调整位置");
+ grip.setAttribute("aria-label", `${t(names[key])}:${grip.title}`);
+ grip.append(createUiIcon("grip-vertical"));
+ heading.prepend(grip);
+ const move = offset => {
+ const from = layout.order.indexOf(key);
+ const to = Math.max(0, Math.min(layout.order.length - 1, from + offset));
+ layout.order.splice(from, 1); layout.order.splice(to, 0, key);
+ apply(); void save(); grip.focus();
+ };
+ grip.addEventListener("keydown", event => {
+ if (!["ArrowUp", "ArrowDown"].includes(event.key)) return;
+ event.preventDefault(); move(event.key === "ArrowUp" ? -1 : 1);
+ });
+ grip.addEventListener("dragstart", event => {
+ event.dataTransfer.setData("application/x-promptdirector-module", key);
+ event.dataTransfer.effectAllowed = "move";
+ });
+ heading.addEventListener("dragover", event => {
+ if (!event.dataTransfer.types.includes("application/x-promptdirector-module")) return;
+ event.preventDefault(); event.dataTransfer.dropEffect = "move";
+ heading.classList.add("module-drop-target");
+ });
+ heading.addEventListener("dragleave", () => heading.classList.remove("module-drop-target"));
+ heading.addEventListener("drop", event => {
+ heading.classList.remove("module-drop-target");
+ const source = event.dataTransfer.getData("application/x-promptdirector-module");
+ if (!modules.has(source)) return;
+ event.preventDefault(); event.stopPropagation();
+ const targetIndex = layout.order.indexOf(key);
+ layout.order = layout.order.filter(id => id !== source);
+ layout.order.splice(targetIndex, 0, source);
+ apply(); void save();
+ });
+ modules.set(key, { section, button, body: section.querySelector(".sidebar-module-body"), count });
+ }
+ const nav = sidebar.querySelector(".workspace-navigation");
+ nav.querySelector(".filter-heading").remove();
+ const menu = document.createElement("details");
+ menu.className = "sidebar-layout-menu package-menu";
+ const summary = document.createElement("summary");
+ summary.title = t("面板布局"); summary.setAttribute("aria-label", t("面板布局"));
+ summary.append(createUiIcon("ellipsis"));
+ const panel = document.createElement("div");
+ panel.className = "package-menu-panel";
+ for (const [label, action] of [
+ ["全部展开", () => { layout.collapsed = false; layout.open = [...layout.order]; }],
+ ["恢复默认布局", () => { layout = normalizeSidebarLayout(); }]
+ ]) {
+ const button = document.createElement("button");
+ button.type = "button"; button.className = "button-secondary"; button.textContent = t(label);
+ button.addEventListener("click", () => { action(); menu.open = false; apply(); void save(); });
+ panel.append(button);
+ }
+ menu.append(summary, panel);
+ sidebar.append(menu);
+ for (const item of sidebar.querySelectorAll(".workspace-navigation-item")) {
+ item.title = item.textContent.trim(); item.setAttribute("aria-label", item.title);
+ }
+ toggle.addEventListener("click", () => { layout.collapsed = !layout.collapsed; apply(); void save(); });
+ mobile.addEventListener("change", event => { if (event.matches) { layout.collapsed = true; apply(); } });
+ apply();
+ setupCompactToolbar();
+ return {
+ openModule,
+ updateCounts({ types = 0, tags = 0 }) {
+ for (const [key, count] of Object.entries({ types, tags })) {
+ const item = modules.get(key);
+ item.count.textContent = String(count); item.count.hidden = !count;
+ item.button.title = `${t(names[key])}${count ? ` · ${count}` : ""}`;
+ item.button.setAttribute("aria-label", item.button.title);
+ }
+ }
+ };
+}
+
+function setupCompactToolbar() {
+ const heading = document.getElementById("gallery-heading");
+ const controls = document.getElementById("gallery-view-controls");
+ const actions = document.querySelector(".top-actions");
+ const add = document.getElementById("add-menu");
+ const compose = document.getElementById("start-compose");
+ const menu = document.createElement("details");
+ menu.id = "toolbar-more";
+ menu.className = "toolbar-more";
+ const summary = document.createElement("summary");
+ summary.title = t("更多"); summary.setAttribute("aria-label", t("更多"));
+ summary.append(createUiIcon("ellipsis"));
+ const panel = document.createElement("div");
+ panel.className = "toolbar-more-panel";
+ const context = document.createElement("div");
+ context.className = "toolbar-context";
+ const copy = heading.querySelector(".gallery-heading-copy");
+ const breadcrumb = heading.querySelector(".browse-location");
+ const count = document.getElementById("result-count");
+ menu.append(summary, panel); heading.append(menu);
+ const compact = matchMedia("(max-width: 1100px)");
+ function apply() {
+ if (compact.matches) {
+ context.append(breadcrumb, count);
+ panel.append(context, controls, add, compose);
+ }
+ else {
+ copy.prepend(breadcrumb); copy.append(count);
+ heading.querySelector(".global-search").after(controls);
+ actions.prepend(add, compose); menu.open = false;
+ }
+ menu.hidden = !compact.matches;
+ }
+ panel.addEventListener("click", event => {
+ if (event.target.closest("#select-cases, #start-compose, #add-media, #add-video-reference, #add-quick-note")) menu.open = false;
+ });
+ document.addEventListener("click", event => { if (!menu.contains(event.target)) menu.open = false; });
+ document.addEventListener("keydown", event => {
+ if (event.key === "Escape" && menu.open) { menu.open = false; summary.focus(); }
+ });
+ compact.addEventListener("change", apply); apply();
+}
diff --git a/extension/library-model.js b/extension/library-model.js
index ab50e8b..b8f616e 100644
--- a/extension/library-model.js
+++ b/extension/library-model.js
@@ -94,8 +94,8 @@ export function entrySourceMetadataRows(entry = {}, sourceLabel = "来源") {
const seen = new Set();
const english = sourceLabel === "Source";
const labels = english
- ? { provider: "Provider", itemId: "Work ID", author: "Author", handle: "Account", publishedAt: "Published", model: "Model", dimensions: "Dimensions", favorites: "Favorites", likes: "Likes", uses: "Uses", views: "Views", shares: "Shares", comments: "Comments", coins: "Coins", danmaku: "Danmaku" }
- : { provider: "来源", itemId: "作品 ID", author: "作者", handle: "账号", publishedAt: "发布时间", model: "模型", dimensions: "尺寸", favorites: "收藏", likes: "点赞", uses: "使用", views: "浏览", shares: "分享", comments: "评论", coins: "投币", danmaku: "弹幕" };
+ ? { provider: "Provider", itemId: "Work ID", author: "Author", handle: "Account", publishedAt: "Published", model: "Model", dimensions: "Dimensions", repins: "Saves", reactions: "Reactions", favorites: "Favorites", likes: "Likes", uses: "Uses", views: "Views", shares: "Shares", comments: "Comments", coins: "Coins", danmaku: "Danmaku" }
+ : { provider: "来源", itemId: "作品 ID", author: "作者", handle: "账号", publishedAt: "发布时间", model: "模型", dimensions: "尺寸", repins: "收藏次数", reactions: "回应", favorites: "收藏", likes: "点赞", uses: "使用", views: "浏览", shares: "分享", comments: "评论", coins: "投币", danmaku: "弹幕" };
const addField = (label, value) => {
const text = String(value ?? "").trim();
const key = `${label}\n${text}`;
@@ -107,6 +107,10 @@ export function entrySourceMetadataRows(entry = {}, sourceLabel = "来源") {
for (const name of ["provider", "itemId", "author", "handle", "publishedAt", "model", "dimensions"]) {
addField(labels[name], sourceFacts[name]);
}
+ addField(english ? "Author URL" : "作者主页", sourceFacts.authorUrl);
+ addField(english ? "Original source" : "作品原始来源", sourceFacts.originalSourceUrl);
+ addField(english ? "Image description" : "图片描述", sourceFacts.imageDescription);
+ addField(english ? "Metadata incomplete" : "元信息未补全", sourceFacts.metadataError);
const description = String(sourceFacts.description || "").trim();
if (description && !String(entry.text || "").includes(description)) addField(english ? "Description" : "作品说明", description);
for (const [name, amount] of Object.entries(sourceFacts.engagement || {})) {
diff --git a/extension/library-package-migrations.js b/extension/library-package-migrations.js
index dd6d32e..1bd88ff 100644
--- a/extension/library-package-migrations.js
+++ b/extension/library-package-migrations.js
@@ -129,7 +129,7 @@ export function prepareLibraryPackageDraft(value = {}) {
stats: {
inputCases: lexical.entries.length,
keptCases: migrated.entries.length,
- skippedCases: lexical.entries.length - migrated.entries.length,
+ skippedCases: lexical.entries.length - preSalvagedEntries.length,
droppedAiAssignments,
droppedMediaDescriptors
}
diff --git a/extension/library-package.js b/extension/library-package.js
index fd0f9e8..9c10d10 100644
--- a/extension/library-package.js
+++ b/extension/library-package.js
@@ -1,3 +1,5 @@
+import { libraryStoredAssets } from "./library-asset-inventory.js";
+import { mediaIdentity, sameMediaIdentity, sharedLibraryMediaFiles } from "./library-shared-media.js";
import { normalizeFacetCatalog, uniqueNames } from "./facets.js";
import { normalizeSettings } from "./lib.js";
import { SCHEMA_VERSION, mergeTaxonomies, normalizeTaxonomy } from "./taxonomy.js";
@@ -19,6 +21,7 @@ import { expandLogicalCaseIds, normalizeCompoundCases, removeEntriesFromCompound
import { prepareLibraryPackageDraft } from "./library-package-migrations.js";
import { remapArticleDocumentAssets } from "./article-document.js";
import { caseSemanticFingerprint } from "./library-semantic-identity.js";
+import { libraryCaseScopes } from "./library-case-scope.js";
import { normalizeTrashState } from "./trash.js";
import { verifiedDocumentBlob, isSupportedDocumentMimeType } from "./bounded-media.js";
import {
@@ -35,7 +38,7 @@ export function hasLibrarySalvageDiagnostics(diagnosticsValue) {
.some((item) => item?.action === "dropped" || item?.action === "skipped");
}
-export async function parseCompleteFolderBackup(value, files = new Map(), limitsValue = {}) {
+export async function parseCompleteFolderBackup(value, files = new Map(), limitsValue = {}, options = {}) {
const preparedFiles = new Map(files);
const limits = libraryTransferLimits(limitsValue);
for (const [path, mimeType] of completeBackupDocumentPaths(value)) {
@@ -44,7 +47,7 @@ export async function parseCompleteFolderBackup(value, files = new Map(), limits
const verified = await verifiedDocumentBlob(blob, mimeType, limits.maxFileBytes);
preparedFiles.set(path, verified);
}
- return parseLibraryPackage(value, preparedFiles, { ...limitsValue, salvageInvalidMedia: false });
+ return parseLibraryPackage(value, await sharedLibraryMediaFiles(value, preparedFiles, options), { ...limitsValue, salvageInvalidMedia: false });
}
export function parseLibraryPackage(value, files = new Map(), limitsValue = {}) {
@@ -84,7 +87,14 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
}
}
const ids = new Set();
- const visualIds = new Set();
+ const mediaIdentities = new Map();
+ const claimMedia = (asset, blob) => {
+ const identity = mediaIdentity(asset, blob);
+ const existing = mediaIdentities.get(asset.id);
+ if (existing && !sameMediaIdentity(existing, identity)) return false;
+ mediaIdentities.set(asset.id, identity);
+ return true;
+ };
const assets = new Map();
const images = new Map();
const skillAssets = new Map();
@@ -131,9 +141,21 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
const entryAssets = new Map();
const droppedAssetIds = [...(normalizationDroppedAssetIds.get(entryIndex) ?? [])];
for (const asset of entry.mediaAssets) {
- if (visualIds.has(asset.id)) throw new Error("案例包包含重复的媒体编号");
- visualIds.add(asset.id);
- if (asset.storageMode === "reference") continue;
+ const identityBlob = asset.storageMode === "reference" ? undefined : files.get(clean(asset.assetPath));
+ const existingIdentity = mediaIdentities.get(asset.id);
+ if (existingIdentity && !sameMediaIdentity(existingIdentity, mediaIdentity(asset, identityBlob))) {
+ if (!salvageInvalidMedia) throw new Error("案例包包含冲突的媒体编号");
+ droppedAssetIds.push(asset.id);
+ importStats.droppedMediaDescriptors += 1;
+ importDiagnostics.push({ code: "media_descriptor_dropped", severity: "media", action: "dropped",
+ entryId: entry.id, assetId: asset.id, path: clean(asset.assetPath), reason: "duplicate_asset_id",
+ message: "同一媒体编号对应不同内容,本项不能自动恢复" });
+ continue;
+ }
+ if (asset.storageMode === "reference") {
+ claimMedia(asset, undefined);
+ continue;
+ }
const path = clean(asset.assetPath);
let format;
try {
@@ -169,6 +191,7 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
});
continue;
}
+ claimMedia(asset, blob);
entryAssets.set(asset.id, blob);
}
for (const assetId of droppedAssetIds) entry = removeEntryMedia(entry, assetId);
@@ -233,15 +256,19 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
});
const droppedAssetIds = [];
for (const asset of entry.mediaAssets) {
- if (visualIds.has(asset.id)) {
- if (!salvageInvalidMedia) throw new Error("完整备份包含重复的媒体编号");
+ const identityBlob = asset.storageMode === "reference" ? undefined : files.get(clean(asset.assetPath));
+ const existingIdentity = mediaIdentities.get(asset.id);
+ if (existingIdentity && !sameMediaIdentity(existingIdentity, mediaIdentity(asset, identityBlob))) {
+ if (!salvageInvalidMedia) throw new Error("完整备份包含冲突的媒体编号");
droppedAssetIds.push(asset.id);
importStats.droppedTrashMedia += 1;
importDiagnostics.push(trashMediaDiagnostic(item, asset, "duplicate_asset_id"));
continue;
}
- visualIds.add(asset.id);
- if (asset.storageMode === "reference") continue;
+ if (asset.storageMode === "reference") {
+ claimMedia(asset, undefined);
+ continue;
+ }
const path = clean(asset.assetPath);
let format;
try {
@@ -264,6 +291,7 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
importDiagnostics.push(trashMediaDiagnostic(item, asset, failure.reason));
continue;
}
+ claimMedia(asset, blob);
assets.set(asset.id, blob);
if (asset.kind === "image") images.set(asset.id, blob);
}
@@ -371,15 +399,13 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
importDiagnostics.push(privateResourceDiagnostic("temporary_asset_dropped", asset, path, "byte_size_mismatch"));
continue;
}
- const existing = assets.get(asset.assetId);
- if ((existing && existing.size !== blob.size) || (visualIds.has(asset.assetId) && !existing)) {
+ if (!claimMedia({ ...asset, id: asset.assetId }, blob)) {
if (!salvageInvalidMedia) throw new Error("案例包包含冲突的临时附件编号");
droppedAssetIds.add(asset.assetId);
importStats.droppedTemporaryAssets += 1;
importDiagnostics.push(privateResourceDiagnostic("temporary_asset_dropped", asset, path, "duplicate_asset_id"));
continue;
}
- visualIds.add(asset.assetId);
assets.set(asset.assetId, blob);
if (asset.kind === "image") images.set(asset.assetId, blob);
retainedAssetRefs.push(asset);
@@ -421,14 +447,12 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
importDiagnostics.push(privateResourceDiagnostic("creative_output_dropped", visual, path, "size_limit"));
continue;
}
- const existingAsset = assets.get(visual.id);
- if (visualIds.has(visual.id) && existingAsset && existingAsset.size !== asset.size) {
+ if (!claimMedia({ ...visual, kind: video ? "video" : "image" }, asset)) {
if (!salvageInvalidMedia) throw new Error("案例包包含冲突的结果媒体编号");
importStats.droppedCreativeOutputs += 1;
importDiagnostics.push(privateResourceDiagnostic("creative_output_dropped", visual, path, "duplicate_asset_id"));
continue;
}
- visualIds.add(visual.id);
assets.set(visual.id, asset);
if (!video) images.set(visual.id, asset);
retainedOutputs.push(output);
@@ -526,6 +550,20 @@ export function selectLibraryPackage(state = {}, entryIds = []) {
creativeRuns: [],
creativeSkills: { version: 1, items: [] }
};
+ const equivalent = new Map();
+ for (const entry of selected.entries) {
+ const fingerprint = caseSemanticFingerprint(entry);
+ if (!fingerprint) continue;
+ const group = equivalent.get(fingerprint) ?? [];
+ group.push(entry);
+ equivalent.set(fingerprint, group);
+ }
+ // Selection sharing omits private folders. Preserve separately selected cases
+ // that would otherwise become indistinguishable once that context is removed.
+ for (const group of equivalent.values()) {
+ if (group.length < 2) continue;
+ for (const entry of group) entry.caseInstanceId ||= `case-instance:${entry.id}`;
+ }
return selected;
}
@@ -683,8 +721,14 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
const entriesById = new Map(next.entries.map((entry) => [entry.id, entry]));
const entriesByFingerprint = new Map();
const fingerprintById = new Map();
- function indexEntry(entry) {
- const fingerprint = caseSemanticFingerprint(normalizeEntryMedia(entry));
+ const currentScopes = libraryCaseScopes(next);
+ const importedScopes = libraryCaseScopes(imported);
+ function scopedFingerprint(entry, scope) {
+ const content = caseSemanticFingerprint(normalizeEntryMedia(entry));
+ return content ? JSON.stringify([scope, content]) : "";
+ }
+ function indexEntry(entry, scope = currentScopes.get(entry.id)) {
+ const fingerprint = scopedFingerprint(entry, scope);
if (!fingerprint) return;
const matches = entriesByFingerprint.get(fingerprint) ?? new Set();
matches.add(entry);
@@ -708,8 +752,13 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
let skippedCount = 0;
for (const source of imported.entries) {
let idCollision = usedEntryIds.has(source.id);
- const sourceFingerprint = caseSemanticFingerprint(normalizeEntryMedia(source));
- const identical = sourceFingerprint && entriesByFingerprint.get(sourceFingerprint)?.values().next().value;
+ const sourceFingerprint = scopedFingerprint(source, importedScopes.get(source.id));
+ const existing = entriesById.get(source.id);
+ const sameExportedInstance = source.caseInstanceId === `case-instance:${source.id}` && existing && !existing.caseInstanceId
+ && currentScopes.get(existing.id) === importedScopes.get(source.id)
+ && scopedFingerprint({ ...source, caseInstanceId: undefined }, importedScopes.get(source.id)) === scopedFingerprint(existing, currentScopes.get(existing.id));
+ const identical = !options.preserveCaseIdentities && sourceFingerprint &&
+ (entriesByFingerprint.get(sourceFingerprint)?.values().next().value || (sameExportedInstance ? existing : null));
if (identical) {
skippedCount += 1;
entryIdMap[source.id] = identical.id;
@@ -770,11 +819,11 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
entry.mediaAssets = entry.mediaAssets.map((visual) => {
const preferredVisualId = visual.id === source.id && targetId !== source.id ? targetId : visual.id;
const mappedVisualId = clean(options.visualIdMap?.[visual.id]);
- const targetVisualId = usedVisualIds.has(preferredVisualId)
+ const targetVisualId = createdVisualIdMap[visual.id] || (usedVisualIds.has(preferredVisualId)
? mappedVisualId && !usedVisualIds.has(mappedVisualId)
? mappedVisualId
: uniqueId("visual", usedVisualIds)
- : preferredVisualId;
+ : preferredVisualId);
usedVisualIds.add(targetVisualId);
visualIdMap[visual.id] = targetVisualId;
createdVisualIdMap[visual.id] = targetVisualId;
@@ -816,7 +865,7 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
});
next.entries.push(entry);
entriesById.set(targetId, entry);
- indexEntry(entry);
+ indexEntry(entry, importedScopes.get(source.id));
usedEntryIds.add(targetId);
createdEntryIds.push(targetId);
entryIdMap[source.id] = targetId;
@@ -915,7 +964,8 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
preferredEntryIdMap: options.trashEntryIdMap,
preferredCollectionIdMap: options.trashCollectionIdMap,
preferredCompoundIdMap: options.trashCompoundIdMap,
- preferredVisualIdMap: options.visualIdMap
+ preferredVisualIdMap: options.visualIdMap,
+ sharedVisualIdMap: visualIdMap
});
next.trashState = trashMerge.trashState;
Object.assign(visualIdMap, trashMerge.visualIdMap);
@@ -1156,6 +1206,7 @@ function mergeImportedTrashState(currentValue, importedValue, context = {}) {
}
}
const visualIdMap = {};
+ const sharedVisualIdMap = { ...context.sharedVisualIdMap };
const moved = imported.items.map((sourceItem) => {
const item = structuredClone(sourceItem);
if (item.kind === "collection") {
@@ -1169,8 +1220,9 @@ function mergeImportedTrashState(currentValue, importedValue, context = {}) {
}
if (item.kind === "entry") {
const targetId = entryIdMap[item.targetId];
- const remapped = remapTrashedEntrySnapshot(item.snapshot, targetId, usedVisualIds, context.preferredVisualIdMap);
+ const remapped = remapTrashedEntrySnapshot(item.snapshot, targetId, usedVisualIds, context.preferredVisualIdMap, sharedVisualIdMap);
Object.assign(visualIdMap, remapped.visualIdMap);
+ Object.assign(sharedVisualIdMap, remapped.visualIdMap);
item.targetId = targetId;
item.id = `trash:entry:${targetId}`;
item.snapshot = remapped.entry;
@@ -1191,8 +1243,9 @@ function mergeImportedTrashState(currentValue, importedValue, context = {}) {
id: parentEntryId || `trash-media:${item.targetId}`,
mediaAssets: item.snapshot?.mediaAssets ?? [],
primaryMediaId: ""
- }, parentEntryId || `trash-media:${item.targetId}`, usedVisualIds, context.preferredVisualIdMap);
+ }, parentEntryId || `trash-media:${item.targetId}`, usedVisualIds, context.preferredVisualIdMap, sharedVisualIdMap);
Object.assign(visualIdMap, remapped.visualIdMap);
+ Object.assign(sharedVisualIdMap, remapped.visualIdMap);
const targetId = remapped.visualIdMap[item.targetId] ?? item.targetId;
item.targetId = targetId;
item.id = ["trash", "media", parentEntryId, targetId].filter(Boolean).join(":");
@@ -1215,15 +1268,15 @@ function mergeImportedTrashState(currentValue, importedValue, context = {}) {
};
}
-function remapTrashedEntrySnapshot(entryValue, targetEntryId, usedVisualIds, preferredVisualIdMap = {}) {
+function remapTrashedEntrySnapshot(entryValue, targetEntryId, usedVisualIds, preferredVisualIdMap = {}, sharedVisualIdMap = {}) {
const entry = normalizeEntryMedia(entryValue);
const visualIdMap = {};
entry.mediaAssets = entry.mediaAssets.map((asset) => {
const preferredId = asset.id === entry.id && targetEntryId !== entry.id ? targetEntryId : asset.id;
const plannedId = clean(preferredVisualIdMap[asset.id]);
- const targetId = usedVisualIds.has(preferredId)
+ const targetId = sharedVisualIdMap[asset.id] || (usedVisualIds.has(preferredId)
? plannedId && !usedVisualIds.has(plannedId) ? plannedId : uniqueId("visual", usedVisualIds)
- : preferredId;
+ : preferredId);
usedVisualIds.add(targetId);
visualIdMap[asset.id] = targetId;
return { ...asset, id: targetId };
@@ -1283,7 +1336,19 @@ function packageImagePlaceholders(value) {
const trashAssets = trashMediaAssets(value?.trashState).flatMap((asset) => asset.assetPath
? [[asset.assetPath, new Blob(["placeholder"], { type: mediaType(asset.assetPath, asset.kind, asset.mimeType) })]]
: []);
- return new Map([...entryImages, ...creativeAssets, ...skillFiles, ...tempFiles, ...trashAssets]);
+ const files = new Map([...entryImages, ...creativeAssets, ...skillFiles, ...tempFiles, ...trashAssets]);
+ // Merge validates structure with placeholders after the real-byte inspection.
+ // Preserve shared media identity across the placeholder paths as well.
+ const byId = new Map();
+ for (const asset of libraryStoredAssets(value)) {
+ const path = asset.assetPath || asset.screenshotPath || asset.archivePath;
+ const blob = files.get(path);
+ if (!blob) continue;
+ const key = `${asset.id || asset.assetId}:${blob.type}`;
+ if (byId.has(key)) files.set(path, byId.get(key));
+ else byId.set(key, blob);
+ }
+ return files;
}
function trashMediaAssets(trashStateValue) {
diff --git a/extension/library-portable-media.js b/extension/library-portable-media.js
new file mode 100644
index 0000000..1ec4cce
--- /dev/null
+++ b/extension/library-portable-media.js
@@ -0,0 +1,82 @@
+import { libraryStoredAssetIds } from "./library-asset-inventory.js";
+
+// Package-only projection. Local shared originals keep their storage ids; each
+// case in the package gets independent ids while retaining the existing paths.
+export function projectPortableMedia(stateValue) {
+ const state = structuredClone(stateValue);
+ const entries = [...(state.entries ?? []), ...(state.trashState?.items ?? [])
+ .filter(item => item.kind === "entry").map(item => item.snapshot)];
+ const mediaTrash = new Map();
+ for (const item of state.trashState?.items ?? []) {
+ if (item.kind !== "media") continue;
+ const container = { id: item.id, mediaAssets: item.snapshot?.mediaAssets ?? [] };
+ entries.push(container);
+ mediaTrash.set(container, item);
+ }
+ const reserved = libraryStoredAssetIds(state);
+ const claimed = new Set();
+ const maps = new Map();
+ for (const entry of entries) {
+ const mapping = new Map();
+ for (const asset of entry.mediaAssets ?? []) {
+ if (claimed.has(asset.id)) {
+ const base = `portable:${encodeURIComponent(entry.id)}:${encodeURIComponent(asset.id)}`;
+ let id = base;
+ let suffix = 1;
+ while (reserved.has(id)) id = `${base}:${suffix++}`;
+ reserved.add(id);
+ mapping.set(asset.id, id);
+ } else claimed.add(asset.id);
+ }
+ if (!mediaTrash.has(entry)) maps.set(entry.id, mapping);
+ if (!mapping.size) continue;
+ remapMediaReferences(entry, mapping);
+ for (const asset of entry.mediaAssets) asset.id = mapping.get(asset.id) ?? asset.id;
+ const trashItem = mediaTrash.get(entry);
+ if (trashItem) {
+ remapMediaReferences(trashItem.relationships, mapping);
+ trashItem.targetId = mapping.get(trashItem.targetId) ?? trashItem.targetId;
+ trashItem.id = ["trash", "media", trashItem.relationships?.entryId, trashItem.targetId].filter(Boolean).join(":");
+ }
+ }
+ for (const compound of state.compoundCases ?? []) remapCompound(compound, maps);
+ for (const item of state.trashState?.items ?? []) {
+ for (const compound of item.relationships?.compoundCases ?? []) remapCompound(compound, maps);
+ }
+ for (const session of state.composerSessions ?? []) {
+ for (const reference of session.referenceSnapshots ?? []) {
+ const mapping = maps.get(reference.entryId);
+ if (!mapping?.size) continue;
+ remapMediaReferences(reference, mapping);
+ if (typeof reference.referenceId === "string") {
+ for (const [before, after] of mapping) {
+ if (reference.referenceId === `${reference.entryId}:${before}`) reference.referenceId = `${reference.entryId}:${after}`;
+ }
+ }
+ }
+ }
+ return state;
+}
+
+const MEDIA_FIELDS = new Set(["assetId", "visualId", "primaryMediaId", "primaryVisualId", "coverVisualId", "posterAssetId", "derivedFromAssetId", "frameAssetId"]);
+const MEDIA_LISTS = new Set(["assetIds", "mediaIds", "visualIds"]);
+export function remapEntryMediaIds(entryValue, mapping) {
+ const entry = structuredClone(entryValue);
+ remapMediaReferences(entry, mapping);
+ for (const asset of entry.mediaAssets ?? []) asset.id = mapping.get(asset.id) ?? asset.id;
+ return entry;
+}
+function remapMediaReferences(value, mapping) {
+ if (!value || typeof value !== "object") return;
+ for (const [key, child] of Object.entries(value)) {
+ if (MEDIA_FIELDS.has(key) && typeof child === "string") value[key] = mapping.get(child) ?? child;
+ else if (MEDIA_LISTS.has(key) && Array.isArray(child)) value[key] = child.map(id => mapping.get(id) ?? id);
+ else if (child && typeof child === "object") remapMediaReferences(child, mapping);
+ }
+}
+function remapCompound(compound, maps) {
+ for (const id of compound.memberEntryIds ?? []) {
+ const mapped = maps.get(id)?.get(compound.coverVisualId);
+ if (mapped) { compound.coverVisualId = mapped; return; }
+ }
+}
diff --git a/extension/library-selection.js b/extension/library-selection.js
index 81b9c55..adf8d2c 100644
--- a/extension/library-selection.js
+++ b/extension/library-selection.js
@@ -8,7 +8,7 @@ export const LIBRARY_BATCH_ACTIONS = Object.freeze({
moveToTrash: "BATCH_MOVE_TO_TRASH"
});
-const PROJECT_MODES = new Set(["add", "remove", "move"]);
+const PROJECT_MODES = new Set(["add", "copy", "remove", "move"]);
export function normalizeSelectedLogicalCaseIds(values = []) {
return uniqueIds(values);
@@ -66,7 +66,7 @@ export function buildLibraryBatchPayload(selectedLogicalCaseIds = [], compoundCa
const collectionId = clean(operation.collectionId);
const mode = clean(operation.mode);
if (!collectionId) throw new Error("请选择项目");
- if (!PROJECT_MODES.has(mode)) throw new Error("项目批量操作必须明确选择加入、移出或移动");
+ if (!PROJECT_MODES.has(mode)) throw new Error("项目批量操作必须明确选择复制、移出或移动");
return {
type: LIBRARY_BATCH_ACTIONS.setProject,
entryIds,
diff --git a/extension/library-semantic-identity.js b/extension/library-semantic-identity.js
index 47c6113..f01b22a 100644
--- a/extension/library-semantic-identity.js
+++ b/extension/library-semantic-identity.js
@@ -1,3 +1,5 @@
+import { libraryCaseScopes } from "./library-case-scope.js";
+
const RECEIVER_LOCAL_FIELDS = new Set([
"libraryAddedAt",
"importBatchId",
@@ -25,9 +27,11 @@ export function reconcileLibrarySemanticIdentity(stateValue = {}) {
const state = stateValue && typeof stateValue === "object" ? structuredClone(stateValue) : {};
const entries = Array.isArray(state.entries) ? state.entries : [];
const groups = new Map();
+ const scopes = libraryCaseScopes(state);
for (const entry of entries) {
- const fingerprint = caseSemanticFingerprint(entry);
- if (!fingerprint) continue;
+ const content = caseSemanticFingerprint(entry);
+ if (!content) continue;
+ const fingerprint = JSON.stringify([scopes.get(entry.id), content]);
const group = groups.get(fingerprint) ?? [];
group.push(entry);
groups.set(fingerprint, group);
diff --git a/extension/library-shared-media.js b/extension/library-shared-media.js
new file mode 100644
index 0000000..fbe6eaa
--- /dev/null
+++ b/extension/library-shared-media.js
@@ -0,0 +1,42 @@
+import { sha256Blob } from "./blob-digest.js";
+import { libraryStoredAssets } from "./library-asset-inventory.js";
+
+// A media id may be referenced by several cases, trash items or creative runs.
+// Compare actual bytes only for repeated ids; package-provided hashes and sizes
+// alone cannot prove that two originals are the same.
+export async function sharedLibraryMediaFiles(library, files, { signal, digest = sha256Blob } = {}) {
+ const pathsById = new Map();
+ for (const asset of libraryStoredAssets(library)) {
+ const id = String(asset.id || asset.assetId || "").trim();
+ const path = asset.assetPath || asset.screenshotPath || asset.archivePath;
+ if (!id || !path || !(files.get(path) instanceof Blob)) continue;
+ const paths = pathsById.get(id) ?? new Set();
+ paths.add(path);
+ pathsById.set(id, paths);
+ }
+ const result = new Map(files);
+ const digests = new Map();
+ for (const paths of pathsById.values()) {
+ if (paths.size < 2 || new Set([...paths].map((path) => files.get(path))).size < 2) continue;
+ const originals = new Map();
+ for (const path of paths) {
+ signal?.throwIfAborted();
+ const blob = files.get(path);
+ if (!digests.has(blob)) digests.set(blob, await digest(blob));
+ signal?.throwIfAborted();
+ const key = `${blob.type}:${blob.size}:${digests.get(blob)}`;
+ const original = originals.get(key);
+ if (original) result.set(path, original);
+ else originals.set(key, blob);
+ }
+ }
+ return result;
+}
+
+export function mediaIdentity(asset, blob) {
+ return { blob, kind: asset.kind, reference: asset.storageMode === "reference" ? asset.reference?.url || asset.sourceUrl || "" : null };
+}
+
+export function sameMediaIdentity(left, right) {
+ return left.kind === right.kind && left.reference === right.reference && left.blob === right.blob;
+}
diff --git a/extension/library-transfer.js b/extension/library-transfer.js
index 965e889..eef70dc 100644
--- a/extension/library-transfer.js
+++ b/extension/library-transfer.js
@@ -1,3 +1,5 @@
+import { createBlobDigestCache } from "./blob-digest.js";
+import { sharedLibraryMediaFiles } from "./library-shared-media.js";
import {
hasLibrarySalvageDiagnostics,
mergeLibraryPackage,
@@ -30,11 +32,14 @@ export async function inspectLibraryTransfer({
validateImage,
signal,
onImageProgress,
- sourceReport
+ sourceReport,
+ digest = createBlobDigestCache()
} = {}) {
if (!SOURCE_TYPES.has(sourceType)) throw new Error("资料检查缺少有效来源类型");
if (!(files instanceof Map)) throw new Error("资料检查缺少有效资源清单");
+ files = await sharedLibraryMediaFiles(library, files, { signal, digest });
+
const strict = sourceType === LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP;
const sourceDiagnostics = Array.isArray(sourceReport?.diagnostics)
? structuredClone(sourceReport.diagnostics)
@@ -43,7 +48,7 @@ export async function inspectLibraryTransfer({
let inspected;
if (strict) {
try {
- inspected = await parseCompleteFolderBackup(library, files, limits);
+ inspected = await parseCompleteFolderBackup(library, files, limits, { signal, digest });
} catch (error) {
let rescued;
try {
@@ -150,6 +155,7 @@ export function planLibraryTransfer({ currentState = {}, inspection, options = {
: currentState;
const result = mergeLibraryPackage(mergeReceiver, inspection.state, {
preserveLibraryConfiguration: mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE || preserveLibraryConfiguration,
+ preserveCaseIdentities: mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE,
libraryAddedAt,
importBatchId,
importReport,
diff --git a/extension/library.css b/extension/library.css
index 5ae2320..2796b4c 100644
--- a/extension/library.css
+++ b/extension/library.css
@@ -3,7 +3,6 @@
--visual-card-radius: 2px;
}
-html { scrollbar-gutter: stable; }
html.detail-open, html.detail-open body { overflow: hidden; }
.library-loading { position: fixed; z-index: 100; inset: 0; min-height: 100vh; overflow: hidden; color: var(--muted); background: var(--paper); }
@@ -234,8 +233,8 @@ button[aria-busy="true"] { cursor: progress; }
.selection-simple-actions > button, .selection-selected-actions > button, .selection-menu { flex: 0 0 auto; }
.selection-selected-actions[hidden] { display: none; }
.selection-selected-actions { margin-right: 0; }
-.gallery-select-button { display: inline-flex; align-items: center; gap: 5px; }
-.gallery-select-button .ui-icon { width: 15px; height: 15px; }
+.gallery-select-button, .gallery-view-button { display: inline-flex; align-items: center; gap: 5px; }
+.gallery-select-button .ui-icon, .gallery-view-button .ui-icon { width: 15px; height: 15px; }
.selection-compact-action, .selection-menu > summary { display: flex; min-height: 32px; align-items: center; justify-content: center; gap: 5px; padding: 5px 9px; white-space: nowrap; }
.selection-compact-action .ui-icon, .selection-menu > summary .ui-icon { width: 15px; height: 15px; }
.selection-menu { position: relative; }
@@ -317,13 +316,13 @@ details:not([open]) > .selection-menu-panel { display: none; }
align-items: center;
gap: 3px;
padding-left: calc(var(--project-depth, 0) * 16px);
+ border: 1px solid transparent;
+ border-radius: var(--ui-container-radius);
}
.project-disclosure { display: grid; width: 18px; min-height: 28px; place-items: center; padding: 0; color: var(--muted); border: 0; background: transparent; }
.project-disclosure .ui-icon { width: 13px; height: 13px; }
.project-disclosure.is-placeholder { visibility: hidden; }
.project-row.project-draggable {
- border: 1px solid transparent;
- border-radius: var(--ui-container-radius);
cursor: grab;
touch-action: none;
-webkit-user-select: none;
@@ -389,13 +388,12 @@ details:not([open]) > .selection-menu-panel { display: none; }
.pending-switch strong { margin-left: auto; }
.project-folder-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 10px; margin-bottom: 14px; }
.project-folder-list:empty { display: none; }
-.project-folder-card { display: grid; min-width: 0; grid-template-columns: 28px minmax(0, 1fr) auto; align-items: center; gap: 9px; min-height: 58px; padding: 10px 12px; color: var(--ink); border: 1px solid var(--line); border-radius: var(--ui-container-radius); background: var(--card); text-align: left; box-shadow: var(--ui-card-shadow); }
-.project-folder-card:hover { border-color: var(--selection-edge); background: var(--selection-hover); }
-.project-folder-card > .ui-icon { width: 24px; height: 24px; color: var(--accent-ink); }
-.project-folder-copy { display: grid; min-width: 0; gap: 2px; }
-.project-folder-name { overflow: hidden; font-weight: 750; text-overflow: ellipsis; white-space: nowrap; }
-.project-folder-meta { color: var(--muted); font-size: 11px; }
-.project-folder-arrow { color: var(--muted); }
+.project-folder-card { display: grid; width: 100%; min-width: 0; grid-template-columns: 24px minmax(0, 1fr); align-items: center; justify-content: start; gap: 12px; min-height: 72px; padding: 14px; color: var(--ink); border: 1px solid var(--line); border-radius: var(--ui-container-radius); background: var(--card); text-align: left; box-shadow: none; }
+.project-folder-card:hover:not(:disabled), .project-folder-card:focus-visible { border-color: var(--selection-edge); background: var(--hover); color: var(--ink); }
+.project-folder-card > .ui-icon { width: 20px; height: 20px; color: var(--accent-ink); }
+.project-folder-copy { display: grid; min-width: 0; gap: 4px; }
+.project-folder-name { min-width: 0; font-size: 13px; font-weight: 600; line-height: 1.5; overflow-wrap: anywhere; white-space: normal; }
+.project-folder-meta { min-width: 0; overflow-wrap: anywhere; white-space: normal; color: var(--muted); font-size: 11px; font-weight: 400; }
.facet-filters { display: grid; gap: 0; margin-top: 4px; border-top: 1px solid var(--line); padding-top: 5px; }
.facet-filter { border-top: 1px solid var(--line); }
.facet-filter:first-child { border-top: 0; }
@@ -875,7 +873,7 @@ details:not([open]) > .selection-menu-panel { display: none; }
.settings-tabs { display: flex; gap: 8px; margin-bottom: 4px; border-bottom: 1px solid var(--line); padding-bottom: 10px; }
.settings-tabs button { min-height: 32px; color: var(--muted); background: transparent; }
.settings-tabs button[aria-selected="true"] { color: var(--ink); background: var(--selection); box-shadow: inset 0 -1px var(--selection-indicator); }
-.settings-panel { min-width: 0; min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; scrollbar-gutter: stable; }
+.settings-panel { min-width: 0; min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; }
.settings-rules-panel { display: grid; align-content: start; gap: 12px; }
.settings-rules-panel .analysis-kind-tabs { position: sticky; top: 0; z-index: 1; background: var(--card); margin: 0; padding-block: 8px; flex-wrap: wrap; }
.settings-rules-panel .analysis-protocol > summary { cursor: pointer; font-weight: 600; }
@@ -1043,12 +1041,7 @@ details:not([open]) > .selection-menu-panel { display: none; }
.gallery-heading.selection-mode { min-height: 34px; }
.share-bar { flex-wrap: nowrap; gap: 6px; }
.gallery-view-controls { min-height: 36px; }
- .gallery-heading.selection-mode .gallery-heading-copy { display: none; }
.selection-simple-actions, .selection-selected-actions { gap: 4px; }
- .share-bar { display: grid; width: 100%; max-width: 100%; grid-template-columns: 1fr auto; }
- .share-bar > strong { grid-column: 1; grid-row: 1; }
- .share-bar > #share-cancel { grid-column: 2; grid-row: 1; }
- .share-bar > .selection-simple-actions { grid-column: 1 / -1; grid-row: 2; }
.selection-selected-actions { max-width: 100%; flex-wrap: wrap; }
.selection-compact-action, .selection-menu > summary { min-height: 36px; padding: 5px 8px; }
.selection-menu { position: static; }
@@ -1486,15 +1479,7 @@ details:not([open]) > .selection-menu-panel { display: none; }
.compact-general .sync-settings-body button { padding: 7px 8px; font-size: 11px; }
}
-@media (min-width: 681px) {
- .settings-dialog { --settings-top: max(20px, calc((100dvh - 680px) / 2)); inset: var(--settings-top) 0 auto; margin: 0 auto; max-height: calc(100dvh - var(--settings-top) - 20px); }
- .settings-dialog:has(.compact-general:not([hidden])) { height: auto; }
-}
-
-.project-search { width: 100%; min-height: 30px; padding: 5px 8px; font-size: 12px; }
-.project-search-label, .project-search-path { display: block; min-width: 0; }
-.project-search-path { margin-top: 3px; color: var(--muted); font-size: 10px; overflow-wrap: anywhere; }
-.project-search-empty, .project-move-preview { color: var(--muted); font-size: 12px; }
+.project-move-preview { color: var(--muted); font-size: 12px; }
.project-move-feedback { position: fixed; bottom: 20px; left: 20px; z-index: 90; display: flex; align-items: center; gap: 10px; max-width: min(440px, calc(100vw - 40px)); border: 1px solid var(--line); border-radius: var(--ui-control-radius); padding: 10px 12px; color: var(--ink); background: var(--card); box-shadow: var(--shadow); }
.project-move-feedback p { flex: 1; min-width: 0; margin: 0; font-size: 11px; overflow-wrap: anywhere; }
.project-move-feedback button { flex: none; min-height: 28px; padding: 4px 7px; font-size: 11px; }
@@ -1502,16 +1487,9 @@ details:not([open]) > .selection-menu-panel { display: none; }
.project-root-drop { position: fixed; z-index: 12; background: var(--sidebar); }
.project-tree-tools { position: sticky; top: -15px; z-index: 10; display: grid; gap: 8px; padding-block: 8px; background: var(--sidebar); }
-.project-row.project-search-result { grid-template-columns: minmax(0, 1fr) auto; }
-/* Reviewed settings surfaces; the general settings and case viewer keep their layout. */
-.settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) {
- display: flex; flex-direction: column; height: fit-content; min-height: 0;
- inset: 0; margin: auto; max-height: calc(100dvh - 40px);
-}
-.settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) > .data-safety-header { flex: none; }
-.settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) .settings-shell { display: flex; flex-direction: column; min-height: 0; }
-.settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) .settings-tabs { flex: none; }
+/* All settings tabs share one frame; only their content scrolls. */
+.settings-dialog { inset: 0; margin: auto; }
#settings-ai-panel, #settings-rules-panel, :is(#settings-tasks-panel, #text-batch-dialog) { min-height: 0; overflow: auto; }
:is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel) button { white-space: nowrap; }
#settings-ai-panel .ai-routing-card, #settings-ai-panel .ai-routing-regions > section { border: 0; padding: 0; background: transparent; }
@@ -1567,9 +1545,9 @@ details:not([open]) > .selection-menu-panel { display: none; }
#import-dialog .tag-editor-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; }
#import-dialog .tag-editor-row button { justify-self: auto; white-space: nowrap; }
@media (max-width: 700px) {
- .settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) { width: calc(100vw - 16px); max-height: calc(100dvh - 24px); border-radius: var(--ui-container-radius); }
- .settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) .settings-tabs { display: flex; flex-wrap: wrap; gap: 4px; }
- .settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) .settings-tabs button { width: auto; flex: none; white-space: nowrap; }
+ .settings-dialog { width: calc(100vw - 16px); height: calc(100dvh - 24px); max-height: calc(100dvh - 24px); border-radius: var(--ui-container-radius); }
+ .settings-dialog .settings-tabs { display: flex; flex-wrap: wrap; gap: 4px; }
+ .settings-dialog .settings-tabs button { width: auto; flex: none; white-space: nowrap; }
#settings-ai-panel .ai-assignment-row { grid-template-columns: 88px minmax(0, 1fr); gap: 12px; }
#settings-ai-panel .ai-provider-row { grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; }
#settings-ai-panel .ai-provider-row > span { grid-column: 1; grid-row: 2; text-align: left; }
@@ -1617,3 +1595,82 @@ details:not([open]) > .selection-menu-panel { display: none; }
.case-cover-option { padding: 4px; overflow: hidden; }
.case-cover-option img { display: block; width: 100%; height: 100px; object-fit: cover; }
.case-cover-option[aria-pressed="true"] { border-color: var(--accent); }
+
+/* One case surface, with shared selection/detail behavior in all views. */
+.gallery-heading { flex-wrap: wrap; }
+.gallery-heading-copy { flex: 1 1 180px; flex-wrap: wrap; }
+.gallery-view-controls { flex-wrap: wrap; }
+.gallery-view-switch { display: flex; flex: none; align-items: center; gap: 2px; }
+.share-bar { flex: 1 1 auto; max-width: 100%; flex-wrap: wrap; }
+.selection-simple-actions, .selection-selected-actions { flex-wrap: wrap; }
+.filter-sidebar { min-width: 0; }
+.browse-location { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 12px 0; }
+#browse-breadcrumb { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; min-width: 0; flex: 1; }
+#browse-breadcrumb > .ui-icon { flex: none; width: 12px; height: 12px; color: var(--muted); }
+.browse-project-button { min-width: 0; border: 0; background: transparent; color: var(--ink); text-align: left; overflow-wrap: anywhere; white-space: normal; }
+#browse-breadcrumb button { padding: 4px 6px; font-size: 12px; }
+#browse-breadcrumb [aria-current="page"] { background: var(--selection); }
+#browse-scope { display: flex; flex: none; align-items: center; gap: 6px; font-size: 12px; }
+#browse-scope input { width: 15px; min-height: 0; height: 15px; accent-color: var(--accent-emphasis); }
+.browse-results { min-width: 0; }
+.case-row-details { display: none; }
+.gallery-shell:not([data-view="waterfall"]) .case-card { position: relative; display: grid; grid-template-columns: 64px minmax(0, 1fr); align-items: center; gap: 12px; padding: 8px; margin-bottom: 3px; border-radius: var(--ui-control-radius); }
+.gallery-shell:not([data-view="waterfall"]) .case-card > :first-child { min-width: 0; width: 64px; height: 64px; min-height: 0; max-height: 64px; padding: 0; overflow: hidden; border-radius: var(--ui-control-radius); }
+.gallery-shell:not([data-view="waterfall"]) .case-shot { height: 64px; width: 64px; object-fit: contain; }
+.gallery-shell:not([data-view="waterfall"]) .case-card .case-row-details { display: grid; grid-template-columns: minmax(0, 1fr) minmax(80px, 18%) minmax(80px, 16%); align-items: center; gap: 14px; min-width: 0; padding-right: 30px; }
+.case-row-title { font-size: 13px; font-weight: 600; overflow-wrap: anywhere; }
+.case-row-type, .case-row-date { font-size: 11px; color: var(--muted); overflow-wrap: anywhere; }
+.gallery-shell:not([data-view="waterfall"]) .project-folder-list { grid-template-columns: minmax(0, 1fr); gap: 3px; }
+.browse-project-button[aria-current="page"] { background: var(--selection); border-radius: var(--ui-control-radius); }
+@media (max-width: 700px) {
+ .gallery-heading-copy { flex-basis: 100%; }
+ .gallery-view-controls { margin-left: 0; }
+ .gallery-shell:not([data-view="waterfall"]) .case-card .case-row-details { grid-template-columns: minmax(0, 1fr); gap: 3px; }
+ .project-folder-list { grid-template-columns: minmax(0, 1fr); }
+}
+
+.case-row-placeholder { display: none; }
+.gallery-shell[data-view="list"] .case-card.has-row-placeholder > :first-child { display: none; }
+.gallery-shell[data-view="list"] .case-row-placeholder { display: grid; width: 64px; height: 64px; place-items: center; border-radius: var(--ui-control-radius); background: var(--raised); color: var(--muted); }
+.case-row-placeholder .ui-icon { width: 26px; height: 26px; }
+
+
+/* Management overlays the same single toolbar row without reflowing content. */
+.gallery-heading:not(.project-selection-mode) { display: flex; flex-wrap: nowrap; align-items: center; min-height: 34px; }
+.gallery-heading:not(.project-selection-mode) .gallery-heading-copy { display: flex; flex: 1 1 0; flex-wrap: nowrap; align-items: center; min-width: 0; height: 34px; }
+.gallery-heading:not(.project-selection-mode) #result-count[hidden] { display: block !important; }
+.gallery-heading:not(.project-selection-mode) .gallery-view-controls { display: flex; flex: 0 1 auto; flex-wrap: nowrap; align-items: center; min-width: 0; height: 34px; min-height: 34px; overflow-x: auto; }
+.gallery-heading:not(.project-selection-mode) .gallery-view-controls > * { flex-shrink: 0; }
+.gallery-heading:not(.project-selection-mode) .gallery-view-controls[hidden] { display: flex !important; visibility: hidden; pointer-events: none; }
+.gallery-heading.selection-mode .gallery-heading-copy { visibility: hidden; pointer-events: none; }
+.gallery-heading:not(.project-selection-mode) .share-bar { position: absolute; inset: 8px; display: flex; flex-wrap: nowrap; height: 34px; min-height: 34px; margin: 0; align-items: center; gap: 8px; }
+.gallery-heading:not(.project-selection-mode) .selection-simple-actions,
+.gallery-heading:not(.project-selection-mode) .selection-selected-actions { flex-wrap: nowrap; }
+.gallery-heading .browse-location { flex: 0 0 auto; min-width: 0; max-width: 35%; margin: 0; }
+.gallery-heading #browse-breadcrumb { flex-wrap: nowrap; overflow: hidden; }
+.gallery-heading #browse-breadcrumb button { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.gallery-heading .browse-location + h1 { flex: 0 1 auto; }
+.gallery-heading #browse-scope { margin-right: 10px; }
+.gallery-view-switch { gap: 6px; margin-right: 6px; }
+.gallery-view-button[aria-pressed="true"] { color: var(--ink); border-color: var(--selection-edge); background: var(--selection); }
+@media (max-width: 700px) {
+ .gallery-heading:not(.project-selection-mode) .gallery-heading-copy { max-width: 24%; }
+ .gallery-heading:not(.project-selection-mode) .gallery-heading-copy #result-count,
+ .gallery-heading:not(.project-selection-mode) .gallery-heading-copy #result-count[hidden],
+ .gallery-heading .browse-location { display: none !important; }
+ .gallery-heading:not(.project-selection-mode) .selection-action-label { display: none; }
+ .gallery-heading:not(.project-selection-mode) .selection-menu > summary,
+ .gallery-heading:not(.project-selection-mode) .selection-compact-action { width: 32px; min-width: 32px; min-height: 34px; padding: 6px; }
+ .gallery-heading #manage-case-order { min-height: 32px; }
+}
+
+.gallery-view-button { width: 34px; min-width: 34px; justify-content: center; }
+
+.browse-project-button:hover:not(:disabled),
+.project-disclosure:hover:not(:disabled),
+.filter-heading button:hover:not(:disabled) { background: var(--hover); color: var(--ink); }
+.local-discovery-item:hover:not(:disabled) { background: var(--card); }
+
+.project-row.case-drop-target,
+#workspace-unassigned.case-drop-target,
+#open-trash.case-drop-target { box-shadow: inset 0 0 0 1px var(--accent-ink); background: var(--hover); }
diff --git a/extension/library.html b/extension/library.html
index e7f2150..b0a8c67 100644
--- a/extension/library.html
+++ b/extension/library.html
@@ -7,8 +7,9 @@
<script src="theme-bootstrap.js"></script>
<link rel="stylesheet" href="ui-foundation.css" />
<link rel="stylesheet" href="library.css" />
+ <link rel="stylesheet" href="library-layout.css" />
</head>
- <body data-library-state="loading">
+ <body class="modular-library" data-library-state="loading">
<div id="library-loading" class="library-loading" role="status" aria-live="polite">
<div class="library-loading-bar"></div>
<div class="library-loading-body">
@@ -22,63 +23,18 @@
<img class="brand-mark product-brand-mark" src="assets/icons/icon-source.svg" alt="" />
<div class="product-brand-copy"><strong class="brand-wordmark product-brand-name">PromptDirector</strong><span class="product-brand-tagline" data-i18n="视觉创作灵感库">视觉创作灵感库</span></div>
</div>
+ <div id="gallery-heading" class="gallery-heading">
+ <div class="gallery-heading-copy"><div class="browse-location"><nav id="browse-breadcrumb" aria-label="项目路径" data-i18n-aria-label="项目路径"></nav></div><h1 id="library-title"></h1><strong id="result-count"></strong></div>
<label class="global-search">
<span class="sr-only" data-i18n="搜索提示词、来源或 AI 标签">搜索提示词、来源或 AI 标签</span>
<input id="search-input" type="search" placeholder="搜索画面、提示词,或输入 type:video…" data-i18n-placeholder="搜索画面、提示词,或输入 type:video…" />
</label>
- <div class="top-actions">
- <details id="add-menu" class="package-menu add-menu">
- <summary class="button-secondary" data-i18n="添加">添加</summary>
- <div class="package-menu-panel">
- <button id="add-media" class="ui-content-row" type="button"><strong data-i18n="导入本机资料">导入本机资料</strong><span data-i18n="选择文件或文件夹,统一确认后导入">选择文件或文件夹,统一确认后导入</span></button>
- <button id="add-video-reference" class="button-secondary ui-content-row" type="button"><strong data-i18n="视频链接">视频链接</strong><span data-i18n="保存 YouTube、Vimeo 或来源网页">保存 YouTube、Vimeo 或来源网页</span></button>
- <button id="add-quick-note" class="button-secondary ui-content-row" type="button"><strong data-i18n="快速笔记">快速笔记</strong><span data-i18n="立即记下一段创作想法">立即记下一段创作想法</span></button>
- </div>
- </details>
- <button id="start-compose" type="button" data-i18n="开始创作">开始创作</button>
- <button id="open-settings" class="icon-button settings-entry-button" type="button" aria-label="设置" data-i18n-aria-label="设置" title="设置" data-i18n-title="设置"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-settings"></use></svg><span id="settings-update-badge" class="settings-update-badge" aria-label="有可用更新" hidden data-i18n-aria-label="有可用更新"></span></button>
- <input id="media-file" class="sr-only" type="file" multiple />
- <input id="media-folder" class="sr-only" type="file" multiple webkitdirectory />
- </div>
- </header>
-
- <div class="workspace">
- <aside id="filter-sidebar" class="filter-sidebar" aria-label="案例筛选" data-i18n-aria-label="案例筛选">
- <nav class="workspace-navigation" aria-label="工作空间" data-i18n-aria-label="工作空间">
- <div class="filter-heading"><strong data-i18n="工作空间">工作空间</strong></div>
- <button id="workspace-library" class="workspace-navigation-item" type="button" aria-current="page"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-library"></use></svg><span data-i18n="案例库">案例库</span></button>
- <button id="workspace-unassigned" class="workspace-navigation-item" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-folder"></use></svg><span data-i18n="未归项目">未归项目</span></button>
- <button id="open-curated" class="workspace-navigation-item" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-sparkles"></use></svg><span data-i18n="精选案例">精选案例</span></button>
- <button id="open-skills" class="workspace-navigation-item" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-wand-sparkles"></use></svg><span data-i18n="创作 Skill">创作 Skill</span></button>
- </nav>
- <section id="project-section" class="project-section">
- <div class="project-tree-tools">
- <div class="filter-heading"><strong data-i18n="项目">项目</strong><span><button id="create-collection" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-plus"></use></svg><span data-i18n="新建">新建</span></button><button id="collapse-projects" class="icon-button" type="button" aria-label="全部折叠" title="全部折叠" data-i18n-aria-label="全部折叠" data-i18n-title="全部折叠"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-chevron-left"></use></svg></button></span></div>
- <input id="project-search" class="project-search" type="search" aria-label="搜索项目" placeholder="搜索项目" data-i18n-aria-label="搜索项目" data-i18n-placeholder="搜索项目" />
- </div>
- <div id="project-root-drop" class="project-root-drop" hidden data-i18n="移到根级">移到根级</div>
- <div id="collection-filters" class="project-list" role="tree" aria-label="项目树" data-i18n-aria-label="项目树"></div>
- <div id="project-move-feedback" class="project-move-feedback" hidden><p id="project-order-status" role="status" aria-live="polite"></p><button id="project-move-undo" class="button-secondary" type="button" data-i18n="撤销">撤销</button><button class="icon-button project-move-dismiss" type="button" aria-label="关闭" data-i18n-aria-label="关闭"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-x"></use></svg></button></div>
- </section>
- <section class="sidebar-trash-section">
- <button id="open-trash" class="workspace-navigation-item" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-trash-2"></use></svg><span data-i18n="回收站">回收站</span><strong id="trash-count" class="workspace-navigation-count" hidden></strong></button>
- </section>
- <section class="filter-section">
- <div class="filter-heading"><strong data-i18n="内容类型">内容类型</strong><button id="manage-facets" type="button" data-i18n="分类与标签">整理</button></div>
- <div id="content-filters" class="filter-options"></div>
- <label class="pending-switch"><input id="pending-filter" type="checkbox" /><span data-i18n="只看待确认">只看待确认</span><strong id="pending-count"></strong></label>
- </section>
- <section class="filter-section tag-navigation-section">
- <div class="filter-heading"><strong data-i18n="属性筛选">属性筛选</strong></div>
- <div id="facet-filters" class="facet-filters"></div>
- </section>
- </aside>
- <div id="sidebar-resizer" class="sidebar-resizer" role="separator" tabindex="0" aria-label="调整项目侧栏宽度" aria-orientation="vertical" aria-valuemin="216" aria-valuemax="420" aria-valuenow="244" data-i18n-aria-label="调整项目侧栏宽度"></div>
-
- <main class="gallery-shell">
- <div id="gallery-heading" class="gallery-heading">
- <div class="gallery-heading-copy"><h1 id="library-title"></h1><strong id="result-count"></strong></div>
<div id="gallery-view-controls" class="gallery-view-controls">
+ <label id="browse-scope"><input id="include-subprojects" type="checkbox"><span data-i18n="包含子项目">包含子项目</span></label>
+ <div class="gallery-view-switch" role="group" aria-label="案例视图" data-i18n-aria-label="案例视图">
+ <button type="button" class="button-secondary gallery-view-button" data-gallery-view="waterfall" aria-pressed="false" aria-label="瀑布流" title="瀑布流" data-i18n-aria-label="瀑布流" data-i18n-title="瀑布流"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-image"></use></svg></button>
+ <button type="button" class="button-secondary gallery-view-button" data-gallery-view="list" aria-pressed="false" aria-label="列表" title="列表" data-i18n-aria-label="列表" data-i18n-title="列表"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-menu"></use></svg></button>
+ </div>
<label class="gallery-sort-field"><span class="sr-only" data-i18n="案例排序">案例排序</span><select id="gallery-sort" aria-label="案例排序" data-i18n-aria-label="案例排序"><option value="added-desc" data-i18n="最近加入">最近加入</option><option value="updated-desc" data-i18n="最近更新">最近更新</option><option value="title" data-i18n="标题">标题</option><option id="project-manual-sort-option" value="project-manual" hidden data-i18n="手动排序">手动排序</option></select></label>
<button id="manage-case-order" class="icon-button" type="button" aria-label="管理案例顺序" title="管理案例顺序" hidden data-i18n-aria-label="管理案例顺序" data-i18n-title="管理案例顺序"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-sliders-horizontal"></use></svg></button>
<button id="select-cases" class="button-secondary gallery-select-button" type="button" aria-label="管理案例" data-i18n-aria-label="管理案例" title="管理案例" data-i18n-title="管理案例"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-square-check-big"></use></svg><span data-i18n="管理">管理</span></button>
@@ -89,13 +45,13 @@
<button id="selection-select-filtered" class="button-secondary" type="button" data-i18n="全选筛选结果">全选筛选结果</button>
<div id="selection-selected-actions" class="selection-selected-actions" hidden>
<details id="selection-project-menu" class="selection-menu">
- <summary aria-label="项目" data-i18n-aria-label="项目"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-folder"></use></svg><span class="selection-action-label" data-i18n="项目">项目</span></summary>
+ <summary aria-label="项目" data-i18n-aria-label="项目" title="项目" data-i18n-title="项目"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-folder"></use></svg><span class="selection-action-label" data-i18n="项目">项目</span></summary>
<div class="project-menu-panel selection-menu-panel selection-project-panel">
<strong id="selection-project-impact" class="selection-project-impact"></strong>
<label><span data-i18n="选择目标项目">选择目标项目</span><select id="selection-project-target" aria-label="选择目标项目" data-i18n-aria-label="选择目标项目"><option value="" data-i18n="选择项目…">选择项目…</option></select></label>
<div class="selection-project-actions">
<button id="selection-move-project" class="project-menu-primary" type="button" disabled data-i18n="移动">移动</button>
- <button id="selection-add-project" class="button-secondary" type="button" disabled data-i18n="同时加入">同时加入</button>
+ <button id="selection-copy-project" class="button-secondary" type="button" disabled data-i18n="复制到项目">复制到项目</button>
<button id="selection-remove-project" class="button-secondary" type="button" disabled data-i18n="移出当前项目">移出当前项目</button>
</div>
<button id="selection-new-project" class="button-secondary" type="button" disabled data-i18n="新建项目并移动">新建项目并移动</button>
@@ -103,7 +59,7 @@
</details>
<button id="selection-trash" class="button-secondary quiet-danger selection-compact-action" type="button" disabled aria-label="移入回收站" data-i18n-aria-label="移入回收站" title="移入回收站" data-i18n-title="移入回收站"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-trash-2"></use></svg><span class="selection-action-label" data-i18n="删除">删除</span></button>
<details id="selection-classification-menu" class="selection-menu">
- <summary aria-label="修改分类" data-i18n-aria-label="修改分类"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-list-checks"></use></svg><span class="selection-action-label" data-i18n="分类">分类</span></summary>
+ <summary aria-label="修改分类" data-i18n-aria-label="修改分类" title="修改分类" data-i18n-title="修改分类"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-list-checks"></use></svg><span class="selection-action-label" data-i18n="分类">分类</span></summary>
<div class="project-menu-panel selection-menu-panel">
<strong id="selection-classification-impact"></strong>
<select id="selection-content-type" aria-label="案例类型" data-i18n-aria-label="案例类型"></select>
@@ -111,14 +67,14 @@
</div>
</details>
<details id="selection-label-menu" class="selection-menu">
- <summary aria-label="添加标签" data-i18n-aria-label="添加标签"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-tag"></use></svg><span class="selection-action-label" data-i18n="标签">标签</span></summary>
+ <summary aria-label="添加标签" data-i18n-aria-label="添加标签" title="添加标签" data-i18n-title="添加标签"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-tag"></use></svg><span class="selection-action-label" data-i18n="标签">标签</span></summary>
<div class="project-menu-panel selection-menu-panel selection-label-panel">
<label class="selection-label-field"><span data-i18n="添加标签">添加标签</span><input id="selection-label-input" type="text" placeholder="输入标签名" data-i18n-placeholder="输入标签名" autocomplete="off" /></label>
<button id="selection-add-labels" class="project-menu-primary" type="button" disabled data-i18n="添加标签">添加标签</button>
</div>
</details>
<details id="selection-more-menu" class="selection-menu">
- <summary aria-label="更多" data-i18n-aria-label="更多"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-ellipsis"></use></svg><span class="selection-action-label" data-i18n="更多">更多</span></summary>
+ <summary aria-label="更多" data-i18n-aria-label="更多" title="更多" data-i18n-title="更多"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-ellipsis"></use></svg><span class="selection-action-label" data-i18n="更多">更多</span></summary>
<div class="project-menu-panel selection-menu-panel selection-more-panel">
<button id="share-export" class="button-secondary" type="button" disabled data-i18n="分享">分享</button>
<button id="selection-combine" class="button-secondary" type="button" disabled data-i18n="组合案例">组合案例</button>
@@ -142,7 +98,63 @@
<button id="project-selection-save" type="button" data-i18n="保存项目案例">保存项目案例</button>
</div>
</div>
+ <div class="top-actions">
+ <details id="add-menu" class="package-menu add-menu">
+ <summary class="button-secondary" data-i18n="添加">添加</summary>
+ <div class="package-menu-panel">
+ <button id="add-media" class="ui-content-row" type="button"><strong data-i18n="导入本机资料">导入本机资料</strong><span data-i18n="选择文件或文件夹,统一确认后导入">选择文件或文件夹,统一确认后导入</span></button>
+ <button id="add-video-reference" class="button-secondary ui-content-row" type="button"><strong data-i18n="视频链接">视频链接</strong><span data-i18n="保存 YouTube、Vimeo 或来源网页">保存 YouTube、Vimeo 或来源网页</span></button>
+ <button id="add-quick-note" class="button-secondary ui-content-row" type="button"><strong data-i18n="快速笔记">快速笔记</strong><span data-i18n="立即记下一段创作想法">立即记下一段创作想法</span></button>
+ </div>
+ </details>
+ <button id="start-compose" type="button" data-i18n="开始创作">开始创作</button>
+ <button id="open-settings" class="icon-button settings-entry-button" type="button" aria-label="设置" data-i18n-aria-label="设置" title="设置" data-i18n-title="设置"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-settings"></use></svg><span id="settings-update-badge" class="settings-update-badge" aria-label="有可用更新" hidden data-i18n-aria-label="有可用更新"></span></button>
+ <input id="media-file" class="sr-only" type="file" multiple />
+ <input id="media-folder" class="sr-only" type="file" multiple webkitdirectory />
+ </div>
+ </header>
+
+ <div class="workspace">
+ <aside id="filter-sidebar" class="filter-sidebar" aria-label="案例筛选" data-i18n-aria-label="案例筛选">
+ <nav class="workspace-navigation" aria-label="工作空间" data-i18n-aria-label="工作空间">
+ <div class="filter-heading"><strong data-i18n="工作空间">工作空间</strong></div>
+ <button id="workspace-library" class="workspace-navigation-item" type="button" aria-current="page"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-library"></use></svg><span data-i18n="案例库">案例库</span></button>
+ <button id="workspace-unassigned" class="workspace-navigation-item" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-folder"></use></svg><span data-i18n="未归项目">未归项目</span></button>
+ <button id="open-curated" class="workspace-navigation-item" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-sparkles"></use></svg><span data-i18n="精选案例">精选案例</span></button>
+ <button id="open-skills" class="workspace-navigation-item" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-wand-sparkles"></use></svg><span data-i18n="创作 Skill">创作 Skill</span></button>
+ </nav>
+ <div id="sidebar-modules" class="sidebar-modules">
+ <section id="project-section" class="project-section sidebar-module" data-sidebar-module="projects">
+ <div class="project-tree-tools">
+ <div class="filter-heading"><strong data-i18n="项目">项目</strong><span><button id="create-collection" type="button" aria-label="新建项目" title="新建项目" data-i18n-aria-label="新建项目" data-i18n-title="新建项目"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-plus"></use></svg><span data-i18n="新建">新建</span></button><button id="collapse-projects" class="icon-button" type="button" aria-label="全部折叠" title="全部折叠" data-i18n-aria-label="全部折叠" data-i18n-title="全部折叠"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-chevron-left"></use></svg></button></span></div>
+ </div>
+ <div id="sidebar-projects-body" class="sidebar-module-body">
+ <div id="project-root-drop" class="project-root-drop" hidden data-i18n="移到根级">移到根级</div>
+ <div id="collection-filters" class="project-list" role="tree" aria-label="项目树" data-i18n-aria-label="项目树"></div>
+ <div id="project-move-feedback" class="project-move-feedback" hidden><p id="project-order-status" role="status" aria-live="polite"></p><button id="project-move-undo" class="button-secondary" type="button" data-i18n="撤销">撤销</button><button class="icon-button project-move-dismiss" type="button" aria-label="关闭" data-i18n-aria-label="关闭"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-x"></use></svg></button></div>
+ </div>
+ </section>
+ <section class="filter-section sidebar-module" data-sidebar-module="types">
+ <div class="filter-heading"><strong data-i18n="内容类型">内容类型</strong><button id="manage-facets" class="icon-button" type="button" aria-label="分类与标签" title="分类与标签" data-i18n-aria-label="分类与标签" data-i18n-title="分类与标签"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-sliders-horizontal"></use></svg></button></div>
+ <div id="sidebar-types-body" class="sidebar-module-body">
+ <div id="content-filters" class="filter-options"></div>
+ <label class="pending-switch"><input id="pending-filter" type="checkbox" /><span data-i18n="只看待确认">只看待确认</span><strong id="pending-count"></strong></label>
+ </div>
+ </section>
+ <section class="filter-section tag-navigation-section sidebar-module" data-sidebar-module="tags">
+ <div class="filter-heading"><strong data-i18n="属性筛选">属性筛选</strong></div>
+ <div id="sidebar-tags-body" class="sidebar-module-body"><div id="facet-filters" class="facet-filters"></div></div>
+ </section>
+ </div>
+ <section class="sidebar-trash-section">
+ <button id="open-trash" class="workspace-navigation-item" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-trash-2"></use></svg><span data-i18n="回收站">回收站</span><strong id="trash-count" class="workspace-navigation-count" hidden></strong></button>
+ </section>
+ </aside>
+ <div id="sidebar-resizer" class="sidebar-resizer" role="separator" tabindex="0" aria-label="调整项目侧栏宽度" aria-orientation="vertical" aria-valuemin="216" aria-valuemax="420" aria-valuenow="244" data-i18n-aria-label="调整项目侧栏宽度"></div>
+
+ <main class="gallery-shell">
<p id="feedback" class="ui-feedback-toast" role="status" aria-live="polite"></p>
+ <div class="browse-results">
<section id="project-folder-list" class="project-folder-list" aria-label="子项目" data-i18n-aria-label="子项目"></section>
<section id="case-list" class="masonry" aria-live="polite"></section>
<div id="load-sentinel" class="load-sentinel" aria-hidden="true"></div>
@@ -160,6 +172,7 @@
</section>
<section id="empty-filter" hidden><strong data-i18n="没有匹配的案例">没有匹配的案例</strong><p data-i18n="调整筛选条件,或保存新的图片、视频提示词。">调整筛选条件,或保存新的图片、视频提示词。</p></section>
</div>
+ </div>
</main>
</div>
diff --git a/extension/library.js b/extension/library.js
index 86ce0c4..2a77ad3 100644
--- a/extension/library.js
+++ b/extension/library.js
@@ -1,7 +1,10 @@
+import { createBlobDigestCache } from "./blob-digest.js";
+import { createLibraryLayout } from "./library-layout.js";
+import { renderBrowseNavigation, appendCaseRowDetails } from "./library-browse-view.js";
import { attachDetailSplit } from "./detail-split.js";
import { sendWithGenerationPromptConfirmation } from "./image-generation-confirmation.js";
import { createGenerationInfoViewReader } from "./image-generation-view.js";
-import { downloadMediaCopies, showQuickMenu } from "./library-quick-actions.js";
+import { copyFilename, downloadMediaCopies, showQuickMenu } from "./library-quick-actions.js";
import { assetFormatForExtension } from "./asset-formats.js";
import { docxImageLoader } from "./docx-ingestion.js";
import { applyLibraryImportWithReceipt } from "./library-import-client.js";
@@ -191,9 +194,8 @@ import {
LOCAL_ASSET_REFERENCE_RECORD_TYPE,
createUnsupportedLocalAssetReference,
extractLocalDocumentText,
- findExactMediaDuplicate,
- prepareLocalMedia as prepareSharedLocalMedia,
- sha256Blob
+ createExactMediaDuplicateIndex,
+ prepareLocalMedia as prepareSharedLocalMedia
} from "./local-media.js";
import {
LOCAL_ASSET_LINK_STATUS,
@@ -242,8 +244,8 @@ const elements = Object.fromEntries([
"add-quick-note", "organize-detail-tags", "organize-detail-status", "pause-analysis-batch", "pause-library-maintenance", "preview-analysis-batch", "preview-analysis-reanalyze", "preview-reanalyze", "reanalyze-preview", "result-count", "resume-analysis-batch", "resume-library-maintenance", "retry-analysis-failures", "retry-library-maintenance", "start-analysis-reanalyze",
"project-selection-actions", "project-selection-cancel", "project-selection-clear", "project-selection-count", "project-selection-save", "project-selection-select-all", "project-selection-select-filtered", "project-selection-title", "project-order-status", "restore-analysis-default", "search-input", "share-bar", "share-cancel", "share-count", "share-export", "start-analysis-batch", "start-compose", "toggle-filters", "undo-analysis-batch", "undo-facet", "vocabulary-facet", "workspace-library", "workspace-unassigned",
"share-dialog", "share-dialog-public", "share-dialog-public-panel", "share-dialog-close", "share-dialog-title", "share-dialog-meta", "share-dialog-options", "share-dialog-export", "share-dialog-submit", "share-dialog-disclosure", "share-dialog-result", "share-dialog-result-text", "share-dialog-show-files", "share-dialog-open-form",
- "text-batch-dialog", "text-batch-close", "text-batch-content", "text-batch-card", "analysis-batch-details", "selection-content-type", "selection-classification-impact", "selection-set-classification", "selection-text-analyze", "add-menu", "export-path-setting", "media-file", "media-folder", "library-name-setting", "save-library-settings", "select-cases", "selection-select-filtered", "selection-clear", "selection-label-input", "selection-add-labels", "selection-add-project", "selection-move-project", "selection-remove-project", "selection-new-project", "selection-combine", "selection-analyze", "selection-video-analyze", "selection-project-impact", "selection-project-target", "selection-trash", "open-settings", "settings-dialog", "settings-close", "settings-update-badge", "open-about", "local-extension-package", "library-settings-feedback", "update-status", "check-extension-update", "apply-extension-update", "update-feedback",
- "project-section", "project-root-drop", "collapse-projects", "project-search", "project-move-feedback", "project-move-undo", "selection-simple-actions", "selection-selected-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree",
+ "text-batch-dialog", "text-batch-close", "text-batch-content", "text-batch-card", "analysis-batch-details", "selection-content-type", "selection-classification-impact", "selection-set-classification", "selection-text-analyze", "add-menu", "export-path-setting", "media-file", "media-folder", "library-name-setting", "save-library-settings", "select-cases", "selection-select-filtered", "selection-clear", "selection-label-input", "selection-add-labels", "selection-copy-project", "selection-move-project", "selection-remove-project", "selection-new-project", "selection-combine", "selection-analyze", "selection-video-analyze", "selection-project-impact", "selection-project-target", "selection-trash", "open-settings", "settings-dialog", "settings-close", "settings-update-badge", "open-about", "local-extension-package", "library-settings-feedback", "update-status", "check-extension-update", "apply-extension-update", "update-feedback",
+ "project-section", "project-root-drop", "collapse-projects", "project-move-feedback", "project-move-undo", "selection-simple-actions", "selection-selected-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree",
"vision-instructions-en", "vision-instructions-zh", "vision-protocol", "vision-settings-form", "vision-settings-status", "restore-vision-default",
"video-instructions-en", "video-instructions-zh", "video-settings-form", "video-settings-status", "restore-video-default", "video-protocol",
"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",
@@ -272,7 +274,7 @@ const managerPanels = {
vocabulary: elements.managerVocabulary
};
const workspace = document.querySelector(".workspace");
-const galleryMasonry = createStableMasonry(elements.caseList, {
+let galleryMasonry = createStableMasonry(elements.caseList, {
layoutDependencies: [document.querySelector(".topbar")],
onLayout: () => scheduleLoadCheck()
});
@@ -366,6 +368,7 @@ let maintenanceCheckPromise = null;
let maintenanceCheckedJob = "";
let visionBatchJob = null;
let activeMediaBatchKind = "image";
+let visionBatchSelection = null;
let canUndoAnalysisBatch = false;
let analysisBatchPreview = null;
let analysisDiagnostics = [];
@@ -434,9 +437,9 @@ function projectComboboxCollections() {
}
const mobileLayout = matchMedia("(max-width: 640px)");
-if (mobileLayout.matches) workspace.classList.add("filters-collapsed");
+
mobileLayout.addEventListener("change", (event) => {
- if (event.matches) workspace.classList.add("filters-collapsed");
+
renderFilterToggleState();
applyDetailViewPreferences();
});
@@ -476,6 +479,14 @@ window.addEventListener("focus", () => {
if (externalLibraryRefreshPending) scheduleExternalLibraryRefresh();
});
+const libraryLayout = createLibraryLayout({
+ preferences: uiPreferences,
+ persist: async sidebarLayout => {
+ try { uiPreferences = await updateUiPreferences({ ...uiPreferences, sidebarLayout }); }
+ catch (error) { showFeedback(error.message, true); }
+ },
+ onToggle: renderFilterToggleState
+});
bindEvents();
const libraryTopbar = document.querySelector(".topbar");
const libraryToolbarObserver = new ResizeObserver(() => {
@@ -508,7 +519,7 @@ openRequestedSettings();
window.addEventListener("pagehide", saveLibraryReturnSnapshot);
window.addEventListener("unload", () => {
- galleryMasonry.destroy();
+ galleryMasonry?.destroy();
if (mediaHydrationFrame) cancelAnimationFrame(mediaHydrationFrame);
if (maintenancePollTimer) clearTimeout(maintenancePollTimer);
if (importPollTimer) clearTimeout(importPollTimer);
@@ -703,6 +714,14 @@ function bindEvents() {
activeAiRoutingTab = button.dataset.aiRoutingTab || "tasks";
renderAiRoutingView();
}));
+ for (const button of document.querySelectorAll("[data-gallery-view]")) {
+ button.addEventListener("click", async () => {
+ await saveBrowsePreference({ galleryView: button.dataset.galleryView });
+ });
+ }
+ document.querySelector("#include-subprojects").addEventListener("change", async (event) => {
+ await saveBrowsePreference({ includeSubprojects: event.target.checked });
+ });
elements.createCollection.addEventListener("click", () => createProjectCollection(elements.createCollection));
elements.gallerySort.addEventListener("change", () => {
caseSortMode = elements.gallerySort.value;
@@ -713,10 +732,8 @@ function bindEvents() {
elements.collapseProjects.addEventListener("click", () => {
projectTreeController().cancel();
expandedProjectIds.clear();
- elements.projectSearch.value = "";
renderProjectFilters();
});
- elements.projectSearch.addEventListener("input", renderProjectFilters);
elements.projectSelectionSelectFiltered.addEventListener("click", () => selectVisionCases("filtered"));
elements.projectSelectionSelectAll.addEventListener("click", () => selectVisionCases("all"));
elements.projectSelectionClear.addEventListener("click", clearVisionSelection);
@@ -726,6 +743,7 @@ function bindEvents() {
for (const select of [elements.uiLocale, elements.uiTheme, elements.uiMotion]) {
select.addEventListener("change", async () => {
await updateUiPreferences({
+ ...uiPreferences,
locale: elements.uiLocale.value,
theme: elements.uiTheme.value,
motion: elements.uiMotion.value,
@@ -738,13 +756,10 @@ function bindEvents() {
});
}
elements.showAnalysisDiagnostics.addEventListener("change", updateAnalysisDiagnosticsPreference);
- elements.toggleFilters.addEventListener("click", () => {
- workspace.classList.toggle("filters-collapsed");
- renderFilterToggleState();
- });
bindSidebarResize();
elements.workspaceLibrary.addEventListener("click", clearFilters);
elements.workspaceUnassigned.addEventListener("click", openUnassignedView);
+ bindCaseDrop(elements.workspaceUnassigned);
elements.openCurated.addEventListener("click", () => {
navigateWithinPromptDirector("curated.html");
});
@@ -779,8 +794,15 @@ function bindEvents() {
await runDataSafetyAction(elements.disconnectSyncFolder, { type: "DISCONNECT_SYNC_FOLDER" });
});
elements.visionBatchClose.addEventListener("click", () => elements.visionBatchDialog.close());
- elements.visionBatchDialog.addEventListener("click", (event) => {
- if (event.target === elements.visionBatchDialog) elements.visionBatchDialog.close();
+ elements.visionBatchDialog.addEventListener("close", () => {
+ const job = visionBatchJob;
+ const sameSelection = visionBatchSelection?.caseIds.length === selectedCaseIds.size
+ && visionBatchSelection.caseIds.every((id) => selectedCaseIds.has(id));
+ if (sameSelection && job?.id === visionBatchSelection.jobId && job.status === "completed"
+ && job.counts?.succeeded > 0 && !job.counts.failed && !job.counts.pending && !job.counts.running) {
+ exitSelectionMode();
+ }
+ visionBatchSelection = null;
});
for (const checkbox of [elements.visionBatchAllImages, elements.visionBatchReanalyze]) {
checkbox.addEventListener("change", () => {
@@ -800,9 +822,6 @@ function bindEvents() {
elements.shareCancel.addEventListener("click", exitSelectionMode);
elements.shareExport.addEventListener("click", completeSelection);
elements.shareDialogClose.addEventListener("click", closeShareDialog);
- elements.shareDialog.addEventListener("click", (event) => {
- if (event.target === elements.shareDialog) closeShareDialog();
- });
elements.shareDialogPublic.addEventListener("click", () => {
const expanded = elements.shareDialogPublicPanel.hidden;
elements.shareDialogPublicPanel.hidden = !expanded;
@@ -828,7 +847,7 @@ function bindEvents() {
elements.selectionAddLabels.addEventListener("click", addLabelsToSelection);
elements.selectionSetClassification.addEventListener("click", setSelectionClassification);
elements.selectionContentType.addEventListener("change", updateSelectionBar);
- elements.selectionAddProject.addEventListener("click", addSelectionToProject);
+ elements.selectionCopyProject.addEventListener("click", copySelectionToProject);
elements.selectionMoveProject.addEventListener("click", moveSelectionToProject);
elements.selectionRemoveProject.addEventListener("click", removeSelectionFromProject);
elements.selectionNewProject.addEventListener("click", createProjectFromSelection);
@@ -851,12 +870,10 @@ function bindEvents() {
updateSelectionBar();
});
elements.openTrash.addEventListener("click", openTrashDialog);
+ bindCaseDrop(elements.openTrash, { toTrash: true });
elements.trashClose.addEventListener("click", () => elements.trashDialog.close());
elements.trashRestoreAll.addEventListener("click", restoreAllTrashItems);
elements.trashEmpty.addEventListener("click", emptyTrashFromDialog);
- elements.trashDialog.addEventListener("click", (event) => {
- if (event.target === elements.trashDialog) elements.trashDialog.close();
- });
elements.manageFacets.addEventListener("click", () => {
elements.managerFeedback.hidden = true;
activeManagerTab = "content-types";
@@ -864,9 +881,6 @@ function bindEvents() {
elements.managerDialog.showModal();
});
elements.managerClose.addEventListener("click", () => elements.managerDialog.close());
- elements.managerDialog.addEventListener("click", (event) => {
- if (event.target === elements.managerDialog) elements.managerDialog.close();
- });
managerTabs.forEach((button) => button.addEventListener("click", () => {
activeManagerTab = button.dataset.managerTab;
renderManager();
@@ -1217,7 +1231,7 @@ function renderGallery() {
: logicalCases.filter((entry) => (entry.memberEntryIds ?? [entry.id])
.some((entryId) => isEntryVisibleInLibrary(organizerState, entryId)));
const projectEntryIds = selectedCollectionId && selectionMode !== "project"
- ? new Set(selectionMode === "vision"
+ ? new Set(selectionMode === "vision" || uiPreferences.includeSubprojects
? collectionEntryIds(organizerState, selectedCollectionId, { subtree: true })
: organizerState.collections.find((item) => item.id === selectedCollectionId)?.entryIds ?? [])
: null;
@@ -1284,6 +1298,7 @@ function renderGalleryResults({ refreshNavigation }) {
? organizerState.collections.find((item) => item.id === selectedCollectionId)
: null;
const childProjects = project ? projectChildren(project.id) : [];
+ syncBrowseView(project);
visibleEntries = sortLibraryCases(visibleEntries, {
mode: caseSortMode,
projectEntryIds: project?.entryIds ?? []
@@ -1291,7 +1306,8 @@ function renderGalleryResults({ refreshNavigation }) {
renderedCount = 0;
imageObserver.disconnect();
reconcileInitialCaseCards();
- renderProjectFolderCards(childProjects);
+ const folderProjects = project && uiPreferences.includeSubprojects ? [] : childProjects;
+ renderProjectFolderCards(folderProjects);
if (refreshNavigation) {
renderProjectFilters();
elements.workspaceLibrary.setAttribute("aria-current", selectedCollectionId || unassignedViewActive ? "false" : "page");
@@ -1301,8 +1317,7 @@ function renderGalleryResults({ refreshNavigation }) {
}
syncStructuredFilterControls();
renderActiveFilters();
- galleryMasonry.reset();
- galleryMasonry.append([...elements.caseList.children]);
+ layoutBrowseCards();
observePendingCardMedia([...elements.caseList.children]);
scheduleVisibleMediaHydration();
renderedCount = elements.caseList.children.length;
@@ -1312,50 +1327,106 @@ function renderGalleryResults({ refreshNavigation }) {
loadObserver.observe(elements.loadSentinel);
scheduleLoadCheck(generation);
});
- elements.emptyState.hidden = visibleEntries.length > 0 || childProjects.length > 0;
+ elements.emptyState.hidden = visibleEntries.length > 0 || folderProjects.length > 0;
elements.emptyLibrary.hidden = logicalCases.length > 0;
elements.emptyFilter.hidden = logicalCases.length === 0;
renderEmptyFilter();
elements.libraryTitle.textContent = unassignedViewActive
? t("未归项目")
: project?.name || libraryTitleForLocale(settings.libraryTitle, currentLocale());
+ elements.libraryTitle.title = elements.libraryTitle.textContent;
elements.resultCount.textContent = project
- ? `${visibleEntries.length} 个直接案例 · ${childProjects.length} 个子项目`
+ ? `${translateUiMessage(`${visibleEntries.length} 个案例`)} · ${childProjects.length} ${t("子项目")}`
: translateUiMessage(`${visibleEntries.length} 个案例`);
elements.pendingCount.textContent = String(pendingCount);
}
+async function saveBrowsePreference(change) {
+ const controls = [...document.querySelectorAll("[data-gallery-view], #include-subprojects")];
+ controls.forEach((control) => { control.disabled = true; });
+ try {
+ uiPreferences = await updateUiPreferences({ ...uiPreferences, ...change });
+ caseOrderManagementActive = false;
+ } catch (error) {
+ showFeedback(error.message, true);
+ } finally {
+ controls.forEach((control) => { control.disabled = false; });
+ renderGallery();
+ }
+}
+
+function navigateBrowseProject(id) {
+ unassignedViewActive = false;
+ selectedCollectionId = id;
+ caseOrderManagementActive = false;
+ renderGallery();
+}
+
+function syncBrowseView(project) {
+ const view = uiPreferences.galleryView;
+ document.querySelector(".gallery-shell").dataset.view = view;
+ for (const button of document.querySelectorAll("[data-gallery-view]")) {
+ button.setAttribute("aria-pressed", String(button.dataset.galleryView === view));
+ }
+ document.querySelector(".browse-location").hidden = !project;
+ document.querySelector("#browse-scope").hidden = !project;
+ document.querySelector("#include-subprojects").checked = uiPreferences.includeSubprojects;
+ document.querySelector("#include-subprojects").disabled = ["project", "vision", "combine"].includes(selectionMode);
+ renderBrowseNavigation({
+ breadcrumb: document.querySelector("#browse-breadcrumb"),
+ path: collectionPath(organizerState, selectedCollectionId),
+ disabled: ["project", "vision", "combine"].includes(selectionMode), selectedId: selectedCollectionId,
+ rootLabel: t("案例库"), navigate: navigateBrowseProject
+ });
+ if (view !== "waterfall") {
+ galleryMasonry?.destroy();
+ galleryMasonry = null;
+ } else if (!galleryMasonry) {
+ galleryMasonry = createStableMasonry(elements.caseList, {
+ layoutDependencies: [document.querySelector(".topbar")], onLayout: () => scheduleLoadCheck()
+ });
+ }
+}
+
+function clearBrowseCardPositions(cards) {
+ elements.caseList.style.removeProperty("height");
+ for (const card of cards) {
+ for (const property of ["width", "left", "top"]) card.style.removeProperty(property);
+ }
+}
+
+function layoutBrowseCards() {
+ if (galleryMasonry) {
+ galleryMasonry.reset();
+ galleryMasonry.append([...elements.caseList.children]);
+ } else clearBrowseCardPositions(elements.caseList.children);
+}
+
function renderProjectFolderCards(childProjects) {
if (!elements.projectFolderList) return;
const cards = childProjects.map((collection) => {
- const button = el("button", "project-folder-card");
+ const button = el("button", "project-folder-card button-secondary");
button.type = "button";
+ button.disabled = ["project", "vision", "combine"].includes(selectionMode);
button.dataset.collectionId = collection.id;
- button.setAttribute("aria-label", `进入子项目 ${collection.name}`);
+ button.setAttribute("aria-label", `${t("打开项目")} ${collection.name}`);
+ button.title = collection.name;
const directCases = collection.entryIds.length;
const nestedProjects = collectionSubtreeIds(organizerState, collection.id).length - 1;
const copy = el("span", "project-folder-copy");
copy.append(
rawTextEl("span", "project-folder-name", collection.name),
- rawTextEl("span", "project-folder-meta", `${directCases} 个直接案例${nestedProjects ? ` · ${nestedProjects} 个下级项目` : ""}`)
+ rawTextEl("span", "project-folder-meta", `${translateUiMessage(`${directCases} 个案例`)}${nestedProjects ? ` · ${nestedProjects} ${t("子项目")}` : ""}`)
);
- button.append(createUiIcon("folder"), copy, createUiIcon("chevron-right"));
- button.lastElementChild.classList.add("project-folder-arrow");
- button.addEventListener("click", () => {
- unassignedViewActive = false;
- selectedCollectionId = collection.id;
- expandedProjectIds.add(collection.parentId);
- caseOrderManagementActive = false;
- renderGallery();
- window.scrollTo({ top: 0, behavior: uiPreferences.motion === "reduced" ? "auto" : "smooth" });
- });
+ button.append(createUiIcon("folder"), copy);
+ button.addEventListener("click", () => navigateBrowseProject(collection.id));
return button;
});
elements.projectFolderList.replaceChildren(...cards);
}
function projectManualOrderAvailable() {
- return Boolean(selectedCollectionId && !selectionMode &&
+ return Boolean(selectedCollectionId && (!uiPreferences.includeSubprojects || !projectChildren(selectedCollectionId).length) && !selectionMode &&
!selectedContentId && !selectedFacets.size && !elements.pendingFilter.checked && !elements.searchInput.value.trim());
}
@@ -1366,11 +1437,13 @@ function syncGallerySortControl() {
elements.projectManualSortOption.disabled = !available;
if (!available && caseSortMode === "project-manual") caseSortMode = "added-desc";
elements.gallerySort.value = caseSortMode;
- elements.manageCaseOrder.hidden = !available;
- elements.selectCases.hidden = caseOrderManagementActive;
+ elements.manageCaseOrder.hidden = false;
+ elements.manageCaseOrder.disabled = !available;
+ elements.selectCases.hidden = false;
+ elements.selectCases.disabled = caseOrderManagementActive;
const label = caseOrderManagementActive ? "完成案例排序" : "管理案例顺序";
elements.manageCaseOrder.setAttribute("aria-label", label);
- elements.manageCaseOrder.title = label;
+ elements.manageCaseOrder.title = t(available ? label : "仅当前项目、无筛选时可手动排序");
elements.manageCaseOrder.replaceChildren(createUiIcon(caseOrderManagementActive ? "circle-check-big" : "sliders-horizontal"));
}
@@ -1453,7 +1526,8 @@ function renderNextBatch(generation = galleryGeneration) {
const fragment = document.createDocumentFragment();
fragment.append(...cards);
elements.caseList.append(fragment);
- galleryMasonry.append([...elements.caseList.children].slice(renderedCount));
+ if (galleryMasonry) galleryMasonry.append([...elements.caseList.children].slice(renderedCount));
+ else clearBrowseCardPositions(cards);
observePendingCardMedia(cards);
scheduleVisibleMediaHydration();
renderedCount += next.length;
@@ -1504,6 +1578,12 @@ function createCaseCard(entry) {
let suppressSelectionClick = false;
bindCaseSelectionSweep(card, entry, (value) => { suppressSelectionClick = value; });
bindCaseOrderDrag(card, entry, (value) => { suppressSelectionClick = value; });
+ card.draggable = !selectionMode && !caseOrderManagementActive;
+ card.addEventListener("dragstart", (event) => {
+ if (selectionMode || caseOrderManagementActive || !event.dataTransfer) return;
+ event.dataTransfer.setData("application/x-promptdirector-case", entry.id);
+ event.dataTransfer.effectAllowed = "move";
+ });
const open = () => {
if (suppressSelectionClick) {
suppressSelectionClick = false;
@@ -1549,6 +1629,41 @@ function createCaseCard(entry) {
image.loading = "lazy";
const cached = thumbnailUrls.get(cover.id);
if (cached) image.src = cached;
+ let exportUrl = "";
+ let preparingOriginal;
+ const prepareOriginal = () => {
+ if (exportUrl) { image.src = exportUrl; return; }
+ if (preparingOriginal) return;
+ preparingOriginal = originalScreenshotUrl(cover.id).then(url => {
+ exportUrl = url;
+ if (url && image.isConnected) image.src = url;
+ }).catch(error => console.debug("PromptDirector original image drag", error))
+ .finally(() => { preparingOriginal = null; });
+ };
+ // Resolve only the approached card; never load every original in the library.
+ card.addEventListener("pointerenter", prepareOriginal);
+ card.addEventListener("focusin", prepareOriginal);
+ image.addEventListener("pointerdown", prepareOriginal);
+ card.addEventListener("dragstart", event => {
+ if (selectionMode || caseOrderManagementActive || !event.dataTransfer) return;
+ if (!exportUrl) {
+ event.preventDefault();
+ prepareOriginal();
+ showFeedback("原图正在读取,请稍后再拖动", true);
+ return;
+ }
+ image.src = exportUrl;
+ event.dataTransfer.clearData();
+ event.dataTransfer.setData("application/x-promptdirector-case", entry.id);
+ event.dataTransfer.effectAllowed = "copyMove";
+ event.dataTransfer.setData("DownloadURL", `${cover.mimeType || "application/octet-stream"}:${copyFilename(cover, entry.title, 0)}:${exportUrl}`);
+ event.dataTransfer.setData("text/uri-list", exportUrl);
+ event.dataTransfer.setData("text/plain", exportUrl);
+ const exportedImage = document.createElement("img");
+ exportedImage.src = exportUrl;
+ exportedImage.alt = image.alt;
+ event.dataTransfer.setData("text/html", exportedImage.outerHTML);
+ });
wrap.append(image);
card.append(wrap);
} else if (mainVisual?.kind === "video") {
@@ -1593,6 +1708,9 @@ function createCaseCard(entry) {
event.preventDefault(); event.stopPropagation();
showCaseQuickMenu(entry, card, { x: event.clientX, y: event.clientY });
});
+ appendCaseRowDetails(card, entry, {
+ typeLabel: entryContentTypeIds(entry).map(contentLabel).join(" · "), locale: currentLocale()
+ });
card.append(textEl("span", "share-check", "✓"));
return card;
}
@@ -1940,35 +2058,32 @@ function renderProjectFilters() {
?.closest(".project-row")?.dataset.collectionId;
const fragment = document.createDocumentFragment();
const subtreeEntryIdsByProject = collectionSubtreeEntryIdsById(organizerState);
- const pathLabelsByProject = collectionPathLabelsById(organizerState);
const childrenByParent = indexProjectChildren();
- const query = elements.projectSearch.value.trim();
const projectOrderingUnavailable = Boolean(selectionMode);
if (selectedCollectionId !== lastProjectSelection) {
lastProjectSelection = selectedCollectionId;
for (const ancestor of collectionPath(organizerState, selectedCollectionId).slice(0, -1)) expandedProjectIds.add(ancestor.id);
}
elements.collapseProjects.disabled = !expandedProjectIds.size;
- const visibleCollections = projectTreeRows(childrenByParent, expandedProjectIds, query, pathLabelsByProject);
+ const visibleCollections = projectTreeRows(childrenByParent, expandedProjectIds);
for (const [projectIndex, { collection, depth }] of visibleCollections.entries()) {
const children = childrenByParent.get(collection.id) ?? [];
const siblings = childrenByParent.get(collection.parentId) ?? [];
const row = el("div", "project-row");
row.dataset.collectionId = collection.id;
- row.style.setProperty("--project-depth", String(query ? 0 : depth));
+ bindCaseDrop(row, { collectionId: collection.id });
+ row.style.setProperty("--project-depth", String(depth));
row.setAttribute("role", "treeitem");
- row.setAttribute("aria-level", String(query ? 1 : depth + 1));
- row.setAttribute("aria-setsize", String(query ? visibleCollections.length : siblings.length));
- row.setAttribute("aria-posinset", String(query ? projectIndex + 1 : siblings.findIndex((item) => item.id === collection.id) + 1));
- if (children.length && !query) row.setAttribute("aria-expanded", String(expandedProjectIds.has(collection.id)));
+ row.setAttribute("aria-level", String(depth + 1));
+ row.setAttribute("aria-setsize", String(siblings.length));
+ row.setAttribute("aria-posinset", String(siblings.findIndex((item) => item.id === collection.id) + 1));
+ if (children.length) row.setAttribute("aria-expanded", String(expandedProjectIds.has(collection.id)));
row.classList.toggle("project-draggable", !projectOrderingUnavailable);
- row.classList.toggle("project-search-result", Boolean(query));
row.tabIndex = -1;
- row.setAttribute("aria-label", query ? pathLabelsByProject.get(collection.id) : collection.name);
+ row.setAttribute("aria-label", collection.name);
const disclosure = el("button", "project-disclosure");
disclosure.type = "button";
disclosure.tabIndex = -1;
- disclosure.hidden = Boolean(query);
disclosure.setAttribute("aria-label", expandedProjectIds.has(collection.id) ? `折叠 ${collection.name}` : `展开 ${collection.name}`);
disclosure.classList.toggle("is-placeholder", !children.length);
if (children.length) disclosure.append(createUiIcon(expandedProjectIds.has(collection.id) ? "chevron-down" : "chevron-right"));
@@ -1991,18 +2106,28 @@ function renderProjectFilters() {
caseOrderManagementActive = false;
unassignedViewActive = false;
selectedCollectionId = selectedCollectionId === collection.id ? "" : collection.id;
- if (query) elements.projectSearch.value = "";
renderGallery();
});
if (collection.visibility === COLLECTION_VISIBILITY.projectOnly) {
meta.append(textEl("span", "project-visibility", "仅项目"));
}
const name = rawTextEl("span", "project-filter-name", collection.name);
- if (query) {
- const label = el("span", "project-search-label");
- label.append(name, rawTextEl("small", "project-search-path", pathLabelsByProject.get(collection.id)));
- filter.append(label, meta);
- } else filter.append(name, meta);
+ filter.append(name, meta);
+ const menu = createProjectMenu(collection);
+ bindProjectTreeNavigation(row, collection);
+ row.append(disclosure, filter, menu);
+ fragment.append(row);
+ }
+ elements.collectionFilters.replaceChildren(fragment);
+ if (openProjectId) {
+ const menu = elements.collectionFilters.querySelector(`[data-collection-id="${CSS.escape(openProjectId)}"] .project-menu`);
+ if (menu && !menu.hidden) menu.open = true;
+ }
+ projectTreeController().sync();
+}
+
+function createProjectMenu(collection) {
+ const projectOrderingUnavailable = Boolean(selectionMode);
const menu = el("details", "project-menu");
menu.hidden = ["project", "vision", "combine"].includes(selectionMode);
const summary = el("summary", "");
@@ -2037,17 +2162,7 @@ function renderProjectFilters() {
removeWithEntries.addEventListener("click", () => deleteProjectCollectionWithEntries(collection, removeWithEntries));
actions.append(manage, move, analyze, share, visibility, rename, remove, removeWithEntries);
menu.append(summary, actions);
- bindProjectTreeNavigation(row, collection);
- row.append(disclosure, filter, menu);
- fragment.append(row);
- }
- if (!visibleCollections.length && query) fragment.append(textEl("p", "project-search-empty", "没有匹配的项目"));
- elements.collectionFilters.replaceChildren(fragment);
- if (openProjectId) {
- const menu = elements.collectionFilters.querySelector(`[data-collection-id="${CSS.escape(openProjectId)}"] .project-menu`);
- if (menu && !menu.hidden) menu.open = true;
- }
- projectTreeController().sync();
+ return menu;
}
function projectChildren(parentId = null) {
@@ -2079,6 +2194,44 @@ function projectTreeController() {
});
}
+function bindCaseDrop(row, { collectionId = null, toTrash = false } = {}) {
+ const isCaseDrag = event => event.dataTransfer?.types.includes("application/x-promptdirector-case");
+ row.addEventListener("dragover", event => {
+ if (!isCaseDrag(event)) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ row.classList.add("case-drop-target");
+ });
+ row.addEventListener("dragleave", event => {
+ if (!row.contains(event.relatedTarget)) row.classList.remove("case-drop-target");
+ });
+ row.addEventListener("drop", async event => {
+ row.classList.remove("case-drop-target");
+ if (!isCaseDrag(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const id = event.dataTransfer.getData("application/x-promptdirector-case");
+ if (!logicalCases.some(entry => entry.id === id)) return;
+ try {
+ const memberIds = expandLogicalCaseIds([id], compoundCases);
+ const source = organizerState.collections.find(collection => collection.entryIds.some(entryId => memberIds.includes(entryId)));
+ // 未归项目是移出当前归属,不创建项目,也不删除案例。
+ if (!toTrash && !collectionId && !source) return;
+ const response = await chrome.runtime.sendMessage(buildLibraryBatchPayload([id], compoundCases, toTrash ? {
+ type: LIBRARY_BATCH_ACTIONS.moveToTrash
+ } : {
+ type: LIBRARY_BATCH_ACTIONS.setProject,
+ mode: collectionId ? "move" : "remove",
+ collectionId: collectionId || source.id
+ }));
+ if (!response?.ok) throw new Error(response?.message || "移动失败");
+ await refreshLibrary();
+ showFeedback(response.message);
+ } catch (error) { showFeedback(error.message, true); }
+ });
+ row.addEventListener("dragend", () => row.classList.remove("case-drop-target"));
+}
+
function bindProjectTreeNavigation(row, collection) {
row.addEventListener("keydown", (event) => {
if (event.target.closest(".project-menu")) return;
@@ -2090,14 +2243,14 @@ function bindProjectTreeNavigation(row, collection) {
: event.key === "End" ? rows.at(-1)
: rows[index + (event.key === "ArrowDown" ? 1 : -1)];
target?.querySelector(".project-filter")?.focus();
- } else if (event.key === "ArrowRight" && !elements.projectSearch.value.trim()) {
+ } else if (event.key === "ArrowRight") {
event.preventDefault();
if (projectChildren(collection.id).length && !expandedProjectIds.has(collection.id)) {
expandedProjectIds.add(collection.id);
renderProjectFilters();
queueMicrotask(() => focusProjectRow(collection.id));
} else if (projectChildren(collection.id).length) focusProjectRow(projectChildren(collection.id)[0].id);
- } else if (event.key === "ArrowLeft" && !elements.projectSearch.value.trim()) {
+ } else if (event.key === "ArrowLeft") {
event.preventDefault();
if (expandedProjectIds.has(collection.id)) {
expandedProjectIds.delete(collection.id);
@@ -2464,11 +2617,11 @@ function updateSelectionBar() {
elements.selectionProjectImpact.textContent = sourceKind === "project"
? t("来源:{project}", { project: sourceCollection.name })
: sourceKind === "unassigned" ? t("来源:未归项目") : t("案例库");
- elements.selectionMoveProject.hidden = sourceKind === "library";
+ elements.selectionMoveProject.hidden = false;
elements.selectionMoveProject.disabled = moveUnavailable;
elements.selectionMoveProject.title = moveUnavailable && targetCollection?.id === sourceCollection?.id ? t("请选择其他项目") : "";
- elements.selectionAddProject.hidden = sourceKind === "unassigned";
- elements.selectionAddProject.disabled = projectActionUnavailable;
+ elements.selectionCopyProject.hidden = false;
+ elements.selectionCopyProject.disabled = projectActionUnavailable;
elements.selectionRemoveProject.hidden = sourceKind !== "project";
elements.selectionRemoveProject.disabled = !selectedCaseIds.size || removableCount === 0;
elements.selectionRemoveProject.title = !selectedCaseIds.size
@@ -2486,7 +2639,7 @@ function updateSelectionBar() {
elements.selectionCombine.disabled = selectedCaseIds.size < 2;
elements.selectionCombine.title = selectedCaseIds.size < 2 ? t("至少选择 2 个案例") : "";
elements.selectionNewProject.disabled = !selectedCaseIds.size;
- elements.selectionNewProject.textContent = t(sourceKind === "library" ? "新建项目并加入" : "新建项目并移动");
+ elements.selectionNewProject.textContent = t("新建项目并移动");
const selectionHasAnalyzableImage = [...selectedCaseIds]
.some((id) => isVisionSelectableEntry(logicalCases.find((entry) => entry.id === id)));
const selectionHasAnalyzableVideo = [...selectedCaseIds].some((id) => {
@@ -2544,8 +2697,8 @@ function completeSelection() {
return openShareDialog({ entryIds: [...selectedCaseIds], title: t("分享案例") });
}
-async function addSelectionToProject() {
- return updateSelectionProjectMembership("add", elements.selectionAddProject);
+async function copySelectionToProject() {
+ return updateSelectionProjectMembership("copy", elements.selectionCopyProject);
}
async function moveSelectionToProject() {
@@ -2572,6 +2725,7 @@ async function updateSelectionProjectMembership(mode, button, collectionId = ele
if (!response?.ok) throw new Error(response?.message || (mode === "remove" ? "移出项目失败" : "加入项目失败"));
organizerState = response.organizerState ?? organizerState;
rebuildLocalSimilarityIndex();
+ if (mode === "copy") await refreshLibrary();
showFeedback(response.message || (mode === "remove" ? `已移出项目“${collection.name}”` : `已加入项目“${collection.name}”`));
exitSelectionMode();
} catch (error) {
@@ -2626,11 +2780,10 @@ async function moveSelectionToTrash() {
async function createProjectFromSelection() {
if (!selectedCaseIds.size) return;
- const moving = Boolean(selectedCollectionId || unassignedViewActive);
const name = await promptAppText({
title: t("以所选案例新建项目"),
label: t("项目名称"),
- confirmLabel: moving ? t("新建并移动") : t("新建并加入"),
+ confirmLabel: t("新建并移动"),
selectFirst: true
});
if (!name?.trim()) return;
@@ -2640,13 +2793,13 @@ async function createProjectFromSelection() {
name: name.trim(),
parentId: null,
entryIds,
- mode: moving ? "move" : "add",
+ mode: "move",
sourceCollectionId: selectedCollectionId || null
}, false);
if (!response?.ok || !response.created?.id) return;
organizerState = response.organizerState ?? organizerState;
rebuildLocalSimilarityIndex();
- showFeedback(`已新建项目“${response.created.name}”并${moving ? "移动" : "加入"}所选案例`);
+ showFeedback(`已新建项目“${response.created.name}”并移动所选案例`);
exitSelectionMode();
}
@@ -3083,6 +3236,12 @@ async function openVisionBatchConfirmation() {
}
async function previewSelectedVisionBatch() {
+ visionBatchSelection = null;
+ const selectedEntries = new Set(expandLogicalCaseIds([...selectedCaseIds], compoundCases));
+ if (visionBatchJob?.items?.length && ["running", "paused"].includes(visionBatchJob.status)
+ && visionBatchJob.items.every((item) => selectedEntries.has(item.entryId))) {
+ visionBatchSelection = { jobId: visionBatchJob.id, caseIds: [...selectedCaseIds] };
+ }
if (visionBatchJob && ["running", "paused"].includes(visionBatchJob.status)) {
const requestedKind = activeMediaBatchKind === "video" ? "video" : "vision";
if (visionBatchJob.kind !== requestedKind) {
@@ -3183,7 +3342,7 @@ function renderVisionBatchDialog(preview = null) {
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.hidden = Boolean(job);
elements.visionBatchStart.disabled = !requestCount;
elements.visionBatchPause.hidden = !activeJob || activeJob.status !== "running";
elements.visionBatchResume.hidden = !activeJob || activeJob.status !== "paused";
@@ -3233,6 +3392,7 @@ async function startSelectedVisionBatch() {
}
if (!response?.ok) throw new Error(response?.message || (activeMediaBatchKind === "video" ? "无法创建批量视频分析" : "无法创建批量画面分析"));
visionBatchJob = response.visionBatchJob;
+ visionBatchSelection = { jobId: visionBatchJob.id, caseIds: [...selectedCaseIds] };
renderVisionBatchDialog();
} catch (error) {
showVisionBatchFeedback(error.message, true);
@@ -3483,7 +3643,22 @@ function folderBackupRescueDescription(reportValue = {}) {
});
const remaining = Math.max(0, diagnostics.length - visible.length);
const details = [...visible, ...(remaining ? [`另有 ${remaining} 项问题`] : [])].join(";");
- return `预检发现 ${diagnostics.length} 项无法完整写入的资源。继续将剔除这些项目并生成明确标识的救援备份,不会写完整备份标记。${details ? ` ${details}` : ""}`;
+ return `预检发现 ${diagnostics.length} 项无法完整写入的资源。继续将备份可恢复的资料,并保留未能自动恢复的可读原件与原始清单。缺失或损坏项会列入报告,不会标记为完整备份。${details ? ` ${details}` : ""}`;
+}
+
+// Ten updates per second keeps long streaming checks visible without repainting
+// for every chunk/file. Yield even in hidden tabs, where rAF may be suspended.
+function dataSafetyProgress(label) {
+ let lastPaint = -Infinity;
+ return async ({ completed = 0, total, completedBytes, totalBytes } = {}) => {
+ const now = performance.now();
+ if (now - lastPaint < 100 && completed !== total) return;
+ lastPaint = now;
+ const count = total === undefined ? `${completed}` : `${completed} / ${total}`;
+ const bytes = totalBytes === undefined ? "" : ` · ${formatBytes(completedBytes)} / ${formatBytes(totalBytes)}`;
+ showDataSafetyFeedback(`${t(label)} · ${count}${bytes}`);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ };
}
async function createCompleteFolderBackup() {
@@ -3498,6 +3673,8 @@ async function createCompleteFolderBackup() {
stage = "preflight";
const response = await chrome.runtime.sendMessage({ type: "GET_FOLDER_BACKUP_STATE" });
if (!response?.ok) throw new Error(response?.message || "无法读取资料库");
+ const digest = createBlobDigestCache();
+ const mediaProgress = dataSafetyProgress("正在检查媒体");
const plannedFiles = new Map();
const preflightDiagnostics = [];
const resolvedEntries = [];
@@ -3515,7 +3692,9 @@ async function createCompleteFolderBackup() {
plannedFiles.set(assetPath, blob);
mediaCount += 1;
byteSize += blob.size;
- return portableManagedBackupAsset(asset, blob, assetPath, await sha256Blob(blob), portableFormat);
+ return portableManagedBackupAsset(asset, blob, assetPath, await digest(blob, {
+ onProgress: bytes => mediaProgress({ completed: mediaCount, ...bytes })
+ }), portableFormat);
};
const materializeEntry = async (entryValue, scopeId = "") => {
let entry = normalizeEntryMedia(entryValue);
@@ -3675,7 +3854,10 @@ async function createCompleteFolderBackup() {
const initialMediaSizes = [...backupMediaPaths(plannedLibrary)].map((path) => plannedFiles.get(path)?.size ?? 0);
const initialTotalBytes = initialMediaSizes.reduce((sum, size) => sum + size, 0);
const initialLargestMedia = initialMediaSizes.reduce((largest, size) => Math.max(largest, size), 1);
+ showDataSafetyFeedback(t("正在核对备份资料…"));
const inspectPlannedBackup = (sourceType, sourceReport) => inspectLibraryTransfer({
+ digest,
+ onImageProgress: dataSafetyProgress("正在检查图片"),
sourceType,
library: plannedLibrary,
files: plannedFiles,
@@ -3738,8 +3920,12 @@ async function createCompleteFolderBackup() {
const plannedTotalBytes = byteSize;
const trashCaseCount = (exportState.trashState?.items ?? []).filter((item) => item.kind === "entry").length;
const trashProjectCount = (exportState.trashState?.items ?? []).filter((item) => item.kind === "collection").length;
+ showDataSafetyFeedback(t("正在准备备份清单…"));
const writePlan = await buildFolderBackupWritePlan({
+ digest,
+ onProgress: dataSafetyProgress("正在准备备份清单"),
files: finalFiles,
+ sourceFiles: plannedFiles,
report: preflight.report,
metadata: {
createdAt: new Date().toISOString(),
@@ -3771,13 +3957,20 @@ async function createCompleteFolderBackup() {
showDataSafetyFeedback(`正在写入第 ${writtenCount} / ${writePlan.files.size} 个文件`);
await writeDirectoryFile(directory, path, blob);
}
- const writtenFiles = await readDirectoryFiles(directory);
- if (writePlan.mode === "rescue") await verifyFolderRescueCompletion(writePlan.marker, writtenFiles);
- else await verifyFolderBackupCompletion(writePlan.marker, writtenFiles);
+ showDataSafetyFeedback(t("正在读取已写入的文件…"));
+ const writtenFiles = await readDirectoryFiles(directory, "", dataSafetyProgress("正在读取已写入的文件"));
+ // New snapshot and cache: the source digest is never proof of disk writes.
+ const readbackDigest = createBlobDigestCache();
+ const readbackOptions = { digest: readbackDigest, onProgress: dataSafetyProgress("正在校验已写入的文件") };
+ if (writePlan.mode === "rescue") await verifyFolderRescueCompletion(writePlan.marker, writtenFiles, readbackOptions);
+ else await verifyFolderBackupCompletion(writePlan.marker, writtenFiles, readbackOptions);
const writtenLibraryFile = writtenFiles.get("library.json");
if (!(writtenLibraryFile instanceof Blob)) throw new Error("无法回读刚写入的 library.json");
const writtenLibrary = JSON.parse(await writtenLibraryFile.text());
+ showDataSafetyFeedback(t("正在核对备份资料…"));
const writtenVerification = await inspectLibraryTransfer({
+ digest: readbackDigest,
+ onImageProgress: dataSafetyProgress("正在检查已写入的图片"),
sourceType: writePlan.mode === "rescue"
? LIBRARY_TRANSFER_SOURCES.RESCUE_BACKUP
: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,
@@ -3794,6 +3987,7 @@ async function createCompleteFolderBackup() {
sourceReport: writePlan.report
});
assertFolderBackupRoundtrip(exportState.entries, exportState.trashState, writtenVerification.state);
+ showDataSafetyFeedback(t("正在完成备份…"));
await writeDirectoryFile(directory, writePlan.markerPath, new Blob([JSON.stringify(writePlan.marker, null, 2)], { type: "application/json" }));
const completionLabel = writePlan.mode === "rescue" ? "救援备份已完成" : "完整备份已完成";
showDataSafetyFeedback(`${completionLabel} · ${exportState.entries.length} 个案例 · ${mediaCount} 项媒体 · ${formatBytes(byteSize)}`);
@@ -3805,6 +3999,8 @@ async function createCompleteFolderBackup() {
? "目录选择器未在有效用户操作中打开或未获得权限,请重新点击备份按钮并允许访问"
: error.message;
showDataSafetyFeedback(message, true);
+ } else if (stage === "preflight") {
+ showDataSafetyFeedback(`${error.message};备份检查未完成,尚未创建资料夹或写入文件,资料库未改动`, true);
} else {
showDataSafetyFeedback(`${error.message};未写入完成标记的资料夹不会被认定为完整备份,只能尝试救援恢复`, true);
}
@@ -3822,8 +4018,12 @@ async function restoreCompleteFolderBackup() {
setDataSafetyBusy(true);
try {
const directory = await window.showDirectoryPicker({ mode: "read" });
- const files = await readDirectoryFiles(directory);
- const envelope = await inspectFolderBackupEnvelope(files);
+ showDataSafetyFeedback(t("正在读取备份文件…"));
+ const files = await readDirectoryFiles(directory, "", dataSafetyProgress("正在读取备份文件"));
+ const digest = createBlobDigestCache();
+ const envelope = await inspectFolderBackupEnvelope(files, {
+ digest, onProgress: dataSafetyProgress("正在校验备份文件")
+ });
const completion = envelope.marker;
const libraryFile = envelope.libraryFile;
let library;
@@ -3852,6 +4052,8 @@ async function restoreCompleteFolderBackup() {
library,
files,
limits: restoreLimits,
+ digest,
+ onImageProgress: dataSafetyProgress("正在检查图片"),
validateImage: validateImportedImage,
sourceReport: envelope.report
});
@@ -4563,15 +4765,13 @@ async function writeDirectoryFile(root, path, data) {
}
}
-async function readDirectoryFiles(directory, prefix = "") {
- const files = new Map();
+async function readDirectoryFiles(directory, prefix = "", onProgress, files = new Map()) {
for await (const [name, handle] of directory.entries()) {
const path = prefix ? `${prefix}/${name}` : name;
- if (handle.kind === "file") files.set(path, await handle.getFile());
- else {
- const nested = await readDirectoryFiles(handle, path);
- for (const item of nested) files.set(...item);
- }
+ if (handle.kind === "file") {
+ files.set(path, await handle.getFile());
+ await onProgress?.({ completed: files.size });
+ } else await readDirectoryFiles(handle, path, onProgress, files);
}
return files;
}
@@ -4842,6 +5042,8 @@ function contentRoleIconName(role) {
if ([CONTENT_ROLES.promptVideo, CONTENT_ROLES.videoCase].includes(role)) return "video";
if ([CONTENT_ROLES.promptImage, CONTENT_ROLES.imageCase].includes(role)) return "image";
if (role === CONTENT_ROLES.tutorial) return "library";
+ if (role === CONTENT_ROLES.audio) return "audio-lines";
+ if (role === CONTENT_ROLES.sourceFile) return "file-box";
return "file-text";
}
@@ -4943,6 +5145,10 @@ function syncStructuredFilterControls() {
}
function renderActiveFilters() {
+ libraryLayout.updateCounts({
+ types: Number(Boolean(selectedContentId)) + Number(elements.pendingFilter.checked),
+ tags: [...selectedFacets.values()].reduce((sum, ids) => sum + ids.size, 0)
+ });
activeFilterCount = Number(Boolean(selectedContentId)) +
[...selectedFacets.values()].reduce((count, ids) => count + ids.size, 0) +
Number(elements.pendingFilter.checked) +
@@ -5657,7 +5863,7 @@ async function createArticleDocumentReader(entryValue) {
async function appendBlocks(reader, blocks) {
for (const block of blocks) {
if (block.kind === "table" && block.rows) {
- const wrap = el("div", "article-table-scroll");
+ const wrap = el("div", "article-table-scroll ui-scrollbar");
const table = el("table", "article-structured-table");
const body = document.createElement("tbody");
for (const row of block.rows) {
@@ -5972,7 +6178,7 @@ async function createDetailMediaGallery(entryValue, { immersive = false } = {})
mediaActions.push({ label: "移除媒体", danger: true, run: removeMedia });
}
item.addEventListener("contextmenu", event => {
- if (event.target.closest("input, textarea, [contenteditable], .document-text-reader")) return;
+ if (event.target.closest("img, input, textarea, [contenteditable], .document-text-reader")) return;
event.preventDefault(); event.stopPropagation();
showQuickMenu(download, mediaActions, { x: event.clientX, y: event.clientY }, message => showFeedback(message, true));
});
@@ -6349,6 +6555,15 @@ async function createMediaViewer(asset, imageUrl, entry) {
image.classList.toggle("has-alpha-channel", alphaCapableImage(asset));
image.alt = `${entry.title} 图片`;
image.src = imageUrl;
+ image.draggable = true;
+ image.addEventListener("dragstart", event => {
+ if (!event.dataTransfer || !imageUrl) return;
+ // Preserve native image drag data and add Chrome's file-export payload.
+ event.dataTransfer.effectAllowed = "copy";
+ event.dataTransfer.setData("DownloadURL", `${asset.mimeType || "application/octet-stream"}:${copyFilename(asset, entry.title, 0)}:${imageUrl}`);
+ event.dataTransfer.setData("text/uri-list", imageUrl);
+ event.stopPropagation();
+ });
image.tabIndex = 0;
image.role = "button";
image.addEventListener("click", () => openImageLightbox(image, entry));
@@ -7536,7 +7751,8 @@ async function prepareLocalImport(fileItems, { source = "files" } = {}) {
await discardPendingLocalImport();
const browsingScrollY = window.scrollY;
const rootName = source === "folder" ? commonImportRoot(fileItems) : "";
- const draft = { source, rootName, browsingScrollY, customLabels: [], stagedAssets: [], skipped: [] };
+ const draft = { source, rootName, browsingScrollY, customLabels: [], stagedAssets: [], skipped: [],
+ duplicateIndex: createExactMediaDuplicateIndex(entries, { readBlob: getMediaBlob }) };
pendingLocalImport = draft;
elements.importDialogTitle.textContent = t("确认导入");
elements.importSource.hidden = true;
@@ -7586,16 +7802,7 @@ async function prepareImportFile({ file, handle = null, relativePath, forceImpor
type: prepared.blob.type,
lastModified: file.lastModified
});
- const duplicate = await findExactMediaDuplicate(duplicateProbe, entries, {
- readBlob: getMediaBlob,
- candidateAssets: draft.stagedAssets.map((asset) => ({
- id: asset.assetId,
- byteSize: asset.byteSize,
- mimeType: asset.mimeType,
- sourceTitle: asset.name,
- contentHash: asset.contentHash
- }))
- });
+ const duplicate = await draft.duplicateIndex.find(duplicateProbe, { contentHash: prepared.asset.contentHash });
await saveMediaBlob(assetId, prepared.blob);
if (prepared.poster) await saveMediaBlob(prepared.poster.asset.id, prepared.poster.blob);
if (pendingLocalImport !== draft) {
@@ -7627,6 +7834,8 @@ async function prepareImportFile({ file, handle = null, relativePath, forceImpor
...(prepared.warnings?.length ? { warnings: prepared.warnings } : {}),
...(prepared.poster ? { posterAssetId: prepared.poster.asset.id, posterAsset: prepared.poster.asset } : {})
});
+ draft.duplicateIndex.add({ id: assetId, byteSize: prepared.blob.size,
+ mimeType: prepared.asset.mimeType, sourceTitle: file.name, contentHash: duplicate.contentHash });
} catch (error) {
await deleteMediaBlob(assetId).catch(() => undefined);
if (prepared?.poster?.asset?.id) await deleteMediaBlob(prepared.poster.asset.id).catch(() => undefined);
@@ -8131,7 +8340,8 @@ async function addVideoReference(entryId = "") {
fields: [{
id: "url",
label: "视频网页地址",
- type: "url",
+ type: "text",
+ inputMode: "url",
placeholder: "https://…",
autocomplete: "url",
required: true
@@ -10718,7 +10928,8 @@ async function deleteCaseIncrementally(button, entryId) {
selectedCaseIds.delete(entryId);
for (const asset of normalizeEntryMedia(deletingEntry ?? {}).mediaAssets) clearMediaAssetCache(asset.id);
if (visibleCard) {
- galleryMasonry.remove(visibleCard);
+ if (galleryMasonry) galleryMasonry.remove(visibleCard);
+ else visibleCard.remove();
indexedGalleryEntries = indexedGalleryEntries.filter((item) => item.id !== entryId);
visibleEntries = visibleEntries.filter((item) => item.id !== entryId);
renderedCount = elements.caseList.children.length;
@@ -11681,31 +11892,24 @@ function revealCaseProject(project) {
workspace.classList.remove("filters-collapsed");
renderFilterToggleState();
if (project) {
- elements.projectSearch.value = "";
for (const ancestor of collectionPath(organizerState, project.id).slice(0, -1)) expandedProjectIds.add(ancestor.id);
renderProjectFilters();
}
- const sidebar = elements.filterSidebar;
+ libraryLayout.openModule("projects");
const target = project
? [...elements.collectionFilters.querySelectorAll(".project-row")].find(row => row.dataset.collectionId === project.id)
: elements.workspaceUnassigned;
if (!target) return;
target.classList.add("project-located");
- const section = project ? document.getElementById("project-section") : sidebar;
- const tools = project ? section.querySelector(".project-tree-tools") : null;
- const toolsHeight = tools?.getBoundingClientRect().height || 0;
- const sidebarTop = sidebar.getBoundingClientRect().top;
- const targetTop = target.getBoundingClientRect().top - sidebarTop + sidebar.scrollTop;
- const sectionBottom = section.getBoundingClientRect().bottom - sidebarTop + sidebar.scrollTop;
- const space = document.createElement("div");
- space.className = "project-location-space";
- space.setAttribute("aria-hidden", "true");
- space.style.height = `${Math.max(0, targetTop + sidebar.clientHeight - toolsHeight - sectionBottom)}px`;
- section.append(space);
- const stickyTop = tools ? parseFloat(getComputedStyle(tools).top) || 0 : 0;
- sidebar.scrollTop = Math.max(0, targetTop - toolsHeight - stickyTop);
- // Correct for the sticky header's actual position without scrolling the page.
- if (tools) sidebar.scrollTop += target.getBoundingClientRect().top - tools.getBoundingClientRect().bottom;
+ if (project) {
+ const scroller = document.getElementById("sidebar-projects-body");
+ const space = document.createElement("div");
+ space.className = "project-location-space";
+ space.setAttribute("aria-hidden", "true");
+ space.style.height = `${Math.max(0, scroller.clientHeight - target.offsetHeight)}px`;
+ scroller.append(space);
+ scroller.scrollTop += target.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
+ }
target.focus({ preventScroll: true });
}
diff --git a/extension/local-media.js b/extension/local-media.js
index ab5be3c..9c45990 100644
--- a/extension/local-media.js
+++ b/extension/local-media.js
@@ -234,33 +234,58 @@ export async function extractLocalDocumentText(blob, options = {}) {
}
}
-export async function findExactMediaDuplicate(file, entries = [], options = {}) {
- const format = detectLocalMediaFile(file);
- const name = clean(file.name);
- const storedAssets = (Array.isArray(entries) ? entries : []).flatMap((entry) =>
- Array.isArray(entry?.mediaAssets) ? entry.mediaAssets : []
- );
- const candidates = [
- ...storedAssets,
- ...(Array.isArray(options.candidateAssets) ? options.candidateAssets : [])
- ].filter((asset) =>
- Number(asset?.byteSize) === file.size &&
- clean(asset?.mimeType).toLocaleLowerCase("en-US") === format.mimeType &&
- clean(asset?.sourceTitle ?? asset?.name) === name
- );
- const contentHash = await sha256Blob(file);
- for (const asset of candidates) {
- let candidateHash = clean(asset.contentHash);
- if (!candidateHash) {
- const blob = await options.readBlob?.(asset.id);
- if (!(blob instanceof Blob)) continue;
- candidateHash = await sha256Blob(blob);
- }
- if (candidateHash === contentHash) {
- return { contentHash, duplicateAssetId: clean(asset.id) };
+export function createExactMediaDuplicateIndex(entries = [], options = {}) {
+ const buckets = new Map();
+ const keyFor = (size, mimeType, name) => JSON.stringify([Number(size), clean(mimeType).toLocaleLowerCase("en-US"), clean(name)]);
+ const add = (asset) => {
+ const key = keyFor(asset.byteSize, asset.mimeType, asset.sourceTitle ?? asset.name);
+ let bucket = buckets.get(key);
+ if (!bucket) {
+ bucket = { nextOrder: 0, byHash: new Map(), pending: [], cursor: 0 };
+ buckets.set(key, bucket);
}
+ const candidate = { id: clean(asset.id), order: bucket.nextOrder++, hash: clean(asset.contentHash) };
+ if (candidate.hash) {
+ if (!bucket.byHash.has(candidate.hash)) bucket.byHash.set(candidate.hash, candidate);
+ } else bucket.pending.push(candidate);
+ };
+ for (const entry of Array.isArray(entries) ? entries : []) {
+ for (const asset of Array.isArray(entry?.mediaAssets) ? entry.mediaAssets : []) add(asset);
}
- return { contentHash, duplicateAssetId: "" };
+ for (const asset of options.candidateAssets ?? []) add(asset);
+ return {
+ add,
+ async find(file, { contentHash: preparedHash, signal } = {}) {
+ const format = detectLocalMediaFile(file);
+ signal?.throwIfAborted();
+ // Only the caller that just prepared this exact immutable Blob may reuse
+ // its hash. Background admission independently hashes its stored bytes.
+ const contentHash = preparedHash || await sha256Blob(file);
+ signal?.throwIfAborted();
+ const bucket = buckets.get(keyFor(file.size, format.mimeType, file.name));
+ if (!bucket) return { contentHash, duplicateAssetId: "" };
+ let match = bucket.byHash.get(contentHash);
+ while (bucket.cursor < bucket.pending.length) {
+ const candidate = bucket.pending[bucket.cursor];
+ if (match && candidate.order > match.order) break;
+ signal?.throwIfAborted();
+ const blob = await options.readBlob?.(candidate.id);
+ if (blob instanceof Blob) {
+ const hash = await sha256Blob(blob);
+ signal?.throwIfAborted();
+ const known = bucket.byHash.get(hash);
+ if (!known || candidate.order < known.order) bucket.byHash.set(hash, candidate);
+ }
+ bucket.cursor += 1;
+ match = bucket.byHash.get(contentHash);
+ }
+ return { contentHash, duplicateAssetId: match?.id || "" };
+ }
+ };
+}
+
+export async function findExactMediaDuplicate(file, entries = [], options = {}) {
+ return createExactMediaDuplicateIndex(entries, options).find(file);
}
export async function chunkedBlobFingerprint(blob, options = {}) {
diff --git a/extension/manifest.json b/extension/manifest.json
index a16dbca..febb52d 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.23.0",
+ "version": "1.24.0",
"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/extension/manual-sync.js b/extension/manual-sync.js
index ce1d6de..2d0dc84 100644
--- a/extension/manual-sync.js
+++ b/extension/manual-sync.js
@@ -322,6 +322,7 @@ async function runManualSync({ vault, settings: settingsValue, dependencies: dep
state: {
...finalState,
libraryReplacementRecoveryPoint: current.libraryReplacementRecoveryPoint,
+ folderOwnershipBackup: current.folderOwnershipBackup,
creativeJobs: current.creativeJobs,
importStaging: current.importStaging
},
diff --git a/extension/media-reference-resolver.js b/extension/media-reference-resolver.js
index 95213c5..8050c8d 100644
--- a/extension/media-reference-resolver.js
+++ b/extension/media-reference-resolver.js
@@ -218,7 +218,12 @@ function fetchOptions() {
function safeUrl(value) {
try {
- const url = value instanceof URL ? value : new URL(String(value ?? ""));
+ let text = String(value ?? "").trim();
+ if (!text || /[\s\\]/u.test(text)) return null;
+ if (text.startsWith("//")) text = `https:${text}`;
+ // Missing protocol is accepted only for a domain, never a relative path.
+ else if (/^[^/?#:@]+\.[^/?#:@]+(?::\d+)?(?:[/?#]|$)/u.test(text)) text = `https://${text}`;
+ const url = new URL(text);
return ["http:", "https:"].includes(url.protocol) && url.username === "" && url.password === "" ? url : null;
} catch {
return null;
diff --git a/extension/migration.js b/extension/migration.js
index cf39cda..5951ab5 100644
--- a/extension/migration.js
+++ b/extension/migration.js
@@ -7,6 +7,7 @@ import { normalizeEntryVisuals } from "./visuals.js";
import { normalizeCompoundCases } from "./compound-cases.js";
import { isFixedTagTree, migrateLegacyFacetState } from "./tag-taxonomy.js";
import { normalizeTrashState } from "./trash.js";
+import { needsFolderOwnershipMigration, planFolderOwnership } from "./library-folder-ownership.js";
const LEGACY_CONTENT_IDS = new Set([
"content:tutorial:image", "content:tutorial:video", "content:tutorial:general"
@@ -40,8 +41,7 @@ export function migrateLibraryState(stored = {}) {
} else {
facetCatalog = sourceFacetCatalog;
}
- return {
- state: {
+ const preparedState = {
...stored,
schemaVersion: SCHEMA_VERSION,
taxonomy,
@@ -51,7 +51,11 @@ export function migrateLibraryState(stored = {}) {
trashState,
compoundCases: normalizeCompoundCases(stored.compoundCases, entries),
organizerState: normalizeOrganizerState(stored.organizerState, entries.map((entry) => entry.id))
- },
+ };
+ const folderPlan = needsFolderOwnershipMigration(preparedState) ? planFolderOwnership(preparedState) : null;
+ return {
+ state: folderPlan?.state ?? preparedState,
+ folderOwnershipMigrated: Boolean(folderPlan?.changed),
backup,
migratedCount: entries.filter((entry, index) => stored.entries?.[index]?.schemaVersion !== SCHEMA_VERSION).length,
resetPerformed: resetRequired && hasExistingLibrary(stored),
@@ -102,7 +106,7 @@ function applyLegacyTrashFacetMigration(trashState, bindings, migratedEntries) {
}
export function needsMigration(stored = {}) {
- return stored.schemaVersion !== SCHEMA_VERSION || !stored.taxonomy || !stored.facetCatalog ||
+ return needsFolderOwnershipMigration(stored) || stored.schemaVersion !== SCHEMA_VERSION || !stored.taxonomy || !stored.facetCatalog ||
!stored.organizerState || stored.organizerState.version !== ORGANIZER_VERSION || !stored.trashState || !Array.isArray(stored.compoundCases) ||
!isFixedTagTree(stored.facetCatalog) ||
(stored.entries ?? []).some((entry) => entry.schemaVersion !== SCHEMA_VERSION);
diff --git a/extension/organizer.js b/extension/organizer.js
index ac67e7f..81f9a0e 100644
--- a/extension/organizer.js
+++ b/extension/organizer.js
@@ -229,7 +229,11 @@ export function moveEntriesBetweenCollections(stateValue, sourceCollectionId, ta
if (!state.collections.some((item) => item.id === targetId)) throw new Error("目标项目不存在");
if (sourceId) {
if (!state.collections.some((item) => item.id === sourceId)) throw new Error("来源项目不存在");
- state = setEntriesCollection(state, sourceId, entryIds, false);
+ }
+ state = structuredClone(state);
+ const moved = new Set(uniqueIds(entryIds));
+ for (const collection of state.collections) {
+ if (collection.id !== targetId) collection.entryIds = collection.entryIds.filter(id => !moved.has(id));
}
return setEntriesCollection(state, targetId, entryIds, true);
}
diff --git a/extension/page-capture-site-adapters.js b/extension/page-capture-site-adapters.js
index 74219b5..b35272d 100644
--- a/extension/page-capture-site-adapters.js
+++ b/extension/page-capture-site-adapters.js
@@ -167,7 +167,8 @@ export function collectPageCaptureSitePayload(options = {}) {
const maxMedia = Number.isSafeInteger(Number(options.maxMedia)) && Number(options.maxMedia) > 0 ? Number(options.maxMedia) : 0;
const maxNodes = Number.isSafeInteger(Number(options.maxCandidates)) && Number(options.maxCandidates) > 0 ? Number(options.maxCandidates) : 0;
const maxTextCharacters = Number.isSafeInteger(Number(options.maxTextCharacters)) && Number(options.maxTextCharacters) > 0 ? Number(options.maxTextCharacters) : 0;
- const host = clean(globalThis.location?.hostname).toLocaleLowerCase("en-US");
+ const captureLocation = options.pinterestUrl ? new URL(options.pinterestUrl) : globalThis.location;
+ const host = clean(captureLocation?.hostname).toLocaleLowerCase("en-US");
if (host === "midjourney.com" || host.endsWith(".midjourney.com")) {
const pageUrl = new URL(globalThis.location.href);
const jobId = /^\/jobs\/([a-f0-9-]+)\/?$/iu.exec(pageUrl.pathname)?.[1];
@@ -368,6 +369,40 @@ export function collectPageCaptureSitePayload(options = {}) {
return { adapter: "krea", pageKind: "feed", canonicalUrl: clean(globalThis.location?.href), items, status: items.length ? "complete" : "partial" };
}
if (host === "higgsfield.ai" || host.endsWith(".higgsfield.ai")) {
+ // Asset previews keep the project URL and schema behind the dialog.
+ // Read only the selected output and its prompt, never the background brief.
+ const assetDialog = globalThis.document?.querySelector?.('[role="dialog"][aria-description="asset showcase dialog view"][data-state="open"]');
+ if (assetDialog) {
+ const originalUrl = (value) => {
+ if (!value) return "";
+ try {
+ const url = new URL(value, globalThis.location.href);
+ return url.hostname === "images.higgs.ai" ? url.searchParams.get("url") || url.href : url.href;
+ } catch { return ""; }
+ };
+ const videos = [...assetDialog.querySelectorAll('video')].filter(node => !node.closest('[role="tabpanel"],[aria-hidden="true"]'));
+ const images = [...assetDialog.querySelectorAll('img[alt="raw media image"]')];
+ const video = videos.map(node => ({contentUrl: originalUrl(node.currentSrc || node.src || node.querySelector('source[src]')?.src), thumbnailUrl: originalUrl(node.poster), width: node.videoWidth, height: node.videoHeight}));
+ const image = images.map(node => ({contentUrl: originalUrl(node.currentSrc || node.src), width: node.naturalWidth, height: node.naturalHeight}));
+ const prompt = String(assetDialog.querySelector('[role="textbox"]')?.innerText || "").trim().slice(0, maxTextCharacters);
+ const author = clean(assetDialog.querySelector('h2:not([hidden])')?.textContent);
+ const assetLink = assetDialog.querySelector('a[href*="assetId="]');
+ const source = new URL(assetLink?.href || globalThis.location.href, globalThis.location.href);
+ const assetId = source.searchParams.get("assetId") || "";
+ // Reference links expose the current asset ID as well as an input ID.
+ if (assetId && source.origin === globalThis.location.origin) {
+ source.searchParams.delete("inputMediaId");
+ source.searchParams.delete("inputMediaType");
+ }
+ return {
+ adapter: "higgsfield", pageKind: "detail", captureScope: "asset",
+ canonicalUrl: assetId ? source.href : globalThis.location.href,
+ jsonLd: [{"@type": "CreativeWork", url: assetId ? source.href : globalThis.location.href,
+ identifier: assetId || video[0]?.contentUrl || image[0]?.contentUrl,
+ name: "", description: prompt, author: {name: author}, video: video.slice(0,maxMedia), image: image.slice(0,maxMedia)}],
+ status: video.length || image.length ? "complete" : "partial"
+ };
+ }
const compactPerson = (person) => {
const value = person?.mainEntity || person;
return value && typeof value === "object" ? {
@@ -445,7 +480,7 @@ export function collectPageCaptureSitePayload(options = {}) {
status: jsonLd.length ? "complete" : "partial"
};
}
- if ((host === "pinterest.com" || host.endsWith(".pinterest.com")) && /^\/pin\/(?:[^/]*--)?\d+\/?$/u.test(clean(globalThis.location?.pathname))) {
+ if ((host === "pinterest.com" || host.endsWith(".pinterest.com")) && /^\/pin\/(?:[^/]*--)?\d+\/?$/u.test(clean(captureLocation?.pathname))) {
const parseRelayResponse = (source) => {
const text = String(source || "");
const marker = "window.__PWS_RELAY_REGISTER_COMPLETED_REQUEST__";
@@ -477,12 +512,18 @@ export function collectPageCaptureSitePayload(options = {}) {
}
return null;
};
+ const expectedId = captureLocation.pathname.match(/(?:--)?(\d+)\/?$/u)?.[1];
+ const scripts = options.pinterestHtml
+ ? [...String(options.pinterestHtml).matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/giu)].map(match => ({ textContent: match[1] }))
+ : [...(globalThis.document?.scripts || [])];
let rawPin = null;
- for (const script of [...(globalThis.document?.scripts || [])]) {
+ for (const script of scripts) {
const text = String(script?.textContent || "");
if (!text.includes("v3GetPinQueryv2")) continue;
- rawPin = parseRelayResponse(text)?.data?.v3GetPinQueryv2?.data || null;
- if (rawPin) break;
+ const part = parseRelayResponse(text)?.data?.v3GetPinQueryv2?.data;
+ if (clean(part?.entityId) === expectedId) {
+ rawPin = { ...rawPin, ...Object.fromEntries(Object.entries(part).filter(([, value]) => value !== null && value !== undefined && value !== "")) };
+ }
}
if (!rawPin || typeof rawPin !== "object") return { adapter: "pinterest", pageKind: "detail", status: "partial" };
const image = (value) => ({
@@ -491,16 +532,35 @@ export function collectPageCaptureSitePayload(options = {}) {
height: Number(value?.height) || 0
});
const creator = rawPin.nativeCreator || rawPin.closeupAttribution || rawPin.pinner || {};
- const repins = Number(globalThis.document?.querySelector?.('meta[property="pinterestapp:repins"],meta[name="pinterestapp:repins"]')?.content);
+ const document = options.pinterestHtml ? null : globalThis.document;
+ const count = value => value !== null && value !== undefined && String(value).trim() !== "" && Number.isSafeInteger(Number(value)) && Number(value) >= 0 ? Number(value) : undefined;
+ const repins = count(rawPin.repinCount ?? document?.querySelector?.('meta[property="pinterestapp:repins"],meta[name="pinterestapp:repins"]')?.content);
+ const observedCounts = {};
+ const closeup = document?.querySelector?.('[aria-label="Closeup content container"]') || document?.querySelector?.('[data-test-id="closeup-body"]');
+ for (const button of closeup?.querySelectorAll?.('button,[role="button"]') || []) {
+ const label = clean(button.getAttribute('aria-label') || button.textContent);
+ const key = /^(?:回应|React|Reactions)$/iu.test(label) ? 'reactions' : /^(?:评论|Comments)$/iu.test(label) ? 'comments' : '';
+ if (!key) continue;
+ for (let parent = button.parentElement; parent && parent !== closeup; parent = parent.parentElement) {
+ if (parent.querySelectorAll('button,[role="button"]').length > 1) break;
+ const text = String(parent.textContent || '').trim();
+ const match = text.match(/^(?:(?:回应|React|Reactions|评论|Comments)\s*)?(\d[\d,]*)$/iu);
+ const value = match ? count(match[1].replace(/,/gu, '')) : undefined;
+ if (value !== undefined) { observedCounts[key] = value; break; }
+ }
+ }
return {
adapter: "pinterest",
pageKind: "detail",
- canonicalUrl: clean(globalThis.location?.href),
+ canonicalUrl: clean(captureLocation?.href),
pin: {
entityId: clean(rawPin.entityId),
- title: clean(rawPin.gridTitle || rawPin.seoTitle),
+ title: clean(rawPin.title || rawPin.gridTitle || rawPin.closeupUnifiedTitle || rawPin.seoTitle),
description: String(rawPin.gridDescription || rawPin.description || "").slice(0, maxTextCharacters).trim(),
createdAt: clean(rawPin.createdAt),
+ originalSourceUrl: clean(rawPin.link || rawPin.mobileLink),
+ imageDescription: clean(rawPin.seoAltText || rawPin.seoDescription),
+ engagement: observedCounts,
author: {
fullName: clean(creator.fullName || creator.name || creator.firstName),
username: clean(creator.username)
@@ -1092,7 +1152,10 @@ function normalizeHiggsfieldPayload(value, canonicalUrlValue) {
url: canonicalUrl,
video: [...(Array.isArray(work.video) ? work.video : work.video ? [work.video] : []), ...videos]
}, value?.brief);
- return candidate ? { ...candidate, pageKind, candidates: [candidate] } : null;
+ if (candidate && value?.captureScope === "asset") {
+ candidate.media = candidate.media.map(item => ({ ...item, placement: "inline" }));
+ }
+ return candidate ? { ...candidate, pageKind, captureScope: value?.captureScope === "asset" ? "asset" : "document", candidates: [candidate] } : null;
}
function normalizeHiggsfieldWork(value, briefValue) {
@@ -1108,7 +1171,7 @@ function normalizeHiggsfieldWork(value, briefValue) {
const author = clean(person?.name);
const handle = clean(person?.alternateName || handlePart || person?.identifier).replace(/^@/u, "");
const publicationId = ["publications", "community"].includes(pathParts[0]) ? clean(pathParts[1]) : "";
- const itemId = publicationId || (projectSlug ? [handle, projectSlug].filter(Boolean).join("/") : "") || clean(value?.identifier) || stableTextHash(canonicalUrl);
+ const itemId = clean(value?.identifier) || publicationId || (projectSlug ? [handle, projectSlug].filter(Boolean).join("/") : "") || stableTextHash(canonicalUrl);
const imageValues = Array.isArray(value?.image) ? [...value.image] : value?.image ? [value.image] : [];
const types = Array.isArray(value?.["@type"]) ? value["@type"] : [value?.["@type"]];
const videoValues = [...(Array.isArray(value?.video) ? value.video : value?.video ? [value.video] : []), ...(types.includes("VideoObject") ? [value] : [])];
@@ -1155,7 +1218,7 @@ function normalizeHiggsfieldWork(value, briefValue) {
adapter: "higgsfield",
pageType,
canonicalUrl,
- title: title || author || `Higgsfield ${projectSlug || itemId}`,
+ title: title || captureTextTitle(contentText) || `Higgsfield ${itemId}`,
contentText,
media,
completeness: complete ? "complete" : "partial",
@@ -1205,7 +1268,7 @@ function normalizeBehancePayload(value, canonicalUrlValue) {
adapter: "behance",
pageType: "artwork",
canonicalUrl,
- title: title || author || `Behance ${itemId}`,
+ title: title || captureTextTitle(contentText) || `Behance ${itemId}`,
contentText,
media,
completeness: complete ? "complete" : "partial",
@@ -1242,11 +1305,11 @@ function normalizePinterestPayload(value, canonicalUrlValue) {
const first = variants[0];
const contentText = cleanMultiline(pin.description);
const media = first ? [{
- id: `pinterest:${itemId}:1`, kind: "image", url: first.url,
+ id: `pinterest:${itemId}:1`, kind: "image", placement: "inline", url: first.url,
width: first.width, height: first.height, sourceKind: first.sourceKind,
captureMethod: "source", variants
}] : [];
- const engagement = Number.isSafeInteger(Number(pin.repins)) && Number(pin.repins) >= 0 ? { repins: Number(pin.repins) } : {};
+ const engagement = Object.fromEntries(Object.entries({ ...pin.engagement, ...(pin.repins !== undefined && pin.repins !== null ? { repins: pin.repins } : {}) }).filter(([,value]) => value !== "" && Number.isSafeInteger(Number(value)) && Number(value) >= 0).map(([key,value]) => [key, Number(value)]));
const title = clean(pin.title);
const complete = Boolean(title && author && contentText && media.length);
const candidate = {
@@ -1254,13 +1317,16 @@ function normalizePinterestPayload(value, canonicalUrlValue) {
adapter: "pinterest",
pageType: "artwork",
canonicalUrl,
- title: title || author || `Pinterest ${itemId}`,
+ title: title || captureTextTitle(contentText) || `Pinterest ${itemId}`,
contentText,
media,
completeness: complete ? "complete" : "partial",
extraction: { scope: "document", method: "structured", textBlockCount: contentText ? 1 : 0 },
sourceFacts: {
provider: "pinterest", pageType: "artwork", itemId, author, handle,
+ authorUrl: handle ? `https://www.pinterest.com/${encodeURIComponent(handle)}/` : "",
+ originalSourceUrl: safeHttpUrl(pin.originalSourceUrl),
+ imageDescription: clean(pin.imageDescription),
publishedAt: validIso(pin.createdAt), engagement,
extractionMethod: "structured", status: complete ? "complete" : "partial"
}
@@ -1316,7 +1382,7 @@ function normalizeLiblibPayload(value, canonicalUrlValue) {
adapter: "liblibai",
pageType: "artwork",
canonicalUrl,
- title: clean(data.title) || author || "LiblibAI 作品",
+ title: clean(data.title) || captureTextTitle(promptText) || `LiblibAI ${itemId}`,
contentText: promptText,
media,
completeness: complete ? "complete" : "partial",
@@ -1354,7 +1420,7 @@ function normalizeWechatPayload(value, canonicalUrlValue) {
adapter: "wechat",
pageType: "article",
canonicalUrl,
- title: title || author || "微信公众号文章",
+ title: title || captureTextTitle(contentText) || canonicalUrl,
contentText,
media,
completeness: complete ? "complete" : "partial",
@@ -1526,3 +1592,7 @@ function clean(value) {
function cleanMultiline(value) {
return String(value ?? "").replace(/\r\n?/g, "\n").replace(/[\t ]+$/gm, "").replace(/\n{3,}/g, "\n\n").trim();
}
+
+function captureTextTitle(value) {
+ return String(value || "").replace(/\s+/gu, " ").trim().slice(0, 160);
+}
diff --git a/extension/page-capture.js b/extension/page-capture.js
index 69c3db0..bf3a4c2 100644
--- a/extension/page-capture.js
+++ b/extension/page-capture.js
@@ -346,9 +346,10 @@ function filterCandidateArticleDocument(value, selection) {
export function normalizePageCaptureCandidate(value = {}) {
const canonicalUrl = safeUrl(value.canonicalUrl || value.url);
- const title = clean(value.title);
- if (!canonicalUrl && !title) return null;
+ const capturedTitle = cleanCaptureImageDescription(value.title);
+ if (!canonicalUrl && !capturedTitle) return null;
const sourceFacts = normalizeSourceFacts(value.sourceFacts, canonicalUrl);
+ const title = capturedTitle || captureSourceLabel(canonicalUrl, sourceFacts);
const rawContentText = normalizeText(value.contentText);
const rawTextBlocks = normalizeTextBlocks(value.textBlocks, rawContentText, canonicalUrl);
const prepared = rawTextBlocks.some((item) => item.kind && item.kind !== "section")
@@ -402,6 +403,20 @@ export function normalizePageCaptureCandidate(value = {}) {
};
}
+// Accessibility wrappers describe an image element, not the work's name.
+// Keep the supplied description, but never invent a subject for an untitled work.
+function cleanCaptureImageDescription(value) {
+ return clean(value).replace(/^(?:其中包括(?:图片)?|图片中可能包括|图像中可能包括)\s*[::]\s*/u, "")
+ .replace(/^(?:image may contain|this may contain)\s*:?\s*/iu, "").trim();
+}
+
+function captureSourceLabel(url, facts) {
+ if (!url) return facts.provider;
+ const source = new URL(url);
+ const identity = facts.itemId || source.pathname.replace(/^\/+|\/+$/gu, "") || source.search;
+ return [facts.provider === "pinterest" ? "Pinterest" : source.hostname, identity].filter(Boolean).join(" · ");
+}
+
function suppressVideoPosterImages(values) {
const posterIdentities = new Set(values
.filter((item) => item.kind === "video")
@@ -540,6 +555,10 @@ export function normalizeSourceFacts(value = {}, canonicalUrl = "") {
...(typeof value.originalPromptAvailable === "boolean" ? { originalPromptAvailable: value.originalPromptAvailable } : {}),
pageType: PAGE_TYPES.has(value.pageType) ? value.pageType : "generic",
itemId: clean(value.itemId),
+ authorUrl: safeUrl(value.authorUrl),
+ originalSourceUrl: safeUrl(value.originalSourceUrl),
+ imageDescription: clean(value.imageDescription),
+ metadataError: clean(value.metadataError),
author: clean(value.author),
handle: clean(value.handle),
publishedAt: validIso(value.publishedAt),
@@ -689,9 +708,10 @@ export async function collectPageCaptureSnapshot(options = {}) {
element.removeAttribute?.("data-promptdirector-capture-region");
}
const adapter = detectAdapter(location.hostname);
- const declaredContent = (adapter.fields?.content || []).map(selector => document.querySelector(selector)).find(Boolean);
+ const assetDetail = options.siteData?.adapter === "higgsfield" && options.siteData?.captureScope === "asset";
+ const declaredContent = (assetDetail ? [] : adapter.fields?.content || []).map(selector => document.querySelector(selector)).find(Boolean);
if (declaredContent) maxMedia = Math.max(maxMedia, declaredContent.querySelectorAll("img,video").length);
- const pendingContentMedia = (options.feishuDocument ? 0 : await prepareArticleImages(declaredContent)) + await prepareContentMedia(adapter) + (Number(options.downloads?.failures) || 0) + (Number(options.feishuDocument?.pendingMediaCount) || 0);
+ const pendingContentMedia = (options.feishuDocument ? 0 : await prepareArticleImages(declaredContent)) + (assetDetail ? 0 : await prepareContentMedia(adapter)) + (Number(options.downloads?.failures) || 0) + (Number(options.feishuDocument?.pendingMediaCount) || 0);
const canonicalUrl = safeHttpUrl(document.querySelector('link[rel="canonical"]')?.href || location.href);
const metadata = collectMetadata();
const structured = collectStructuredData();
@@ -731,7 +751,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
siteStatus: siteData.completeness === "complete" ? "complete" : "partial"
};
}
- if (["jimeng", "youtube", "bilibili", "midjourney"].includes(siteData?.adapter) && siteData.pageKind === "detail" && !pageSelection) {
+ if ((assetDetail || ["jimeng", "youtube", "bilibili", "midjourney", "pinterest"].includes(siteData?.adapter)) && siteData.pageKind === "detail" && !pageSelection) {
return {
id: sessionId, sourceUrl: canonicalUrl, adapter: adapter.id,
candidates: Array.isArray(siteData.candidates) ? siteData.candidates.slice(0, 1) : [],
@@ -813,15 +833,16 @@ export async function collectPageCaptureSnapshot(options = {}) {
const collectVisible = () => {
if (contentRoot || siteData?.pageKind === "detail") return [];
const current = [];
- const adapterRoots = adapter.cardSelectors.flatMap((selector) => [...document.querySelectorAll(selector)]);
- const repeatedRoots = adapterRoots.length > 1 ? [] : collectRepeatedCardRoots(maxCandidates);
+ const pinRoots = adapter.id === "pinterest" && !/^\/pin\//u.test(location.pathname) ? [...document.querySelectorAll('[data-test-id="pinWrapper"]')] : [];
+ const adapterRoots = pinRoots.length ? pinRoots : adapter.cardSelectors.flatMap((selector) => [...document.querySelectorAll(selector)]);
+ const repeatedRoots = adapterRoots.length > 1 || pinRoots.length ? [] : collectRepeatedCardRoots(maxCandidates);
const cardRoots = [...adapterRoots, ...repeatedRoots];
const roots = [...new Set(cardRoots)].filter(isContentRoot);
const pageType = detectPageType({ adapter, metadata, structured, article, cardCount: roots.length });
for (const [index, root] of roots.entries()) {
const candidate = candidateForRoot(root, index, {
adapter, metadata, structured, article: null, siteData: null, canonicalUrl,
- pageType: options.listMode ? "gallery" : pageType, maxMedia
+ pageType: options.listMode || pinRoots.length ? "gallery" : pageType, maxMedia
});
if (candidate) current.push(candidate);
}
@@ -866,7 +887,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
})
: [];
if (regionCandidates.length) await attachViewportFallbacks(regionCandidates);
- const candidates = capturedCards.length > 1 && (options.listMode || ["feed", "gallery"].includes(pageType))
+ const candidates = capturedCards.length > 0 && (adapter.id === "pinterest" && !/^\/pin\//u.test(location.pathname) && !siteData && !pageSelection || capturedCards.length > 1 && (options.listMode || ["feed", "gallery"].includes(pageType)))
? capturedCards.slice(0, maxCandidates)
: regionCandidates.length ? regionCandidates
: bodyCandidate ? [bodyCandidate] : capturedCards.slice(0, maxCandidates);
@@ -1325,6 +1346,13 @@ export async function collectPageCaptureSnapshot(options = {}) {
function candidateForRoot(root, index, context) {
const isPageRoot = root === document.body || root === context.pageRoot;
+ let textRoot = root;
+ if (!isPageRoot && context.adapter.id === "pinterest") {
+ // Hover controls are not artwork descriptions. Their transient presence
+ // must not change the structure used to select other cards in a board.
+ textRoot = root.cloneNode(true);
+ for (const control of textRoot.querySelectorAll('button,input,select,textarea,[role="button"],[role="combobox"],[hidden],[aria-hidden="true"]')) control.remove();
+ }
const siteData = isPageRoot ? context.siteData : null;
const adapterFields = collectAdapterFields(root, context.adapter);
const capturePost = context.adapter.id === "x" && !context.pageSelection && !options.editedRegion?.token;
@@ -1332,7 +1360,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
if (capturePost && !post) return null;
const cardLink = isPageRoot || context.pageType === "article" ? "" : safeHttpUrl(root.querySelector("a[href]")?.href);
const canonicalUrl = adapterFields.canonicalUrl || cardLink || safeHttpUrl(siteData?.canonicalUrl) || context.canonicalUrl;
- const structured = context.structured.find((item) => sameUrl(item.url || item.mainEntityOfPage, canonicalUrl)) || context.structured[0] || {};
+ const structured = context.structured.find((item) => sameUrl(item.url || item.mainEntityOfPage, canonicalUrl)) || (isPageRoot ? context.structured[0] : null) || {};
let title = cleanText(isPageRoot
? options.feishuDocument?.title || siteData?.title || (context.contentRoot ? adapterFields.title : "") || context.article?.title || structured.headline || structured.name || (context.pageType === "post" ? "" : context.metadata.title)
: adapterFields.title || root.querySelector("h1,h2,h3,[role=heading]")?.textContent || structured.headline || structured.name || (context.pageType === "post" ? "" : root.querySelector("img[alt]")?.alt));
@@ -1344,7 +1372,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
const captureRoots = contentParts.length ? contentParts : [root];
const text = post ? post.text : cleanBlockText(context.contentRoot ? (options.feishuDocument?.text || (contentParts.length ? contentParts.map(readBlockText).filter(Boolean).join("\n\n") : root.innerText || root.textContent)) : isPageRoot
? pageSelection?.text || articleText || siteData?.contentText || context.article?.textContent || structured.articleBody || root.innerText || context.metadata.description
- : root.innerText || root.textContent);
+ : textRoot.innerText || textRoot.textContent);
const contentHtml = post ? post.html : context.contentRoot ? contentRootHtml(root, contentParts) : isPageRoot
? pageSelection?.html || context.article?.content || ""
: "";
@@ -1358,7 +1386,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
sourceOrder: 0
}]
: null;
- const textBlocks = post?.textBlocks || pageSelection?.textBlocks || structuredTextBlocks || collectTextBlocks(root, contentHtml, text);
+ const textBlocks = post?.textBlocks || pageSelection?.textBlocks || structuredTextBlocks || collectTextBlocks(textRoot, contentHtml, text);
const siteMedia = [...(options.feishuDocument?.media || []), ...(Array.isArray(siteData?.media) ? siteData.media : []), ...collectStructuredMedia(structured)];
const domMedia = post?.media || (pageSelection || (root.isConnected === false && !options.manualContentHtml) ? [] : captureRoots.flatMap(part => collectMedia(part, context.maxMedia)));
const pairedDomIds = new Set();
@@ -1380,7 +1408,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
...pairedSiteMedia,
...domMedia.filter((item) => !pairedDomIds.has(item.id))
], context.maxMedia);
- const article = collectArticleDocument(root, contentHtml, textBlocks, media, context.maxMedia);
+ const article = collectArticleDocument(textRoot, contentHtml, textBlocks, media, context.maxMedia);
if (capturePost) {
for (const item of media.filter(item => item.postMediaUrl)) {
item.quotedPostUrl = sameUrl(item.postMediaUrl, canonicalUrl) ? "" : item.postMediaUrl;
@@ -1394,7 +1422,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
media = mergeCollectedMedia([...media, ...article.media], context.maxMedia);
if (!title && !text && !media.length) return null;
const pageType = isPageRoot || context.pageType === "article" ? context.pageType : ["post", "video"].includes(context.adapter.pageType) ? context.adapter.pageType : "artwork";
- const author = cleanText(siteData?.sourceFacts?.author || adapterFields.author || structuredAuthorName(structured.author) || context.metadata.author || root.querySelector('[rel=author],[data-testid*=author],[class*=author]')?.textContent);
+ const author = cleanText(siteData?.sourceFacts?.author || adapterFields.author || structuredAuthorName(structured.author) || (isPageRoot ? context.metadata.author : "") || root.querySelector('[rel=author],[data-testid*=author],[class*=author]')?.textContent);
if (!title && pageType === "post") {
const identity = author || (adapterFields.handle ? `@${adapterFields.handle}` : "");
title = [identity, cleanText(text).slice(0, 96)].filter(Boolean).join(" · ") || context.metadata.siteName || location.hostname;
@@ -1427,16 +1455,19 @@ export async function collectPageCaptureSnapshot(options = {}) {
return {
id: `${context.adapter.id}:${itemId || index}:${hashText(`${canonicalUrl}\n${title}`)}`,
pageType,
- title: title || context.metadata.siteName || location.hostname,
+ title,
canonicalUrl,
contentHtml,
contentText: text,
textBlocks,
articleDocument: placed.articleDocument,
region,
- excerpt: cleanText(context.article?.excerpt || context.metadata.description),
+ excerpt: cleanText(context.article?.excerpt || (isPageRoot ? context.metadata.description : "")),
media,
sourceFacts: {
+ authorUrl: siteData?.sourceFacts?.authorUrl || "",
+ originalSourceUrl: siteData?.sourceFacts?.originalSourceUrl || "",
+ imageDescription: siteData?.sourceFacts?.imageDescription || "",
...(typeof siteData?.sourceFacts?.originalPromptAvailable === "boolean" ? { originalPromptAvailable: siteData.sourceFacts.originalPromptAvailable } : {}),
...(siteData?.sourceFacts?.description ? { description: cleanBlockText(siteData.sourceFacts.description) } : {}),
provider: cleanText(siteData?.sourceFacts?.provider) || (context.adapter.id === "generic" ? location.hostname : context.adapter.id),
@@ -1444,7 +1475,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
itemId,
author,
handle: cleanText(siteData?.sourceFacts?.handle || adapterFields.handle) || (author.startsWith("@") ? author.slice(1) : ""),
- publishedAt: siteData?.sourceFacts?.publishedAt || adapterFields.publishedAt || structured.datePublished || context.metadata.publishedAt || "",
+ publishedAt: siteData?.sourceFacts?.publishedAt || adapterFields.publishedAt || structured.datePublished || (isPageRoot ? context.metadata.publishedAt : "") || "",
capturedAt,
model: cleanText(siteData?.sourceFacts?.model || adapterFields.model || structured.model || root.querySelector('[class*=model],[data-testid*=model]')?.textContent),
dimensions: cleanText(siteData?.sourceFacts?.dimensions || (structured.width && structured.height ? `${structured.width}×${structured.height}` : "")),
@@ -2556,13 +2587,13 @@ function uniqueMedia(values) {
...(previewDataUrl ? { previewDataUrl } : {}),
...(normalizeFallbackRect(value?.fallbackRect) ? { fallbackRect: normalizeFallbackRect(value.fallbackRect) } : {}),
variants,
- alt: clean(value.alt),
+ alt: cleanCaptureImageDescription(value.alt),
...(clean(value.originalPrompt) ? { originalPrompt: normalizeText(value.originalPrompt) } : {}),
filename: clean(value.filename),
mimeType: clean(value.mimeType).toLocaleLowerCase("en-US"),
...(["document", "attachment"].includes(kind) && /^data:(?:text\/[a-z0-9.+-]+|application\/(?:pdf|rtf|zip|gzip|x-gzip|octet-stream))(?:;charset=[a-z0-9-]+)?;base64,[a-z0-9+/=]+$/i.test(value.downloadDataUrl || "")
&& value.downloadDataUrl.length <= PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes ? { downloadDataUrl: value.downloadDataUrl } : {}),
- sourceTitle: clean(value.sourceTitle),
+ sourceTitle: cleanCaptureImageDescription(value.sourceTitle),
sourceAuthor: clean(value.sourceAuthor),
originalWorkUrl: safeUrl(value.originalWorkUrl),
width: positiveInteger(variants[0]?.width || value.width, 0),
diff --git a/extension/pinterest-capture.js b/extension/pinterest-capture.js
new file mode 100644
index 0000000..0c63549
--- /dev/null
+++ b/extension/pinterest-capture.js
@@ -0,0 +1,62 @@
+import { collectPageCaptureSitePayload, normalizePageCaptureSitePayload } from './page-capture-site-adapters.js';
+import { PAGE_CAPTURE_LIMITS, PORTABLE_LIBRARY_LIMITS } from './resource-limits.js';
+
+// Read each work, not the board's metadata. Keep the candidate/media identities
+// so selections and manually chosen media remain attached to the same work.
+export async function enrichPinterestCandidates(snapshot, { cache = new Map(), cancelled = () => false, readHtml } = {}) {
+ if (snapshot.adapter !== 'pinterest') return snapshot;
+ const fetchHtml = readHtml || readPinterestHtml;
+ const candidates = [];
+ for (const candidate of snapshot.candidates || []) {
+ if (cancelled()) {
+ candidates.push({ ...candidate, completeness: 'partial', sourceFacts: { ...candidate.sourceFacts, status: 'partial', metadataError: '作品元信息补读已停止' } });
+ continue;
+ }
+ const url = candidate.canonicalUrl;
+ if (!/^https:\/\/(?:www\.)?pinterest\.com\/pin\/(?:[^/]*--)?\d+\/?(?:\?.*)?$/u.test(url || '')) {
+ candidates.push(candidate); continue;
+ }
+ try {
+ let detail = cache.get(url);
+ if (!detail) {
+ const html = await fetchHtml(url);
+ const payload = collectPageCaptureSitePayload({ pinterestUrl: url, pinterestHtml: html,
+ maxCandidates: 1, maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate,
+ maxTextCharacters: PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes });
+ detail = normalizePageCaptureSitePayload(payload, url);
+ if (!detail?.sourceFacts?.itemId || !payload?.pin?.entityId) throw new Error('作品详情元信息尚未取得');
+ if (!payload.pin.title && !detail.contentText) detail = { ...detail, title: candidate.title };
+ cache.set(url, detail);
+ }
+ candidates.push({ ...candidate, title: detail.title,
+ contentText: candidate.contentText || detail.contentText,
+ sourceFacts: { ...candidate.sourceFacts, ...detail.sourceFacts,
+ engagement: { ...detail.sourceFacts.engagement, ...candidate.sourceFacts?.engagement } },
+ media: (candidate.media || []).map(media => ({ ...media, sourceTitle: detail.title })) });
+ } catch (error) {
+ candidates.push({ ...candidate, completeness: 'partial',
+ sourceFacts: { ...candidate.sourceFacts, status: 'partial', metadataError: String(error.message || error) } });
+ }
+ }
+ return { ...snapshot, candidates };
+}
+
+export async function readPinterestHtml(url) {
+ const response = await fetch(url, { credentials: 'omit', redirect: 'error',
+ referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(PAGE_CAPTURE_LIMITS.navigationTimeoutMs) });
+ if (!response.ok) throw new Error(`作品详情读取失败(HTTP ${response.status})`);
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let size = 0;
+ let html = '';
+ try {
+ for (;;) {
+ const {done, value} = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes) throw new Error('作品详情超出读取上限');
+ html += decoder.decode(value, {stream:true});
+ }
+ return html + decoder.decode();
+ } finally { await reader.cancel().catch(() => {}); reader.releaseLock(); }
+}
diff --git a/extension/preferences.js b/extension/preferences.js
index 51785ff..88b9e4a 100644
--- a/extension/preferences.js
+++ b/extension/preferences.js
@@ -4,8 +4,11 @@ export const DEFAULT_UI_PREFERENCES = Object.freeze({
motion: "system",
analysisDiagnostics: false,
sidebarWidth: 244,
+ sidebarLayout: { collapsed: false, open: ["projects"], order: ["projects", "types", "tags"] },
detailMode: "fullscreen",
detailSidebarWidth: 760,
+ galleryView: "waterfall",
+ includeSubprojects: false,
detailPanelRatio: null
});
@@ -31,6 +34,9 @@ export function normalizeUiPreferences(value = {}) {
motion: value.motion === "none" ? "reduced" : (["system", "reduced"].includes(value.motion) ? value.motion : "system"),
analysisDiagnostics: value.analysisDiagnostics === true,
sidebarWidth: normalizeSidebarWidth(value.sidebarWidth),
+ sidebarLayout: normalizeSidebarLayout(value.sidebarLayout),
+ galleryView: ["waterfall", "list"].includes(value.galleryView) ? value.galleryView : "waterfall",
+ includeSubprojects: value.includeSubprojects === true,
detailMode: value.detailMode === "sidebar" ? "sidebar" : "fullscreen",
detailSidebarWidth: normalizeDetailSidebarWidth(value.detailSidebarWidth),
detailPanelRatio: typeof value.detailPanelRatio === "number" && Number.isFinite(value.detailPanelRatio) && value.detailPanelRatio > 0 && value.detailPanelRatio < 1 ? value.detailPanelRatio : null
@@ -42,3 +48,11 @@ export function resolveLocale(preferences = DEFAULT_UI_PREFERENCES, browserLocal
if (normalized.locale !== "system") return normalized.locale;
return String(browserLocale).toLocaleLowerCase().startsWith("zh") ? "zh-CN" : "en";
}
+
+export function normalizeSidebarLayout(value = {}) {
+ const keys = ["projects", "types", "tags"];
+ const layout = value && typeof value === "object" ? value : {};
+ const order = [...new Set([...(Array.isArray(layout.order) ? layout.order : []), ...keys])].filter(key => keys.includes(key));
+ const open = [...new Set(Array.isArray(layout.open) ? layout.open : ["projects"])].filter(key => keys.includes(key));
+ return { collapsed: layout.collapsed === true, open, order };
+}
diff --git a/extension/project-tree.js b/extension/project-tree.js
index 43dbb5a..c179fb4 100644
--- a/extension/project-tree.js
+++ b/extension/project-tree.js
@@ -51,7 +51,7 @@ export function createProjectTreeInteractions({ elements, expanded, getState, un
const root = elements.projectRootDrop;
const status = elements.projectOrderStatus;
const undoButton = elements.projectMoveUndo;
- const scroller = list.closest(".filter-sidebar");
+ const scroller = list.closest(".sidebar-module-body") || list.closest(".filter-sidebar");
document.body.append(elements.projectMoveFeedback);
elements.projectMoveFeedback.querySelector(".project-move-dismiss").addEventListener("click", () => {
elements.projectMoveFeedback.hidden = true;
@@ -210,7 +210,8 @@ export function createProjectTreeInteractions({ elements, expanded, getState, un
if (!drag?.moved) return;
const bounds = scroller.getBoundingClientRect();
root.style.left = `${bounds.left + 8}px`;
- root.style.top = `${Math.max(8, bounds.top + 8)}px`;
+ const tools = list.closest(".project-section")?.querySelector(".project-tree-tools");
+ root.style.top = `${Math.max(8, tools ? tools.getBoundingClientRect().top : bounds.top + 8)}px`;
root.style.width = `${bounds.width - 16}px`;
clearIndicators();
drag.drop = null;
diff --git a/extension/skill-cover-ui.js b/extension/skill-cover-ui.js
index 1e57aae..c21852b 100644
--- a/extension/skill-cover-ui.js
+++ b/extension/skill-cover-ui.js
@@ -71,7 +71,6 @@ export function createSkillCoverEditor({ host, readFile, sources, reportError })
host.append(preview, controls, dialog);
add.addEventListener("click", () => input.click());
close.addEventListener("click", () => dialog.close());
- dialog.addEventListener("click", event => { if (event.target === dialog) dialog.close(); });
dialog.addEventListener("close", () => { for (const child of grid.children) clearSkillCoverImage(child); grid.replaceChildren(); });
remove.addEventListener("click", () => { generation++; loading = false; pending = null; automatic = false; upload = null; selectedSource = ""; render(); });
input.addEventListener("change", async () => {
diff --git a/extension/skills-page.css b/extension/skills-page.css
index 499d771..b41dbf1 100644
--- a/extension/skills-page.css
+++ b/extension/skills-page.css
@@ -54,8 +54,8 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skill-project-picker > summary::-webkit-details-marker { display: none; }
.skill-project-picker > summary .ui-icon { width: 14px; height: 14px; color: var(--muted); transition: transform 140ms ease; }
.skill-project-picker[open] > summary .ui-icon { transform: rotate(180deg); }
-.skill-project-filter { position: absolute; z-index: 12; top: calc(100% + 5px); right: 0; left: 0; display: grid; gap: 2px; max-height: 240px; overflow: auto; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); padding: 5px; background: var(--raised); box-shadow: var(--shadow); }
-.skill-project-filter button { width: 100%; min-height: 32px; justify-content: flex-start; border-color: transparent; padding: 6px 8px; color: var(--muted); background: transparent; text-align: left; }
+.skill-project-filter { width: min(360px, calc(100vw - 80px)); position: absolute; z-index: 12; top: calc(100% + 5px); left: 0; display: grid; gap: 2px; max-height: 240px; overflow: auto; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); padding: 5px; background: var(--raised); box-shadow: var(--shadow); }
+.skill-project-filter button { white-space: normal; overflow-wrap: anywhere; flex-shrink: 0; width: 100%; min-height: 32px; justify-content: flex-start; border-color: transparent; padding: 6px 8px; color: var(--muted); background: transparent; text-align: left; }
.skill-project-filter button[aria-selected="true"] { color: var(--ink); border-color: var(--selection-edge); background: var(--selection); box-shadow: inset 2px 0 var(--accent-emphasis); }
#skill-clear-selection { width: 100%; }
.skill-builder-content { display: grid; gap: 12px; min-width: 0; }
@@ -68,7 +68,7 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skill-selection-summary { display: flex; flex-wrap: wrap; align-items: center; gap: 5px 12px; min-height: 34px; margin: -4px 0 10px; border-bottom: 1px solid var(--skill-line); padding: 0 0 10px; color: var(--muted); font-size: 11px; }
.skill-selection-summary strong { color: var(--ink); font-size: 12px; }
.skill-selection-summary small { margin-left: auto; color: var(--muted); }
-.skill-case-scroll { max-height: 540px; overflow: auto; overscroll-behavior: contain; scrollbar-gutter: stable; }
+.skill-case-scroll { max-height: 540px; overflow: auto; overscroll-behavior: contain; }
.skill-case-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); align-content: start; gap: 8px; }
.skill-case { position: relative; min-width: 0; overflow: hidden; border: 1px solid var(--skill-line); border-radius: var(--visual-card-radius); background: var(--card); color: var(--ink); }
.skill-case:hover { border-color: var(--selection-edge); box-shadow: 0 8px 20px color-mix(in srgb, var(--ink) 8%, transparent); }
@@ -84,7 +84,8 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skill-case[data-selected="true"] .skill-case-state { background: var(--accent-emphasis); }
.skill-case-state[hidden] { display: none; }
.skill-case-detail { position: absolute; z-index: 3; right: 7px; bottom: 10px; min-height: 26px; max-width: 70px; overflow: hidden; border-color: var(--skill-line); padding: 4px 7px; color: var(--muted); background: var(--raised); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
-.skill-case-load-more { display: flex; margin: 12px auto 2px; }
+.skill-case-load-more { height: 1px; }
+.skill-case-load-more[hidden] { display: none; }
.skill-evidence-note { margin: 0 0 10px; color: var(--muted, #697069); font-size: 11px; line-height: 1.5; }
.skill-run-evidence-list { display: grid; gap: 6px; }
.skill-run-evidence { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 9px; align-items: start; border: 1px solid var(--skill-line); border-radius: 4px; padding: 10px; cursor: pointer; }
@@ -196,7 +197,7 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skill-source-inspector-actions #skill-source-clear { margin-left: auto; color: var(--danger); }
.skill-source-text-option { display: flex; align-items: center; gap: 9px; border-bottom: 1px solid var(--skill-line); padding: 11px 14px; font-size: 12px; }
.skill-source-text-option input { width: auto; min-height: 0; accent-color: var(--accent-emphasis); }
-.skill-source-asset-list { display: grid; align-content: start; gap: 3px; overflow: auto; padding: 10px; }
+.skill-source-asset-list { grid-row: 4; display: grid; align-content: start; gap: 3px; overflow: auto; padding: 10px; }
.skill-source-asset { display: grid; grid-template-columns: 76px minmax(0,1fr) auto; align-items: center; gap: 10px; min-height: 70px; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); padding: 6px; background: var(--subtle-card); }
.skill-source-asset[data-selected="true"] { border-color: var(--selection-indicator); }
.skill-source-asset-preview { display: grid; width: 76px; height: 56px; place-items: center; overflow: hidden; border-radius: var(--visual-card-radius); color: var(--muted); background: var(--viewer-bg); font-size: 10px; }
@@ -205,7 +206,7 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skill-source-asset-copy strong { font-size: 12px; }
.skill-source-asset-copy small { overflow: hidden; color: var(--muted); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
.skill-source-asset input { width: auto; min-height: 0; accent-color: var(--accent-emphasis); }
-.skill-source-inspector-footer { display: flex; justify-content: flex-end; gap: 8px; border-top: 1px solid var(--skill-line); padding: 12px 14px; background: var(--bar); }
+.skill-source-inspector-footer { grid-row: 5; display: flex; justify-content: flex-end; gap: 8px; border-top: 1px solid var(--skill-line); padding: 12px 14px; background: var(--bar); }
@media (max-width: 1320px) {
.skill-case-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
@@ -290,3 +291,19 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
}
.skills-page:is([data-skill-view="create"], [data-skill-view="refine"]) .skills-topbar { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
.skills-page:is([data-skill-view="create"], [data-skill-view="refine"]) .skills-top-actions { margin: 0; flex-wrap: wrap; }
+
+
+.skill-video-cover { display: grid; place-items: center; width: 100%; height: 100%; }
+.skill-case-visual .skill-video-cover :is(video, img) { width: 100%; height: 100%; object-fit: contain; }
+.skill-case-play { position: absolute; z-index: 3; top: 12px; left: 12px; min-width: 36px; min-height: 36px; padding: 6px; }
+.skill-builder[data-stage="result"] > .skill-builder-content { display: block; }
+.skill-builder[data-stage="result"] :is(#skill-source-step, #skill-target-step, #skill-run-evidence-step) { display: none; }
+.skill-builder[data-stage="sources"]:is([data-mode="create"], [data-mode="refine"]) :is(#skill-draft-step, #skill-versions-step) { display: none; }
+.skill-draft-step { scroll-margin-top: 80px; }
+.skill-result-actions { position: sticky; top: 64px; z-index: 5; display: flex; justify-content: space-between; gap: 12px; padding: 10px 0; margin-bottom: 12px; background: var(--skill-panel); }
+.skill-draft-preview { padding-block: 12px; overflow-wrap: anywhere; }
+#skill-source-step #skill-project-picker > summary { max-width: min(240px, 45vw); }
+#skill-project-label { overflow: hidden; text-overflow: ellipsis; }
+
+.skill-case-visual { position: relative; }
+.skill-case-visual > .case-video-preview { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; pointer-events: none; }
diff --git a/extension/skills-page.js b/extension/skills-page.js
index 0ae794d..a0b5e39 100644
--- a/extension/skills-page.js
+++ b/extension/skills-page.js
@@ -1,3 +1,6 @@
+import { createUiIcon } from "./ui-icons.js";
+import { bindVideoHoverPreview } from "./video-hover-preview.js";
+import { createSourceVideoPreview, bindSourceVideoCover } from "./source-video-preview.js";
import { createSkillCoverEditor, showSkillCoverImage, clearSkillCoverImage } from "./skill-cover-ui.js";
import { readSkillCover } from "./skill-cover.js";
import { DEFAULT_COMPOSER_REQUEST_TIMEOUT_MS, normalizeAiSettings } from "./deepseek.js";
@@ -70,7 +73,7 @@ const elements = Object.fromEntries([
"skill-detail", "skill-detail-title", "skill-detail-call-name", "skill-detail-feedback", "skill-detail-description", "skill-detail-version", "skill-detail-source", "skill-detail-updated", "skill-detail-markdown", "skill-detail-edit", "skill-detail-more", "skill-detail-refine", "skill-export", "skill-submit-curated",
"skill-workspace", "skill-workspace-kicker", "skill-workspace-title", "skill-delete", "skill-builder", "skill-source-sidebar", "skill-source-step", "skill-target-step", "skill-selected-count", "skill-project-picker", "skill-project-label", "skill-project-filter", "skill-case-search", "skill-clear-selection", "skill-visible-select", "skill-selection-summary", "skill-case-scroll", "skill-case-grid", "skill-case-load-more",
"skill-run-evidence-step", "skill-run-evidence-count", "skill-run-evidence-list",
- "skill-goal", "skill-use-vision", "skill-vision-toggle-note", "skill-vision-preview", "skill-advanced", "skill-text-provider-menu", "skill-vision-provider-menu", "skill-text-instruction", "skill-vision-instruction", "skill-restore-instructions", "skill-request-preview", "skill-generate", "skill-retry-vision", "skill-run-panel", "skill-generation-status", "skill-run-elapsed", "skill-stop-run", "skill-run-progress", "skill-run-stages", "skill-run-log", "skill-generation-feedback", "skill-draft-step", "skill-draft-editor", "skill-version-label", "skill-call-name", "skill-description", "skill-markdown", "skill-save", "skill-test", "skill-save-status", "skill-versions-step", "skill-version-list",
+ "skill-show-draft", "skill-back-sources", "skill-draft-preview", "skill-goal", "skill-use-vision", "skill-vision-toggle-note", "skill-vision-preview", "skill-advanced", "skill-text-provider-menu", "skill-vision-provider-menu", "skill-text-instruction", "skill-vision-instruction", "skill-restore-instructions", "skill-request-preview", "skill-generate", "skill-retry-vision", "skill-run-panel", "skill-generation-status", "skill-run-elapsed", "skill-stop-run", "skill-run-progress", "skill-run-stages", "skill-run-log", "skill-generation-feedback", "skill-draft-step", "skill-draft-editor", "skill-version-label", "skill-call-name", "skill-description", "skill-markdown", "skill-save", "skill-test", "skill-save-status", "skill-versions-step", "skill-version-list",
"skill-source-inspector-backdrop", "skill-source-inspector", "skill-source-inspector-title", "skill-source-inspector-close", "skill-source-select-all", "skill-source-clear", "skill-source-text-option", "skill-source-include-text", "skill-source-asset-list", "skill-source-cancel", "skill-source-apply",
"skill-import-dialog", "skill-import-close", "skill-import-zip", "skill-import-folder",
"skill-submission-dialog", "skill-submission-close", "skill-submission-author", "skill-submission-author-error", "skill-submission-summary", "skill-submission-summary-error", "skill-submission-rights", "skill-submission-rights-error", "skill-submission-refresh", "skill-submission-open", "skill-submission-feedback", "skill-submission-findings", "skill-submission-preview"
@@ -93,6 +96,8 @@ let inspectorDraftSelection = null;
let inspectorReturnFocus = null;
let renderedSourceCount = SKILL_SOURCE_BATCH_SIZE;
let thumbnailUrls = new Map();
+let sourceVideoCovers = [];
+let sourceScrollPosition = 0;
let visualSuccesses = [];
let visualFailures = [];
let pendingAfterVision = false;
@@ -135,7 +140,13 @@ function bindEvents() {
elements.skillCaseSearch.addEventListener("input", () => renderCases({ reset: true }));
elements.skillClearSelection.addEventListener("click", clearAllSourceSelections);
elements.skillVisibleSelect.addEventListener("click", toggleVisibleCases);
- elements.skillCaseLoadMore.addEventListener("click", loadMoreSourceCases);
+ const sourceLoader = new IntersectionObserver(records => {
+ if (records.some(record => record.isIntersecting) && !elements.skillCaseLoadMore.hidden) loadMoreSourceCases();
+ }, { root: elements.skillCaseScroll });
+ sourceLoader.observe(elements.skillCaseLoadMore);
+ elements.skillShowDraft.addEventListener("click", showDraftResult);
+ elements.skillBackSources.addEventListener("click", showSourceWorkspace);
+ elements.skillMarkdown.addEventListener("input", renderDraftPreview);
elements.skillGoal.addEventListener("input", renderRequestPreview);
elements.skillUseVision.addEventListener("change", () => { visionPreferenceTouched = true; renderVisionPreview(); renderRequestPreview(); });
elements.skillTextInstruction.addEventListener("input", renderRequestPreview);
@@ -158,7 +169,7 @@ function bindEvents() {
addEventListener("keydown", (event) => {
if (event.key === "Escape" && !elements.skillSourceInspector.hidden) cancelSourceInspector();
});
- addEventListener("beforeunload", () => { activeSkillRun?.controller.abort(); releaseThumbnails(); });
+ addEventListener("beforeunload", () => { activeSkillRun?.controller.abort(); releaseThumbnails(); releaseSourceVideos(); });
}
async function refreshState() {
@@ -368,6 +379,11 @@ function renderWorkspace(view, skillId = "") {
coverEditor.reset(skill);
const selectingSources = view === "create" || view === "refine";
elements.skillBuilder.dataset.mode = view;
+ elements.skillBuilder.dataset.stage = "sources";
+ elements.skillShowDraft.hidden = true;
+ elements.skillGenerate.textContent = t("生成可编辑草稿");
+ elements.skillGenerate.classList.remove("button-secondary");
+ elements.skillBackSources.hidden = !selectingSources;
elements.skillSourceSidebar.hidden = !selectingSources;
elements.skillSourceStep.hidden = !selectingSources;
elements.skillTargetStep.hidden = !selectingSources;
@@ -384,6 +400,7 @@ function renderWorkspace(view, skillId = "") {
}
renderRunEvidence(view);
if (skill) {
+ elements.skillShowDraft.hidden = !selectingSources;
const version = currentCreativeSkillVersion(skill);
elements.skillCallName.value = skill.callName;
elements.skillDescription.value = skill.description;
@@ -404,6 +421,7 @@ function renderWorkspace(view, skillId = "") {
setFeedback(elements.skillGenerationStatus, "");
setFeedback(elements.skillGenerationFeedback, "");
setFeedback(elements.skillSaveStatus, "");
+ renderDraftPreview();
if (selectingSources) prepareSkillRuntimeControls();
}
@@ -454,7 +472,7 @@ function renderProjectControls() {
}
function renderCases(options = {}) {
- releaseThumbnails();
+ if (!options.append) releaseThumbnails();
const projectId = selectedProjectId;
const members = projectId ? new Set(collectionEntryIds(organizerState, projectId, { subtree: true })) : null;
const visible = filterSkillSourceEntries(entries, {
@@ -467,19 +485,16 @@ function renderCases(options = {}) {
}
visibleEntryIds = visible.map((entry) => entry.id);
const rendered = pageSkillSourceEntries(visible, renderedSourceCount);
- elements.skillCaseGrid.replaceChildren(...rendered.map(caseCard));
+ if (options.append) elements.skillCaseGrid.append(...rendered.slice(elements.skillCaseGrid.children.length).map(caseCard));
+ else elements.skillCaseGrid.replaceChildren(...rendered.map(caseCard));
elements.skillCaseLoadMore.hidden = rendered.length >= visible.length;
- elements.skillCaseLoadMore.textContent = t("加载更多案例(已显示 {shown}/{total})", {
- shown: rendered.length,
- total: visible.length
- });
renderSourceSelectionSummary();
renderVisibleSelectionAction();
}
function loadMoreSourceCases() {
renderedSourceCount += SKILL_SOURCE_BATCH_SIZE;
- renderCases();
+ renderCases({ append: true });
}
function toggleVisibleCases() {
@@ -516,7 +531,17 @@ function caseCard(entry) {
button.setAttribute("aria-label", entry.title || t("未命名案例"));
const visual = el("span", "skill-case-visual");
const asset = primaryImageAsset(entry);
- if (asset) {
+ const videoAsset = availableSkillAssets(entry).find(asset => asset.kind === "video");
+ if (videoAsset) {
+ const cover = el("span", "skill-video-cover");
+ cover.textContent = t("视频");
+ visual.append(cover);
+ sourceVideoCovers.push(bindSourceVideoCover(cover, entry, videoAsset, elements.skillCaseScroll));
+ if (videoAsset.storageMode !== "reference") {
+ const hover = bindVideoHoverPreview(visual, { loadBlob: () => getMediaBlob(videoAsset.id) });
+ sourceVideoCovers.push(() => hover.destroy());
+ }
+ } else if (asset) {
const image = document.createElement("img");
image.alt = "";
image.loading = "lazy";
@@ -546,8 +571,21 @@ function caseCard(entry) {
renderRequestPreview();
});
card.append(button);
+ if (videoAsset) {
+ const play = document.createElement("button");
+ play.append(createUiIcon("play"));
+ play.title = t("播放视频");
+ play.type = "button";
+ play.className = "skill-case-play icon-button";
+ play.setAttribute("aria-label", t("播放视频"));
+ play.addEventListener("click", () => {
+ openSourceInspector(entry.id, play);
+ elements.skillSourceAssetList.querySelector(".skill-source-video button")?.click();
+ });
+ card.append(play);
+ }
const assets = availableSkillAssets(entry);
- if (assets.length > 1 || String(entry.text ?? "").trim() || hasSelectableVideoSources(entry, assets)) {
+ if (assets.some(asset => asset.kind === "video") || assets.length > 1 || String(entry.text ?? "").trim() || hasSelectableVideoSources(entry, assets)) {
const details = textEl("button", sourceSelectionCountLabel(entry));
details.type = "button";
details.className = "skill-case-detail";
@@ -665,7 +703,13 @@ function openSourceInspector(entryId, returnFocus = null) {
elements.skillSourceInspectorClose.focus();
}
+function releaseSourceVideos() {
+ elements.skillSourceAssetList.querySelectorAll(".skill-source-video").forEach(host => host.releaseMedia());
+}
+
function closeSourceInspector() {
+ releaseSourceVideos();
+ elements.skillSourceAssetList.replaceChildren();
inspectedEntryId = "";
inspectorDraftSelection = null;
elements.skillSourceInspector.hidden = true;
@@ -699,8 +743,10 @@ function renderSourceInspector() {
const hasText = Boolean(String(entry.text ?? "").trim());
elements.skillSourceTextOption.hidden = !hasText;
elements.skillSourceIncludeText.checked = hasText && selection.includeEntryText;
+ releaseSourceVideos();
elements.skillSourceAssetList.replaceChildren(...availableSkillAssets(entry).flatMap((asset, index) => [
sourceAssetOption(entry, asset, index),
+ ...(asset.kind === "video" ? [createSourceVideoPreview(entry, asset)] : []),
...(asset.kind === "video" && selection.assetIds.has(asset.id) ? videoSourceOptions(entry, asset) : [])
]));
}
@@ -1055,6 +1101,30 @@ async function generateTextDraft(settingsValue = null, sourcesValue = null) {
pendingAfterVision = false;
finishSkillRun(t("草稿已生成 · {model}", { model: result.model }));
appendSkillRunLog(t("文字提炼完成 · {model}", { model: result.model }));
+ showDraftResult();
+}
+
+function renderDraftPreview() {
+ elements.skillDraftPreview.replaceChildren(renderMarkdownDocument(elements.skillMarkdown.value));
+}
+
+function showDraftResult() {
+ sourceScrollPosition = window.scrollY;
+ closeSourceInspector();
+ renderDraftPreview();
+ elements.skillDraftEditor.open = false;
+ elements.skillBuilder.dataset.stage = "result";
+ elements.skillDraftStep.hidden = false;
+ elements.skillShowDraft.hidden = false;
+ elements.skillGenerate.textContent = t("重新提炼");
+ elements.skillGenerate.classList.add("button-secondary");
+ elements.skillDraftStep.scrollIntoView({ block: "start" });
+ elements.skillDraftStep.focus({ preventScroll: true });
+}
+
+function showSourceWorkspace() {
+ elements.skillBuilder.dataset.stage = "sources";
+ window.scrollTo({ top: sourceScrollPosition });
}
async function saveSkill() {
@@ -1601,6 +1671,8 @@ function formatDate(value) {
}
function releaseThumbnails() {
+ sourceVideoCovers.forEach(release => release());
+ sourceVideoCovers = [];
for (const url of thumbnailUrls.values()) URL.revokeObjectURL(url);
thumbnailUrls = new Map();
}
diff --git a/extension/skills.html b/extension/skills.html
index 607fca9..2ae2b75 100644
--- a/extension/skills.html
+++ b/extension/skills.html
@@ -9,6 +9,7 @@
<link rel="stylesheet" href="library.css" />
<link rel="stylesheet" href="skills-page.css" />
<link rel="stylesheet" href="skill-cover.css" />
+ <link rel="stylesheet" href="source-video-preview.css" />
</head>
<body class="skills-page" data-skill-view="list">
<header class="skills-topbar">
@@ -76,7 +77,7 @@
<button class="icon-button" title="清空全部案例" aria-label="清空全部案例" data-i18n-title="清空全部案例" data-i18n-aria-label="清空全部案例" id="skill-clear-selection" type="button" disabled><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-x"></use></svg></button>
</aside>
<div id="skill-selection-summary" class="skill-selection-summary"></div>
- <div id="skill-case-scroll" class="skill-case-scroll"><div id="skill-case-grid" class="skill-case-grid"></div><button id="skill-case-load-more" class="button-secondary skill-case-load-more" type="button" hidden data-i18n="加载更多案例">加载更多案例</button></div>
+ <div id="skill-case-scroll" class="skill-case-scroll"><div id="skill-case-grid" class="skill-case-grid"></div><div id="skill-case-load-more" class="skill-case-load-more" hidden aria-hidden="true"></div></div>
</section>
<section id="skill-run-evidence-step" class="skill-step" hidden>
@@ -103,7 +104,7 @@
<div id="skill-request-preview" class="skill-request-preview"></div>
</div>
</details>
- <div class="skill-step-actions"><button id="skill-generate" type="button" data-i18n="生成可编辑草稿">生成可编辑草稿</button><button id="skill-retry-vision" class="button-secondary" type="button" hidden data-i18n="重试失败批次">重试失败批次</button></div>
+ <div class="skill-step-actions"><button data-i18n="查看草稿" id="skill-show-draft" class="button-secondary" type="button" hidden>查看草稿</button><button id="skill-generate" type="button" data-i18n="生成可编辑草稿">生成可编辑草稿</button><button id="skill-retry-vision" class="button-secondary" type="button" hidden data-i18n="重试失败批次">重试失败批次</button></div>
<section id="skill-run-panel" class="skill-run-panel" hidden aria-live="polite">
<div class="skill-run-heading"><div><strong id="skill-generation-status"></strong><span id="skill-run-elapsed"></span></div><button id="skill-stop-run" class="button-secondary" type="button" data-i18n="停止">停止</button></div>
<div class="skill-run-track"><span id="skill-run-progress"></span></div>
@@ -113,15 +114,17 @@
<p id="skill-generation-feedback" class="skill-feedback" role="status"></p>
</section>
- <section id="skill-draft-step" class="skill-step skill-draft-step" hidden>
+ <section id="skill-draft-step" class="skill-step skill-draft-step" tabindex="-1" hidden>
<div class="skill-section-heading"><div><small>03</small><strong data-i18n="编辑并保存">编辑并保存</strong></div><span id="skill-version-label"></span></div>
+ <div class="skill-result-actions"><button data-i18n="返回选材" id="skill-back-sources" class="button-secondary" type="button">返回选材</button><button id="skill-save" type="button" data-i18n="保存 Skill">保存 Skill</button></div>
<div class="skill-name-grid">
<label><span data-i18n="调用名">调用名</span><div class="skill-call-name"><b>/</b><input id="skill-call-name" maxlength="80" placeholder="你的 Skill 名称" data-i18n-placeholder="你的 Skill 名称" /></div></label>
<label><span data-i18n="说明">说明</span><input id="skill-description" maxlength="240" placeholder="它在什么创作任务中发挥作用" data-i18n-placeholder="它在什么创作任务中发挥作用" /></label>
</div>
<div id="skill-cover-editor"></div>
+ <article id="skill-draft-preview" class="skill-draft-preview"></article>
<details id="skill-draft-editor" class="skill-draft-editor"><summary data-i18n="查看并编辑 SKILL.md">查看并编辑 SKILL.md</summary><label><span data-i18n="SKILL.md 正文">SKILL.md 正文</span><textarea id="skill-markdown" class="skill-markdown-editor" rows="22"></textarea></label></details>
- <div class="skill-step-actions"><button id="skill-save" type="button" data-i18n="保存 Skill">保存 Skill</button></div>
+
<p id="skill-save-status" class="skill-feedback" role="status"></p>
</section>
diff --git a/extension/source-video-preview.css b/extension/source-video-preview.css
new file mode 100644
index 0000000..78454bd
--- /dev/null
+++ b/extension/source-video-preview.css
@@ -0,0 +1,3 @@
+.skill-source-video { display: grid; justify-items: center; gap: 8px; min-width: 0; padding: 8px; background: var(--viewer-bg); border-radius: var(--visual-card-radius); }
+.skill-source-video video, .skill-source-video iframe { display: block; width: 100%; max-height: 260px; aspect-ratio: 16 / 9; object-fit: contain; border: 0; }
+.skill-source-video p { margin: 0; color: var(--muted); font-size: 12px; }
diff --git a/extension/source-video-preview.js b/extension/source-video-preview.js
new file mode 100644
index 0000000..e72f2f8
--- /dev/null
+++ b/extension/source-video-preview.js
@@ -0,0 +1,142 @@
+import { getMediaBlob } from "./media-store.js";
+import { posterAssetForVideo } from "./media.js";
+import { attachRemoteVideo } from "./remote-video-player.js";
+import { officialMediaEmbedUrl } from "./media-reference-resolver.js";
+import { ensureYouTubePlaybackPermission } from "./media-playback.js";
+import { t } from "./i18n.js";
+
+// Preview is independent of the source-selection checkbox and model input.
+export function createSourceVideoPreview(entry, asset) {
+ const host = document.createElement("div");
+ host.className = "skill-source-video";
+ const video = document.createElement("video");
+ video.preload = "none";
+ video.playsInline = true;
+ video.setAttribute("aria-label", asset.sourceTitle || t("视频"));
+ const play = document.createElement("button");
+ play.type = "button";
+ play.className = "button-secondary";
+ play.textContent = t("播放视频");
+ const status = document.createElement("p");
+ status.hidden = true;
+ status.setAttribute("role", "status");
+ host.append(video, play, status);
+ let disposed = false;
+ let controller;
+ let frame;
+ const urls = [];
+ const blobUrl = blob => {
+ const url = URL.createObjectURL(blob);
+ urls.push(url);
+ return url;
+ };
+ const report = message => {
+ if (disposed) return;
+ status.textContent = t(message);
+ status.hidden = false;
+ };
+ const poster = posterAssetForVideo(entry, asset);
+ if (poster) void getMediaBlob(poster.id).then(blob => {
+ if (!disposed && blob) video.poster = blobUrl(blob);
+ }).catch(() => {});
+ video.addEventListener("error", () => report("视频无法播放,请在案例库检查原件或打开来源"));
+ play.addEventListener("click", async () => {
+ play.disabled = true;
+ status.hidden = true;
+ try {
+ const reference = asset.reference || {};
+ if (asset.storageMode === "reference") {
+ if (reference.playbackUrl || reference.streamUrl) {
+ controller?.destroy();
+ controller = await attachRemoteVideo(video, reference, (message, failed) => {
+ if (failed) report(message);
+ }, { defer: true });
+ if (disposed) { controller.destroy(); return; }
+ await video.preparePlayback();
+ } else {
+ const embed = officialMediaEmbedUrl(reference.url || asset.sourceUrl, reference.provider);
+ if (!embed) throw new Error(t("视频暂不可播放,请在案例库检查来源"));
+ if (new URL(embed).hostname === "www.youtube-nocookie.com"
+ && !await ensureYouTubePlaybackPermission(chrome, { request: false })) {
+ throw new Error(t("请先在案例库授权 YouTube 播放器"));
+ }
+ if (disposed) return;
+ frame = document.createElement("iframe");
+ frame.title = asset.sourceTitle || t("视频");
+ frame.allow = "autoplay; encrypted-media; fullscreen; picture-in-picture";
+ frame.allowFullscreen = true;
+ frame.src = embed;
+ video.replaceWith(frame);
+ play.hidden = true;
+ return;
+ }
+ } else if (!video.getAttribute("src")) {
+ const blob = await getMediaBlob(asset.id);
+ if (disposed) return;
+ if (!blob) throw new Error(t("本地媒体文件缺失;请从完整备份恢复"));
+ video.src = blobUrl(blob);
+ }
+ if (disposed) return;
+ video.controls = true;
+ await video.play();
+ if (!disposed) play.hidden = true;
+ } catch (error) {
+ report(error.message || t("视频暂不可播放"));
+ } finally {
+ if (!disposed) play.disabled = false;
+ }
+ });
+ host.releaseMedia = () => {
+ disposed = true;
+ controller?.destroy();
+ video.pause();
+ video.removeAttribute("src");
+ video.load();
+ frame?.remove();
+ urls.forEach(url => URL.revokeObjectURL(url));
+ };
+ return host;
+}
+
+// Decode only visible local videos without a saved poster; never autoplay cards.
+export function bindSourceVideoCover(host, entry, asset, root) {
+ let disposed = false;
+ let url = "";
+ let preview;
+ const poster = posterAssetForVideo(entry, asset);
+ const observer = new IntersectionObserver(async records => {
+ if (!records.some(record => record.isIntersecting) || disposed) return;
+ observer.disconnect();
+ try {
+ const blob = poster ? await getMediaBlob(poster.id)
+ : asset.storageMode !== "reference" ? await getMediaBlob(asset.id) : null;
+ if (disposed) return;
+ if (!blob) { host.textContent = t("视频 · 点击播放"); return; }
+ url = URL.createObjectURL(blob);
+ if (poster) {
+ preview = document.createElement("img");
+ preview.alt = t("视频封面");
+ } else {
+ preview = document.createElement("video");
+ preview.muted = true;
+ preview.playsInline = true;
+ preview.preload = "metadata";
+ preview.addEventListener("loadedmetadata", () => {
+ if (!disposed && Number.isFinite(preview.duration)) preview.currentTime = Math.min(0.1, preview.duration / 2);
+ }, { once: true });
+ }
+ preview.addEventListener("error", () => { if (!disposed) host.textContent = t("视频预览不可用 · 点击检查"); }, { once: true });
+ preview.src = url;
+ host.replaceChildren(preview);
+ } catch { if (!disposed) host.textContent = t("视频预览不可用 · 点击检查"); }
+ }, { root });
+ observer.observe(host);
+ return () => {
+ disposed = true;
+ observer.disconnect();
+ if (preview?.tagName === "VIDEO") {
+ preview.pause(); preview.removeAttribute("src"); preview.load();
+ }
+ if (url) URL.revokeObjectURL(url);
+ };
+}
diff --git a/extension/ui-dialogs.js b/extension/ui-dialogs.js
index 74b617c..beeab6c 100644
--- a/extension/ui-dialogs.js
+++ b/extension/ui-dialogs.js
@@ -68,6 +68,7 @@ export async function showAppDialog(options = {}) {
return new Promise((resolve) => {
let settled = false;
+ let submitting = false;
let initialControlState = "";
let dismissConfirmationArmed = false;
const controlState = () => JSON.stringify([...controls].map(([id, input]) => [
@@ -88,6 +89,7 @@ export async function showAppDialog(options = {}) {
if (status && !status.classList.contains("error")) status.textContent = "";
};
const dismiss = () => {
+ if (submitting) return;
const dirty = options.confirmDismissWhenDirty === true && controlState() !== initialControlState;
if (!dirty || dismissConfirmationArmed) return finish(null);
dismissConfirmationArmed = true;
@@ -100,13 +102,16 @@ export async function showAppDialog(options = {}) {
cancel.addEventListener("click", dismiss);
dialog.addEventListener("cancel", (event) => { event.preventDefault(); dismiss(); });
dialog.addEventListener("click", (event) => {
- if (event.target === dialog && options.dismissOnBackdrop !== false) dismiss();
+ const hasInput = Boolean(form.querySelector("input, textarea, select, [contenteditable='true']"));
+ const dismissOnBackdrop = options.dismissOnBackdrop ?? (!hasInput && typeof options.onSubmit !== "function");
+ if (event.target === dialog && dismissOnBackdrop) dismiss();
});
form.addEventListener("input", resetDismissConfirmation);
form.addEventListener("change", resetDismissConfirmation);
form.addEventListener("submit", async (event) => {
event.preventDefault();
- if (!form.reportValidity()) return;
+ if (submitting || !form.reportValidity()) return;
+ submitting = true;
const values = Object.fromEntries([...controls].map(([id, input]) => [
id,
input.type === "checkbox" ? input.checked : input.value
@@ -130,6 +135,7 @@ export async function showAppDialog(options = {}) {
statusLine.textContent = uiText(error?.message) || t("操作失败,请重试");
statusLine.classList.add("error");
} finally {
+ submitting = false;
if (!settled) { confirm.disabled = false; cancel.disabled = false; close.disabled = false; }
}
});
@@ -186,6 +192,7 @@ function createField(field = {}) {
}
input.id = `${DIALOG_ID}-${id}`;
input.name = id;
+ if (clean(field.inputMode)) input.inputMode = clean(field.inputMode);
if (field.type === "secret") {
input.classList.add("app-dialog-secret-input");
input.dataset.secretInput = "true";
diff --git a/extension/ui-foundation.css b/extension/ui-foundation.css
index 931779c..f06f8b4 100644
--- a/extension/ui-foundation.css
+++ b/extension/ui-foundation.css
@@ -590,3 +590,31 @@ html[data-motion="reduced"] *::after {
animation-iteration-count: 1 !important;
transition-duration: .01ms !important;
}
+
+/* Controls are clicked, while document text and editing fields remain selectable. */
+button, summary, label, nav a, [role="button"], [role="tab"], [role="menuitem"] {
+ -webkit-user-select: none;
+ user-select: none;
+}
+input, textarea, [contenteditable]:not([contenteditable="false"]) {
+ -webkit-user-select: text;
+ user-select: text;
+}
+
+/* Ordinary surfaces scroll without tracks. Opt in only where dragging the
+ scrollbar helps navigate an editor, zoomed document or wide table. */
+:where(*) { scrollbar-width: none; scrollbar-gutter: auto; }
+:where(*)::-webkit-scrollbar { display: none; }
+:where(.ui-scrollbar, textarea:not([readonly]):not([disabled]), [contenteditable]:not([contenteditable="false"])) {
+ scrollbar-width: thin;
+ scrollbar-color: var(--ui-border-strong) transparent;
+}
+:where(.ui-scrollbar, textarea:not([readonly]):not([disabled]), [contenteditable]:not([contenteditable="false"]))::-webkit-scrollbar {
+ display: block;
+ width: var(--ui-space-1);
+ height: var(--ui-space-1);
+}
+:where(.ui-scrollbar, textarea:not([readonly]):not([disabled]), [contenteditable]:not([contenteditable="false"]))::-webkit-scrollbar-thumb {
+ background: var(--ui-border-strong);
+ border-radius: var(--ui-control-radius);
+}
diff --git a/package-lock.json b/package-lock.json
index ca86445..c9c5620 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "prompt-case-collector",
- "version": "1.23.0",
+ "version": "1.24.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.23.0",
+ "version": "1.24.0",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
diff --git a/package.json b/package.json
index 6a15205..b00b528 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.23.0",
+ "version": "1.24.0",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
diff --git a/store/DISTRIBUTION.md b/store/DISTRIBUTION.md
index 75b6355..2c7606a 100644
--- a/store/DISTRIBUTION.md
+++ b/store/DISTRIBUTION.md
@@ -6,7 +6,7 @@ Public distribution formats and the permissions used by PromptDirector.
- 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 upload artifact: `dist/store/PromptDirector-1.23.0-Chrome-Web-Store.zip`. Keep this artifact local for Web Store submission. The sole GitHub extension installation package is `PromptDirector-1.23.0.zip`, with stable identity and the local updater.
+- Current upload artifact: `dist/store/PromptDirector-1.24.0-Chrome-Web-Store.zip`. Keep this artifact local for Web Store submission. The sole GitHub extension installation package is `PromptDirector-1.24.0.zip`, with stable identity and the local updater.
- 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 and excludes the local program installer.
## Store listing
diff --git a/test/asset-formats.test.js b/test/asset-formats.test.js
index 4fd141a..4f58784 100644
--- a/test/asset-formats.test.js
+++ b/test/asset-formats.test.js
@@ -105,3 +105,11 @@ test("portable asset format round-trips every registered kind without a second f
assert.equal(isReportedMimeCompatible(definition, resolved.mimeType), true, definition.id);
}
});
+
+
+test("desktop skill MIME is recognized consistently without treating it as a case ZIP", () => {
+ const file = { name: "original.skill", type: "application/vnd.openai.codex.skill" };
+ assert.equal(assetKindFromFileMetadata(file), "attachment");
+ assert.equal(importContainerKindForFile(file), "");
+ assert.equal(isReportedMimeCompatible(assetFormatForExtension("skill"), file.type), true);
+});
diff --git a/test/asset_board_capture_e2e.py b/test/asset_board_capture_e2e.py
new file mode 100644
index 0000000..bdaab59
--- /dev/null
+++ b/test/asset_board_capture_e2e.py
@@ -0,0 +1,128 @@
+"""Reduced real-DOM regressions for asset-dialog ownership and Pinterest boards."""
+import json
+import tempfile
+from pathlib import Path
+from datetime import datetime, timezone
+from e2e_support import EXTENSION_DIR, extension_session
+from page_capture_e2e import PNG
+
+HIGGS = 'https://higgsfield.ai/'
+BOARD = 'https://www.pinterest.com/fixture/board/'
+CDN = 'https://d8j0ntlcm91z4.cloudfront.net'
+PROMPT = 'Original asset prompt.\n' + ' '.join(['Detailed original direction.'] * 420) + '\nFinal prompt paragraph must survive.'
+
+
+def main():
+ with tempfile.TemporaryDirectory(prefix='pd-capture30-extension-') as temp:
+ extension = Path(temp)
+ for path in EXTENSION_DIR.iterdir():
+ if path.name != 'manifest.json':
+ (extension/path.name).symlink_to(path, target_is_directory=path.is_dir())
+ manifest = json.loads((EXTENSION_DIR/'manifest.json').read_text())
+ manifest['host_permissions'] += ['https://higgsfield.ai/*', CDN+'/*', 'https://www.pinterest.com/*', 'https://i.pinimg.com/*']
+ (extension/'manifest.json').write_text(json.dumps(manifest))
+ with extension_session('pd-capture30-', extension_dir=extension) as run:
+ video_bytes=(Path(__file__).parent/'fixtures/zhipu-local-video-smoke.mp4').read_bytes()
+ def route(r):
+ u=r.request.url
+ if u.startswith(CDN) or u.startswith('https://i.pinimg.com/'):
+ r.fulfill(status=200,content_type='video/mp4' if '.mp4' in u else 'image/png',body=video_bytes if '.mp4' in u else PNG)
+ else:r.fulfill(status=200,content_type='text/html',body='<html><body></body></html>')
+ for host in ['https://higgsfield.ai/**','https://www.pinterest.com/**',CDN+'/**','https://i.pinimg.com/**']:run.context.route(host,route)
+ collector=run.open_page('collector.html')
+ run.seed_storage(collector,{'schemaVersion':24,'entries':[],'capturePermissionOnboarding':{'version':1,'acknowledgedAt':datetime.now(timezone.utc).isoformat(),'clipboardIncluded':True}})
+ source=run.context.new_page()
+ def capture():
+ source.bring_to_front()
+ result=collector.evaluate("async()=>chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'})")
+ assert result.get('ok'),result
+ return result['batch']
+ source.goto(HIGGS)
+ background='<section aria-label="Project brief: wrong"><p>BACKGROUND PROJECT MUST NOT BE CAPTURED</p><img src="'+CDN+'/background.png"></section>'
+ for index,kind in enumerate(['video','image']):
+ media=f'<video src="{CDN}/movie.mp4" poster="{CDN}/poster.png" controls></video>' if kind=='video' else f'<img alt="raw media image" src="{CDN}/output.png">'
+ reference = f'<a href="/asset/all?inputMediaId=reference&inputMediaType=image&assetId=asset-{index}"><img src="{CDN}/reference.png"></a>' if index else ''
+ source.set_content(background+f'''<div role="dialog" aria-description="asset showcase dialog view" data-state="open">
+ {media}<h2 hidden>Asset showcase</h2><h2>Fixture author</h2><div role="tabpanel"><p>Prompt</p>{reference}<div role="textbox" style="white-space:pre-wrap">{PROMPT}</div></div></div>''')
+ batch=capture(); assert len(batch['candidates'])==1,batch
+ c=batch['candidates'][0]
+ assert c['contentText']==PROMPT,c
+ assert c['title']==' '.join(PROMPT.split())[:160],c
+ assert c['sourceFacts']['author']=='Fixture author',c
+ assert all(m.get('placement')=='inline' for m in c['media']),c
+ assert len(c['media'])==1 and c['media'][0]['kind']==kind,c
+ assert c['canonicalUrl'] == (HIGGS if not index else HIGGS+'asset/all?assetId=asset-1'),c
+ selected=collector.evaluate("async c=>(await import('./page-capture.js')).pageCaptureDefaultMediaIds(c)",c)
+ assert len(selected)==1,c
+ batch['selections']=[{'candidateId':c['id'],'includeText':True,'selectedMediaIds':selected,'mediaDecision':'confirmed'}]
+ saved=collector.evaluate("async batch=>chrome.runtime.sendMessage({type:'COMMIT_PAGE_CAPTURE',batch})",batch)
+ assert saved.get('ok'),saved
+ stored=collector.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_STATE'})).entries")
+ assert len(stored)==2,stored
+ assert all(e['text']==PROMPT for e in stored),stored
+ assert all(any(m.get('storageMode')=='managed' for m in e['mediaAssets']) for e in stored),stored
+ source.set_content(background + '<section data-asset-id=other><img src="'+CDN+'/other.png"></section>')
+ article = capture()['candidates'][0]
+ assert 'BACKGROUND PROJECT MUST NOT BE CAPTURED' in article['contentText'],article
+ assert all(m['url'].endswith('/background.png') for m in article['media']),article
+ source.goto(BOARD)
+ def cards(count):
+ return '<main><h1>Fixture board</h1><p>Save Share More actions</p>'+''.join(f'''<div data-grid-item><div data-test-id="pin"><div data-test-id="pinWrapper"><a href="/pin/{100000+i}/"><img alt="Artwork {i}" style="width:240px;height:320px" src="https://i.pinimg.com/236x/{i}.png" srcset="https://i.pinimg.com/236x/{i}.png 1x, https://i.pinimg.com/originals/{i}.png 4x"></a><button>Save</button></div></div></div>''' for i in range(count))+'</main>'
+ for count in [1,3]:
+ source.set_content(cards(count))
+ # The same Pin gets transient board/save controls under hover.
+ source.locator('[data-test-id="pinWrapper"]').last.evaluate("node=>node.insertAdjacentHTML('beforeend','<div role=button><p>Board name</p><button>Save</button></div>')")
+ batch=capture();cs=batch['candidates']
+ assert len(cs)==count,(count,cs)
+ assert len({c['canonicalUrl'] for c in cs})==count,cs
+ assert all('/pin/' in c['canonicalUrl'] for c in cs),cs
+ assert all(len(c['media'])==1 and '/originals/' in c['media'][0]['url'] for c in cs),cs
+ assert all(not c['contentText'] and not c['textBlocks'] for c in cs),cs
+ assert collector.evaluate("async cs=>{const {pageCaptureStructureMatches}=await import('./page-capture.js');return cs.every(c=>pageCaptureStructureMatches(cs[0],c))}",cs),cs
+ # Board-wide metadata must not become the metadata of every artwork.
+ source.set_content('<meta name="author" content="BOARD OWNER"><meta property="article:published_time" content="2024-01-01T00:00:00Z"><script type="application/ld+json">'+json.dumps({'@type':'CollectionPage','name':'BOARD TITLE','author':{'name':'BOARD OWNER'},'url':BOARD})+'</script>'+cards(3))
+ for i, label in enumerate(['其中包括图片:', '其中包括图片: Dragon and Artemis', 'This may contain: Forest temple']):
+ source.locator('[data-test-id="pinWrapper"] img').nth(i).evaluate('(node,label)=>node.alt=label',label)
+ batch=capture();cs=batch['candidates']
+ assert cs[0]['title']=='Pinterest · 100000',cs
+ assert cs[1]['title']=='Dragon and Artemis' and cs[2]['title']=='Forest temple',cs
+ assert all(not c['sourceFacts']['author'] and not c['sourceFacts']['publishedAt'] for c in cs),cs
+ selections=collector.evaluate("""async candidates => {
+ const {pageCaptureDefaultMediaIds}=await import('./page-capture.js');
+ return candidates.map(c=>({candidateId:c.id,includeText:true,
+ selectedMediaIds:pageCaptureDefaultMediaIds(c),mediaDecision:'confirmed'}));
+ }""",cs)
+ assert all(len(s['selectedMediaIds'])==1 for s in selections),selections
+ batch['selections']=selections
+ saved=collector.evaluate("async batch=>chrome.runtime.sendMessage({type:'COMMIT_PAGE_CAPTURE',batch})",batch)
+ assert saved.get('ok'),saved
+ collector.reload()
+ readback=collector.evaluate("""async () => {
+ const {entries}=await chrome.runtime.sendMessage({type:'GET_STATE'});
+ const {getMediaBlob}=await import('./media-store.js');
+ const {sha256Blob}=await import('./blob-digest.js');
+ return Promise.all(entries.filter(e=>e.url.includes('pinterest.com')).map(async e=>({
+ url:e.url,title:e.title,media:await Promise.all(e.mediaAssets.map(async a=>{
+ const blob=await getMediaBlob(a.id);
+ return {name:a.sourceTitle,mode:a.storageMode,bytes:blob?.size,hash:blob?await sha256Blob(blob):null};
+ }))
+ })));
+ }""")
+ import hashlib
+ assert len(readback)==3,readback
+ assert {e['title'] for e in readback}=={c['title'] for c in cs},readback
+ assert all('其中包括' not in m['name'] and m['name'] for e in readback for m in e['media']),readback
+ assert {e['url'] for e in readback}=={c['canonicalUrl'] for c in cs},readback
+ assert all(len(e['media'])==1 and e['media'][0]['mode']=='managed' and
+ e['media'][0]['hash']==hashlib.sha256(PNG).hexdigest() for e in readback),readback
+ source.set_content(cards(1))
+ source.locator('[data-test-id="pinWrapper"]').evaluate("node=>node.insertAdjacentHTML('beforeend','<p>Original artwork description</p><div role=button><p>Board name</p><button>Save</button></div>')")
+ described=capture()['candidates'][0]
+ # Existing section selection may put short descriptions in review;
+ # filtering controls must still preserve their text and document block.
+ assert 'Original artwork description' in [described['contentText']]+[b['text'] for b in described['possibleOmissions']],described
+ assert any(b.get('text')=='Original artwork description' for b in described['articleDocument']['blocks']),described
+ assert all('Board name' not in b.get('text','') for b in described['articleDocument']['blocks']),described
+ print('PASS asset image/video prompt ownership, managed save/readback; Pinterest singleton/nested cards/original variants')
+
+if __name__=='__main__':main()
diff --git a/test/blob-digest.test.js b/test/blob-digest.test.js
new file mode 100644
index 0000000..f65fd37
--- /dev/null
+++ b/test/blob-digest.test.js
@@ -0,0 +1,51 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createBlobDigestCache, sha256Blob } from '../extension/blob-digest.js';
+import { buildFolderBackupWritePlan, verifyFolderBackupCompletion } from '../extension/library-export-plan.js';
+
+function countedBlob(text) {
+ const blob = new Blob([text]);
+ const stream = blob.stream.bind(blob);
+ let reads = 0;
+ blob.stream = () => { reads++; return stream(); };
+ return { blob, reads: () => reads };
+}
+
+test('backup preflight and manifest reuse actual bytes, not asset ids or claimed hashes', async () => {
+ const original = countedBlob('original');
+ const digest = createBlobDigestCache();
+ await Promise.all([digest(original.blob), digest(original.blob)]);
+ const files = new Map([['library.json', new Blob(['{}'])], ['videos/source.mp4', original.blob]]);
+ const plan = await buildFolderBackupWritePlan({ files, digest });
+ assert.equal(original.reads(), 1);
+ // Even with the same name and size, disk readback is an independent snapshot.
+ const damaged = countedBlob('damaged!');
+ files.set('videos/source.mp4', damaged.blob);
+ await assert.rejects(verifyFolderBackupCompletion(plan.marker, files, { digest }), /完整性校验失败/);
+ assert.equal(damaged.reads(), 1);
+ const readback = countedBlob('original');
+ files.set('videos/source.mp4', readback.blob);
+ await verifyFolderBackupCompletion(plan.marker, files, { digest });
+ assert.equal(readback.reads(), 1);
+});
+
+test('failed reads can retry and caches never survive an operation', async () => {
+ const original = countedBlob('retry');
+ const stream = original.blob.stream;
+ original.blob.stream = () => { throw new Error('unavailable'); };
+ const digest = createBlobDigestCache();
+ await assert.rejects(digest(original.blob), /unavailable/);
+ original.blob.stream = stream;
+ assert.equal(await digest(original.blob), await sha256Blob(new Blob(['retry'])));
+ await createBlobDigestCache()(original.blob);
+ assert.equal(original.reads(), 2);
+});
+
+test('long media report actual streamed bytes through completion', async () => {
+ const blob = new Blob([new Uint8Array(1024 * 1024)]);
+ const progress = [];
+ await sha256Blob(blob, { onProgress: value => progress.push(value) });
+ assert.ok(progress.length);
+ assert.equal(progress.at(-1).completedBytes, blob.size);
+ assert.ok(progress.every((p, i) => p.totalBytes === blob.size && (!i || p.completedBytes >= progress[i - 1].completedBytes)));
+});
diff --git a/test/brand_i18n_e2e.py b/test/brand_i18n_e2e.py
index dfd37c8..34026f9 100644
--- a/test/brand_i18n_e2e.py
+++ b/test/brand_i18n_e2e.py
@@ -41,6 +41,9 @@ def main() -> None:
if path == "composer.html":
page.locator("#composer-shell").evaluate("node => node.classList.add('nav-open')")
page.wait_for_timeout(250)
+ if path == "library.html":
+ expect(page.locator(".product-brand").first).to_be_hidden()
+ page.set_viewport_size({"width": 1280, "height": 844})
brand = page.locator(".product-brand").first
expect(brand).to_be_visible()
expect(brand.locator(".product-brand-name")).to_have_text("PromptDirector")
diff --git a/test/case-management-ui.test.js b/test/case-management-ui.test.js
index a2b4133..0a7202f 100644
--- a/test/case-management-ui.test.js
+++ b/test/case-management-ui.test.js
@@ -18,7 +18,7 @@ test("selection mode exposes all filtered results, user tags, projects, sharing,
"selection-label-input",
"selection-add-labels",
"selection-project-target",
- "selection-add-project",
+ "selection-copy-project",
"selection-move-project",
"selection-remove-project",
"share-export",
@@ -53,7 +53,7 @@ test("batch project management uses a wide source-aware move surface and one ato
const panel = html.slice(html.indexOf('id="selection-project-menu"'), html.indexOf('id="share-export"'));
assert.match(panel, /id="selection-project-impact"/);
assert.match(panel, /id="selection-move-project"[\s\S]*>移动</);
- assert.match(panel, /id="selection-add-project"[\s\S]*>同时加入</);
+ assert.match(panel, /id="selection-copy-project"[\s\S]*>复制到项目</);
assert.match(panel, /id="selection-remove-project"[\s\S]*>移出当前项目</);
assert.doesNotMatch(panel, /所选项目作为父项目/);
assert.match(css, /\.project-menu-panel\.selection-project-panel\s*\{[^}]*width:\s*min\(430px/);
diff --git a/test/case_management_batch_regression_e2e.py b/test/case_management_batch_regression_e2e.py
index 46b7568..8450387 100644
--- a/test/case_management_batch_regression_e2e.py
+++ b/test/case_management_batch_regression_e2e.py
@@ -92,8 +92,10 @@ def main() -> None:
"uiPreferences": {"locale": "zh-CN", "theme": "dark", "motion": "reduced"},
})
library = session.open_page("library.html", wait_until="networkidle")
- expect(library.locator("#case-list > .case-card")).to_have_count(10)
+ expect(library.locator("#case-list > .case-card")).to_have_count(15)
+ migrated_members = organizer_members(library)
+ assert len(set(sum(migrated_members.values(), []))) == sum(map(len, migrated_members.values()))
library.locator(".project-filter", has_text="来源项目").click()
expect(library.locator("#case-list > .case-card")).to_have_count(4)
library.locator("#select-cases").click()
@@ -120,12 +122,13 @@ def main() -> None:
assert panel_geometry["overflow"] is False, panel_geometry
assert len(panel_geometry["buttons"]) == 3, panel_geometry
assert all(button["scrollWidth"] <= button["clientWidth"] for button in panel_geometry["buttons"]), panel_geometry
- library.locator("#selection-add-project").click()
- expect(library.locator("#feedback")).to_contain_text("加入项目")
+ library.locator("#selection-copy-project").click()
+ expect(library.locator("#feedback")).to_contain_text("已复制")
after_add = organizer_members(library)
assert after_add["来源项目"] == ["batch-case-0", "batch-case-1", "batch-case-2", "batch-case-3"], after_add
- assert after_add["保留项目"] == ["batch-case-0", "batch-case-1", "batch-case-2", "batch-case-3", "batch-case-4"], after_add
- assert after_add["目标项目"] == ["batch-case-4", *first_selection], after_add
+ assert after_add["保留项目"] == migrated_members["保留项目"], after_add
+ copied_ids = after_add["目标项目"][len(migrated_members["目标项目"]):]
+ assert len(copied_ids) == len(first_selection) and not set(copied_ids) & set(first_selection)
library.locator("#select-cases").click()
for entry_id in first_selection:
@@ -136,8 +139,8 @@ def main() -> None:
after_move = organizer_members(library)
remaining_source = [entry_id for entry_id in organizer["collections"][0]["entryIds"] if entry_id not in first_selection]
assert after_move["来源项目"] == remaining_source, after_move
- assert after_move["保留项目"] == ["batch-case-0", "batch-case-1", "batch-case-2", "batch-case-3", "batch-case-4"], after_move
- assert after_move["目标项目"] == ["batch-case-4", *first_selection], after_move
+ assert after_move["保留项目"] == migrated_members["保留项目"], after_move
+ assert after_move["目标项目"] == [*after_add["目标项目"], *first_selection], after_move
expect(library.locator("#case-list > .case-card")).to_have_count(2)
library.locator("#select-cases").click()
@@ -156,10 +159,10 @@ def main() -> None:
after_create = organizer_members(library)
assert after_create["来源项目"] == [], after_create
assert after_create["新建移动项目"] == second_selection, after_create
- assert after_create["保留项目"] == ["batch-case-0", "batch-case-1", "batch-case-2", "batch-case-3", "batch-case-4"], after_create
+ assert after_create["保留项目"] == migrated_members["保留项目"], after_create
library.locator("#workspace-library").click()
- expect(library.locator("#case-list > .case-card")).to_have_count(10)
+ expect(library.locator("#case-list > .case-card")).to_have_count(17)
library.locator("#select-cases").click()
library.locator('.case-card[data-entry-id="batch-case-5"]').click()
select_target(library, target_id)
@@ -174,7 +177,7 @@ def main() -> None:
)
assert aggregate_geometry["width"] >= 360, aggregate_geometry
assert aggregate_geometry["overflow"] is False, aggregate_geometry
- assert aggregate_geometry["visibleActions"] == 1, aggregate_geometry
+ assert aggregate_geometry["visibleActions"] == 2, aggregate_geometry
before_failure = organizer_members(library)
library.evaluate(
@@ -185,7 +188,7 @@ def main() -> None:
: window.__caseManagementSendMessage.call(chrome.runtime, message, ...rest);
}"""
)
- library.locator("#selection-add-project").click()
+ library.locator("#selection-copy-project").click()
expect(library.locator("#feedback")).to_contain_text("模拟项目写入失败")
assert organizer_members(library) == before_failure
library.evaluate("() => { chrome.runtime.sendMessage = window.__caseManagementSendMessage; }")
@@ -219,10 +222,10 @@ def main() -> None:
print({
"sweep_select_and_cancel": True,
- "batch_add": after_add,
+ "batch_copy": after_add,
"batch_move": after_move,
"create_and_move": after_create,
- "aggregate_count": 10,
+ "aggregate_count": 17,
"failed_write_unchanged": True,
"project_panel": panel_geometry,
"aggregate_panel": aggregate_geometry,
diff --git a/test/creative_skills_e2e.py b/test/creative_skills_e2e.py
index ce025d3..ded1665 100644
--- a/test/creative_skills_e2e.py
+++ b/test/creative_skills_e2e.py
@@ -133,7 +133,7 @@ Run `scripts/helper.py` before applying the composition guidance.
expect(skills.locator("#skill-source-inspector")).to_be_visible()
expect(skills.locator(".skill-source-asset")).to_have_count(2)
expect(skills.locator(".skill-source-asset input:checked")).to_have_count(1)
- skills.screenshot(path="/tmp/promptdirector-skills-inspector-light.png")
+ skills.screenshot(path=str(Path(tempfile.gettempdir()) / "promptdirector-skills-inspector-light.png"))
skills.locator("#skill-source-clear").click()
expect(skills.locator("#skill-selected-count")).to_have_text("1")
skills.locator("#skill-source-cancel").click()
@@ -150,7 +150,7 @@ Run `scripts/helper.py` before applying the composition guidance.
skills.locator("#skill-visible-select").click()
expect(skills.locator("#skill-selected-count")).to_have_text("2")
skills.locator("#skill-goal").fill("只提炼我喜欢的构图、色彩和人物光线")
- skills.screenshot(path="/tmp/promptdirector-skills-create-light.png", full_page=True)
+ skills.screenshot(path=str(Path(tempfile.gettempdir()) / "promptdirector-skills-create-light.png"), full_page=True)
skills.locator("#skill-generate").click()
preflight = skills.locator("#promptdirector-app-dialog")
expect(preflight).to_be_visible()
@@ -160,7 +160,14 @@ Run `scripts/helper.py` before applying the composition guidance.
preflight.get_by_role("button", name="开始提炼").click()
expect(skills.locator("#skill-draft-step")).to_be_visible()
expect(skills.locator("#skill-markdown")).to_have_value(re.compile("视觉组织方法"))
- expect(skills.locator("#skill-run-panel")).to_be_visible()
+ expect(skills.locator("#skill-target-step")).to_be_hidden()
+ expect(skills.locator("#skill-draft-preview")).to_contain_text("视觉组织方法")
+ expect(skills.locator("#skill-save")).to_be_in_viewport()
+ skills.screenshot(path=str(Path(tempfile.gettempdir()) / "pd-skill-result.png"))
+ skills.locator("#skill-back-sources").click()
+ expect(skills.locator("#skill-selected-count")).to_have_text("2")
+ expect(skills.locator("#skill-goal")).to_have_value("只提炼我喜欢的构图、色彩和人物光线")
+ skills.locator("#skill-show-draft").click()
expect(skills.locator("#skill-generation-status")).to_contain_text("草稿已生成")
expect(skills.locator("#skill-run-progress")).to_have_attribute("style", re.compile("100%"))
expect(skills.locator("#skill-run-log")).to_contain_text("文字提炼完成")
@@ -189,7 +196,7 @@ Run `scripts/helper.py` before applying the composition guidance.
exported_skill, _ = wait_for_download(skills)
assert zipfile.is_zipfile(exported_skill)
expect(skills.locator("#skill-detail-feedback")).to_contain_text("Skill 已导出")
- skills.screenshot(path="/tmp/promptdirector-skills-desktop-light.png")
+ skills.screenshot(path=str(Path(tempfile.gettempdir()) / "promptdirector-skills-desktop-light.png"))
skills.locator("#skill-detail-edit").click()
expect(skills.locator("#skill-version-label")).to_have_text("当前 v1")
@@ -275,7 +282,10 @@ Run `scripts/helper.py` before applying the composition guidance.
skills.locator("#skill-detail-more > summary").click()
skills.locator("#skill-detail-refine").click()
expect(skills.locator("#skill-source-sidebar")).to_be_visible()
- expect(skills.locator("#skill-draft-step")).to_be_visible()
+ expect(skills.locator("#skill-draft-step")).to_be_hidden()
+ skills.locator("#skill-show-draft").click()
+ expect(skills.locator("#skill-draft-preview")).to_contain_text("视觉组织方法")
+ skills.locator("#skill-back-sources").click()
expect(skills.locator("#skill-run-evidence-step")).to_be_visible()
expect(skills.locator("#skill-run-evidence-list")).to_contain_text("保留主体层级")
evidence_checkbox = skills.locator("#skill-run-evidence-list input")
@@ -324,7 +334,7 @@ Run `scripts/helper.py` before applying the composition guidance.
expect(composer.locator("#composer-projects-panel")).to_be_visible()
expect(composer.locator(".composer-skill-card")).to_have_count(2)
expect(composer.locator(".composer-skill-card .skill-cover-card img")).to_be_visible()
- composer.screenshot(path="/tmp/promptdirector-composer-skills-after.png")
+ composer.screenshot(path=str(Path(tempfile.gettempdir()) / "promptdirector-composer-skills-after.png"))
skill_workspace_layout = composer.evaluate("""() => {
const body = document.querySelector('.composer-reference-body').getBoundingClientRect();
const panel = document.querySelector('#composer-projects-panel').getBoundingClientRect();
@@ -387,7 +397,7 @@ Run `scripts/helper.py` before applying the composition guidance.
assert max(rgb_channels(layout["background"])) < 60, layout
assert max(rgb_channels(layout["cardBackground"])) < 80, layout
assert min(rgb_channels(layout["cardColor"])) > 180, layout
- skills.screenshot(path="/tmp/promptdirector-skills-mobile-dark-en.png")
+ skills.screenshot(path=str(Path(tempfile.gettempdir()) / "promptdirector-skills-mobile-dark-en.png"))
skills.locator(".skill-card", has_text="external-method").click()
skills.locator("#skill-detail-edit").click()
diff --git a/test/detail_image_export_e2e.py b/test/detail_image_export_e2e.py
new file mode 100644
index 0000000..f32f573
--- /dev/null
+++ b/test/detail_image_export_e2e.py
@@ -0,0 +1,94 @@
+"""Detail copy/drag must expose the original, not the generated gallery thumbnail."""
+from playwright.sync_api import expect
+from e2e_support import extension_session, base_entry
+
+
+def main():
+ with extension_session('detail-image-export-') as run:
+ setup = run.open_page('collector.html')
+ original = setup.evaluate('''async () => {
+ const {saveMediaBlob} = await import('./media-store.js');
+ const canvas = document.createElement('canvas');
+ canvas.width = 1800; canvas.height = 1200;
+ canvas.getContext('2d').fillRect(0, 0, 1800, 1200);
+ const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
+ await saveMediaBlob('export-original', blob);
+ return {size:blob.size, digest:Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', await blob.arrayBuffer()))).join(',')};
+ }''')
+ entry = base_entry('export-case', '原图拖出', '', 'content:image-case', 0)
+ entry.update(primaryMediaId='export-original', mediaAssets=[{
+ 'id':'export-original', 'kind':'image', 'storageMode':'managed',
+ 'mimeType':'image/png', 'sourceTitle':'原件.png', 'width':1800, 'height':1200}])
+ run.seed_storage(setup, {'entries':[entry], 'uiPreferences':{'motion':'reduced'}})
+ page = run.open_page('library.html')
+ page.locator('.case-card[data-entry-id="export-case"]').click()
+ picture = page.locator('.detail-image')
+ expect(picture).to_be_visible()
+ page.wait_for_function("document.querySelector('.detail-image')?.naturalWidth === 1800")
+ result = picture.evaluate('''async image => {
+ const context = new MouseEvent('contextmenu', {bubbles:true, cancelable:true});
+ image.dispatchEvent(context);
+ const data = new DataTransfer();
+ image.dispatchEvent(new DragEvent('dragstart', {bubbles:true, cancelable:true, dataTransfer:data}));
+ const url = data.getData('text/uri-list');
+ const blob = await (await fetch(url)).blob();
+ return {prevented:context.defaultPrevented, menu:!!document.querySelector('.quick-action-menu'),
+ payload:data.getData('DownloadURL'), url, size:blob.size,
+ digest:Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', await blob.arrayBuffer()))).join(',')};
+ }''')
+ assert not result['prevented'] and not result['menu'], result
+ assert result['payload'] == 'image/png:原件.png:' + result['url'], result
+ assert result['size'] == original['size'] and result['digest'] == original['digest'], result
+ page.evaluate("""() => {
+ document.querySelector('.detail-image').addEventListener('dragstart', event => {
+ window.originalDrag = {trusted:event.isTrusted, payload:event.dataTransfer.getData('DownloadURL')};
+ });
+ const target = document.createElement('div');
+ target.id = 'original-drop-target';
+ target.style = 'position:fixed;right:10px;top:10px;width:160px;height:120px;z-index:99999;background:white';
+ target.addEventListener('dragover', event => event.preventDefault());
+ target.addEventListener('drop', event => {
+ event.preventDefault();
+ window.originalDrop = {trusted:event.isTrusted, url:event.dataTransfer.getData('text/uri-list'),
+ payload:event.dataTransfer.getData('DownloadURL')};
+ });
+ document.body.append(target);
+ }""")
+ picture.drag_to(page.locator('#original-drop-target'))
+ dropped = page.evaluate('window.originalDrop')
+ assert dropped and dropped['trusted'] and dropped['url'] == result['url'], dropped
+ started = page.evaluate('window.originalDrag')
+ assert started['trusted'] and started['payload'] == result['payload'], started
+ # Chromium does not expose its native DownloadURL flavor to a webpage drop target.
+ # Verify the received standard URL, while OS file export remains a separate acceptance.
+ assert page.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_STATE'})).entries.length") == 1
+ page.locator('#original-drop-target').evaluate("target => { target.style.top = '300px'; }")
+ page.locator('#detail-close').click()
+ card_image = page.locator('.case-card[data-entry-id="export-case"] .case-shot')
+ card_image.hover()
+ page.wait_for_function("document.querySelector('.case-shot')?.naturalWidth === 1800")
+ card_image.evaluate("""image => image.closest('.case-card').addEventListener('dragstart', event => {
+ // Observe after the event bubbles through the card's project-move handler.
+ window.cardDrag = {
+ trusted:event.isTrusted, payload:event.dataTransfer.getData('DownloadURL'),
+ caseId:event.dataTransfer.getData('application/x-promptdirector-case'),
+ effect:event.dataTransfer.effectAllowed
+ };
+ })""")
+ card_image.drag_to(page.locator('#original-drop-target'))
+ card_drag = page.evaluate('window.cardDrag')
+ dropped = page.evaluate('window.originalDrop')
+ assert card_drag['trusted'] and card_drag['caseId'] == 'export-case', card_drag
+ assert card_drag['effect'] == 'copyMove', card_drag
+ assert card_drag['payload'] == 'image/png:原件.png:' + dropped['url'], card_drag
+ received = page.evaluate("""async url => {
+ const blob = await (await fetch(url)).blob();
+ return {type:blob.type, size:blob.size,
+ digest:Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', await blob.arrayBuffer()))).join(',')};
+ }""", dropped['url'])
+ assert received['type'] == 'image/png' and received['digest'] == original['digest'], received
+ print('PASS original detail image context menu and drag payload: 1800x1200 PNG, original SHA-256 preserved; case retained; gallery card exports PNG original with project-move identity')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/test/dialog_input_safety_e2e.py b/test/dialog_input_safety_e2e.py
new file mode 100644
index 0000000..1f10a0f
--- /dev/null
+++ b/test/dialog_input_safety_e2e.py
@@ -0,0 +1,75 @@
+from pathlib import Path
+import re
+import tempfile
+from playwright.sync_api import expect
+from e2e_support import extension_session
+
+
+def main():
+ with extension_session('pd-input-safety-') as run:
+ run.context.set_offline(True)
+ # This checks our saved reference and embed URL, not third-party playback.
+ run.context.route('https://player.bilibili.com/**', lambda route: route.fulfill(content_type='text/html', body='<title>Player fixture</title>'))
+ page = run.open_page('library.html', wait_until='networkidle')
+ if page.locator('#settings-dialog').is_visible():
+ page.locator('#settings-close').click()
+ page.evaluate('chrome.permissions.request = async () => false')
+ page.locator('#add-menu > summary').click()
+ page.locator('#add-video-reference').click()
+ dialog = page.locator('#promptdirector-app-dialog')
+ url = 'bilibili.com/video/BV1gveN6WEpC/?trackid=abc&spm_id_from=333.1007&p=2'
+ dialog.locator('[name="url"]').fill(url)
+ page.mouse.click(5, 5)
+ expect(dialog).to_be_visible()
+ expect(dialog.locator('[name="url"]')).to_have_value(url)
+ shot = Path(tempfile.gettempdir()) / 'pd-input-safety.png'
+ page.screenshot(path=str(shot))
+ dialog.locator('[type="submit"]').click()
+ expect(dialog).not_to_be_visible()
+ entry = page.evaluate('''async () => {
+ const state = await chrome.runtime.sendMessage({type:'GET_STATE'});
+ return state.entries.find(e => e.mediaAssets.some(a=>a.reference?.url?.includes('BV1gveN6WEpC')));
+ }''')
+ assert entry, 'Protocol-less video link must save an actual case'
+ assert entry['mediaAssets'][0]['reference']['url'] == 'https://www.bilibili.com/video/BV1gveN6WEpC/?p=2'
+ page.locator(f'.case-card[data-entry-id="{entry["id"]}"]').click()
+ expect(page.locator('.referenced-video-embed iframe')).to_have_attribute('src', re.compile('.*bvid=BV1gveN6WEpC.*'))
+ page.locator('#detail-close').click()
+ page.locator('#select-cases').click()
+ page.locator('.case-card').first.click()
+ if not page.locator('#share-export').is_visible():
+ page.locator('#selection-more-menu > summary').click()
+ page.locator('#share-export').click()
+ expect(page.locator('#share-dialog')).to_be_visible()
+ page.mouse.click(5, 5)
+ expect(page.locator('#share-dialog')).to_be_visible()
+ page.locator('#share-dialog-close').click()
+ # Exercise the shared dialog used by renaming and other input callers.
+ page.evaluate('''() => { import('./ui-dialogs.js').then(({promptAppText}) => {
+ window.dialogResult = 'waiting';
+ promptAppText({title:'重命名项目',value:'保留输入'}).then(v=>window.dialogResult=v);
+ }); }''')
+ expect(dialog).to_be_visible()
+ page.mouse.click(5, 5)
+ expect(dialog.locator('input')).to_have_value('保留输入')
+ dialog.locator('.app-dialog-close').click()
+ expect(dialog).not_to_be_visible()
+ # Backdrop/Escape cannot settle a pending action or lose its failure.
+ page.evaluate('''() => { import('./ui-dialogs.js').then(({showAppDialog}) => {
+ window.dialogResult='waiting';
+ showAppDialog({title:'执行中',fields:[{id:'value',value:'draft'}],onSubmit:()=>new Promise((_,reject)=>window.rejectSubmit=reject)}).then(v=>window.dialogResult=v);
+ }); }''')
+ expect(dialog).to_be_visible()
+ dialog.locator('[type="submit"]').click()
+ page.keyboard.press('Escape')
+ page.mouse.click(5, 5)
+ expect(dialog).to_be_visible()
+ assert page.evaluate('window.dialogResult') == 'waiting'
+ page.evaluate('window.rejectSubmit(new Error("保留错误和输入"))')
+ expect(dialog.locator('.app-dialog-status')).to_have_text('保留错误和输入')
+ expect(dialog.locator('input')).to_have_value('draft')
+ dialog.locator('.app-dialog-close').click()
+ expect(dialog).not_to_be_visible()
+ print({'bare_url_saved_and_reopened': True, 'input_backdrop_preserved': True, 'pending_escape_preserved': True, 'screenshot': str(shot)})
+
+if __name__ == '__main__': main()
diff --git a/test/english_interaction_states_e2e.py b/test/english_interaction_states_e2e.py
index 10a1d2f..fb1d118 100644
--- a/test/english_interaction_states_e2e.py
+++ b/test/english_interaction_states_e2e.py
@@ -129,6 +129,8 @@ def main() -> None:
library = session.open_page("library.html", wait_until="networkidle")
+ if not library.locator("#add-menu > summary").is_visible():
+ library.locator("#toolbar-more > summary").click()
library.locator("#add-menu > summary").click()
library.locator("#add-quick-note").click()
quick_note = library.locator("#promptdirector-app-dialog")
@@ -136,6 +138,8 @@ def main() -> None:
assert_no_visible_chinese(quick_note, "quick note dialog")
quick_note.get_by_role("button", name="Cancel", exact=True).click()
+ if not library.locator("#add-menu > summary").is_visible():
+ library.locator("#toolbar-more > summary").click()
library.locator("#add-menu > summary").click()
library.locator("#add-video-reference").click()
video_link = library.locator("#promptdirector-app-dialog")
@@ -153,11 +157,13 @@ def main() -> None:
library.set_viewport_size({"width": 390, "height": 800})
library.locator("#toggle-filters").click()
expect(library.locator("#filter-sidebar")).to_be_visible()
+ library.wait_for_function("() => document.querySelector('#filter-sidebar').getBoundingClientRect().left >= 0")
project_menu.locator(":scope > summary").click()
assert_no_visible_chinese(project_menu.locator(".project-menu-panel"), "project menu")
assert_panel_contains_children(project_menu.locator(".project-menu-panel"), "project menu at 390px")
project_menu.locator(":scope > summary").click()
+ library.locator('[data-sidebar-module="types"] .sidebar-module-toggle').click()
category_menu = library.locator(".content-filter-menu").first
category_menu.locator(":scope > summary").click()
assert_no_visible_chinese(category_menu.locator(".project-menu-panel"), "category menu")
@@ -171,6 +177,8 @@ def main() -> None:
assert_no_visible_chinese(library.locator("#detail-drawer"), "case details")
library.locator("#detail-close").click()
+ if not library.locator("#add-menu > summary").is_visible():
+ library.locator("#toolbar-more > summary").click()
library.locator("#add-menu > summary").click()
library.locator("#add-media").click()
expect(library.locator("#import-last-job")).to_be_visible()
diff --git a/test/fixtures/pinterest-pin-metadata.json b/test/fixtures/pinterest-pin-metadata.json
new file mode 100644
index 0000000..343c4be
--- /dev/null
+++ b/test/fixtures/pinterest-pin-metadata.json
@@ -0,0 +1,23 @@
+{
+ "entityId": "812477589050766640",
+ "title": "Wukong vs heaven",
+ "gridTitle": "Wukong vs heaven",
+ "description": " ",
+ "gridDescription": " ",
+ "createdAt": "Thu, 24 Aug 2023 11:05:00 +0000",
+ "seoDescription": "A fantasy scene featuring a figure holding a large staff with red ropes attached to it. The background includes swirling clouds and a large, menacing creature with sharp teeth. Demon, Black myth wukong, Wu kong",
+ "repinCount": 471,
+ "images_orig": {
+ "__typename": "ImageDetails",
+ "url": "https://i.pinimg.com/originals/97/ef/56/97ef5675426073cb808aa3f2ad7db5f0.jpg"
+ },
+ "images_736x": {
+ "url": "https://i.pinimg.com/736x/97/ef/56/97ef5675426073cb808aa3f2ad7db5f0.jpg",
+ "height": 1041,
+ "width": 736
+ },
+ "nativeCreator": {
+ "fullName": "ʀᴇᴅɢʀᴀᴠᴇ",
+ "username": "LastSon_"
+ }
+}
diff --git a/test/import-ui.test.js b/test/import-ui.test.js
index 5960a52..b73dfb8 100644
--- a/test/import-ui.test.js
+++ b/test/import-ui.test.js
@@ -171,7 +171,7 @@ test("shared ZIP and degraded folders salvage individual failures while verified
const folderRestore = js.slice(js.indexOf("async function restoreCompleteFolderBackup"), js.indexOf("async function importSharedLibraryPackage"));
assert.match(sharedImport, /inspectLibraryTransfer\(\{[\s\S]*?sourceType:\s*LIBRARY_TRANSFER_SOURCES\.SHARE_PACKAGE/);
assert.match(folderRestore, /sourceType:\s*envelope\.mode === "complete"[\s\S]*LIBRARY_TRANSFER_SOURCES\.COMPLETE_BACKUP[\s\S]*LIBRARY_TRANSFER_SOURCES\.RESCUE_BACKUP/);
- assert.match(folderRestore, /inspectFolderBackupEnvelope\(files\)/);
+ assert.match(folderRestore, /inspectFolderBackupEnvelope\(files,\s*\{\s*digest,\s*onProgress:/);
assert.match(folderRestore, /sourceReport:\s*envelope\.report/);
assert.match(sharedImport, /validateImage:\s*validateImportedImage/);
assert.match(folderRestore, /validateImage:\s*validateImportedImage/);
diff --git a/test/large_library_e2e.py b/test/large_library_e2e.py
index 8a4bba6..a798fbb 100644
--- a/test/large_library_e2e.py
+++ b/test/large_library_e2e.py
@@ -172,6 +172,7 @@ def main() -> None:
}, batch
assert len(analysis_requests) == 1, analysis_requests
+ library.locator('[data-sidebar-module="tags"] .sidebar-module-toggle').click()
style_facet = library.locator('.facet-filter[data-facet-id="style"]')
style_facet.locator("summary").click()
style_category = style_facet.locator('[data-facet-node-id="style.render"]')
diff --git a/test/library-case-scope.test.js b/test/library-case-scope.test.js
new file mode 100644
index 0000000..e5eafec
--- /dev/null
+++ b/test/library-case-scope.test.js
@@ -0,0 +1,34 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { libraryCaseScopes } from "../extension/library-case-scope.js";
+
+test("folder identity follows full paths, not device ids or leaf names", () => {
+ function scopes(prefix, rootName) {
+ return libraryCaseScopes({ entries: [{ id: "case" }], organizerState: { collections: [
+ { id: `${prefix}:root`, name: rootName, entryIds: [] },
+ { id: `${prefix}:child`, parentId: `${prefix}:root`, name: "素材", entryIds: ["case"] }
+ ] } }).get("case");
+ }
+ assert.equal(scopes("local", "Project A"), scopes("incoming", "project_a"));
+ assert.notEqual(scopes("local", "Project A"), scopes("incoming", "Project B"));
+});
+
+test("legacy multi-folder ownership is compared as a complete set, without mutating it", () => {
+ const state = { entries: [{ id: "a" }, { id: "b" }, { id: "c" }], organizerState: { collections: [
+ { id: "p", name: "P", entryIds: ["a", "b", "c"] },
+ { id: "q", name: "Q", entryIds: ["a", "b"] }
+ ] } };
+ const before = structuredClone(state);
+ const scopes = libraryCaseScopes(state);
+ assert.equal(scopes.get("a"), scopes.get("b"));
+ assert.notEqual(scopes.get("a"), scopes.get("c"));
+ assert.deepEqual(state, before);
+});
+
+test("identical members inside one compound retain independent identities and order", () => {
+ const scopes = libraryCaseScopes({
+ entries: [{ id: "a" }, { id: "b" }, { id: "c" }],
+ compoundCases: [{ id: "pair", memberEntryIds: ["a", "b"] }]
+ });
+ assert.equal(new Set(scopes.values()).size, 3);
+});
diff --git a/test/library-export-plan.test.js b/test/library-export-plan.test.js
index eb854d7..1785479 100644
--- a/test/library-export-plan.test.js
+++ b/test/library-export-plan.test.js
@@ -159,3 +159,30 @@ test("write plan chooses exactly one honest marker after preflight", async () =>
assert.equal(complete.files.has("rescue.json"), false);
assert.equal(rescue.files.has("complete.json"), false);
});
+
+test("rescue writes readable conflicting originals and the source manifest alongside restorable cases", async () => {
+ const { mkdtemp, mkdir, writeFile, readFile, rm } = await import("node:fs/promises");
+ const { tmpdir } = await import("node:os");
+ const { join, dirname } = await import("node:path");
+ const original = new Blob(['{"original":true}'], { type: "application/json" });
+ const conflict = new Blob(["conflicting-original"], { type: "image/webp" });
+ const sourceFiles = new Map([["library.json", original], ["images/conflict.webp", conflict]]);
+ const plan = await buildFolderBackupWritePlan({ files: new Map([["library.json", new Blob(['{"restorable":true}'])]]), sourceFiles,
+ report: { status: "partial", diagnostics: [{ reason: "duplicate_asset_id" }] } });
+ assert.equal(plan.mode, "rescue");
+ assert.equal(await plan.files.get("images/conflict.webp").text(), "conflicting-original");
+ assert.equal(plan.files.get("recovery/source-library.json"), original);
+ const directory = await mkdtemp(join(tmpdir(), "pd-backup42-"));
+ try {
+ const written = new Map();
+ for (const [path, blob] of plan.files) {
+ const target = join(directory, path);
+ await mkdir(dirname(target), { recursive: true });
+ await writeFile(target, new Uint8Array(await blob.arrayBuffer()));
+ written.set(path, new Blob([await readFile(target)], { type: blob.type }));
+ }
+ await verifyFolderRescueCompletion(plan.marker, written);
+ await writeFile(join(directory, plan.markerPath), JSON.stringify(plan.marker));
+ assert.equal(JSON.parse(await readFile(join(directory, "rescue.json"), "utf8")).files.length, 3);
+ } finally { await rm(directory, { recursive: true, force: true }); }
+});
diff --git a/test/library-folder-ownership.test.js b/test/library-folder-ownership.test.js
new file mode 100644
index 0000000..a2eedc6
--- /dev/null
+++ b/test/library-folder-ownership.test.js
@@ -0,0 +1,128 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { planFolderOwnership, planCaseCopies, needsFolderOwnershipMigration } from '../extension/library-folder-ownership.js';
+import { projectPortableMedia } from '../extension/library-portable-media.js';
+import { caseSemanticFingerprint, reconcileLibrarySemanticIdentity } from '../extension/library-semantic-identity.js';
+import { collectRetainedLocalAssetIds } from '../extension/import-staging.js';
+
+function fixture() {
+ return { entries: [{ id: 'a', title: '人工标题', text: '正文', customLabels: ['人工标签'],
+ mediaAssets: [{ id: 'asset', kind: 'image', storageMode: 'managed', assetPath: 'images/a.png', contentHash: 'a'.repeat(64) }],
+ primaryMediaId: 'asset', articleDocument: { blocks: [{ type: 'image', assetId: 'asset' }] } }],
+ organizerState: { collections: [
+ { id: 'p', name: 'P', entryIds: ['a'] }, { id: 'q', name: 'Q', entryIds: ['a'] }
+ ] }, compoundCases: [], composerSessions: [{ referenceSnapshots: [{ entryId: 'a', assetRefs: [{ assetId: 'asset' }] }] }],
+ trashState: { items: [] } };
+}
+
+test('legacy multi-folder cases retain every location and original references; conversion is idempotent', () => {
+ const source = fixture(), before = structuredClone(source);
+ const result = planFolderOwnership(source);
+ assert.deepEqual(source, before);
+ assert.equal(result.copies.length, 1);
+ assert.equal(result.state.entries.length, 2);
+ const copy = result.state.entries[1];
+ assert.deepEqual(result.state.organizerState.collections.map(c => c.entryIds), [['a'], [copy.id]]);
+ assert.equal(copy.text, source.entries[0].text);
+ assert.deepEqual(result.state.composerSessions, source.composerSessions);
+ assert.equal(needsFolderOwnershipMigration(result.state), false);
+ assert.deepEqual(planFolderOwnership(result.state).state, result.state);
+ copy.customLabels.push('副本新标签');
+ copy.articleDocument.blocks[0].assetId = 'changed';
+ assert.deepEqual(result.state.entries[0].customLabels, ['人工标签']);
+ assert.equal(result.state.entries[0].articleDocument.blocks[0].assetId, 'asset');
+});
+
+test('a compound visible through different members in legacy folders becomes complete independent compositions', () => {
+ const source = fixture();
+ source.entries.push({ id: 'b', title: '镜头二', text: '第二段', mediaAssets: [] });
+ source.compoundCases = [{ id: 'pair', title: '完整组合', memberEntryIds: ['b', 'a'], coverVisualId: 'asset', customLabels: ['组合标签'] }];
+ source.organizerState.collections[1].entryIds = ['b'];
+ const result = planFolderOwnership(source).state;
+ assert.equal(result.compoundCases.length, 2);
+ assert.deepEqual(result.compoundCases[0].memberEntryIds, ['b', 'a']);
+ assert.equal(result.compoundCases[1].title, '完整组合');
+ assert.deepEqual(result.organizerState.collections[0].entryIds, ['b', 'a']);
+ assert.deepEqual(result.organizerState.collections[1].entryIds, result.compoundCases[1].memberEntryIds);
+ assert.equal(new Set(result.organizerState.collections.flatMap(c => c.entryIds)).size, 4);
+});
+
+test('explicit copies in the same folder stay independent after content reconciliation and project-free sharing', () => {
+ const state = fixture(); state.organizerState.collections[1].entryIds = [];
+ const result = planCaseCopies(state, ['a'], 'p', { idFactory: () => 'copy' });
+ assert.equal(result.state.entries.length, 2);
+ assert.notEqual(caseSemanticFingerprint(result.state.entries[0]), caseSemanticFingerprint(result.state.entries[1]));
+ result.state.organizerState.collections = [];
+ assert.equal(reconcileLibrarySemanticIdentity(result.state).state.entries.length, 2);
+ const copy = result.state.entries.find(e => e.id === 'copy');
+ result.state.entries = [copy];
+ assert.ok(collectRetainedLocalAssetIds(result.state).has('asset'), 'deleting the original must not release the copy media');
+});
+
+test('invalid members or identity collisions abort the entire plan without changing the source', () => {
+ const source = fixture(), before = structuredClone(source);
+ assert.throws(() => planCaseCopies(source, ['a', 'missing'], 'p'));
+ assert.throws(() => planCaseCopies(source, ['a'], 'p', { idFactory: () => 'a' }));
+ assert.deepEqual(source, before);
+ source.compoundCases = [{ id: 'bad', memberEntryIds: ['a', 'missing'] }];
+ assert.throws(() => planFolderOwnership(source));
+});
+
+test('portable copies get unique media ids while paths, bytes and original state stay untouched', () => {
+ const source = planFolderOwnership(fixture()).state;
+ const copy = source.entries[1];
+ source.compoundCases = [{ id: 'copy-group', memberEntryIds: [copy.id], coverVisualId: 'asset' }];
+ source.composerSessions.push({ referenceSnapshots: [{ entryId: copy.id, referenceId: `${copy.id}:asset`, assetRefs: [{ assetId: 'asset' }] }] });
+ const before = structuredClone(source);
+ const exported = projectPortableMedia(source);
+ const assetId = exported.entries[1].mediaAssets[0].id;
+ assert.notEqual(assetId, 'asset');
+ assert.equal(exported.entries[1].primaryMediaId, assetId);
+ assert.equal(exported.entries[1].articleDocument.blocks[0].assetId, assetId);
+ assert.equal(exported.compoundCases[0].coverVisualId, assetId);
+ assert.equal(exported.composerSessions[1].referenceSnapshots[0].assetRefs[0].assetId, assetId);
+ assert.equal(exported.entries[1].mediaAssets[0].assetPath, source.entries[1].mediaAssets[0].assetPath);
+ assert.deepEqual(source, before);
+ assert.deepEqual(projectPortableMedia(exported), exported);
+});
+
+test('selection sharing retains separately selected equivalent cases after private folders are omitted', async () => {
+ const { selectLibraryPackage, mergeLibraryPackage, parseLibraryPackage } = await import('../extension/library-package.js');
+ const { renderLibraryJson } = await import('../extension/lib.js');
+ const state = parseLibraryPackage(JSON.parse(renderLibraryJson([
+ { id: 'a', title: '相同', text: '相同正文', mediaAssets: [] },
+ { id: 'b', title: '相同', text: '相同正文', mediaAssets: [] }
+ ])));
+ const share = selectLibraryPackage(state, ['a', 'b']);
+ assert.equal(share.organizerState.collections.length, 0);
+ assert.notEqual(share.entries[0].caseInstanceId, share.entries[1].caseInstanceId);
+ const imported = mergeLibraryPackage({ entries: [] }, share).state;
+ assert.equal(imported.entries.length, 2);
+ assert.equal(mergeLibraryPackage(imported, share).state.entries.length, 2);
+ assert.equal(mergeLibraryPackage(state, share).state.entries.length, 2, 'exporting then importing into the source library must not multiply cases');
+});
+
+test('a deleted shared media item has its own portable id and can be restored without colliding with the live copy', () => {
+ const source = fixture();
+ source.trashState.items = [{ id: 'trash:media:b:asset', kind: 'media', targetId: 'asset',
+ snapshot: { mediaAssets: structuredClone(source.entries[0].mediaAssets) },
+ relationships: { entryId: 'b', positions: [{ assetId: 'asset', index: 0 }], primaryMediaId: 'asset' } }];
+ const projected = projectPortableMedia(source);
+ const item = projected.trashState.items[0];
+ const id = item.snapshot.mediaAssets[0].id;
+ assert.notEqual(id, 'asset');
+ assert.equal(item.targetId, id);
+ assert.equal(item.relationships.positions[0].assetId, id);
+ assert.equal(item.relationships.primaryMediaId, id);
+ assert.equal(source.trashState.items[0].targetId, 'asset');
+});
+
+test('migration keeps a pre-existing case whose id happens to match the planned copy id', () => {
+ const source = fixture();
+ source.entries.push({ id: 'folder-copy:a:q', title: '已有的另一个案例', text: '必须保留', mediaAssets: [] });
+ const result = planFolderOwnership(source).state;
+ assert.equal(result.entries.length, 3);
+ assert.equal(result.entries.find(entry => entry.id==='folder-copy:a:q').text, '必须保留');
+ assert.notEqual(result.organizerState.collections[1].entryIds[0], 'folder-copy:a:q');
+ assert.deepEqual(planFolderOwnership(result).state, result);
+});
diff --git a/test/library-interaction-regressions.test.js b/test/library-interaction-regressions.test.js
index 4dd4abb..d443f6c 100644
--- a/test/library-interaction-regressions.test.js
+++ b/test/library-interaction-regressions.test.js
@@ -68,7 +68,7 @@ test("vision batch dialog only revives running or paused jobs and otherwise show
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\.visionBatchStart\.hidden = Boolean\(job\)/);
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/);
diff --git a/test/library-navigation.test.js b/test/library-navigation.test.js
index b669da9..555368c 100644
--- a/test/library-navigation.test.js
+++ b/test/library-navigation.test.js
@@ -65,7 +65,7 @@ test("desktop sidebar width is adjustable and persists as a bounded UI preferenc
test("share and combine are contextual actions after entering selection mode", () => {
const selection = html.slice(html.indexOf('id="gallery-heading"'), html.indexOf('<p id="feedback"'));
- assert.match(selection, /id="selection-add-project"/);
+ assert.match(selection, /id="selection-copy-project"/);
assert.match(selection, /id="selection-new-project"/);
assert.match(selection, /id="selection-combine"/);
assert.match(selection, /id="selection-analyze"/);
diff --git a/test/library-package.test.js b/test/library-package.test.js
index 8b14074..13ea49d 100644
--- a/test/library-package.test.js
+++ b/test/library-package.test.js
@@ -1413,3 +1413,21 @@ test("backup media kinds retain large temporary images, videos and generated vid
assert.equal(parsed.assets.get("result:video").size, 16);
assert.throws(() => parseLibraryPackage(data, files, { ...limits, maxVideoBytes: 12 }), /超过/);
});
+
+
+test("folder restore preserves skill attachments reported with the desktop registered MIME", async () => {
+ const data = packageData([], catalog());
+ data.version = 5;
+ const path = "attachments/skill-case/original.skill";
+ const blob = new Blob(["original archive bytes"], { type: "application/vnd.openai.codex.skill" });
+ data.entries = [{
+ ...entry("skill-case"), hasScreenshot: undefined, screenshotPath: undefined,
+ mediaAssets: [{ id: "skill-original", kind: "attachment", storageMode: "managed", sourceTitle: "original.skill",
+ sourceFormat: "skill", mimeType: "application/zip", byteSize: blob.size, assetPath: path }]
+ }];
+ const { parseCompleteFolderBackup } = await import("../extension/library-package.js");
+ const restored = await parseCompleteFolderBackup(data, new Map([[path, blob]]));
+ assert.equal(restored.entries[0].mediaAssets.length, 1);
+ assert.equal(restored.assets.get("skill-original"), blob);
+ assert.equal(restored.importDiagnostics.length, 0);
+});
diff --git a/test/library-selection.test.js b/test/library-selection.test.js
index 8f07a1a..1b88129 100644
--- a/test/library-selection.test.js
+++ b/test/library-selection.test.js
@@ -114,7 +114,7 @@ test("free-tag batch payload expands compounds and normalizes optional labels",
assert.deepEqual(withoutLabels.customLabels, []);
});
-test("project batch payload requires explicit add, remove, or move semantics", () => {
+test("project batch payload requires explicit copy, remove, or move semantics with a legacy add alias", () => {
const added = buildLibraryBatchPayload(["entry:a"], [], {
type: LIBRARY_BATCH_ACTIONS.setProject,
collectionId: " collection:campaign ",
@@ -151,7 +151,7 @@ test("project batch payload requires explicit add, remove, or move semantics", (
type: LIBRARY_BATCH_ACTIONS.setProject,
collectionId: "collection:campaign"
}),
- /明确选择加入、移出或移动/
+ /明确选择复制、移出或移动/
);
});
diff --git a/test/library-semantic-identity.test.js b/test/library-semantic-identity.test.js
index c22d253..f317df8 100644
--- a/test/library-semantic-identity.test.js
+++ b/test/library-semantic-identity.test.js
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { reconcileLibrarySemanticIdentity } from "../extension/library-semantic-identity.js";
-test("complete semantic duplicates converge to one stable case and keep every project relationship", () => {
+test("complete duplicates within one folder converge while preserving creative references", () => {
const first = semanticEntry("case:a", "asset:a", "a".repeat(64));
const duplicate = semanticEntry("case:b", "asset:b", "a".repeat(64));
first.creationMeta = { sourceEntryIds: ["case:a"] };
@@ -14,14 +14,8 @@ test("complete semantic duplicates converge to one stable case and keep every pr
const result = reconcileLibrarySemanticIdentity({
entries: [duplicate, distinct, first],
organizerState: { collections: [
- { id: "project:a", entryIds: ["case:a"] },
- { id: "project:b", entryIds: ["case:b"] }
+ { id: "project:a", name: "One folder", entryIds: ["case:a", "case:b"] }
] },
- compoundCases: [{
- id: "compound:one",
- memberEntryIds: ["case:b", "case:c"],
- coverVisualId: "asset:b"
- }],
composerSessions: [{
id: "session:one",
referenceSnapshots: [{
@@ -35,11 +29,8 @@ test("complete semantic duplicates converge to one stable case and keep every pr
assert.equal(result.changed, true);
assert.deepEqual(result.state.entries.map((entry) => entry.id), ["case:a", "case:c"]);
assert.deepEqual(result.state.organizerState.collections.map((project) => project.entryIds), [
- ["case:a"],
["case:a"]
]);
- assert.deepEqual(result.state.compoundCases[0].memberEntryIds, ["case:a", "case:c"]);
- assert.equal(result.state.compoundCases[0].coverVisualId, "asset:a");
assert.equal(result.state.composerSessions[0].referenceSnapshots[0].entryId, "case:a");
assert.equal(result.state.composerSessions[0].referenceSnapshots[0].referenceId, "case:a:asset:a");
assert.equal(result.state.composerSessions[0].referenceSnapshots[0].assetRefs[0].assetId, "asset:a");
@@ -73,3 +64,22 @@ function semanticEntry(id, assetId, contentHash) {
primaryMediaId: assetId
};
}
+
+for (const kind of ["different folders", "compound members", "assigned and unassigned"]) {
+ test(`sync must retain independent cases: ${kind}`, () => {
+ const state = {
+ entries: [semanticEntry("a", "asset:a", "a".repeat(64)), semanticEntry("b", "asset:b", "a".repeat(64))],
+ organizerState: { collections: kind === "different folders" ? [
+ { id: "p:a", name: "A", entryIds: ["a"] },
+ { id: "p:b", name: "B", entryIds: ["b"] }
+ ] : kind === "assigned and unassigned" ? [{ id: "p:a", name: "A", entryIds: ["a"] }] : [] },
+ compoundCases: kind === "compound members" ? [{ id: "pair", memberEntryIds: ["a", "b"] }] : [],
+ composerSessions: [{ referenceSnapshots: [{ entryId: "b", assetRefs: [{ assetId: "asset:b" }] }] }]
+ };
+ const before = structuredClone(state);
+ const result = reconcileLibrarySemanticIdentity(state);
+ assert.equal(result.changed, false);
+ assert.deepEqual(result.state, before);
+ assert.deepEqual(state, before);
+ });
+}
diff --git a/test/library-sorting-ui.test.js b/test/library-sorting-ui.test.js
index b0799bc..176b5e8 100644
--- a/test/library-sorting-ui.test.js
+++ b/test/library-sorting-ui.test.js
@@ -19,7 +19,7 @@ test("library exposes four case sorts and allows project management without a mo
assert.doesNotMatch(html, /id="project-sort"|最近创建|项目排序/);
assert.match(html, /id="collapse-projects"[^>]*aria-label="全部折叠"/);
- assert.match(html, /id="project-search"/);
+ assert.doesNotMatch(html, /id="project-search"/);
});
test("sidebar derives an unassigned workspace without persisting smart or import-batch views", () => {
diff --git a/test/library-transfer.test.js b/test/library-transfer.test.js
index 2ff73cc..4e9ca77 100644
--- a/test/library-transfer.test.js
+++ b/test/library-transfer.test.js
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import { createDefaultFacetCatalog } from "../extension/facets.js";
import { createDefaultTaxonomy, SCHEMA_VERSION } from "../extension/taxonomy.js";
+import { selectProjectPackage } from "../extension/library-package.js";
import {
LIBRARY_TRANSFER_MODES,
LIBRARY_TRANSFER_SOURCES,
@@ -507,7 +508,7 @@ test("safe merge can adopt the incoming conflict and move that case to the incom
assert.equal(plan.conflicts[0].resolution, "use-incoming");
});
-test("safe merge deduplicates identical meaning across different ids and combines project membership", async () => {
+test("safe merge preserves independent cases with identical content in different folders", async () => {
const currentInspection = await inspectLibraryTransfer({
sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP,
library: portablePackage([portableTextEntry("case:local", "同一内容")])
@@ -539,11 +540,11 @@ test("safe merge deduplicates identical meaning across different ids and combine
options: { mode: LIBRARY_TRANSFER_MODES.SAFE_MERGE }
});
- assert.equal(plan.targetState.entries.length, 1);
- assert.equal(plan.mappings.entryIds["case:incoming"], "case:local");
+ assert.equal(plan.targetState.entries.length, 2);
+ assert.equal(plan.mappings.entryIds["case:incoming"], "case:incoming");
assert.deepEqual(
plan.targetState.organizerState.collections.map((collection) => collection.entryIds),
- [["case:local"], ["case:local"]]
+ [["case:local"], ["case:incoming"]]
);
});
@@ -667,7 +668,7 @@ test("a share-package batch produces one replayable plan and keeps each resource
assert.equal(replay.planToken, first.planToken);
});
-test("a share-package batch deduplicates identical cases and combines project membership", async () => {
+test("a share-package batch preserves identical content in separate folders", async () => {
const firstSource = portablePackage([portableTextEntry("case:first", "同一内容")]);
firstSource.organizerState.collections = [{
id: "collection:first",
@@ -692,12 +693,12 @@ test("a share-package batch deduplicates identical cases and combines project me
const plan = planLibraryTransferBatch({ currentState: portablePackage([]), inspections });
assert.equal(plan.canApply, true);
- assert.equal(plan.targetState.entries.length, 1);
+ assert.equal(plan.targetState.entries.length, 2);
assert.deepEqual(plan.targetState.organizerState.collections.map((collection) => collection.entryIds), [
["case:first"],
- ["case:first"]
+ ["case:second"]
]);
- assert.equal(plan.skippedCount, 1);
+ assert.equal(plan.skippedCount, 0);
});
test("a package-to-package same-id conflict blocks the batch until explicitly resolved", async () => {
@@ -874,3 +875,152 @@ function portableSkill(id, assetId, callName) {
updatedAt: "2026-08-27T00:00:00.000Z"
};
}
+
+for (const sourceType of Object.values(LIBRARY_TRANSFER_SOURCES)) {
+ test(`${sourceType}: shared original media must survive backup inspection in both cases`, async () => {
+ const source = portablePackage([portableEntry("case:first", "image:shared"), portableEntry("case:second", "image:shared")]);
+ const files = new Map(source.entries.map(entry => [entry.mediaAssets[0].assetPath, new Blob(["same"], { type: "image/webp" })]));
+ const before = structuredClone(source);
+ const inspected = await inspectLibraryTransfer({ sourceType, library: source, files });
+ assert.equal(inspected.report.status, "ready");
+ assert.equal(inspected.state.entries.length, 2);
+ assert.ok(inspected.state.entries.every(entry => entry.mediaAssets.length === 1));
+ assert.equal(await inspected.resources.assets.get("image:shared").text(), "same");
+ assert.deepEqual(source, before);
+ });
+}
+
+test("conflicting media must not block healthy cases or silently overwrite equal-sized original bytes", async () => {
+ const source = portablePackage([portableEntry("case:first", "image:shared"), portableEntry("case:conflict", "image:shared"), portableEntry("case:good", "image:good")]);
+ const files = new Map(source.entries.map((entry, index) => [entry.mediaAssets[0].assetPath, new Blob([index === 1 ? "diff" : "same"], { type: "image/webp" })]));
+ const inspected = await inspectLibraryTransfer({ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP, library: source, files });
+ assert.equal(inspected.report.status, "partial");
+ assert.equal(inspected.state.entries.length, 3);
+ assert.equal(inspected.state.entries[1].text, "正文");
+ assert.equal(inspected.state.entries[2].mediaAssets.length, 1);
+ assert.equal(await inspected.resources.assets.get("image:shared").text(), "same");
+ assert.ok(inspected.report.diagnostics.some(item => item.entryId === "case:conflict" && item.reason === "duplicate_asset_id"));
+});
+
+for (const mode of Object.values(LIBRARY_TRANSFER_MODES)) {
+ test(`${mode}: restoring shared originals retains a resource write for every case reference`, async () => {
+ const source = portablePackage([portableEntry("case:first", "image:shared"), portableEntry("case:second", "image:shared")]);
+ source.entries[1].text = "独立的第二份提示词";
+ const files = new Map(source.entries.map(entry => [entry.mediaAssets[0].assetPath, new Blob(["same"], { type: "image/webp" })]));
+ const inspection = await inspectLibraryTransfer({ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP, library: source, files });
+ const current = portablePackage([portableEntry("case:local", "image:shared")]);
+ const plan = planLibraryTransfer({ currentState: current, inspection, options: { mode } });
+ const restored = plan.targetState.entries.filter(entry => entry.id !== "case:local");
+ assert.equal(restored.length, 2);
+ assert.equal(restored[0].mediaAssets[0].id, restored[1].mediaAssets[0].id);
+ for (const entry of restored) {
+ assert.ok(plan.resourceWrites.some(write => write.targetId === entry.mediaAssets[0].id));
+ }
+ const replay = planLibraryTransfer({ currentState: current, inspection, options: { mode, preferredPlan: plan.context } });
+ assert.deepEqual(replay.targetState, plan.targetState);
+ });
+}
+
+test("active and trashed cases sharing an original both survive merge and exact restore", async () => {
+ const source = portablePackage([portableEntry("case:active", "image:shared")]);
+ const trashed = trashedEntry("case:trash", "回收站独立正文");
+ trashed.snapshot = portableEntry("case:trash", "image:shared");
+ source.trashState.items = [trashed];
+ const files = new Map([source.entries[0], trashed.snapshot].map(entry => [entry.mediaAssets[0].assetPath, new Blob(["same"], { type: "image/webp" })]));
+ const inspection = await inspectLibraryTransfer({ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP, library: source, files });
+ assert.equal(inspection.report.status, "ready");
+ for (const mode of Object.values(LIBRARY_TRANSFER_MODES)) {
+ const plan = planLibraryTransfer({ currentState: portablePackage([portableTextEntry("local", "保留本机")]), inspection, options: { mode } });
+ const active = plan.targetState.entries.find(entry => entry.id === "case:active");
+ const trash = plan.targetState.trashState.items[0].snapshot;
+ assert.equal(active.mediaAssets[0].id, trash.mediaAssets[0].id);
+ assert.ok(plan.resourceWrites.some(write => write.targetId === trash.mediaAssets[0].id));
+ }
+});
+
+test("a missing first occurrence does not discard a later readable original using the same id", async () => {
+ const source = portablePackage([portableEntry("case:missing", "image:shared"), portableEntry("case:good", "image:shared")]);
+ const files = new Map([[source.entries[1].mediaAssets[0].assetPath, new Blob(["good"], { type: "image/webp" })]]);
+ const inspection = await inspectLibraryTransfer({ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP, library: source, files });
+ assert.equal(inspection.state.entries[1].mediaAssets.length, 1);
+ assert.equal(await inspection.resources.assets.get("image:shared").text(), "good");
+});
+
+test("exact restore preserves intentionally separate identical cases and their project memberships", async () => {
+ const source = portablePackage([portableEntry("case:first", "image:shared"), portableEntry("case:second", "image:shared")]);
+ const { sha256Blob } = await import("../extension/blob-digest.js");
+ const blob = new Blob(["same"], { type: "image/webp" });
+ for (const entry of source.entries) entry.mediaAssets[0].contentHash = await sha256Blob(blob);
+ source.organizerState.collections = source.entries.map(entry => ({ id: `project:${entry.id}`, name: entry.id, entryIds: [entry.id] }));
+ const files = new Map(source.entries.map(entry => [entry.mediaAssets[0].assetPath, blob]));
+ const inspection = await inspectLibraryTransfer({ sourceType: LIBRARY_TRANSFER_SOURCES.COMPLETE_BACKUP, library: source, files });
+ const plan = planLibraryTransfer({ inspection, options: { mode: LIBRARY_TRANSFER_MODES.EXACT_REPLACE } });
+ assert.deepEqual(plan.targetState.entries.map(entry => entry.id), ["case:first", "case:second"]);
+ assert.deepEqual(plan.targetState.organizerState.collections.map(project => project.entryIds), [["case:first"], ["case:second"]]);
+});
+
+for (const sameParent of [true, false]) {
+ test(`import compares complete folder paths and ${sameParent ? "skips same-folder repeats" : "preserves copies under different parents"}`, async () => {
+ function source(id, prefix, parentName) {
+ const value = portablePackage([portableTextEntry(id, "相同完整正文")]);
+ value.organizerState.collections = [
+ { id: `${prefix}:root`, name: parentName, parentId: null, entryIds: [] },
+ { id: `${prefix}:child`, name: "素材", parentId: `${prefix}:root`, entryIds: [id] }
+ ];
+ return value;
+ }
+ const current = (await inspectLibraryTransfer({ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,
+ library: source("local", "local", "项目A") })).state;
+ const inspection = await inspectLibraryTransfer({ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,
+ library: source("incoming", "incoming", sameParent ? "项目A" : "项目B") });
+ const before = structuredClone(current);
+ const plan = planLibraryTransfer({ currentState: current, inspection });
+ assert.equal(plan.targetState.entries.length, sameParent ? 1 : 2);
+ assert.equal(plan.skippedCount, sameParent ? 1 : 0);
+ assert.deepEqual(current, before);
+ const replay = planLibraryTransfer({ currentState: plan.targetState, inspection });
+ assert.equal(replay.targetState.entries.length, plan.targetState.entries.length, "reimport must not multiply cases");
+ });
+}
+
+test("import does not collapse equal-content compound members or lose the composition", async () => {
+ const source = portablePackage([portableTextEntry("a", "同一内容"), portableTextEntry("b", "同一内容")]);
+ source.compoundCases = [{ id: "pair", title: "有意重复的分镜", memberEntryIds: ["b", "a"],
+ customLabels: ["导演标注"], createdAt: "2026-09-23T00:00:00.000Z" }];
+ const inspection = await inspectLibraryTransfer({ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE, library: source });
+ const plan = planLibraryTransfer({ currentState: portablePackage([]), inspection });
+ assert.equal(plan.targetState.entries.length, 2);
+ assert.deepEqual(plan.targetState.compoundCases[0].memberEntryIds, ["b", "a"]);
+ assert.equal(plan.targetState.compoundCases[0].title, "有意重复的分镜");
+ assert.deepEqual(plan.targetState.compoundCases[0].customLabels, ["导演标注"]);
+});
+
+test("project sharing round trip retains equal-content folder copies and both original media writes", async () => {
+ const a = portableEntry("a", "asset:a");
+ const b = portableEntry("b", "asset:b");
+ for (const entry of [a, b]) {
+ entry.mediaAssets[0].sourceTitle = "same.webp";
+ entry.mediaAssets[0].contentHash = "a".repeat(64);
+ }
+ const source = portablePackage([a, b]);
+ source.organizerState.collections = [
+ { id: "root", name: "分享项目", entryIds: [] },
+ { id: "first", name: "目录一", parentId: "root", entryIds: ["a"] },
+ { id: "second", name: "目录二", parentId: "root", entryIds: ["b"] }
+ ];
+ const blob = new Blob(["good"], { type: "image/webp" });
+ const exported = selectProjectPackage(source, "root");
+ const inspection = await inspectLibraryTransfer({
+ sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,
+ library: exported,
+ files: new Map([a, b].map(entry => [entry.mediaAssets[0].assetPath, blob]))
+ });
+ const plan = planLibraryTransfer({ currentState: portablePackage([]), inspection });
+ assert.equal(plan.targetState.entries.length, 2);
+ assert.equal(plan.resourceWrites.length, 2);
+ for (const write of plan.resourceWrites) {
+ assert.equal(await inspection.resources.assets.get(write.sourceId).text(), "good");
+ }
+ assert.deepEqual(plan.targetState.organizerState.collections.map(item => item.entryIds), [[], ["a"], ["b"]]);
+ assert.equal(planLibraryTransfer({ currentState: plan.targetState, inspection }).targetState.entries.length, 2);
+});
diff --git a/test/library_132_e2e.py b/test/library_132_e2e.py
index 11e2826..4fa8890 100644
--- a/test/library_132_e2e.py
+++ b/test/library_132_e2e.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import tempfile
+import re
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError, expect, sync_playwright
@@ -125,6 +126,7 @@ def main() -> None:
const actions = document.querySelector('.top-actions').getBoundingClientRect();
return {
viewportWidth: innerWidth,
+ padding: parseFloat(getComputedStyle(document.querySelector(".topbar")).paddingRight),
searchLeft: search.left,
searchRight: search.right,
actionsLeft: actions.left,
@@ -134,10 +136,12 @@ def main() -> None:
}"""
)
assert header["documentWidth"] <= header["viewportWidth"], (width, header)
- assert header["searchLeft"] >= 10
- assert header["searchRight"] <= header["viewportWidth"] - 10
- assert header["actionsLeft"] >= 10
- assert header["actionsRight"] <= header["viewportWidth"] - 10
+ assert header["searchLeft"] >= header["padding"]
+ assert header["searchRight"] <= header["viewportWidth"] - header["padding"]
+ assert header["actionsLeft"] >= header["padding"]
+ assert header["actionsRight"] <= header["viewportWidth"] - header["padding"]
+ if not library.locator("#add-menu > summary").is_visible():
+ library.locator("#toolbar-more > summary").click()
library.locator("#add-menu > summary").click()
add_menu = library.evaluate(
"""() => {
@@ -163,6 +167,8 @@ def main() -> None:
assert add_menu["panelRight"] <= add_menu["viewportWidth"] - 10, (width, add_menu)
assert add_menu["panelTop"] >= add_menu["headerBottom"] - 1, (width, add_menu)
assert add_menu["panelBottom"] <= add_menu["viewportHeight"] - 10, (width, add_menu)
+ if not library.locator("#add-menu > summary").is_visible():
+ library.locator("#toolbar-more > summary").click()
library.locator("#add-menu > summary").click()
library.set_viewport_size({"width": 1280, "height": 820})
library.reload()
@@ -172,6 +178,7 @@ def main() -> None:
gallery_top_before_filter = library.locator(".gallery-shell").evaluate(
"element => element.getBoundingClientRect().top"
)
+ library.locator('[data-sidebar-module="types"] .sidebar-module-toggle').click()
image_filter = library.locator("#content-filters").get_by_role("button", name="图片案例 100", exact=True)
image_filter.click()
expect(image_filter).to_have_attribute("aria-pressed", "true")
@@ -350,12 +357,12 @@ def main() -> None:
"""() => {
const topbar = document.querySelector('.topbar').getBoundingClientRect();
const toolbar = document.querySelector('#gallery-heading').getBoundingClientRect();
- return {topbarBottom: topbar.bottom, toolbarTop: toolbar.top, shellPadding: parseFloat(getComputedStyle(document.querySelector(".gallery-shell")).paddingTop)};
+ return {topbarTop: topbar.top, topbarBottom: topbar.bottom, toolbarTop: toolbar.top, toolbarBottom: toolbar.bottom};
}"""
)
- assert abs(selection_geometry["toolbarTop"] - selection_geometry["topbarBottom"] - selection_geometry["shellPadding"]) <= 1, selection_geometry
+ assert selection_geometry["toolbarTop"] >= selection_geometry["topbarTop"] and selection_geometry["toolbarBottom"] <= selection_geometry["topbarBottom"], selection_geometry
library.evaluate("scrollTo(0, 100)")
- library.wait_for_function("Math.abs(document.querySelector('#gallery-heading').getBoundingClientRect().top - document.querySelector('.topbar').getBoundingClientRect().bottom) <= 1")
+ library.wait_for_function("() => { const bar = document.querySelector('.topbar').getBoundingClientRect(); const heading = document.querySelector('#gallery-heading').getBoundingClientRect(); return heading.top >= bar.top && heading.bottom <= bar.bottom; }")
library.evaluate("scrollTo(0, 0)")
library.screenshot(path="/tmp/prompt-director-132-project-selection.png")
library.locator("#search-input").fill("Prompt")
@@ -366,7 +373,7 @@ def main() -> None:
)
library.locator("#load-more").click()
expect(library.locator(".case-card[data-entry-id='case-099']")).to_have_class(
- "case-card share-selectable selected-for-share"
+ re.compile(r"\bshare-selectable\s+selected-for-share\b")
)
selected_position_after_append = library.locator(".case-card[data-entry-id='case-099']").evaluate(
"card => { const rect = card.getBoundingClientRect(); return {x: rect.x + scrollX, y: rect.y + scrollY}; }"
diff --git a/test/library_browse_return_e2e.py b/test/library_browse_return_e2e.py
index f14e93b..8753212 100644
--- a/test/library_browse_return_e2e.py
+++ b/test/library_browse_return_e2e.py
@@ -27,7 +27,9 @@ def main() -> None:
else:
library.locator(f'[data-collection-id="{project_id}"] .project-filter').click()
library.locator("#search-input").fill("雨夜")
+ library.locator('#toolbar-more > summary').click()
library.locator("#gallery-sort").select_option("title")
+ library.locator('#toolbar-more > summary').click()
# Scroll to a case beyond the first batch, not just within the initial viewport.
while library.locator("#case-list > .case-card").count() <= 60:
previous = library.locator("#case-list > .case-card").count()
@@ -35,6 +37,7 @@ def main() -> None:
library.wait_for_function("count => document.querySelectorAll('#case-list > .case-card').length > count", arg=previous)
library.locator("#case-list > .case-card").nth(60).scroll_into_view_if_needed()
library.wait_for_function("scrollY > innerHeight")
+ library.locator('#toolbar-more > summary').click()
library.locator("#start-compose").click()
library.wait_for_url("**/composer.html*")
saved = library.evaluate("JSON.parse(sessionStorage.getItem('promptDirector.libraryReturn'))")
@@ -49,6 +52,7 @@ def main() -> None:
assert library.locator("#case-list > .case-card").count() > 24
# A project deleted while away must resolve to the library, not a phantom project.
+ library.locator('#toolbar-more > summary').click()
library.locator("#start-compose").click()
library.wait_for_url("**/composer.html*")
await_result = library.evaluate("""async () => {
diff --git a/test/library_browse_views_e2e.py b/test/library_browse_views_e2e.py
new file mode 100644
index 0000000..15066cb
--- /dev/null
+++ b/test/library_browse_views_e2e.py
@@ -0,0 +1,208 @@
+"""Two views preserve cases, navigation and selection without widening the sidebar."""
+from pathlib import Path
+import tempfile
+from playwright.sync_api import expect
+from e2e_support import extension_session, base_entry
+
+
+def main():
+ output = Path(tempfile.gettempdir()) / 'pd-browse18-evidence'
+ output.mkdir(exist_ok=True)
+ long_name = '非常长的项目名称LongProjectNameWithoutSpaces' * 4
+ entries = [base_entry('browse-a', '根项目直属案例', 'root prompt', 'content:prompt:image', 0),
+ base_entry('browse-b', '子项目案例', 'child prompt', 'content:prompt:image', 1),
+ base_entry('browse-c', '孙项目案例', 'grandchild prompt', 'content:prompt:image', 2)]
+ projects = [dict(id='root', name=long_name, parentId=None, entryIds=['browse-a'], order=0, visibility='library'),
+ dict(id='child', name=long_name, parentId='root', entryIds=['browse-b','browse-a'], order=0, visibility='library'),
+ dict(id='grand', name='孙项目', parentId='child', entryIds=['browse-c'], order=0, visibility='library')]
+ projects += [dict(id=f'sibling-{i}', name=f'普通项目 {i}', parentId=None, entryIds=[], order=i+1, visibility='library') for i in range(6)]
+ with extension_session('pd-browse18-', viewport={'width':1440,'height':900}) as session:
+ setup = session.open_page('collector.html')
+ session.seed_storage(setup, {'entries': entries, 'organizerState': {'version':1, 'collections':projects}, 'uiPreferences': {'locale':'zh-CN','theme':'dark','motion':'reduced'}})
+ page = session.open_page('library.html', wait_until='networkidle')
+ page.locator('.project-row[data-collection-id="root"] .project-filter').click()
+ expect(page.locator('#case-list .case-card')).to_have_count(1)
+ page.locator('#include-subprojects').uncheck()
+ expect(page.locator('#case-list .case-card')).to_have_count(1)
+ toolbar_geometry = """() => [...document.querySelectorAll('#browse-scope, [data-gallery-view], #gallery-sort, #manage-case-order, #select-cases')].map(el => {
+ const r=el.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height};
+ })"""
+ before_scope = page.evaluate(toolbar_geometry)
+ page.locator('#manage-case-order').click()
+ expect(page.locator('#select-cases')).to_be_visible()
+ expect(page.locator('#select-cases')).to_be_disabled()
+ assert page.evaluate(toolbar_geometry) == before_scope
+ page.locator('#manage-case-order').click()
+ page.locator('#gallery-sort').select_option('added-desc')
+ expect(page.locator('#select-cases')).to_be_enabled()
+ assert page.evaluate(toolbar_geometry) == before_scope
+ page.locator('#include-subprojects').check()
+ expect(page.locator('#case-list .case-card')).to_have_count(4)
+ expect(page.locator('#manage-case-order')).to_be_visible()
+ expect(page.locator('#manage-case-order')).to_be_disabled()
+ assert page.evaluate(toolbar_geometry) == before_scope
+ page.locator('#browse-scope span').dblclick()
+ assert page.evaluate('getSelection().toString()') == ''
+ assert page.locator('#search-input').evaluate('el => getComputedStyle(el).userSelect') == 'text'
+ assert page.locator('.case-row-title').first.evaluate('el => getComputedStyle(el).userSelect') == 'none'
+ page.locator('#include-subprojects').check()
+ assert page.evaluate(toolbar_geometry) == before_scope
+ for button in page.locator('[data-gallery-view]').all():
+ assert not button.inner_text().strip()
+ assert button.get_attribute('aria-label')
+
+ for mode in ['list','waterfall','list']:
+ page.locator(f'[data-gallery-view="{mode}"]').click()
+ expect(page.locator(f'[data-gallery-view="{mode}"]')).to_have_attribute('aria-pressed','true')
+ expect(page.locator('#case-list .case-card')).to_have_count(4)
+ expect(page.locator('#project-section')).to_be_visible()
+ page.locator('#search-input').fill('grandchild')
+ expect(page.locator('#case-list .case-card')).to_have_count(1)
+ page.locator('#search-input').fill('no-result-for-this-query')
+ expect(page.locator('#case-list .case-card')).to_have_count(0)
+ expect(page.locator('#empty-state')).to_be_visible()
+ page.locator('#search-input').fill('')
+ expect(page.locator('#case-list .case-card')).to_have_count(4)
+ page.screenshot(path=str(output / f'desktop-{mode}.png'))
+ if mode == 'list': page.locator('#gallery-view-controls').screenshot(path=str(output / 'view-controls.png'))
+ page.locator('#include-subprojects').uncheck()
+ page.locator('.project-folder-card[data-collection-id="child"]').click()
+ expect(page.locator('#case-list .case-card')).to_have_count(2)
+ page.locator('.project-folder-card[data-collection-id="grand"]').click()
+ expect(page.locator('#case-list .case-card')).to_have_count(1)
+ page.locator('#browse-breadcrumb [data-project-id="root"]').click()
+ expect(page.locator('#case-list .case-card')).to_have_count(1)
+ expect(page.locator('#project-folder-list .project-menu')).to_have_count(0)
+ folder = page.locator('.project-folder-card').first
+ before_folder = folder.bounding_box()
+ folder.hover()
+ assert folder.bounding_box() == before_folder
+ expect(folder).to_have_class(__import__('re').compile('.*button-secondary.*'))
+ page.evaluate('() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))')
+ folder_colors = folder.evaluate("""el => {
+ const probe=document.createElement('span');probe.style.backgroundColor='var(--hover)';el.append(probe);
+ const expected=getComputedStyle(probe).backgroundColor;probe.remove();
+ return {expected,actual:getComputedStyle(el).backgroundColor};
+ }""")
+ assert folder_colors['actual'] == folder_colors['expected'], folder_colors
+ folder.focus()
+ assert folder.bounding_box() == before_folder
+ page.screenshot(path=str(output / 'folder-focus.png'))
+ page.locator('.project-row[data-collection-id="child"] .project-menu summary').click()
+ expect(page.locator('.project-row[data-collection-id="child"] .project-menu[open]')).to_contain_text('重命名')
+ page.locator('.project-row[data-collection-id="child"] .project-menu summary').click()
+ page.locator('#include-subprojects').check()
+ page.locator('[data-gallery-view="list"]').click()
+ sidebar = page.locator('#filter-sidebar').bounding_box()
+ project_geometry = """() => [...document.querySelectorAll('.project-row')].map(row => {
+ const r = row.getBoundingClientRect(), label = row.querySelector('.project-filter').getBoundingClientRect();
+ return {id: row.dataset.collectionId, x:r.x, y:r.y, width:r.width, height:r.height, nameWidth:label.width};
+ })"""
+ before_rows = page.evaluate(project_geometry)
+ page.locator('#select-cases').click()
+ page.locator('#case-list .case-card').first.click()
+ expect(page.locator('#case-list .selected-for-share')).to_have_count(1)
+ assert page.locator('#filter-sidebar').bounding_box()['width'] == sidebar['width']
+ after_rows = page.evaluate(project_geometry)
+ assert before_rows == after_rows, {'before':before_rows, 'after':after_rows}
+ icon_sizes = page.evaluate("""() => ['[data-gallery-view="waterfall"] .ui-icon', '[data-gallery-view="list"] .ui-icon', '#select-cases .ui-icon'].map(selector => {
+ const css=getComputedStyle(document.querySelector(selector)); return [css.width,css.height,css.strokeWidth];
+ })""")
+ assert icon_sizes[0] == icon_sizes[1] == icon_sizes[2], icon_sizes
+ page.screenshot(path=str(output / 'desktop-management.png'))
+ page.locator('#share-cancel').click()
+ page.locator('#case-list .case-card').first.click()
+ expect(page.locator('#detail-drawer')).to_have_attribute('aria-hidden','false')
+ assert page.locator('#detail-content').evaluate('el => getComputedStyle(el).userSelect') != 'none'
+ page.keyboard.press('Escape')
+ page.locator('#include-subprojects').uncheck()
+ browse_geometry = """() => ['.gallery-heading','#project-folder-list','#case-list','#case-list .case-card'].map(selector => {
+ const r=document.querySelector(selector).getBoundingClientRect(); return {selector,x:r.x,y:r.y,width:r.width,height:r.height};
+ })"""
+ for width in [1440,900,390]:
+ page.set_viewport_size({'width':width,'height':844})
+ for mode in ['waterfall','list']:
+ if width <= 1100: page.locator('#toolbar-more > summary').click()
+ page.locator(f'[data-gallery-view="{mode}"]').click()
+ page.evaluate('() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))')
+ assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), (width,mode)
+ for name in page.locator('.project-folder-name').all():
+ assert name.evaluate('el => el.scrollWidth <= el.clientWidth + 1')
+ page.screenshot(path=str(output / f'{width}-{mode}.png'))
+ assert page.locator('.gallery-heading').bounding_box()['height'] <= 53
+ scope_box = page.locator('#browse-scope').bounding_box()
+ controls_box = page.locator('#gallery-view-controls').bounding_box()
+ if width > 1100:
+ assert abs(scope_box['y'] + scope_box['height']/2 - controls_box['y'] - controls_box['height']/2) <= 1
+ else:
+ assert scope_box['x'] >= 0 and scope_box['x'] + scope_box['width'] <= width
+ assert controls_box['y'] <= scope_box['y'] < controls_box['y'] + controls_box['height']
+ before_browse = page.evaluate(browse_geometry)
+ page.locator('#select-cases').click()
+ assert page.evaluate(browse_geometry) == before_browse, ('enter management',width,mode,before_browse,page.evaluate(browse_geometry))
+ page.locator('#case-list .case-card').first.click()
+ assert page.evaluate(browse_geometry) == before_browse, ('select case',width,mode,before_browse,page.evaluate(browse_geometry))
+ assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), ('selection',width,mode)
+ page.screenshot(path=str(output / f'{width}-{mode}-management.png'))
+ page.locator('#share-cancel').click()
+ assert page.evaluate(browse_geometry) == before_browse, ('exit management',width,mode)
+ page.reload(wait_until='networkidle')
+ expect(page.locator('[data-gallery-view="list"]')).to_have_attribute('aria-pressed','true')
+ # Theme/locale switches preserve browse preferences.
+ page.evaluate("async () => { const {updateUiPreferences} = await import(chrome.runtime.getURL('i18n.js')); const {uiPreferences} = await chrome.storage.local.get('uiPreferences'); await updateUiPreferences({...uiPreferences, locale:'en',theme:'light'}); }")
+ page.wait_for_load_state('networkidle')
+ expect(page.locator('[data-gallery-view="list"]')).to_have_attribute('aria-pressed','true')
+ expect(page.locator('[data-gallery-view="list"]')).to_have_attribute('title','List')
+ page.screenshot(path=str(output / '390-light-en-list.png'))
+ english_before = page.evaluate(browse_geometry)
+ page.locator('#toolbar-more > summary').click()
+ page.locator('#select-cases').click()
+ page.locator('#case-list .case-card').first.click()
+ assert page.evaluate(browse_geometry) == english_before
+ assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1')
+ page.locator('#selection-project-menu summary').click()
+ expect(page.locator('#selection-project-target')).to_be_visible()
+ menu_box = page.locator('#selection-project-menu .selection-menu-panel').bounding_box()
+ assert menu_box['x'] >= 0 and menu_box['x'] + menu_box['width'] <= 390
+ page.screenshot(path=str(output / '390-light-en-management.png'))
+ page.locator('#selection-project-menu summary').click()
+ page.locator('#share-cancel').click()
+ assert page.evaluate(browse_geometry) == english_before
+ assert not session.page_errors, session.page_errors
+ page.close()
+ session.seed_storage(setup, {'entries':entries,'organizerState':{'version':1,'collections':[
+ dict(id='sample-root',name='Higgs开源精选',parentId=None,entryIds=[],order=0,visibility='library'),
+ dict(id='sample-video',name='Higgs视频',parentId='sample-root',entryIds=['browse-a','browse-b'],order=0,visibility='library'),
+ dict(id='sample-curated',name='Higgsfield 精选案例',parentId='sample-root',entryIds=['browse-c'],order=1,visibility='library')
+ ]},'uiPreferences':{'locale':'zh-CN','theme':'dark','motion':'reduced','galleryView':'waterfall'}})
+ preview = session.open_page('library.html',wait_until='networkidle')
+ preview.set_viewport_size({'width':1440,'height':800})
+ preview.locator('.project-row[data-collection-id="sample-root"] .project-filter').click()
+ for content_id, icon in [('content:audio','audio-lines'),('content:source-file','file-box'),('content:reference','file-text')]:
+ use = preview.locator(f'[data-content-filter-id="{content_id}"] .ui-icon use')
+ expect(use).to_have_attribute('href', __import__('re').compile(f'.*#icon-{icon}$'))
+ for selector in ['#browse-breadcrumb button', '.project-disclosure:not(.is-placeholder)', '#create-collection']:
+ control = preview.locator(selector).first
+ control.hover()
+ expected = control.evaluate("""el => {
+ const probe=document.createElement('span');probe.style.backgroundColor='var(--hover)';el.append(probe);
+ const value=getComputedStyle(probe).backgroundColor;probe.remove();return value;
+ }""")
+ expect(control).to_have_css('background-color', expected)
+ folder_icon = preview.locator('.project-folder-card > .ui-icon').first
+ accent = folder_icon.evaluate("""el => {
+ const probe=document.createElement('span');probe.style.color='var(--accent-ink)';el.parentElement.append(probe);
+ const value=getComputedStyle(probe).color;probe.remove();return value;
+ }""")
+ expect(folder_icon).to_have_css('color',accent)
+ preview.locator('[data-sidebar-module="types"] .sidebar-module-toggle').click()
+ preview.locator('#content-filters').screenshot(path=str(output / 'content-icons.png'))
+ preview.locator('.project-folder-card').last.hover()
+ preview.locator('#project-folder-list').screenshot(path=str(output / 'folder-cards.png'))
+ preview.locator('.project-folder-card').last.click()
+ expect(preview.locator('#case-list .case-card')).to_have_count(1)
+
+ print({'views':2,'nested_scope':True,'management':True,'responsive':True,'persisted':True,'screenshots':str(output)})
+
+if __name__ == '__main__':
+ main()
diff --git a/test/library_core_e2e.py b/test/library_core_e2e.py
index 872a31e..7035a53 100644
--- a/test/library_core_e2e.py
+++ b/test/library_core_e2e.py
@@ -38,8 +38,9 @@ def main() -> None:
library.locator("#search-input").fill("library-")
expect(library.locator(".case-card")).to_have_count(3)
expect(library.locator("#filter-sidebar")).to_contain_text("内容类型")
- expect(library.locator("#filter-sidebar")).to_contain_text("属性筛选")
+ expect(library.locator("#filter-sidebar")).to_contain_text("标签筛选")
+ library.locator('[data-sidebar-module="tags"] .sidebar-module-toggle').click()
style_filter = library.locator("#facet-filters > .facet-filter", has_text="视觉风格")
expect(style_filter).to_have_count(1)
style_filter.locator(":scope > summary").click()
diff --git a/test/library_detail_actions_e2e.py b/test/library_detail_actions_e2e.py
index e24f402..5745f28 100644
--- a/test/library_detail_actions_e2e.py
+++ b/test/library_detail_actions_e2e.py
@@ -77,10 +77,11 @@ def main() -> None:
expect(library.get_by_role("button", name="以此创作")).to_be_enabled()
expect(library.get_by_role("button", name="编辑共享提示词", exact=True)).to_have_count(0)
project_menu = library.locator(".detail-project-menu")
- expect(project_menu.locator(":scope > summary")).to_have_text("已加入 21 个项目")
+ expect(project_menu.locator(":scope > summary")).to_have_text("详情项目 00")
closed_height = project_menu.locator(":scope > summary").evaluate("node => node.getBoundingClientRect().height")
assert closed_height <= 40, closed_height
- project_menu.locator(":scope > summary").click()
+ summary = project_menu.locator(":scope > summary")
+ summary.click(position={"x": summary.bounding_box()["width"] - 8, "y": 12})
expect(project_menu.locator(".detail-project-option")).to_have_count(21)
checkbox_widths = project_menu.locator('.detail-project-option input[type="checkbox"]').evaluate_all(
"nodes => nodes.map(node => node.getBoundingClientRect().width)"
@@ -89,10 +90,10 @@ def main() -> None:
long_project = project_menu.locator(".detail-project-option").nth(20)
expect(long_project).to_contain_text("完整项目名称需要换行显示")
long_project.locator("input").click()
- expect(project_menu.locator(":scope > summary")).to_have_text("已加入 20 个项目")
+ expect(project_menu.locator(":scope > summary")).to_have_text("详情项目 20 完整项目名称需要换行显示")
project_menu.locator('input[aria-label="新项目名称"]').fill("详情新建项目")
project_menu.get_by_role("button", name="新建并加入", exact=True).click()
- expect(library.locator(".detail-project-menu > summary")).to_have_text("已加入 21 个项目")
+ expect(library.locator(".detail-project-menu > summary")).to_have_text("详情新建项目")
expect(library.locator(".detail-quick-organization")).not_to_contain_text("快捷整理")
detail_order = library.evaluate(
"""() => {
@@ -171,7 +172,8 @@ def main() -> None:
for _ in range(5):
if mobile_project_menu.get_attribute("open") is not None and mobile_project_popover.is_visible():
break
- mobile_project_menu.locator(":scope > summary").click()
+ summary = mobile_project_menu.locator(":scope > summary")
+ summary.click(position={"x": summary.bounding_box()["width"] - 8, "y": 12})
library.wait_for_timeout(150)
expect(mobile_project_menu).to_have_attribute("open", "")
expect(mobile_project_popover).to_be_visible()
diff --git a/test/library_folder_ownership_e2e.py b/test/library_folder_ownership_e2e.py
new file mode 100644
index 0000000..e21f34c
--- /dev/null
+++ b/test/library_folder_ownership_e2e.py
@@ -0,0 +1,155 @@
+from __future__ import annotations
+import json
+import tempfile
+from pathlib import Path
+from playwright.sync_api import expect
+from e2e_support import base_entry, extension_session, wait_for_async_condition
+
+
+def main():
+ with extension_session('pd-folder-ownership-', viewport={'width': 1440, 'height': 1000}) as session:
+ setup = session.open_page('collector.html')
+ a = base_entry('a', '原案例', '原始提示词', 'content:prompt:image')
+ a['mediaAssets'] = [{'id': 'asset:a', 'kind': 'image', 'storageMode': 'managed', 'mimeType': 'image/png', 'width': 8, 'height': 8}]
+ a['primaryMediaId'] = 'asset:a'
+ session.seed_storage(setup, {'schemaVersion': 28, 'entries': [a], 'organizerState': {'version': 7, 'collections': [
+ {'id': 'p', 'name': '项目一', 'entryIds': ['a']}, {'id': 'q', 'name': '项目二', 'entryIds': ['a']},
+ {'id': 'r', 'name': '项目三', 'entryIds': []}
+ ]}})
+ setup.evaluate('''async () => {
+ const {saveMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
+ const canvas = document.createElement('canvas'); canvas.width=8; canvas.height=8;
+ canvas.getContext('2d').fillRect(0,0,8,8);
+ await saveMediaBlob('asset:a', await new Promise(r => canvas.toBlob(r)), {checkCapacity:false});
+ }''')
+ library = session.open_page('library.html')
+ expect(library.locator("body[data-library-state='ready']")).to_be_visible()
+ expect(library.locator('#project-search')).to_have_count(0)
+ initial = library.evaluate("async () => chrome.runtime.sendMessage({type:'GET_STATE'})")
+ assert len(initial['entries']) == 2, initial
+ assert 'folderOwnershipBackup' not in initial
+ q_id = next(c for c in initial['organizerState']['collections'] if c['id'] == 'q')['entryIds'][0]
+ assert q_id != 'a'
+ stored = library.evaluate("async () => (await chrome.storage.local.get('folderOwnershipBackup')).folderOwnershipBackup")
+ assert len(stored['state']['entries']) == 1
+ library.reload()
+ expect(library.locator("body[data-library-state='ready']")).to_be_visible()
+ assert library.evaluate("async () => (await chrome.runtime.sendMessage({type:'GET_STATE'})).entries.length") == 2
+ # Native dragging from the library overview into the left project tree.
+ library.locator('.case-card[data-entry-id="a"]').drag_to(library.locator('.project-row[data-collection-id="r"] .project-filter'))
+ wait_for_async_condition(library, """async () => {
+ const s=await chrome.runtime.sendMessage({type:'GET_STATE'});
+ return s.organizerState.collections.find(c=>c.id==='r').entryIds.includes('a');
+ }""")
+ moved = library.evaluate("async () => chrome.runtime.sendMessage({type:'GET_STATE'})")
+ assert next(c for c in moved['organizerState']['collections'] if c['id']=='p')['entryIds'] == []
+ assert next(c for c in moved['organizerState']['collections'] if c['id']=='q')['entryIds'] == [q_id]
+ # A case can leave a project by dropping onto Unassigned, without deletion.
+ library.locator('.project-row[data-collection-id="r"] .project-filter').click()
+ library.locator('.case-card[data-entry-id="a"]').drag_to(library.locator('#workspace-unassigned'))
+ wait_for_async_condition(library, """async () => {
+ const s=await chrome.runtime.sendMessage({type:'GET_STATE'});
+ return s.organizerState.collections.every(c=>!c.entryIds.includes('a'));
+ }""")
+ expect(library.locator('.case-card[data-entry-id="a"]')).to_have_count(0)
+ library.locator('#workspace-unassigned').click()
+ expect(library.locator('.case-card[data-entry-id="a"]')).to_be_visible()
+ unassigned = library.evaluate("async () => chrome.runtime.sendMessage({type:'GET_STATE'})")
+ assert len(unassigned['entries']) == 2
+ assert next(c for c in unassigned['organizerState']['collections'] if c['id']=='q')['entryIds'] == [q_id]
+ assert library.evaluate("async () => (await (await import('./media-store.js')).getMediaBlob('asset:a')).size") > 0
+ # Dropping an already unassigned case is harmless; it can be moved back.
+ library.mouse.move(700, 600)
+ library.locator('.case-card[data-entry-id="a"]').drag_to(library.locator('#workspace-unassigned'))
+ library.locator('.case-card[data-entry-id="a"]').drag_to(library.locator('.project-row[data-collection-id="r"] .project-filter'))
+ wait_for_async_condition(library, """async () => {
+ const s=await chrome.runtime.sendMessage({type:'GET_STATE'});
+ return s.organizerState.collections.find(c=>c.id==='r').entryIds.includes('a');
+ }""")
+ library.locator('.project-row[data-collection-id="r"] .project-filter').click()
+ # Native trash drop is recoverable deletion, including original project membership.
+ library.locator('.case-card[data-entry-id="a"]').drag_to(library.locator('#open-trash'))
+ wait_for_async_condition(library, "async () => !(await chrome.runtime.sendMessage({type:'GET_STATE'})).entries.some(e=>e.id==='a')")
+ expect(library.locator('.case-card[data-entry-id="a"]')).to_have_count(0)
+ assert library.evaluate("async () => (await (await import('./media-store.js')).getMediaBlob('asset:a')).size") > 0
+ library.locator('#open-trash').click()
+ library.locator('#trash-list button[aria-label="恢复:原案例"]').click()
+ wait_for_async_condition(library, """async () => {
+ const s=await chrome.runtime.sendMessage({type:'GET_STATE'});
+ return s.entries.some(e=>e.id==='a') && s.organizerState.collections.find(c=>c.id==='r').entryIds.includes('a');
+ }""")
+ library.locator('#trash-close').click()
+ expect(library.locator('.case-card[data-entry-id="a"]')).to_be_visible()
+ # Exercise the visible Copy action, then check independent metadata.
+ library.locator('#select-cases').click()
+ library.locator('.case-card[data-entry-id="a"]').click()
+ library.locator('#selection-project-menu summary').click()
+ library.locator('#selection-project-target').select_option('r')
+ library.locator('#selection-copy-project').click()
+ wait_for_async_condition(library, "async () => (await chrome.runtime.sendMessage({type:'GET_STATE'})).entries.length===3")
+ copied = library.evaluate("async () => chrome.runtime.sendMessage({type:'GET_STATE'})")
+ copy_id = next(e['id'] for e in copied['entries'] if e['id'] not in ['a', q_id])
+ result = library.evaluate("async id => chrome.runtime.sendMessage({type:'UPDATE_ENTRY_TITLE',entryId:id,title:'副本编辑'})", copy_id)
+ assert result['ok'], result
+ result = library.evaluate("async () => chrome.runtime.sendMessage({type:'BATCH_MOVE_TO_TRASH',entryIds:['a']})")
+ assert result['ok'], result
+ result = library.evaluate("async () => chrome.runtime.sendMessage({type:'EMPTY_TRASH'})")
+ assert result['ok'], result
+ final = library.evaluate("async () => chrome.runtime.sendMessage({type:'GET_STATE'})")
+ assert next(e for e in final['entries'] if e['id']==q_id)['title'] == '原案例'
+ assert next(e for e in final['entries'] if e['id']==copy_id)['title'] == '副本编辑'
+ blob_size = library.evaluate("async () => (await (await import(chrome.runtime.getURL('media-store.js'))).getMediaBlob('asset:a')).size")
+ assert blob_size > 0
+ undo_check = library.evaluate("""async () => {
+ const {saveMediaBlob,getMediaBlob} = await import('./media-store.js');
+ const {createScreenshotSaveUndo} = await import('./save-history.js');
+ const stored=await chrome.storage.local.get('entries');
+ const entry={...structuredClone(stored.entries[0]),id:'legacy-shot',screenshotUpdatedAt:'2026-09-23T00:00:00.000Z',
+ mediaAssets:[{id:'legacy-shot',kind:'image',storageMode:'managed',mimeType:'image/png'}],primaryMediaId:'legacy-shot'};
+ const copy={...structuredClone(entry),id:'legacy-copy'};
+ await saveMediaBlob('legacy-shot',new Blob(['new-image'],{type:'image/png'}));
+ await saveMediaBlob('backup:legacy-shot',new Blob(['old-image'],{type:'image/png'}));
+ await chrome.storage.local.set({entries:[...stored.entries,entry,copy],lastSaveUndo:createScreenshotSaveUndo(
+ entry.id,{hasScreenshot:true},entry.screenshotUpdatedAt,true,'backup:legacy-shot')});
+ const response=await chrome.runtime.sendMessage({type:'UNDO_LAST'});
+ if(!response.ok) throw new Error(response.message);
+ const id=response.entry.primaryMediaId;
+ const original=await getMediaBlob(id), retained=await getMediaBlob('legacy-shot');
+ return {id,original:await original.text(),copy:await retained.text(),hash:response.entry.mediaAssets[0].contentHash};
+ }""")
+ assert undo_check['id'] != 'legacy-shot' and undo_check['original']=='old-image' and undo_check['copy']=='new-image',undo_check
+ assert len(undo_check['hash'])==64,undo_check
+ screenshot = Path(tempfile.gettempdir()) / 'promptdirector-folder-ownership.png'
+ library.screenshot(path=str(screenshot))
+ assert not session.page_errors, session.page_errors
+ print(json.dumps({'migration':True,'idempotent':True,'drag_move':True,'copy_ui':True,'independent_edit':True,'delete_preserves_original':blob_size,'screenshot':str(screenshot)},ensure_ascii=False))
+
+def check_failed_migration():
+ with extension_session('pd-folder-failure-') as session:
+ page = session.open_page('collector.html')
+ page.evaluate("async()=>chrome.runtime.sendMessage({type:'GET_STATE'})")
+ worker = session.context.service_workers[0]
+ worker.evaluate("""() => {
+ globalThis.originalSet = chrome.storage.local.set.bind(chrome.storage.local);
+ chrome.storage.local.set = async payload => {
+ if (payload.folderOwnershipBackup) throw new Error('模拟迁移空间不足');
+ return originalSet(payload);
+ };
+ }""")
+ entry=base_entry('original','旧案例','不能丢失','content:prompt:text')
+ page.evaluate("""async entry=>chrome.storage.local.set({entries:[entry],organizerState:{version:7,collections:[
+ {id:'p',name:'P',entryIds:['original']},{id:'q',name:'Q',entryIds:['original']}
+ ]},compoundCases:[]})""",entry)
+ result=page.evaluate("async()=>chrome.runtime.sendMessage({type:'GET_STATE'})")
+ assert not result['ok'],result
+ stored=page.evaluate("async()=>chrome.storage.local.get(['entries','organizerState','folderOwnershipBackup'])")
+ assert len(stored['entries'])==1 and 'folderOwnershipBackup' not in stored,stored
+ assert [c['entryIds'] for c in stored['organizerState']['collections']]==[['original'],['original']]
+ worker.evaluate("() => {chrome.storage.local.set=originalSet}")
+ result=page.evaluate("async()=>chrome.runtime.sendMessage({type:'GET_STATE'})")
+ assert result['ok'] and len(result['entries'])==2,result
+ print('迁移写入失败保持旧案例及两个位置;重试成功且只创建一份副本')
+
+if __name__=='__main__':
+ main()
+ check_failed_migration()
diff --git a/test/library_hidden_scroll_e2e.py b/test/library_hidden_scroll_e2e.py
new file mode 100644
index 0000000..72ec48e
--- /dev/null
+++ b/test/library_hidden_scroll_e2e.py
@@ -0,0 +1,70 @@
+"""Hidden scrollbar tracks must preserve pointer and keyboard reading of long content."""
+from pathlib import Path
+import tempfile
+from e2e_support import extension_session,base_entry
+from playwright.sync_api import expect
+with extension_session('pd-hidden-scroll-',viewport={'width':1440,'height':900}) as s:
+ setup=s.open_page('collector.html')
+ entry=base_entry('scroll-case','长提示词案例','\n'.join(f'第{i}行提示词,完整保留内容。' for i in range(220)),'content:prompt:image')
+ s.seed_storage(setup,{'entries':[entry]+[base_entry(f'case-{i}',f'案例 {i}','测试正文','content:prompt:image',i+1) for i in range(80)],'organizerState':{'version':7,'collections':[dict(id=f'p{i}',name=f'项目 {i}',entryIds=[],order=i) for i in range(70)]},'uiPreferences':{'locale':'zh-CN','motion':'reduced'}})
+ page=s.open_page('library.html',wait_until='networkidle')
+ assert page.evaluate('getComputedStyle(document.documentElement).scrollbarWidth') == 'none'
+ page.locator('#case-list').hover()
+ page.mouse.wheel(0, 600)
+ page.wait_for_function('()=>window.scrollY > 0')
+ page.evaluate('window.scrollTo(0,0)')
+ page.locator('#open-settings').click()
+ page.locator('[data-settings-tab="general"]').click()
+ page.set_viewport_size({'width':960,'height':710})
+ panel=page.locator('.settings-panel:not([hidden])')
+ assert panel.evaluate('e=>getComputedStyle(e).scrollbarWidth') == 'none'
+ assert panel.evaluate('e=>e.scrollHeight>e.clientHeight')
+ panel.hover();page.mouse.wheel(0,450)
+ page.wait_for_function("()=>document.querySelector('.settings-panel:not([hidden])').scrollTop>0")
+ for theme in ['dark','light']:
+ page.evaluate('v=>{document.documentElement.dataset.theme=v;document.documentElement.dataset.resolvedTheme=v}',theme)
+ page.screenshot(path=str(Path(tempfile.gettempdir()) / f'promptdirector-settings-scroll-{theme}.png'))
+ page.locator('#settings-close').click()
+ page.set_viewport_size({'width':1440,'height':900})
+ body=page.locator('#sidebar-projects-body')
+ assert body.evaluate('e=>getComputedStyle(e).scrollbarWidth')=='none'
+ body.hover(); page.mouse.wheel(0,550)
+ page.wait_for_function("()=>document.querySelector('#sidebar-projects-body').scrollTop>0")
+ page.locator('.case-card[data-entry-id="scroll-case"]').click()
+ expect(page.locator('#detail-drawer')).to_have_attribute('aria-hidden','false')
+ page.get_by_role('button',name='展开全文',exact=True).first.click()
+ page.evaluate("""()=>{const region=[...document.querySelectorAll('#detail-drawer, #detail-drawer *')].find(e=>e.clientHeight>0&&e.scrollHeight>e.clientHeight&&['auto','scroll'].includes(getComputedStyle(e).overflowY));if(!region)throw Error('No overflowing detail region');region.dataset.scrollProbe='true'}""")
+ prompt=page.locator('[data-scroll-probe]')
+ assert prompt.evaluate('e=>getComputedStyle(e).scrollbarWidth')=='none'
+ prompt.hover();page.mouse.wheel(0,500)
+ page.wait_for_function("()=>document.querySelector('[data-scroll-probe]').scrollTop>0")
+ # Native keyboard scrolling remains available when the region is focused.
+ prompt.evaluate('e=>e.focus()')
+ before=prompt.evaluate('e=>e.scrollTop')
+ page.keyboard.press('PageDown')
+ page.wait_for_function('(before)=>document.querySelector("[data-scroll-probe]").scrollTop>before',arg=before)
+ assert page.locator('#detail-drawer').evaluate("e=>[e,...e.querySelectorAll('*')].every(n=>getComputedStyle(n).scrollbarWidth===(n.matches('.ui-scrollbar, textarea:not([readonly]):not([disabled]), [contenteditable]:not([contenteditable=\"false\"])')?'thin':'none'))")
+ page.screenshot(path=str(Path(tempfile.gettempdir()) / 'promptdirector-hidden-scroll.png'))
+ page.locator('#detail-close').click()
+ # The shared opt-in preserves a draggable track for wide content and editors.
+ page.evaluate("""() => {
+ const box=document.createElement('div');box.className='ui-scrollbar';box.id='wide-scroll-probe';
+ box.style.cssText='position:fixed;inset:100px auto auto 300px;width:300px;height:100px;overflow:auto;z-index:10000;background:white';
+ const wide=document.createElement('div');wide.style.cssText='width:1200px;height:40px';wide.textContent='宽表格';box.append(wide);
+ const edit=document.createElement('textarea');edit.id='edit-scroll-probe';edit.style.cssText='position:fixed;inset:250px auto auto 300px;width:300px;height:100px;z-index:10000';edit.value='可编辑长文本\\n'.repeat(100);
+ document.body.append(box,edit);
+ }""")
+ wide=page.locator('#wide-scroll-probe')
+ assert wide.evaluate('e=>getComputedStyle(e).scrollbarWidth')=='thin'
+ wide.hover();page.mouse.wheel(500,0)
+ page.wait_for_function("()=>document.querySelector('#wide-scroll-probe').scrollLeft>0")
+ editor=page.locator('#edit-scroll-probe')
+ assert editor.evaluate('e=>getComputedStyle(e).scrollbarWidth')=='thin'
+ editor.hover();page.mouse.wheel(0,500)
+ page.wait_for_function("()=>document.querySelector('#edit-scroll-probe').scrollTop>0")
+ for url in ['composer.html','skills.html','collector.html','curated.html','curated-skills.html']:
+ other=s.open_page(url,wait_until='domcontentloaded')
+ assert other.evaluate('getComputedStyle(document.documentElement).scrollbarWidth')=='none',url
+ other.close()
+ assert not s.page_errors,s.page_errors
+ print('PASS: library, settings, sidebar, details and shared pages hide tracks; wheel/PageDown and editor/wide-content exceptions remain usable')
diff --git a/test/library_import_ui_e2e.py b/test/library_import_ui_e2e.py
index 39409e3..ec24297 100644
--- a/test/library_import_ui_e2e.py
+++ b/test/library_import_ui_e2e.py
@@ -286,6 +286,7 @@ def main() -> None:
wait_for_confirmation(library, "1")
expect(library.locator("#import-file-list")).to_contain_text("dropped.txt")
library.set_viewport_size({"width": 390, "height": 844})
+ library.wait_for_function("() => document.documentElement.scrollWidth <= innerWidth")
mobile_layout = library.evaluate(
"""() => {
const dialog = document.querySelector('#import-dialog').getBoundingClientRect();
diff --git a/test/library_modular_layout_e2e.py b/test/library_modular_layout_e2e.py
new file mode 100644
index 0000000..fbec827
--- /dev/null
+++ b/test/library_modular_layout_e2e.py
@@ -0,0 +1,133 @@
+"""Approved single-row chrome and vertical panels preserve existing library actions."""
+from pathlib import Path
+import tempfile
+from playwright.sync_api import expect
+from e2e_support import extension_session, base_entry, wait_for_async_condition
+
+OUT = Path(tempfile.gettempdir()) / 'promptdirector-modular-layout'
+OUT.mkdir(exist_ok=True)
+
+def main():
+ with extension_session('pd-modular-', viewport={'width':1440,'height':900}) as session:
+ setup = session.open_page('collector.html')
+ entries = [base_entry(f'case-{i}', f'视觉创作案例 {i+1}', f'创意提示词 {i}', 'content:prompt:image', i) for i in range(12)]
+ projects = [dict(id='root',name='Higgs精选',entryIds=[e['id'] for e in entries],order=0),dict(id='child',name='非常长的项目名称LongProjectWithoutSpaces',parentId='root',entryIds=[],order=0)]
+ projects += [dict(id=f'p-{i}', name=f'项目 {i+1}',entryIds=[],order=i+1) for i in range(25)]
+ session.seed_storage(setup, {'entries':entries,'organizerState':{'version':7,'collections':projects},'uiPreferences':{'locale':'zh-CN','theme':'dark','motion':'reduced'}})
+ page = session.open_page('library.html',wait_until='networkidle')
+ expect(page.locator("body[data-library-state='ready']")).to_be_visible()
+ assert not session.page_errors, session.page_errors
+ page.locator('.project-row[data-collection-id="root"] .project-filter').click()
+ expect(page.locator('#case-list .case-card')).to_have_count(12)
+ expect(page.locator('#sidebar-types-body')).to_be_hidden()
+ expect(page.locator('#sidebar-tags-body')).to_be_hidden()
+ assert page.locator('#gallery-heading').evaluate("e=>e.parentElement.matches('.topbar')")
+ assert page.locator('.topbar').bounding_box()['height']==56
+ page.screenshot(path=str(OUT/'desktop-expanded.png'))
+ # All module disclosures share one right column, independent of action count.
+ arrows=page.locator('.module-chevron').evaluate_all('els=>els.map(e=>({right:e.getBoundingClientRect().right,width:e.getBoundingClientRect().width}))')
+ assert len({r['right'] for r in arrows})==1, arrows
+ labels=page.locator('.module-label').evaluate_all('els=>els.map(e=>e.getBoundingClientRect().left)')
+ assert len(set(labels))==1, labels
+ assert all(r['width']==12 for r in arrows), arrows
+ controls=page.locator('#create-collection,#collapse-projects,#manage-facets').evaluate_all('els=>els.map(e=>({w:e.getBoundingClientRect().width,h:e.getBoundingClientRect().height,border:getComputedStyle(e).borderTopWidth}))')
+ assert all(r=={'w':28,'h':28,'border':'0px'} for r in controls), controls
+ page.locator('[data-sidebar-module="projects"] .module-chevron').click()
+ expect(page.locator('#sidebar-projects-body')).to_be_hidden()
+ page.locator('#filter-sidebar').screenshot(path=str(OUT/'module-headers.png'))
+ page.locator('[data-sidebar-module="projects"] .module-chevron').click()
+ expect(page.locator('#sidebar-projects-body')).to_be_visible()
+ # Module switching cannot resize the canvas; project viewport scrolls separately.
+ before = page.locator('.gallery-shell').bounding_box()
+ page.locator('[data-sidebar-module="types"] .sidebar-module-toggle').click()
+ expect(page.locator('#sidebar-types-body')).to_be_visible()
+ assert page.locator('.gallery-shell').bounding_box()==before
+ page.locator('#content-filters [data-content-filter-id="content:prompt:image"]').click()
+ page.locator('[data-sidebar-module="types"] .sidebar-module-toggle').click()
+ expect(page.locator('[data-sidebar-module="types"] .module-active-count')).to_have_text('1')
+ page.locator('[data-sidebar-module="types"] .sidebar-module-toggle').click()
+ page.locator('#content-filters [data-content-filter-id="content:prompt:image"]').click()
+ page.locator('[data-sidebar-module="types"] .sidebar-module-toggle').click()
+ # Collapse means a useful rail, not a hidden sidebar.
+ page.locator('#toggle-filters').click()
+ expect(page.locator('.workspace')).to_have_class('workspace filters-collapsed')
+ page.wait_for_function("() => document.querySelector('#filter-sidebar').getBoundingClientRect().width===48")
+ expect(page.locator('#open-trash')).to_be_visible()
+ page.screenshot(path=str(OUT/'desktop-rail.png'))
+ page.locator('[data-sidebar-module="tags"] .sidebar-module-toggle').click()
+ expect(page.locator('#sidebar-tags-body')).to_be_visible()
+ expect(page.locator('#sidebar-projects-body')).to_be_hidden()
+ page.locator('[data-sidebar-module="projects"] .sidebar-module-toggle').click()
+ page.locator('[data-sidebar-module="tags"] .sidebar-module-toggle').click()
+ # Keyboard reorder is equivalent to pointer reorder, persists and preserves data.
+ grip=page.locator('[data-sidebar-module="types"] .module-grip')
+ grip.focus(); page.keyboard.press('ArrowUp')
+ wait_for_async_condition(page,"async()=> (await chrome.storage.local.get('uiPreferences')).uiPreferences.sidebarLayout.order[0]==='types'")
+ page.locator('[data-sidebar-module="tags"] .module-grip').drag_to(page.locator('[data-sidebar-module="projects"] .filter-heading'))
+ wait_for_async_condition(page,"async()=> (await chrome.storage.local.get('uiPreferences')).uiPreferences.sidebarLayout.order.join(',')==='types,tags,projects'")
+ page.reload(wait_until='networkidle')
+ assert page.locator('#sidebar-modules > section').first.get_attribute('data-sidebar-module')=='types'
+ page.locator('.sidebar-layout-menu summary').click()
+ page.locator('.sidebar-layout-menu button').filter(has_text='全部展开').click()
+ for key in ['projects','types','tags']: expect(page.locator(f'#sidebar-{key}-body')).to_be_visible()
+ page.locator('.sidebar-layout-menu summary').click()
+ page.locator('.sidebar-layout-menu button').filter(has_text='恢复默认布局').click()
+ expect(page.locator('#sidebar-types-body')).to_be_hidden()
+ # No movement of the canvas when switching management or descendant scope.
+ if page.locator('.project-row[data-collection-id="root"] .project-filter').get_attribute('aria-pressed')!='true':
+ page.locator('.project-row[data-collection-id="root"] .project-filter').click()
+ for width in [1440,900,390]:
+ page.set_viewport_size({'width':width,'height':900})
+ for view in ['waterfall','list']:
+ if width<=1100: page.locator('#toolbar-more > summary').click()
+ page.locator(f'[data-gallery-view="{view}"]').click()
+ page.screenshot(path=str(OUT/f'{width}-{view}-scope.png'))
+ page.locator('#include-subprojects').check()
+ page.locator('#include-subprojects').uncheck()
+ if width<=1100: page.locator('#toolbar-more > summary').click()
+ assert page.evaluate('document.documentElement.scrollWidth<=innerWidth+1'), width
+ before=page.locator('#case-list').bounding_box()
+ if width<=1100: page.locator('#toolbar-more > summary').click()
+ page.locator('#select-cases').click()
+ expect(page.locator('#share-cancel')).to_be_visible()
+ expect(page.locator('#search-input')).to_be_visible()
+ page.locator('#search-input').fill('视觉')
+ expect(page.locator('#case-list .case-card')).to_have_count(12)
+ page.locator('#search-input').fill('')
+ after=page.locator('#case-list').bounding_box()
+ assert before['x']==after['x'] and before['y']==after['y'] and before['width']==after['width'],(width,before,after)
+ page.locator('#case-list .case-card').first.click()
+ page.screenshot(path=str(OUT/f'{width}-{view}-management.png'))
+ assert page.evaluate('document.documentElement.scrollWidth<=innerWidth+1'),width
+ page.locator('#share-cancel').click()
+ page.screenshot(path=str(OUT/f'{width}-{view}.png'))
+ # Existing global actions remain reachable from the compact toolbar.
+ page.locator('#toolbar-more > summary').click()
+ expect(page.locator('#start-compose')).to_be_visible()
+ page.locator('#add-menu summary').click()
+ expect(page.locator('#add-media')).to_be_visible()
+ page.keyboard.press('Escape')
+ page.set_viewport_size({'width':1440,'height':900})
+ if not page.locator('#sidebar-projects-body').is_visible():
+ page.locator('[data-sidebar-module="projects"] .sidebar-module-toggle').click()
+ page.locator('.project-row[data-collection-id="p-0"] .project-filter').click()
+ page.locator('#empty-filter button').click()
+ expect(page.locator('#project-selection-actions')).to_be_visible()
+ for width in [1440,390]:
+ page.set_viewport_size({'width':width,'height':900})
+ page.locator('#search-input').fill('视觉')
+ expect(page.locator('#case-list .case-card')).to_have_count(12)
+ assert page.evaluate('document.documentElement.scrollWidth<=innerWidth+1')
+ page.locator('#project-selection-cancel').click()
+ page.locator('#search-input').fill('')
+ page.set_viewport_size({'width':1440,'height':900})
+ await_theme = """async()=>{const p=(await chrome.storage.local.get('uiPreferences')).uiPreferences;await chrome.runtime.sendMessage({type:'UPDATE_UI_PREFERENCES',preferences:{...p,locale:'en',theme:'light'}})}"""
+ page.evaluate(await_theme)
+ page.wait_for_load_state('networkidle')
+ expect(page.locator('html')).to_have_attribute('lang','en')
+ page.screenshot(path=str(OUT/'english-light.png'))
+ assert page.evaluate('document.documentElement.scrollWidth<=innerWidth+1')
+ assert not session.page_errors,session.page_errors
+ print('PASS: one-row toolbar, vertical dock/rail, independent scrolling, filters, persisted order/reset, two views/management/scope at 1440/900/390, compact actions, English/light')
+
+if __name__=='__main__': main()
diff --git a/test/library_navigation_e2e.py b/test/library_navigation_e2e.py
index 8259975..2293328 100644
--- a/test/library_navigation_e2e.py
+++ b/test/library_navigation_e2e.py
@@ -96,6 +96,8 @@ def main() -> None:
expect(library.locator("#content-filters")).not_to_contain_text("全部")
expect(library.locator("#facet-filters .facet-filter-body .filter-option", has_text="全部")).to_have_count(0)
+ library.locator('[data-sidebar-module="tags"] .sidebar-module-toggle').click()
+ expect(library.locator('#sidebar-tags-body')).to_be_visible()
style = library.locator('.facet-filter[data-facet-id="style"]')
style.locator(":scope > summary").click()
facet_row = style.locator('[data-facet-node-id="style.render"]')
@@ -197,7 +199,7 @@ def main() -> None:
library.locator("#selection-project-menu > summary").click()
expect(library.locator("#selection-project-target")).to_be_visible()
library.locator("#selection-project-target").select_option("collection:navigation")
- expect(library.locator("#selection-add-project")).to_be_enabled()
+ expect(library.locator("#selection-copy-project")).to_be_enabled()
library.locator("#selection-project-menu > summary").press("Escape")
library.locator("#selection-more-menu > summary").click()
expect(library.locator("#selection-combine")).to_be_enabled()
@@ -275,6 +277,8 @@ def main() -> None:
}"""
)
assert drawer["left"] >= -1 and drawer["right"] <= drawer["viewport"] + 1, drawer
+ library.locator('[data-sidebar-module="types"] .sidebar-module-toggle').click()
+ expect(library.locator('#sidebar-types-body')).to_be_visible()
library.locator('[data-content-filter-id="content:prompt:image"]').click()
expect(library.locator("#case-list > .case-card")).to_have_count(1)
overflow = library.evaluate("document.documentElement.scrollWidth > document.documentElement.clientWidth")
@@ -288,6 +292,7 @@ def main() -> None:
library.screenshot(path=str(screenshots / "promptdirector-step2-library-mobile.png"), full_page=True)
library.evaluate("document.querySelector('#toggle-filters').click()")
expect(library.locator(".workspace")).to_have_class("workspace filters-collapsed")
+ library.locator('#toolbar-more > summary').click()
library.locator("#select-cases").click()
expect(library.locator("#selection-selected-actions")).to_be_hidden()
mobile_empty_bar = library.locator("#share-bar").evaluate(
diff --git a/test/library_quick_actions_e2e.py b/test/library_quick_actions_e2e.py
index 1b622d4..2907a37 100644
--- a/test/library_quick_actions_e2e.py
+++ b/test/library_quick_actions_e2e.py
@@ -85,17 +85,16 @@ def main():
page.get_by_role('button',name='关闭详情',exact=True).click()
page.locator('#search-input').fill('快捷测试')
expect(page.locator('#case-list > .case-card')).to_have_count(1)
- page.locator('#project-search').fill('不存在的项目')
before=page.evaluate("""()=>{document.querySelector('.case-card').dataset.probe='same';return {url:location.href,scroll:scrollY,count:history.length};}""")
card.click(button='right'); page.get_by_role('menuitem',name='定位项目').click()
expect(card).to_have_attribute('data-probe','same')
expect(page.locator('#search-input')).to_have_value('快捷测试')
- expect(page.locator('#project-search')).to_have_value('')
+ expect(page.locator('#project-search')).to_have_count(0)
after=page.evaluate("()=>({url:location.href,scroll:scrollY,count:history.length})")
assert before==after,(before,after)
def check_alignment():
bounds=page.evaluate("""()=>{const row=document.querySelector('.project-located');const tools=document.querySelector('.project-tree-tools');
- return {target:row.getBoundingClientRect().top,header:tools.getBoundingClientRect().bottom,scroll:document.querySelector('#filter-sidebar').scrollTop};}""")
+ return {target:row.getBoundingClientRect().top,header:tools.getBoundingClientRect().bottom,scroll:document.querySelector('#sidebar-projects-body').scrollTop};}""")
assert abs(bounds['target']-bounds['header'])<2,bounds
assert bounds['scroll']>0,bounds
check_alignment()
@@ -123,28 +122,29 @@ def main():
expect(page.locator('#case-list')).to_have_attribute('data-probe','same-wall')
expect(page.locator('#detail-drawer')).not_to_have_class(__import__('re').compile(r'.*open.*'))
page.locator('#selection-project-target').select_option('p1')
- page.locator('#selection-add-project').click()
+ page.locator('#selection-copy-project').click()
expect(page.locator('#share-bar')).to_be_hidden()
memberships=page.evaluate("async()=> (await chrome.storage.local.get('organizerState')).organizerState.collections.find(p=>p.id==='p1').entryIds")
- assert memberships==['quick-case'],memberships
- # Multiple memberships select a path without filtering the gallery.
- card.click(button='right'); page.get_by_role('menuitem',name='定位项目').click()
- expect(page.get_by_role('menuitem')).to_have_count(2)
- page.get_by_role('menuitem',name='项目1',exact=True).click(); check_alignment()
+ assert len(memberships)==1 and memberships[0]!='quick-case',memberships
+ copy_id=memberships[0]
+ # A copy has its own location while the original remains in its folder.
+ card.click(button='right'); page.get_by_role('menuitem',name='定位项目').click(); check_alignment()
other_card=page.locator('[data-entry-id="quick-other"].case-card')
other_card.click(button='right'); page.get_by_role('menuitem',name='定位项目').click()
expect(page.locator('#workspace-unassigned')).to_have_class(__import__('re').compile(r'.*project-located.*'))
- expect(page.locator('#case-list > .case-card')).to_have_count(2)
- # Moving removes only the current project membership, retaining other projects.
+ expect(page.locator('#case-list > .case-card')).to_have_count(3)
page.locator('[data-collection-id="p1"] .project-filter').click()
- card.click(button='right'); page.get_by_role('menuitem',name='项目管理').click()
+ copy_card=page.locator(f'[data-entry-id="{copy_id}"].case-card')
+ copy_card.click(button='right'); page.get_by_role('menuitem',name='项目管理').click()
page.locator('#selection-project-target').select_option('p2')
page.locator('#selection-move-project').click()
expect(page.locator('#share-bar')).to_be_hidden()
- memberships=page.evaluate("async()=> (await chrome.storage.local.get('organizerState')).organizerState.collections.filter(p=>p.entryIds.includes('quick-case')).map(p=>p.id)")
- assert set(memberships)=={'p0','p2'},memberships
+ memberships=page.evaluate("async id=> (await chrome.storage.local.get('organizerState')).organizerState.collections.filter(p=>p.entryIds.includes(id)).map(p=>p.id)",copy_id)
+ assert memberships==['p2'],memberships
+ original_members=page.evaluate("async()=> (await chrome.storage.local.get('organizerState')).organizerState.collections.filter(p=>p.entryIds.includes('quick-case')).map(p=>p.id)")
+ assert original_members==['p0'],original_members
page.locator('#workspace-library').click()
- expect(page.locator('#case-list > .case-card')).to_have_count(2)
+ expect(page.locator('#case-list > .case-card')).to_have_count(3)
# Batch takeout still uses Share, without a separate download command.
page.locator('#select-cases').click(); card.click(); other_card.click()
page.locator('#selection-more-menu > summary').click()
diff --git a/test/library_responsive_layout_e2e.py b/test/library_responsive_layout_e2e.py
index 9cbcd1e..1e15407 100644
--- a/test/library_responsive_layout_e2e.py
+++ b/test/library_responsive_layout_e2e.py
@@ -6,13 +6,14 @@ from e2e_support import base_entry, extension_session
def geometry(page) -> dict:
return page.evaluate(
"""() => {
- const viewportWidth = document.documentElement.clientWidth;
+ const viewportWidth = innerWidth;
const gallery = document.querySelector('.gallery-shell').getBoundingClientRect();
const list = document.querySelector('#case-list').getBoundingClientRect();
const cards = [...document.querySelectorAll('#case-list > .case-card')]
.map(card => card.getBoundingClientRect());
return {
viewportWidth,
+ availableWidth: document.documentElement.clientWidth,
gallery: {left: gallery.left, right: gallery.right, width: gallery.width},
list: {left: list.left, right: list.right, width: list.width},
cards: cards.map(card => ({left: card.left, right: card.right, width: card.width})),
@@ -26,7 +27,8 @@ def assert_readable_layout(value: dict) -> None:
gallery = value["gallery"]
case_list = value["list"]
cards = value["cards"]
- minimum_gallery_width = viewport_width - (270 if viewport_width > 640 else 20)
+ # The approved mobile layout retains a 48px navigation rail.
+ minimum_gallery_width = value["availableWidth"] - (270 if viewport_width > 640 else 68)
assert gallery["width"] >= minimum_gallery_width, value
assert case_list["width"] >= gallery["width"] - 40, value
assert cards, value
@@ -36,13 +38,18 @@ def assert_readable_layout(value: dict) -> None:
def wait_for_readable_layout(page) -> None:
page.wait_for_function(
- """() => {
+ """expectedWidth => {
const gallery = document.querySelector('.gallery-shell')?.getBoundingClientRect();
const cards = [...document.querySelectorAll('#case-list > .case-card')]
.map(card => card.getBoundingClientRect());
- return Boolean(gallery && cards.length)
+ return innerWidth === expectedWidth && Boolean(gallery && cards.length)
+ && (!matchMedia('(max-width: 640px)').matches
+ || document.querySelector('.workspace').classList.contains('filters-collapsed'))
+ && (!document.querySelector('.workspace').classList.contains('filters-collapsed')
+ || document.querySelector('#filter-sidebar').getBoundingClientRect().width === 48)
&& cards.every(card => card.left >= gallery.left - 1 && card.right <= gallery.right + 1);
}""",
+ arg=page.viewport_size["width"],
timeout=2000,
)
diff --git a/test/local-asset-reference-background.test.js b/test/local-asset-reference-background.test.js
index cb9604b..ac7801a 100644
--- a/test/local-asset-reference-background.test.js
+++ b/test/local-asset-reference-background.test.js
@@ -15,7 +15,7 @@ test("background imports inert local references without reading a managed media
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 enqueueAutomaticLibraryMaintenance\(imported\)/u);
assert.match(item, /await notifySaved\(entries\.length\)/u);
assert.match(item, /await queueImportJobAnalysis\(finished\.job\)/u);
});
diff --git a/test/local-import-batch.test.js b/test/local-import-batch.test.js
new file mode 100644
index 0000000..c6376fc
--- /dev/null
+++ b/test/local-import-batch.test.js
@@ -0,0 +1,71 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import vm from "node:vm";
+import { createImportJob, startImportJob, finishImportItem } from "../extension/import-jobs.js";
+import { addStagedAsset, stagedAssetById, removeStagedAsset } from "../extension/import-staging.js";
+import { normalizeOrganizerState } from "../extension/organizer.js";
+
+const background = await readFile(new URL("../extension/background.js", import.meta.url), "utf8");
+const implementation = background.slice(background.indexOf("const IMPORT_SLICE_PREPARE_MS"),
+ background.indexOf("function importedEntryFromStagedAsset"));
+
+function harness({ missing = [], failCommit = false, tick = 0 } = {}) {
+ let staging;
+ for (const id of ["first", "middle", "last"]) {
+ staging = addStagedAsset(staging, { id, assetId: id, name: `${id}.txt`, relativePath: `${id}.txt`,
+ kind: "document", mimeType: "text/plain", byteSize: 1, contentHash: "a".repeat(64) }).state;
+ }
+ const created = createImportJob({}, { collectionId: "project", items: staging.assets.map(asset => ({ stagedAssetId: asset.id })) });
+ let durable = { entries: [{ id: "existing" }], importJobs: created.state, importStaging: staging,
+ organizerState: normalizeOrganizerState({ collections: [{ id: "project", name: "Project", entryIds: ["existing"] }] }) };
+ const original = structuredClone(durable);
+ const writes = [], maintained = [];
+ let clock = 0;
+ const context = vm.createContext({ startImportJob, finishImportItem, stagedAssetById, removeStagedAsset, normalizeOrganizerState,
+ performance: { now: () => clock += tick },
+ STORAGE_KEYS: Object.fromEntries(Object.keys(durable).map(key => [key, key])),
+ getMediaBlob: async id => missing.includes(id) ? null : new Blob(["a"]),
+ importedEntryFromStagedAsset: (_state, staged) => ({ id: `entry:${staged.id}` }),
+ userMessage: error => error.message,
+ commitLocalChanges: async update => {
+ if (failCommit) throw new Error("disk full");
+ writes.push(structuredClone(update));
+ durable = { ...durable, ...structuredClone(update) };
+ },
+ enqueueAutomaticLibraryMaintenance: async entries => maintained.push(...entries),
+ notifySaved: async () => {}, queueImportJobAnalysis: async () => {}
+ });
+ vm.runInContext(implementation, context);
+ return { run: () => context.importStagedItems(structuredClone(durable), durable.importJobs.items[0]),
+ state: () => durable, original, writes, maintained };
+}
+
+test("one unreadable original does not block healthy files or remove the failed staging record", async () => {
+ const h = harness({ missing: ["middle"] });
+ await h.run();
+ assert.equal(h.writes.length, 1);
+ assert.deepEqual(h.state().entries.map(e => e.id), ["existing", "entry:first", "entry:last"]);
+ assert.deepEqual(h.state().importJobs.items[0].items.map(i => i.status), ["imported", "failed", "imported"]);
+ assert.deepEqual(h.state().importStaging.assets.map(a => a.id), ["middle"]);
+ assert.deepEqual(h.state().organizerState.collections[0].entryIds, ["existing", "entry:first", "entry:last"]);
+ assert.equal(h.maintained.length, 2);
+});
+
+test("a failed batch commit leaves cases, queued receipts and staged originals unchanged", async () => {
+ const h = harness({ failCommit: true });
+ await assert.rejects(h.run(), /disk full/);
+ assert.deepEqual(h.state(), h.original);
+ assert.equal(h.maintained.length, 0);
+});
+
+test("preparation time budget yields with remaining items queued and resumes without duplicates", async () => {
+ const h = harness({ tick: 101 });
+ await h.run();
+ assert.deepEqual(h.state().importJobs.items[0].items.map(i => i.status), ["imported", "queued", "queued"]);
+ await h.run();
+ await h.run();
+ assert.equal(h.state().entries.length, 4);
+ assert.equal(h.state().importJobs.items[0].status, "completed");
+ assert.equal(h.state().importStaging.assets.length, 0);
+});
diff --git a/test/local-index-maintenance-ui.test.js b/test/local-index-maintenance-ui.test.js
index fff8b1e..dabe155 100644
--- a/test/local-index-maintenance-ui.test.js
+++ b/test/local-index-maintenance-ui.test.js
@@ -36,7 +36,7 @@ test("every material import queues local index completion without coupling it to
const curatedImport = background.slice(background.indexOf("async function applyCuratedImport"), background.indexOf("function curatedImportResponse"));
const automaticCompletion = background.slice(background.indexOf("async function enqueueAutomaticLibraryMaintenance"), background.indexOf("async function libraryMaintenanceStatus"));
- assert.match(localImport, /enqueueAutomaticLibraryMaintenance\(\[entry\]\)/);
+ assert.match(localImport, /enqueueAutomaticLibraryMaintenance\(imported\)/);
assert.match(packageImport, /enqueueAutomaticLibraryMaintenance/);
assert.match(curatedImport, /enqueueAutomaticLibraryMaintenance/);
assert.match(automaticCompletion, /libraryMaintenanceTargets/);
diff --git a/test/local-media.test.js b/test/local-media.test.js
index 08a53a3..9542e02 100644
--- a/test/local-media.test.js
+++ b/test/local-media.test.js
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import {
chunkedBlobFingerprint,
+ createExactMediaDuplicateIndex,
createUnsupportedLocalAssetReference,
detectLocalMediaFile,
findExactMediaDuplicate,
@@ -255,3 +256,48 @@ test("exact duplicate detection includes earlier files from the same import batc
assert.equal(result.duplicateAssetId, "batch:first");
assert.equal(result.contentHash, contentHash.contentHash);
});
+
+
+test("batch duplicate checks index stored metadata once and retain exact filename semantics", async () => {
+ let metadataReads = 0;
+ const entries = Array.from({ length: 1000 }, (_, index) => ({ mediaAssets: [{
+ id: `old:${index}`, get byteSize() { metadataReads += 1; return 4; },
+ mimeType: "image/png", sourceTitle: `old-${index}.png`, contentHash: "a".repeat(64)
+ }] }));
+ const index = createExactMediaDuplicateIndex(entries);
+ for (let i = 0; i < 100; i += 1) {
+ const file = new File(["data"], `new-${i}.png`, { type: "image/png" });
+ const result = await index.find(file);
+ assert.equal(result.duplicateAssetId, "");
+ index.add({ id: `new:${i}`, byteSize: 4, mimeType: "image/png", sourceTitle: file.name, contentHash: result.contentHash });
+ }
+ assert.equal(metadataReads, 1000, "batch growth must not rescan the existing library for each file");
+ assert.equal((await index.find(new File(["data"], "new-42.png", { type: "image/png" }))).duplicateAssetId, "new:42");
+ assert.equal((await index.find(new File(["diff"], "new-42.png", { type: "image/png" }))).duplicateAssetId, "");
+});
+
+test("unhashed stored originals are read only once per import and earlier matches retain priority", async () => {
+ const original = new File(["old!"], "same.png", { type: "image/png" });
+ const hash = (await findExactMediaDuplicate(original)).contentHash;
+ let reads = 0;
+ const index = createExactMediaDuplicateIndex([{ mediaAssets: [
+ { id: "first", byteSize: 4, mimeType: "image/png", sourceTitle: "same.png" },
+ { id: "later", byteSize: 4, mimeType: "image/png", sourceTitle: "same.png", contentHash: hash }
+ ] }], { readBlob: async () => { reads += 1; return original; } });
+ assert.equal((await index.find(original)).duplicateAssetId, "first");
+ for (let i = 0; i < 5; i += 1) await index.find(new File(["new!"], "same.png", { type: "image/png" }));
+ assert.equal(reads, 1);
+});
+
+test("frontend duplicate lookup reuses preparation hash but ordinary admission reads actual incoming bytes", async () => {
+ const file = new File(["data"], "one.png", { type: "image/png" });
+ const hash = (await findExactMediaDuplicate(file)).contentHash;
+ let reads = 0;
+ const stream = file.stream.bind(file);
+ file.stream = () => { reads += 1; return stream(); };
+ const index = createExactMediaDuplicateIndex();
+ assert.equal((await index.find(file, { contentHash: hash })).contentHash, hash);
+ assert.equal(reads, 0);
+ assert.equal((await index.find(file)).contentHash, hash);
+ assert.equal(reads, 1, "background admission must hash its own stored bytes");
+});
diff --git a/test/manual-sync.test.js b/test/manual-sync.test.js
index b78b713..23647ae 100644
--- a/test/manual-sync.test.js
+++ b/test/manual-sync.test.js
@@ -254,7 +254,7 @@ test("replacement recovery media is protected from sync orphan cleanup", async (
assert.equal(fixture.counts().mediaDeletes, 0);
});
-test("different device ids with complete identical meaning converge to one case and keep both projects", async () => {
+test("sync retains independent copies in different folders and fetches both originals", async () => {
const fixture = await createFixture();
fixture.state.entries[0].title = "Same";
fixture.state.entries[0].text = "Same";
@@ -289,10 +289,10 @@ test("different device ids with complete identical meaning converge to one case
const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
assert.equal(result.ok, true);
- assert.deepEqual(fixture.state.entries.map((item) => item.id), ["one"]);
- assert.deepEqual(fixture.state.organizerState.collections.map((project) => project.entryIds), [["one"], ["one"]]);
- assert.equal(fixture.counts().objectReads, 0);
- assert.equal(fixture.media.has("asset:remote"), false);
+ assert.deepEqual(fixture.state.entries.map((item) => item.id).sort(), ["one", "remote"]);
+ assert.deepEqual(fixture.state.organizerState.collections.map((project) => project.entryIds), [["one"], ["remote"]]);
+ assert.equal(fixture.counts().objectReads, 1);
+ assert.equal(fixture.media.has("asset:remote"), true);
});
test("one missing unsynced media item is reported and removed without blocking healthy cases", async () => {
@@ -523,3 +523,15 @@ function entry(id, assetId) {
primaryMediaId: assetId
};
}
+
+test("folder migration recovery originals survive remote deletion and orphan cleanup", async () => {
+ const fixture = await syncedTwoEntryFixture();
+ fixture.state.folderOwnershipBackup = { state: state([entry("one", "asset:one")]) };
+ await addRemoteDeletionOfFirstEntry(fixture);
+ fixture.resetCounts();
+ const result = await fixture.controller.start({ vault: fixture.vault, settings: fixture.settings });
+ assert.equal(result.ok, true);
+ assert.equal(fixture.state.entries.some(item => item.id === "one"), false);
+ assert.equal(fixture.media.has("asset:one"), true);
+ assert.equal(fixture.counts().mediaDeletes, 0);
+});
diff --git a/test/media-archive-ui.test.js b/test/media-archive-ui.test.js
index e79241a..1e32c65 100644
--- a/test/media-archive-ui.test.js
+++ b/test/media-archive-ui.test.js
@@ -83,7 +83,7 @@ test("folder restore derives its media budget before strict or rescue inspection
assert.match(restore, /maxFileBytes: largestMediaBytes/);
assert.match(restore, /maxImageBytes: largestMediaBytes/);
assert.match(restore, /maxVideoBytes: largestMediaBytes/);
- assert.match(restore, /inspectFolderBackupEnvelope\(files\)/);
+ assert.match(restore, /inspectFolderBackupEnvelope\(files,\s*\{\s*digest,\s*onProgress:/);
assert.match(restore, /sourceType:\s*envelope\.mode === "complete"[\s\S]*LIBRARY_TRANSFER_SOURCES\.COMPLETE_BACKUP[\s\S]*LIBRARY_TRANSFER_SOURCES\.RESCUE_BACKUP/);
assert.match(restore, /limits:\s*restoreLimits/);
assert.match(restore, /validateImage:\s*validateImportedImage/);
diff --git a/test/media-reference-resolver.test.js b/test/media-reference-resolver.test.js
index cbeebd2..63eb2f6 100644
--- a/test/media-reference-resolver.test.js
+++ b/test/media-reference-resolver.test.js
@@ -126,3 +126,17 @@ test("X posts remain source references and never masquerade as standalone video
assert.equal(reference.playback.embedUrl, "");
assert.notEqual(reference.playback.status, "playing");
});
+
+test('protocol-less video addresses use the same provider rules as full URLs', () => {
+ const input = 'bilibili.com/video/BV1gveN6WEpC/?trackid=web_pegasus_0.router-web-pegasus-2479516-sm4rx.1790183942202.146&spm_id_from=333.1007.tianma.1-3-3.click';
+ assert.equal(canonicalizeMediaReference(input), canonicalizeMediaReference(`https://${input}`));
+ for (const value of ['youtu.be/abc123', '//vimeo.com/12345', 'b23.tv/abc?token=123', 'example.com/watch?id=2', 'example.com:8443/watch?id=2']) {
+ const full = value.startsWith('//') ? `https:${value}` : `https://${value}`;
+ assert.equal(canonicalizeMediaReference(value), canonicalizeMediaReference(full));
+ assert.equal(detectMediaReferenceProvider(value), detectMediaReferenceProvider(full));
+ }
+ assert.equal(canonicalizeMediaReference('bilibili.com/video/BV1abc?p=3'), 'https://www.bilibili.com/video/BV1abc/?p=3');
+ for (const input of ['javascript:alert(1)', 'data:text/html,x', 'file:///tmp/a', '/video/BV1abc', 'not a url', 'https://user:[email protected]', 'example.com\\@evil.com']) {
+ assert.throws(() => canonicalizeMediaReference(input), /有效/);
+ }
+});
diff --git a/test/media-ui.test.js b/test/media-ui.test.js
index c1a2023..a584b02 100644
--- a/test/media-ui.test.js
+++ b/test/media-ui.test.js
@@ -108,7 +108,7 @@ test("video cards resolve a saved local poster and referenced video details stay
test("one top search surface keeps only a concise placeholder hint", () => {
const header = html.slice(html.indexOf("<header"), html.indexOf("</header>"));
assert.equal((header.match(/type="search"/g) ?? []).length, 1);
- assert.match(html, /id="project-search"[^>]*aria-label="搜索项目"/);
+ assert.doesNotMatch(html, /id="project-search"/);
assert.match(html, /placeholder="[^"]*type:video[^"]*"/);
assert.doesNotMatch(html, /id="search-help"|source:x\.com.*tag:电影感.*has:video/);
});
@@ -134,11 +134,11 @@ test("folder backup opens the picker before asynchronous preparation and creates
assert.ok(pickerCall < backup.indexOf("inspectLibraryTransfer({"));
assert.ok(backup.indexOf("confirmAppAction({") < backup.indexOf("parent.getDirectoryHandle"));
assert.match(backup, /plannedFiles\.set\(assetPath, blob\)/);
- assert.match(backup, /portableManagedBackupAsset\(asset, blob, assetPath, await sha256Blob\(blob\), portableFormat\)/);
+ assert.match(backup, /portableManagedBackupAsset\(asset, blob, assetPath, await digest\(blob, [\s\S]*?\), portableFormat\)/);
assert.match(backup, /materializeEntry\(item\.snapshot, `trash-entry-/);
assert.match(backup, /buildFolderBackupWritePlan\(\{/);
assert.match(backup, /for \(const \[path, blob\] of writePlan\.files\)/);
- assert.match(backup, /verifyFolderBackupCompletion\(writePlan\.marker, writtenFiles\)/);
+ assert.match(backup, /verifyFolderBackupCompletion\(writePlan\.marker, writtenFiles, readbackOptions\)/);
assert.ok(backup.indexOf("for (const [path, blob] of writePlan.files)") < backup.indexOf("writePlan.markerPath"));
assert.match(backup, /inspectPlannedBackup\(LIBRARY_TRANSFER_SOURCES\.COMPLETE_BACKUP\)/);
assert.match(backup, /inspectPlannedBackup\(LIBRARY_TRANSFER_SOURCES\.RESCUE_BACKUP,/);
diff --git a/test/organizer.test.js b/test/organizer.test.js
index 222b9fb..ebd957f 100644
--- a/test/organizer.test.js
+++ b/test/organizer.test.js
@@ -51,7 +51,7 @@ test("a case can belong to multiple project collections", () => {
assert.equal(deleteCollection(state, state.collections[0].id).collections.length, 1);
});
-test("source-aware moves remove only the current source and preserve other project memberships", () => {
+test("folder moves retain exactly one owner regardless of the originating view", () => {
let state = createCollection({}, "来源").state;
state = createCollection(state, "保留").state;
state = createCollection(state, "目标").state;
@@ -61,7 +61,7 @@ test("source-aware moves remove only the current source and preserve other proje
state = moveEntriesBetweenCollections(state, source.id, target.id, ["one"]);
- assert.deepEqual(state.collections.map((item) => item.entryIds), [[], ["one"], ["one"]]);
+ assert.deepEqual(state.collections.map((item) => item.entryIds), [[], [], ["one"]]);
});
test("moving from unassigned adds the target membership without a source collection", () => {
diff --git a/test/page-capture-site-adapters.test.js b/test/page-capture-site-adapters.test.js
index cd8f208..6faa72c 100644
--- a/test/page-capture-site-adapters.test.js
+++ b/test/page-capture-site-adapters.test.js
@@ -712,3 +712,14 @@ test("Krea detail keeps original and preview together and does not assign the wo
assert.equal(result.media[0].originalPrompt, "A cinematic silhouette.");
assert.equal(result.media[1].originalPrompt, undefined);
});
+
+test("untitled Pins use their own description or identity rather than repeating the creator name", () => {
+ const pin = (id, description) => normalizePageCaptureSitePayload({
+ adapter:'pinterest', canonicalUrl:`https://www.pinterest.com/pin/${id}/`,
+ pin:{entityId:id,description,author:{fullName:'Same creator'},images:{original:{url:'https://i.pinimg.com/originals/work.png'}}}
+ });
+ assert.equal(pin('123', 'Forest\n temple').title, 'Forest temple');
+ assert.equal(pin('123', '').title, 'Pinterest 123');
+ assert.equal(pin('456', '').title, 'Pinterest 456');
+ assert.equal(pin('456', '').sourceFacts.author, 'Same creator');
+});
diff --git a/test/page-capture.test.js b/test/page-capture.test.js
index 95db10c..ebc8e14 100644
--- a/test/page-capture.test.js
+++ b/test/page-capture.test.js
@@ -1081,3 +1081,23 @@ test("session image file bytes are not mislabeled as a screenshot fallback", asy
assert.equal(result.captureMethod, "page-session");
assert.equal(result.usedPixelFallback, false);
});
+
+test("capture names strip accessibility wrappers and untitled works retain distinct source identities", () => {
+ const candidate = (title, id) => normalizePageCaptureCandidate({
+ title, canonicalUrl: `https://www.pinterest.com/pin/${id}/`,
+ sourceFacts: { provider: 'pinterest', itemId: id },
+ media: [{ id, kind: 'image', url: `https://i.pinimg.com/originals/${id}.png`, alt: title, sourceTitle: title }]
+ });
+ const empty = candidate('其中包括图片:', '123456');
+ assert.equal(empty.title, 'Pinterest · 123456');
+ assert.equal(empty.media[0].alt, '');
+ assert.equal(empty.media[0].sourceTitle, '');
+ assert.notEqual(empty.title, candidate('其中包括图片:', '654321').title);
+ assert.equal(candidate('其中包括图片: Dragon and Artemis', '1').title, 'Dragon and Artemis');
+ assert.equal(candidate('Image may contain: Forest temple', '2').title, 'Forest temple');
+ assert.equal(candidate('作者原题:山海', '3').title, '作者原题:山海');
+ const generic = normalizePageCaptureCandidate({title:'',canonicalUrl:'https://portfolio.example/art/real-work',sourceFacts:{}});
+ assert.equal(generic.title, 'portfolio.example · art/real-work');
+ assert.equal(generic.sourceFacts.author, '');
+ assert.equal(generic.sourceFacts.publishedAt, '');
+});
diff --git a/test/page_capture_e2e.py b/test/page_capture_e2e.py
index 0282383..f97c7d8 100644
--- a/test/page_capture_e2e.py
+++ b/test/page_capture_e2e.py
@@ -163,9 +163,9 @@ def main() -> None:
collector.locator(".page-capture-article-media").first.click()
expect(collector.locator("#page-capture-media-viewer")).to_be_visible()
expect(collector.locator("#page-capture-media-stage img")).to_be_visible()
- expect(collector.locator("#page-capture-media-position")).to_have_text("媒体 2 / 6")
+ expect(collector.locator("#page-capture-media-position")).to_have_text("媒体 1 / 5")
collector.locator("#page-capture-media-next").click()
- expect(collector.locator("#page-capture-media-position")).to_have_text("媒体 3 / 6")
+ expect(collector.locator("#page-capture-media-position")).to_have_text("媒体 2 / 5")
collector.locator("#page-capture-media-close").click()
collector.locator(".page-capture-inspect").first.click()
@@ -173,8 +173,8 @@ def main() -> None:
collector.locator(".page-capture-confirm").first.click()
expect(collector.locator(".page-capture-item.confirmed")).to_have_count(1)
expect(collector.locator("#page-capture-media-review")).to_be_visible()
- expect(collector.locator("#page-capture-media-review-list .page-capture-media-review-item")).to_have_count(6)
- expect(collector.locator(".page-capture-media-review-group")).to_contain_text("可能遗漏媒体(1)")
+ expect(collector.locator("#page-capture-media-review-list .page-capture-media-review-item")).to_have_count(5)
+ expect(collector.locator(".page-capture-media-review-group")).to_have_count(0)
expect(collector.locator("#page-capture-media-review-status")).to_contain_text("5 项媒体")
expect(collector.locator("#page-capture-save")).to_be_enabled()
# Direct picking replaces the automatic scope, then appends subsequent choices.
diff --git a/test/pinterest-metadata.test.js b/test/pinterest-metadata.test.js
new file mode 100644
index 0000000..a879d02
--- /dev/null
+++ b/test/pinterest-metadata.test.js
@@ -0,0 +1,39 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { enrichPinterestCandidates } from '../extension/pinterest-capture.js';
+import { collectPageCaptureSitePayload, normalizePageCaptureSitePayload } from '../extension/page-capture-site-adapters.js';
+const pin = JSON.parse(await readFile(new URL('./fixtures/pinterest-pin-metadata.json',import.meta.url)));
+const url = `https://www.pinterest.com/pin/${pin.entityId}/`;
+const html = p => `<script>window.__PWS_RELAY_REGISTER_COMPLETED_REQUEST__("public", ${JSON.stringify({data:{v3GetPinQueryv2:{data:p}}})});</script>`;
+test('public work metadata replaces a board ID placeholder without replacing selected media identities', async () => {
+ const card={id:'card',title:`Pinterest ${pin.entityId}`,canonicalUrl:url,media:[{id:'selected-original',url:pin.images_orig.url}],sourceFacts:{provider:'pinterest',engagement:{reactions:252}}};
+ const result=await enrichPinterestCandidates({adapter:'pinterest',candidates:[card]}, {readHtml:async()=>html(pin)});
+ const work=result.candidates[0];
+ assert.equal(work.title,'Wukong vs heaven');assert.equal(work.sourceFacts.author,'ʀᴇᴅɢʀᴀᴠᴇ');
+ assert.equal(work.sourceFacts.authorUrl,'https://www.pinterest.com/LastSon_/');
+ assert.equal(work.sourceFacts.engagement.repins,471);assert.equal(work.sourceFacts.engagement.reactions,252);
+ assert.ok(work.sourceFacts.publishedAt);assert.ok(work.sourceFacts.imageDescription);
+ assert.equal(work.id,card.id);assert.equal(work.media[0].id,'selected-original');assert.equal(work.media[0].sourceTitle,'Wukong vs heaven');
+});
+test('another Pin or unavailable detail cannot masquerade as complete work metadata',async()=>{
+ const card={id:'card',title:'list description',canonicalUrl:url,media:[],sourceFacts:{}};
+ for(const readHtml of [async()=>html({...pin,entityId:'999'}),async()=>{throw new Error('HTTP 429');}]) {
+ const result=await enrichPinterestCandidates({adapter:'pinterest',candidates:[card]},{readHtml});
+ assert.equal(result.candidates[0].title,'list description');assert.equal(result.candidates[0].completeness,'partial');
+ assert.ok(result.candidates[0].sourceFacts.metadataError);
+ }
+});
+test('missing interaction counts remain unknown rather than fabricated zero',()=>{
+ const payload=collectPageCaptureSitePayload({pinterestUrl:url,pinterestHtml:html({...pin,repinCount:undefined}),maxCandidates:1,maxMedia:1,maxTextCharacters:100000});
+ assert.deepEqual(normalizePageCaptureSitePayload(payload,url).sourceFacts.engagement,{});
+});
+test('untitled detail still contributes real creator metadata, and cancellation retains found cards',async()=>{
+ const card={id:'card',title:'Visible artwork description',canonicalUrl:url,media:[{id:'original'}],sourceFacts:{}};
+ const result=await enrichPinterestCandidates({adapter:'pinterest',candidates:[card]}, {readHtml:async()=>html({...pin,title:'',gridTitle:'',seoTitle:'',closeupUnifiedTitle:''})});
+ assert.equal(result.candidates[0].title,card.title);
+ assert.equal(result.candidates[0].sourceFacts.author,'ʀᴇᴅɢʀᴀᴠᴇ');
+ const stopped=await enrichPinterestCandidates({adapter:'pinterest',candidates:[card]}, {cancelled:()=>true,readHtml:()=>{throw new Error('must not fetch');}});
+ assert.equal(stopped.candidates.length,1);assert.deepEqual(stopped.candidates[0].media,card.media);
+ assert.equal(stopped.candidates[0].completeness,'partial');
+});
diff --git a/test/pinterest_metadata_e2e.py b/test/pinterest_metadata_e2e.py
new file mode 100644
index 0000000..7853f99
--- /dev/null
+++ b/test/pinterest_metadata_e2e.py
@@ -0,0 +1,49 @@
+"""User-reported public Pin metadata survives both board and detail capture."""
+import json,tempfile
+from pathlib import Path
+from datetime import datetime,timezone
+from e2e_support import EXTENSION_DIR,extension_session
+from page_capture_e2e import PNG
+
+
+def main():
+ pin=json.loads((Path(__file__).parent/'fixtures/pinterest-pin-metadata.json').read_text())
+ url=f'https://www.pinterest.com/pin/{pin["entityId"]}/'
+ board='https://www.pinterest.com/fixture/metadata/'
+ script='<script>window.__PWS_RELAY_REGISTER_COMPLETED_REQUEST__=()=>{};window.__PWS_RELAY_REGISTER_COMPLETED_REQUEST__("public", '+json.dumps({'data':{'v3GetPinQueryv2':{'data':pin}}})+');</script>'
+ detail=script+f'''<main aria-label="Closeup content container"><h1>{pin['title']}</h1><img src="{pin['images_orig']['url']}" width=240 height=320><div><div><div><div><button aria-label="回应">回应</button></div></div><span>252</span></div><div><button aria-label="评论"></button></div></div></main>'''
+ with tempfile.TemporaryDirectory(prefix='pd-pin-metadata-') as tmp:
+ extension=Path(tmp)
+ for path in EXTENSION_DIR.iterdir():
+ if path.name!='manifest.json':(extension/path.name).symlink_to(path,target_is_directory=path.is_dir())
+ manifest=json.loads((EXTENSION_DIR/'manifest.json').read_text());manifest['host_permissions']+=['https://www.pinterest.com/*','https://i.pinimg.com/*']
+ (extension/'manifest.json').write_text(json.dumps(manifest))
+ with extension_session('pd-pin-metadata-',extension_dir=extension) as run:
+ run.context.route('https://i.pinimg.com/**',lambda r:r.fulfill(status=200,content_type='image/png',body=PNG))
+ run.context.route('https://www.pinterest.com/**',lambda r:r.fulfill(status=200,content_type='text/html; charset=utf-8',body=detail if '/pin/' in r.request.url else f'<main><div data-test-id="pinWrapper"><a href="{url}"><img alt="其中包括图片:" src="{pin["images_orig"]["url"]}" width=240 height=320></a></div></main>'))
+ setup=run.open_page('collector.html');run.seed_storage(setup,{'entries':[],'capturePermissionOnboarding':{'version':1,'acknowledgedAt':datetime.now(timezone.utc).isoformat(),'clipboardIncluded':True}})
+ source=run.context.new_page()
+ for page in [board,url]:
+ source.goto(page);source.bring_to_front()
+ captured=setup.evaluate("async()=>chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'})")
+ assert captured.get('ok'),captured
+ c=captured['batch']['candidates'][0]
+ assert c['title']=='Wukong vs heaven',c
+ assert c['sourceFacts']['author']=='ʀᴇᴅɢʀᴀᴠᴇ',c
+ assert c['sourceFacts']['engagement']['repins']==471,c
+ if page==url:
+ assert c['sourceFacts']['engagement']['reactions']==252,c
+ chosen=setup.evaluate("async c=>(await import('./page-capture.js')).pageCaptureDefaultMediaIds(c)",c)
+ assert len(chosen)==1,c
+ batch=captured['batch']
+ batch['selections']=[{'candidateId':c['id'],'includeText':True,'selectedMediaIds':[m['id'] for m in c['media']],'mediaDecision':'confirmed'}]
+ saved=setup.evaluate("async batch=>chrome.runtime.sendMessage({type:'COMMIT_PAGE_CAPTURE',batch})",batch);assert saved.get('ok'),saved
+ setup.reload();entries=setup.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_STATE'})).entries")
+ assert len(entries)==1,entries
+ work=entries[0];assert work['title']=='Wukong vs heaven',work
+ facts=work['sourceFacts'];assert facts['authorUrl']=='https://www.pinterest.com/LastSon_/',facts
+ assert facts['engagement']=={'repins':471,'reactions':252},facts
+ assert facts['publishedAt'] and facts['imageDescription'],facts
+ print('PASS board detail hydration and single Pin save/reload: title, creator/profile, published time, image description, 471 saves and 252 reactions')
+
+if __name__=='__main__':main()
diff --git a/test/preferences.test.js b/test/preferences.test.js
index 4e1b68c..415fbca 100644
--- a/test/preferences.test.js
+++ b/test/preferences.test.js
@@ -15,8 +15,11 @@ test("UI preferences accept only supported locale theme and motion values", () =
motion: "system",
analysisDiagnostics: false,
sidebarWidth: 244,
+ sidebarLayout: { collapsed: false, open: ["projects"], order: ["projects", "types", "tags"] },
detailMode: "fullscreen",
detailSidebarWidth: 760,
+ galleryView: "waterfall",
+ includeSubprojects: false,
detailPanelRatio: null
});
assert.deepEqual(normalizeUiPreferences({ locale: "en", theme: "dark", motion: "none", analysisDiagnostics: true }), {
@@ -25,8 +28,11 @@ test("UI preferences accept only supported locale theme and motion values", () =
motion: "reduced",
analysisDiagnostics: true,
sidebarWidth: 244,
+ sidebarLayout: { collapsed: false, open: ["projects"], order: ["projects", "types", "tags"] },
detailMode: "fullscreen",
detailSidebarWidth: 760,
+ galleryView: "waterfall",
+ includeSubprojects: false,
detailPanelRatio: null
});
assert.equal(normalizeUiPreferences({ theme: "light", motion: "reduced" }).theme, "light");
@@ -55,3 +61,18 @@ test("system locale resolves Chinese browsers to Chinese and everything else to
assert.equal(resolveLocale({ locale: "system" }, "en-US"), "en");
assert.equal(resolveLocale({ locale: "zh-CN" }, "en-US"), "zh-CN");
});
+
+
+test("browse preferences keep folder scope and reject removed or unknown views", () => {
+ assert.equal(normalizeUiPreferences({galleryView: "list", includeSubprojects: true}).galleryView, "list");
+ assert.equal(normalizeUiPreferences({includeSubprojects: true}).includeSubprojects, true);
+ assert.equal(normalizeUiPreferences({galleryView: "columns"}).galleryView, "waterfall");
+ assert.equal(normalizeUiPreferences({includeSubprojects: "false"}).includeSubprojects, false);
+});
+
+test("sidebar layout keeps old users on projects and sanitizes saved module state", () => {
+ assert.deepEqual(normalizeUiPreferences({}).sidebarLayout, { collapsed: false, open: ["projects"], order: ["projects", "types", "tags"] });
+ assert.deepEqual(normalizeUiPreferences({sidebarLayout: {collapsed:true, open:["tags","tags","unknown"],order:["types","types","unknown"]}}).sidebarLayout,
+ {collapsed:true, open:["tags"], order:["types","projects","tags"]});
+ assert.deepEqual(normalizeUiPreferences({sidebarLayout: {open:[]}}).sidebarLayout.open, []);
+});
diff --git a/test/project_tree_e2e.py b/test/project_tree_e2e.py
index 31a2062..d0384f9 100644
--- a/test/project_tree_e2e.py
+++ b/test/project_tree_e2e.py
@@ -71,19 +71,18 @@ def main():
page.reload(wait_until='networkidle')
expect(row(page,'child')).to_have_count(0)
row(page,'p0').locator('.project-filter').click()
- page.locator('#project-search').fill('子项目')
- expect(page.locator('.project-row')).to_have_count(3)
- expect(row(page,'child').locator('.project-search-path')).to_contain_text('项目 000')
- expect(row(page,'other-child').locator('.project-search-path')).to_contain_text('项目 001')
+ expect(page.locator('#project-search')).to_have_count(0)
+ row(page,'p0').locator('.project-disclosure').click()
+ row(page,'p1').locator('.project-disclosure').click()
+ expect(row(page,'child')).to_be_visible()
+ expect(row(page,'other-child')).to_be_visible()
assert row(page,'child').locator('.project-filter').bounding_box()['width'] > 100
- page.locator('#project-search').fill('')
- expect(row(page,'child')).to_have_count(0)
+ page.locator('#collapse-projects').click()
# A distant target is chosen by name, with no long drag or full expansion.
- page.locator('#project-search').fill('099')
+ row(page,'p99').scroll_into_view_if_needed()
dialog = move_dialog(page,'p99','000','项目 000','before')
dialog.get_by_role('button',name='移动',exact=True).click()
expect(dialog).to_have_count(0)
- page.locator('#project-search').fill('')
expect(page.locator('.project-filter-name').first).to_have_text('项目 099')
page.locator('#project-move-undo').click()
expect(page.locator('.project-filter-name').first).to_have_text('项目 000')
@@ -95,19 +94,19 @@ def main():
assert panel.bounding_box()['y'] >= 0
page.keyboard.press('Escape')
# Move a whole subtree and undo without changing membership.
- page.locator('#project-search').fill('000')
+ row(page,'p0').scroll_into_view_if_needed()
dialog = move_dialog(page,'p0','001','项目 001')
dialog.get_by_role('button',name='移动',exact=True).click()
expect(dialog).to_have_count(0)
moved = {p['id']:p for p in state(page)}
assert moved['p0']['parentId'] == 'p1'
assert moved['child']['parentId'] == 'p0' and moved['child']['entryIds'] == ['case']
- assert moved['grandchild']['entryIds'] == ['case']
+ assert len(moved['grandchild']['entryIds']) == 1 and moved['grandchild']['entryIds'] != ['case']
page.locator('#project-move-undo').click()
expect(page.locator('#project-order-status')).to_contain_text('已撤销')
- page.locator('#project-search').fill('')
# Root moves are accessible through the same picker, with a visible root placement.
- page.locator('#project-search').fill('深层项目')
+ row(page,'p0').locator('.project-disclosure').click()
+ row(page,'child').locator('.project-disclosure').click()
dialog = move_dialog(page,'grandchild','项目根目录','项目根目录')
expect(dialog.locator('[name="position"]')).to_be_disabled()
dialog.get_by_role('button',name='移动',exact=True).click()
@@ -115,7 +114,7 @@ def main():
assert next(p for p in state(page) if p['id']=='grandchild')['parentId'] is None
page.locator('#project-move-undo').click()
expect(page.locator('#project-order-status')).to_contain_text('已撤销')
- page.locator('#project-search').fill('')
+ page.locator('#collapse-projects').click()
# Direct pointer drag, without a manage-mode click.
row(page,'p0').scroll_into_view_if_needed()
drag_to(page,'p2','p1','before')
@@ -137,15 +136,15 @@ def main():
assert state(page) == baseline
# Edge scrolling continues while the pointer is stationary.
drag_to(page,'p2','p3')
- sidebar = page.locator('#filter-sidebar')
+ sidebar = page.locator('#sidebar-projects-body')
box = sidebar.bounding_box()
before = sidebar.evaluate('node => node.scrollTop')
page.mouse.move(box['x']+box['width']/2,box['y']+box['height']-8)
- page.wait_for_function('(before) => document.querySelector("#filter-sidebar").scrollTop > before + 120',arg=before)
+ page.wait_for_function('(before) => document.querySelector("#sidebar-projects-body").scrollTop > before + 120',arg=before)
page.keyboard.press('Escape')
page.mouse.up()
# Failure is explicit and does not claim success or change data.
- page.locator('#project-search').fill('002')
+ row(page,'p2').scroll_into_view_if_needed()
dialog = move_dialog(page,'p2','001','项目 001')
page.evaluate("""() => {window.originalSend=chrome.runtime.sendMessage;chrome.runtime.sendMessage=(m,...args)=>m.type==='MOVE_COLLECTION'?Promise.resolve({ok:false,message:'模拟项目保存失败'}):window.originalSend.call(chrome.runtime,m,...args)}""")
baseline = state(page)
@@ -154,11 +153,10 @@ def main():
assert state(page) == baseline
dialog.get_by_role('button',name='取消',exact=True).click()
page.evaluate('() => {chrome.runtime.sendMessage=window.originalSend}')
- page.locator('#project-search').fill('')
row(page,'p0').scroll_into_view_if_needed()
# Keep toolbar reachable after a long scroll and menu usable in a narrow window.
row(page,'p99').scroll_into_view_if_needed()
- expect(page.locator('#project-search')).to_be_in_viewport()
+ expect(page.locator('#collapse-projects')).to_be_in_viewport()
page.set_viewport_size({'width':760,'height':740})
if not row(page,'p99').is_visible():
page.locator('#toggle-filters').click()
@@ -167,7 +165,7 @@ def main():
expect(row(page,'p99').get_by_role('button',name='移动到…',exact=True)).to_be_in_viewport()
page.keyboard.press('Escape')
page.set_viewport_size({'width':1280,'height':900})
- page.locator('#filter-sidebar').evaluate('node => node.scrollTop = 0')
+ page.locator('#sidebar-projects-body').evaluate('node => node.scrollTop = 0')
if os.environ.get('PROMPTDIRECTOR_PROJECT_TREE_EVIDENCE'):
folder = Path(os.environ['PROMPTDIRECTOR_PROJECT_TREE_EVIDENCE'])
folder.mkdir(parents=True,exist_ok=True)
diff --git a/test/projects_and_categories_e2e.py b/test/projects_and_categories_e2e.py
index 4b3fe17..2601f58 100644
--- a/test/projects_and_categories_e2e.py
+++ b/test/projects_and_categories_e2e.py
@@ -104,7 +104,7 @@ def main() -> None:
library.locator(".project-filter", has_text="辅助项目").click()
expect(library.locator("#project-folder-list .project-folder-card", has_text="项目与分类验收")).to_be_visible()
- expect(library.locator("#result-count")).to_have_text("0 个直接案例 · 1 个子项目")
+ expect(library.locator("#result-count")).to_have_text("0 个案例 · 1 子项目")
library.locator("#project-folder-list .project-folder-card", has_text="项目与分类验收").click()
expect(library.locator("#manage-case-order")).to_be_visible()
library.locator("#gallery-sort").select_option("project-manual")
diff --git a/test/release-experience.test.js b/test/release-experience.test.js
index 301ab35..3d47aa7 100644
--- a/test/release-experience.test.js
+++ b/test/release-experience.test.js
@@ -30,7 +30,8 @@ test("video links and quick notes each use a purpose-built one-step form", async
assert.match(video, /showAppDialog\(\{/);
assert.match(video, /title:\s*"添加视频链接"/);
- assert.match(video, /type:\s*"url"/);
+ assert.match(video, /type:\s*"text"/);
+ assert.match(video, /inputMode:\s*"url"/);
assert.match(video, /pendingLabel:\s*"正在解析链接并保存…"/);
assert.match(note, /showAppDialog\(\{/);
assert.match(note, /type:\s*"textarea"/);
diff --git a/test/run_e2e.py b/test/run_e2e.py
index 74e244e..7606122 100644
--- a/test/run_e2e.py
+++ b/test/run_e2e.py
@@ -23,6 +23,10 @@ SCRIPTS = [
"capture_and_cross_page_e2e.py",
"library_core_e2e.py",
"library_navigation_e2e.py",
+ "library_browse_views_e2e.py",
+ "library_folder_ownership_e2e.py",
+ "library_modular_layout_e2e.py",
+ "library_hidden_scroll_e2e.py",
"library_browse_return_e2e.py",
"curated_workflow_e2e.py",
"curated_skills_install_e2e.py",
@@ -47,6 +51,7 @@ SCRIPTS = [
"case_covers_e2e.py",
"x_post_capture_e2e.py",
"media_reference_cards_e2e.py",
+ "dialog_input_safety_e2e.py",
"library_detail_actions_e2e.py",
"library_detail_rendering_e2e.py",
"library_detail_sidebar_responsive_e2e.py",
@@ -94,6 +99,7 @@ SCRIPTS = [
"x_comment_capture_e2e.py",
"x_video_playback_e2e.py",
"higgsfield_capture_e2e.py",
+ "asset_board_capture_e2e.py",
"feishu_capture_e2e.py",
"generic_scroll_capture_e2e.py",
"article_cases_capture_e2e.py",
@@ -110,6 +116,8 @@ SCRIPTS = [
"composer_video_dialogue_e2e.py",
"composer_reference_inputs_e2e.py",
"creative_skills_e2e.py",
+ "skill_source_video_e2e.py",
+ "selection_video_preview_e2e.py",
"skill_cover_e2e.py",
"skill_source_density_e2e.py",
"manager_regression_e2e.py",
@@ -123,6 +131,7 @@ SCRIPTS = [
"ui_regressions_e2e.py",
"settings_visual_anchor_e2e.py",
"settings_compact_e2e.py",
+ "settings_tab_stability_e2e.py",
"brand_i18n_e2e.py",
"english_interaction_states_e2e.py",
"case_management_batch_regression_e2e.py",
@@ -130,6 +139,10 @@ SCRIPTS = [
CASE_MANAGEMENT_SCRIPTS = [
"library_navigation_e2e.py",
+ "library_browse_views_e2e.py",
+ "library_folder_ownership_e2e.py",
+ "library_modular_layout_e2e.py",
+ "library_hidden_scroll_e2e.py",
"library_browse_return_e2e.py",
"historical_zip_salvage_e2e.py",
"video_detail_layout_e2e.py",
diff --git a/test/selection_video_preview_e2e.py b/test/selection_video_preview_e2e.py
new file mode 100644
index 0000000..c1d7d90
--- /dev/null
+++ b/test/selection_video_preview_e2e.py
@@ -0,0 +1,78 @@
+"""Both selection surfaces show motion without changing the selected references."""
+import tempfile
+import base64
+from pathlib import Path
+from playwright.sync_api import expect
+from e2e_support import base_entry, extension_session
+from video_detail_layout_e2e import video_asset
+
+
+def main():
+ entry = base_entry('motion-source', '动作视频来源', '保留完整原始提示词', 'content:prompt:video', 1)
+ asset = video_asset('motion-video', '2026-08-08T00:00:00.000Z')
+ entry['mediaAssets'] = [asset]
+ entry['primaryMediaId'] = asset['id']
+ entry['mediaPrompts'] = [{'assetId':asset['id'],'text':'保留完整原始提示词'}]
+ long_name = '多层项目中的完整名称必须可以读到最后一个字'
+ with extension_session('pd-selection-video-') as run:
+ setup = run.open_page('collector.html')
+ run.seed_storage(setup, {'entries':[entry], 'organizerState':{'version':6,'collections':[{'id':'collection:long','name':long_name,'order':0,'entryIds':[entry['id']]}]}})
+ setup.evaluate('''async ({id,data}) => { const {saveMediaBlob}=await import('./media-store.js');
+ await saveMediaBlob(id,new Blob([Uint8Array.from(atob(data),c=>c.charCodeAt(0))],{type:'video/mp4'}),{checkCapacity:false});
+ }''', {'id':asset['id'],'data':base64.b64encode((Path(__file__).parent/'fixtures/detail-portrait-smoke.mp4').read_bytes()).decode()})
+ skills = run.open_page('skills.html')
+ skills.locator('#skill-create').click()
+ skills.locator('#skill-project-picker summary').click()
+ menu = skills.locator('#skill-project-filter')
+ expect(menu).to_contain_text(long_name)
+ assert menu.bounding_box()['width'] > 250
+ assert menu.locator('button').last.evaluate('(e)=>e.scrollWidth<=e.clientWidth+1')
+ skills.screenshot(path=str(Path(tempfile.gettempdir()) / "pd-skill-project-menu.png"))
+ menu.get_by_role('option',name=long_name).click()
+ skills.wait_for_function('() => document.querySelector(".skill-video-cover video")?.readyState >= 2')
+ skills.locator('.skill-case-visual').hover()
+ hover=skills.locator('.case-video-preview')
+ expect(hover).to_be_visible()
+ skills.wait_for_function('() => document.querySelector(".case-video-preview")?.currentTime > 0')
+ expect(skills.locator('.skill-case')).to_have_attribute('data-selected','false')
+ skills.locator('#skill-workspace-title').hover()
+ expect(hover).to_have_count(0)
+ skills.locator('.skill-case-play').click()
+ skills.wait_for_function('() => document.querySelector(".skill-source-video video")?.currentTime > 0')
+ skills.locator('#skill-source-cancel').click()
+ expect(skills.locator('#skill-selected-count')).to_have_text('0')
+ page = run.open_page('composer.html?type=video')
+ page.locator('#composer-reference-open').click()
+ surface = page.locator('.composer-case-select-preview').first
+ surface.hover()
+ page.wait_for_function('() => document.querySelector(".case-video-preview")?.currentTime > 0')
+ expect(page.locator('.composer-case-preview-checkbox')).not_to_be_checked()
+ page.screenshot(path=str(Path(tempfile.gettempdir()) / "pd-composer-video-hover.png"))
+ page.locator('#composer-reference-search').hover()
+ expect(page.locator('.case-video-preview')).to_have_count(0)
+ page.get_by_role('button',name='播放视频',exact=True).click()
+ page.wait_for_function('() => document.querySelector(".composer-reference-preview-dialog video")?.currentTime > 0')
+ page.get_by_role('button',name='关闭视频预览').click()
+ expect(page.locator('.composer-reference-preview-dialog')).to_have_count(0)
+ surface.hover()
+ expect(page.locator('.case-video-preview')).to_have_count(1)
+ page.locator('#composer-reference-cancel').click()
+ expect(page.locator('.case-video-preview')).to_have_count(0)
+ # Image-direction users still need to watch a video before borrowing its text.
+ image_page = run.open_page('composer.html?type=image')
+ image_page.locator('#composer-reference-open').click()
+ image_surface = image_page.locator('.composer-case-select-preview').first
+ expect(image_page.locator('.composer-case-inspect svg use')).to_have_attribute('href', __import__('re').compile(r'#icon-play$'))
+ expect(image_page.locator('.composer-case-inspect')).to_have_text('')
+ image_surface.hover()
+ image_page.wait_for_function('() => document.querySelector(".case-video-preview")?.currentTime > 0')
+ image_page.get_by_role('button', name='播放视频', exact=True).click()
+ image_page.wait_for_function('() => document.querySelector(".composer-reference-preview-dialog video")?.currentTime > 0')
+ image_page.get_by_role('button', name='关闭视频预览').click()
+ image_page.locator('.composer-case-preview-checkbox').check()
+ expect(image_page.locator('#composer-case-selection-count')).to_contain_text('1')
+ image_page.locator('#composer-reference-apply').click()
+ expect(image_page.locator('#composer-reference-open')).to_contain_text('1')
+ print('PASS long project menu, decoded video cover, Skill and Composer hover/play/leave/close, selection unchanged')
+
+if __name__=='__main__': main()
diff --git a/test/settings_tab_stability_e2e.py b/test/settings_tab_stability_e2e.py
new file mode 100644
index 0000000..6f635d7
--- /dev/null
+++ b/test/settings_tab_stability_e2e.py
@@ -0,0 +1,48 @@
+"""Settings tabs retain one visible frame while their contents scroll."""
+from pathlib import Path
+import tempfile
+from playwright.sync_api import expect
+from e2e_support import extension_session
+
+
+def main():
+ output = Path(tempfile.gettempdir()) / "pd-settings41-evidence"
+ output.mkdir(exist_ok=True)
+ with extension_session("pd-settings41-") as session:
+ setup = session.open_page("collector.html")
+ for width, height in [(1440, 900), (900, 600), (390, 844)]:
+ for theme in ["light", "dark"]:
+ for locale in ["zh-CN", "en"]:
+ session.seed_storage(setup, {"uiPreferences": {"theme": theme, "locale": locale, "motion": "reduced"}})
+ page = session.open_page("library.html", wait_until="networkidle")
+ page.set_viewport_size({"width": width, "height": height})
+ dialog = page.locator("#settings-dialog")
+ if not dialog.is_visible():
+ page.locator("#open-settings").click()
+ baseline = None
+ for tab in ["general", "ai", "rules", "tasks", "general"]:
+ page.locator(f'[data-settings-tab="{tab}"]').click()
+ expect(page.locator(f'[data-settings-tab="{tab}"]')).to_have_attribute("aria-selected", "true")
+ panel = page.locator(f"#settings-{tab}-panel")
+ expect(panel).to_be_visible()
+ page.evaluate("() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))")
+ box = dialog.bounding_box()
+ if baseline is None:
+ baseline = box
+ assert all(abs(box[key] - baseline[key]) <= 1 for key in box), (tab, baseline, box)
+ assert box["x"] >= 0 and box["y"] >= 0, box
+ assert box["x"] + box["width"] <= width + 1 and box["y"] + box["height"] <= height + 1, (width, height, theme, locale, tab, box, page.evaluate("({width: innerWidth, height: innerHeight, mobile: matchMedia('(max-width: 700px)').matches})"))
+ overflow = panel.evaluate("el => ({width: el.clientWidth, scroll: el.scrollWidth, height: el.clientHeight, content: el.scrollHeight})")
+ assert overflow["scroll"] <= overflow["width"] + 1, (tab, overflow)
+ panel.evaluate("el => el.scrollTop = el.scrollHeight")
+ assert dialog.bounding_box() == box
+ panel.evaluate("el => el.scrollTop = 0")
+ if width in [1440, 390] and locale == "zh-CN" and tab in ["ai", "tasks"]:
+ page.mouse.move(width - 1, height - 1)
+ page.screenshot(path=str(output / f"{width}-{theme}-{tab}.png"))
+ page.close()
+ print({"stable_settings_tabs": True, "viewports": 3, "themes": 2, "locales": 2, "screenshots": str(output)})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/sharing_and_data_safety_e2e.py b/test/sharing_and_data_safety_e2e.py
index 1db54bd..c2819f1 100644
--- a/test/sharing_and_data_safety_e2e.py
+++ b/test/sharing_and_data_safety_e2e.py
@@ -558,6 +558,35 @@ def main() -> None:
assert "local-before-exact" in rollback_state["entryIds"], rollback_state
assert rollback_state["activeImageId"] == "share-image-one", rollback_state
+ # Several cases may intentionally share one stored original. Backup must
+ # keep both cases, their independent prompts and the original bytes.
+ library.evaluate(
+ """async () => {
+ const {entries} = await chrome.storage.local.get('entries');
+ const original = entries.find(entry => entry.mediaAssets?.some(asset => asset.kind === 'image'));
+ window.__beforeSharedBackupEntries = entries;
+ await chrome.storage.local.set({entries: [...entries, {
+ ...original, id: 'shared-original-case', title: '共享原件独立案例', text: '独立正文必须保留'
+ }]});
+ window.__installBackupRoot();
+ }"""
+ )
+ library.locator("#create-folder-backup").click()
+ expect(library.locator("#data-safety-feedback")).to_contain_text("完整备份已完成", timeout=15_000)
+ shared_backup = library.evaluate(
+ """async () => {
+ const folder = [...window.__backupRoot.directories.values()][0];
+ const data = JSON.parse(await (await folder.files.get('library.json').getFile()).text());
+ const shared = data.entries.find(entry => entry.id === 'shared-original-case');
+ return {text: shared.text, mediaCount: shared.mediaAssets.length,
+ complete: folder.files.has('complete.json'),
+ owners: data.entries.filter(entry => entry.mediaAssets.some(asset => asset.id === shared.mediaAssets[0].id)).length};
+ }"""
+ )
+ assert shared_backup["complete"] and shared_backup["mediaCount"] > 0, shared_backup
+ assert shared_backup["owners"] == 1 and shared_backup["text"] == "独立正文必须保留", shared_backup
+ library.evaluate("() => chrome.storage.local.set({entries: window.__beforeSharedBackupEntries})")
+
library.evaluate(
"""async () => {
const stored = await chrome.storage.local.get('entries');
diff --git a/test/skill_source_density_e2e.py b/test/skill_source_density_e2e.py
index acc61e8..fedd938 100644
--- a/test/skill_source_density_e2e.py
+++ b/test/skill_source_density_e2e.py
@@ -124,8 +124,11 @@ def main() -> None:
expect(skills.locator("#skill-selection-summary")).to_contain_text("文档 1")
expect(skills.locator("#skill-selection-summary")).to_contain_text("案例文字 2")
- skills.locator("#skill-case-load-more").click()
+ skills.evaluate("window.firstSkillCard = document.querySelector('.skill-case')")
+ skills.locator("#skill-case-scroll").hover()
+ skills.mouse.wheel(0, 2400)
expect(skills.locator(".skill-case")).to_have_count(48)
+ assert skills.evaluate("window.firstSkillCard === document.querySelector('.skill-case')")
skills.locator("#skill-case-search").fill("真实密度案例 58")
expect(skills.locator(".skill-case")).to_have_count(1)
expect(skills.locator("#skill-selected-count")).to_have_text("2")
diff --git a/test/skill_source_video_e2e.py b/test/skill_source_video_e2e.py
new file mode 100644
index 0000000..24c79ff
--- /dev/null
+++ b/test/skill_source_video_e2e.py
@@ -0,0 +1,59 @@
+"""Video source preview must not change the material selected for Skill extraction."""
+import tempfile
+import base64
+from pathlib import Path
+from playwright.sync_api import expect
+from e2e_support import base_entry, extension_session
+from video_detail_layout_e2e import video_asset
+
+
+def main():
+ entry = base_entry('skill-video', '视频预览验收', '', 'content:prompt:video', 1)
+ entry['text'] = ''
+ asset = video_asset('skill-video-asset', '2026-08-08T00:00:00.000Z')
+ entry['mediaAssets'] = [asset]
+ entry['primaryMediaId'] = asset['id']
+ data = base64.b64encode((Path(__file__).parent/'fixtures/detail-portrait-smoke.mp4').read_bytes()).decode()
+ with extension_session('pd-skill-source-video-') as run:
+ setup = run.open_page('collector.html')
+ run.seed_storage(setup, {'entries':[entry]})
+ setup.evaluate('''async ({data,id}) => {
+ const {saveMediaBlob} = await import('./media-store.js');
+ await saveMediaBlob(id,new Blob([Uint8Array.from(atob(data),c=>c.charCodeAt(0))],{type:'video/mp4'}),{checkCapacity:false});
+ }''', {'data':data,'id':asset['id']})
+ page = run.open_page('skills.html')
+ page.locator('#skill-create').click()
+ page.locator('.skill-case-toggle').click()
+ page.locator('.skill-case-detail').click()
+ video = page.locator('.skill-source-video video')
+ expect(video).to_be_visible()
+ assert video.evaluate('(v)=>!v.getAttribute("src") && v.preload==="none"')
+ selected = page.locator('.skill-source-asset input:checked').count()
+ page.evaluate('''() => {
+ window.previewVideo = document.querySelector('.skill-source-video video');
+ window.previewVideo.muted = true; window.previewVideo.loop = true;
+ }''')
+ page.locator('#skill-source-inspector').get_by_role('button',name='播放视频',exact=True).click()
+ page.wait_for_function('() => window.previewVideo.currentTime > 0 && !window.previewVideo.paused')
+ assert page.locator('.skill-source-asset input:checked').count() == selected
+ assert page.locator('#skill-source-apply').bounding_box()['height'] < 60
+ page.screenshot(path=str(Path(tempfile.gettempdir()) / "pd-skill-video-wide.png"))
+ page.locator('#skill-source-cancel').click()
+ assert page.evaluate('window.previewVideo.paused && !window.previewVideo.getAttribute("src")')
+ page.locator('.skill-case-detail').click()
+ assert page.locator('.skill-source-asset input:checked').count() == selected
+ page.set_viewport_size({'width':390,'height':844})
+ page.screenshot(path=str(Path(tempfile.gettempdir()) / "pd-skill-video-narrow.png"))
+ assert page.locator('#skill-source-inspector').evaluate('(e)=>e.getBoundingClientRect().width<=innerWidth')
+ page.locator('#skill-source-apply').click()
+ expect(page.locator('#skill-selected-count')).to_have_text('1')
+ # Missing original reports the real failure and leaves the selection usable.
+ page.evaluate('''async id => { const {deleteMediaBlobs}=await import('./media-store.js'); await deleteMediaBlobs([id]); }''',asset['id'])
+ page.locator('.skill-case-detail').click()
+ page.locator('#skill-source-inspector').get_by_role('button',name='播放视频',exact=True).click()
+ expect(page.locator('.skill-source-video [role=status]')).to_contain_text('本地媒体文件缺失')
+ assert page.locator('.skill-source-asset input:checked').count() == selected
+ page.locator('#skill-source-cancel').click()
+ print('PASS single-video content entry, lazy real playback, independent selection, close cleanup, reopen, narrow layout and missing-original recovery')
+
+if __name__ == '__main__': main()
diff --git a/test/trash-background.test.js b/test/trash-background.test.js
index 99ba073..633179e 100644
--- a/test/trash-background.test.js
+++ b/test/trash-background.test.js
@@ -43,14 +43,15 @@ test("trash restore and irreversible cleanup have separate explicit message cont
assert.match(cleanup, /永久删除/);
});
-test("free-label and project batch actions are wired with add, remove, and move modes", () => {
+test("project batch actions use independent copies and default moves", () => {
for (const type of ["UPDATE_ENTRY_CUSTOM_LABELS", "BATCH_ADD_CUSTOM_LABELS", "BATCH_SET_PROJECT"]) {
assert.match(background, new RegExp(`case "${type}"`));
}
const labels = functionBlock("updateEntryCustomLabels", "batchAddCustomLabels");
assert.match(labels, /customLabels/);
const projects = functionBlock("batchSetProject", "updateOrganizer");
- assert.match(projects, /\["remove", "move"\]\.includes\(message\.mode\)/);
+ assert.match(projects, /planCaseCopies/);
+ assert.match(projects, /message\.mode === "remove" \? "remove" : "move"/);
assert.match(projects, /mode !== "remove"/);
assert.match(projects, /moveEntriesBetweenCollections/);
assert.match(projects, /message\.sourceCollectionId/);
diff --git a/test/ui_foundation_e2e.py b/test/ui_foundation_e2e.py
index 97d92b0..35bbeb5 100644
--- a/test/ui_foundation_e2e.py
+++ b/test/ui_foundation_e2e.py
@@ -112,6 +112,10 @@ def main() -> None:
)
library.reload(wait_until="networkidle")
library.set_viewport_size({"width": 560, "height": 800})
+ # Resize moves actions into the compact menu asynchronously.
+ expect(library.locator("#toolbar-more #add-menu")).to_have_count(1)
+ if not library.locator("#add-menu > summary").is_visible():
+ library.locator("#toolbar-more > summary").click()
library.locator("#add-menu > summary").click()
add_note_alignment = library.locator("#add-quick-note").evaluate(
"""node => {
@@ -161,6 +165,8 @@ def main() -> None:
expect(project_input).to_have_attribute("aria-expanded", "false")
dialog.get_by_role("button", name="取消", exact=True).click()
+ if not library.locator("#add-menu > summary").is_visible():
+ library.locator("#toolbar-more > summary").click()
library.locator("#add-menu > summary").click()
library.locator("#add-video-reference").click()
video_dialog = library.locator("#promptdirector-app-dialog")
@@ -178,6 +184,8 @@ def main() -> None:
video_dialog.get_by_role("button", name="取消", exact=True).click()
library.set_viewport_size({"width": 390, "height": 844})
+ if not library.locator("#add-menu > summary").is_visible():
+ library.locator("#toolbar-more > summary").click()
library.locator("#add-menu > summary").click()
library.locator("#add-quick-note").click()
mobile_dialog = library.locator("#promptdirector-app-dialog")
diff --git a/test/ui_regressions_e2e.py b/test/ui_regressions_e2e.py
index c05c07c..11913fc 100644
--- a/test/ui_regressions_e2e.py
+++ b/test/ui_regressions_e2e.py
@@ -94,6 +94,7 @@ def main() -> None:
assert selected_style["background"] != "rgba(0, 0, 0, 0)", selected_style
assert selected_style["shadow"] != "none", selected_style
+ library.locator('[data-sidebar-module="tags"] .sidebar-module-toggle').click()
library.locator('.facet-filter[data-facet-id="style"] > summary').click()
facet_button = library.locator('[data-facet-node-id="style.render"]')
expect(facet_button).to_be_visible()
@@ -184,7 +185,7 @@ def main() -> None:
icon_metrics = icon.evaluate(
"image => ({naturalWidth: image.naturalWidth, naturalHeight: image.naturalHeight, width: image.getBoundingClientRect().width})"
)
- assert icon_metrics == {"naturalWidth": 128, "naturalHeight": 128, "width": 36}, icon_metrics
+ assert icon_metrics == {"naturalWidth": 128, "naturalHeight": 128, "width": 28}, icon_metrics
print({
"visibility": visibility,
"navigation_reused": navigation_reused,
diff --git a/test/vision_batch_runner_failure_e2e.py b/test/vision_batch_runner_failure_e2e.py
index a8f0595..31ef58b 100644
--- a/test/vision_batch_runner_failure_e2e.py
+++ b/test/vision_batch_runner_failure_e2e.py
@@ -84,10 +84,15 @@ def main() -> None:
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-feedback")).to_contain_text("服务暂时不可用", timeout=15_000)
+ expect(dialog.locator("#vision-batch-feedback")).to_contain_text("本次结果未保存")
expect(dialog.locator("#vision-batch-retry")).to_be_visible(timeout=15_000)
expect(dialog.locator("#vision-batch-pause")).to_be_hidden(timeout=15_000)
+ expect(dialog.locator("#vision-batch-start")).to_be_hidden()
+ dialog.locator("#vision-batch-close").click()
+ expect(library.locator("#share-bar")).to_be_visible()
+ expect(library.locator(".case-card.selected-for-share")).to_have_count(1)
print({"runner_failure_visible": True, "retry_available": True})
diff --git a/test/vision_batch_running_progress_e2e.py b/test/vision_batch_running_progress_e2e.py
index 4c67001..55fcf77 100644
--- a/test/vision_batch_running_progress_e2e.py
+++ b/test/vision_batch_running_progress_e2e.py
@@ -114,10 +114,12 @@ def main() -> None:
)
library = session.open_page("library.html", wait_until="networkidle")
+ library.locator('#toolbar-more > summary').click()
library.locator("#select-cases").click()
library.locator("#selection-select-filtered").click()
library.locator("#selection-more-menu > summary").click()
library.locator("#selection-analyze").click()
+ expect(library.locator(".case-card.selected-for-share")).to_have_count(2)
dialog = library.locator("#vision-batch-dialog")
dialog.locator("#vision-batch-start").click()
@@ -149,6 +151,10 @@ def main() -> None:
"element => ({value: element.value, max: element.max})"
)
assert completed_progress == {"value": 2, "max": 2}, completed_progress
+ expect(dialog.locator("#vision-batch-start")).to_be_hidden()
+ dialog.locator("#vision-batch-close").click()
+ expect(library.locator("#share-bar")).to_be_hidden()
+ assert library.locator(".case-card.selected-for-share").count() == 0
print({"in_flight_progress_visible": True, "completed": 2, "narrowViewport": layout})
finally:
HangingVisionHandler.release_requests.set()
diff --git a/test/visual-interaction.test.js b/test/visual-interaction.test.js
index 2ee8aa7..56c4287 100644
--- a/test/visual-interaction.test.js
+++ b/test/visual-interaction.test.js
@@ -34,7 +34,7 @@ test("the current project uses the product accent while other library selections
assert.match(rule(source, '.analysis-kind-tabs button[aria-selected="true"]'), /background:\s*var\(--selection\)/);
assert.match(rule(source, ".compact-general .share-package-import"), /display:\s*flex/);
assert.doesNotMatch(rule(source, ".compact-general .share-package-import"), /background:|box-shadow:|justify-content:\s*space-between/);
- assert.match(rule(source, "html"), /scrollbar-gutter:\s*stable/);
+ assert.doesNotMatch(source, /scrollbar-gutter:\s*stable/);
assert.doesNotMatch(source, /0 0 0 (?:2px|3px) color-mix\(in srgb, var\(--accent\)/);
});
diff --git a/tools/build-ui-icons.mjs b/tools/build-ui-icons.mjs
index 9d727a9..9ee375f 100644
--- a/tools/build-ui-icons.mjs
+++ b/tools/build-ui-icons.mjs
@@ -7,8 +7,8 @@ const sourcePath = join(projectRoot, "node_modules", "lucide-static", "icon-node
const outputPath = join(projectRoot, "extension", "assets", "ui-icons.svg");
const iconNames = [
"arrow-down", "arrow-left", "arrow-up", "check", "chevron-down", "chevron-left", "chevron-right", "circle-check-big", "clipboard", "copy",
- "download", "ellipsis", "external-link", "file-text", "folder", "image", "library",
- "list-checks", "maximize-2", "menu", "moon", "panel-left", "paperclip", "pencil", "play", "plus",
+ "download", "ellipsis", "external-link", "file-text", "audio-lines", "file-box", "folder", "image", "library",
+ "list-checks", "maximize-2", "menu", "moon", "panel-left", "panel-left-close", "grip-vertical", "layers", "paperclip", "pencil", "play", "plus",
"refresh-cw", "save", "search", "send", "settings", "sliders-horizontal", "sparkles", "square-check-big",
"square", "sun", "tag", "trash-2", "undo-2", "upload", "video", "wand-sparkles", "x"
];