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. 提示词导演
JavaScript ai-artai-videochrome-extensionclaude-codecodexhiggsfieldjimenglocal-firstmcpmidjourneymoodboardprompt-engineeringprompt-libraryprompt-managerreference-libraryseedancevisual-bookmarksweb-clipper
修复返回案例库时的浏览位置与创作台搜索条件差异
MigenAI0892213569a2
diff --git a/composer-page.js b/composer-page.jsindex 91674e3..a0137fb 100644--- a/composer-page.js+++ b/composer-page.js@@ -65,7 +65,7 @@ import { resolveComposerTurnPolicy } from "./composer-turn-policy.js";import { retrieveComposerSources } from "./composer-retrieval.js";import { deleteScreenshotBlob, getScreenshotBlob, saveScreenshotBlob } from "./image-store.js";import { readImageDimensions } from "./image-metadata.js";-import { deleteMediaBlobs, getDerivedMedia, getMediaBlob, saveDerivedMedia, saveMediaBlob } from "./media-store.js";+import { deleteMediaBlobs, getAllDerivedMetadata, getDerivedMedia, getMediaBlob, saveDerivedMedia, saveMediaBlob } from "./media-store.js";import { prepareLocalMedia } from "./local-media.js";import { readVideoMedia } from "./browser-video-media.js";import { extractPdfSearchText } from "./document-viewer.js";@@ -1466,7 +1466,10 @@ async function createComposerSearchState(sourceEntries) {const documentIds = [...new Set(sourceEntries.flatMap((entry) => entryMediaAssets(entry)).filter((asset) => asset.kind === "document").map((asset) => asset.id))];- const derived = await Promise.all(documentIds.map(async (id) => [id, await getDerivedMedia(id).catch(() => null)]));+ const [derived, metadata] = await Promise.all([+ Promise.all(documentIds.map(async (id) => [id, await getDerivedMedia(id).catch(() => null)])),+ getAllDerivedMetadata()+ ]);const documentText = new Map(derived.flatMap(([id, value]) => value?.searchText ? [[id, value.searchText]] : []));const documentTextByEntryId = new Map(sourceEntries.flatMap((entry) => {const text = entryMediaAssets(entry).map((asset) => documentText.get(asset.id)).filter(Boolean).join("\n").trim();@@ -1474,7 +1477,7 @@ async function createComposerSearchState(sourceEntries) {}));return {documentTextByEntryId,- searchIndex: buildSearchIndex(sourceEntries, facetCatalog, documentText)+ searchIndex: buildSearchIndex(sourceEntries, facetCatalog, documentText, metadata)};}diff --git a/composer-retrieval.js b/composer-retrieval.jsindex 8b921b3..763a9ae 100644--- a/composer-retrieval.js+++ b/composer-retrieval.js@@ -1,6 +1,6 @@import { normalizeFacetCatalog } from "./facets.js";import { entrySearchText } from "./library-model.js";-import { matchesSearchQuery, parseSearchQuery } from "./search-query.js";+import { matchesSearchDocument, matchesSearchQuery, parseSearchQuery } from "./search-query.js";import { searchIndexedEntries } from "./search-index.js";import { CONTENT_ROLES, contentRoleForEntry } from "./taxonomy.js";import { primaryVisionDescription } from "./visuals.js";@@ -40,7 +40,10 @@ export function retrieveComposerSources(input = {}) {const indexed = indexedById.get(entry.id);const documentText = String(input.documentTextByEntryId?.get?.(entry.id) ?? "").trim();const fullText = indexed?.fullText || `${entrySearchText(entry, catalog, nodeById)}\n${documentText}`.toLocaleLowerCase("zh-CN");- if (!matchingIds && !matchesSearchQuery(entry, { terms: [], filters: query.filters }, catalog, fullText)) continue;+ if (!matchingIds) {+ const conditions = { terms: [], filters: query.filters };+ if (!(indexed ? matchesSearchDocument(indexed, conditions) : matchesSearchQuery(entry, conditions, catalog, fullText))) continue;+ }const text = sourceText(entry, role, input.documentTextByEntryId);if (!text) continue;const rank = !query.terms.length && query.filters.lengthdiff --git a/library.js b/library.jsindex adbb800..4f03f84 100644--- a/library.js+++ b/library.js@@ -190,7 +190,7 @@ import {} from "./local-asset-store.js";import {LIBRARY_RETURN_STORAGE_KEY,- parseLibraryReturnSnapshot,+ createLibraryReturnRestore,serializeLibraryReturnSnapshot} from "./navigation-state.js";import { CURATED_SUBMISSION_URL } from "./curated-config.js";@@ -373,7 +373,10 @@ const videoAnalysisTaskQueries = new Map();let promptEditState = null;const visionStatusByEntry = new Map();let activeFilterCount = 0;-let libraryReturnRestored = false;+const restoreLibraryReturnSnapshot = createLibraryReturnRestore({+ storage: { getItem: (key) => sessionStorage.getItem(key) },+ applySnapshot: applyLibraryReturnSnapshot+});let libraryReturnScrollY = null;let pendingLocalImport = null;let pendingLibraryPackageBatch = null;@@ -994,7 +997,7 @@ async function refreshLibrary() {maintenanceJob = response.maintenanceJob ?? maintenanceJob;visionBatchJob = response.visionBatchJob ?? null;canUndoAnalysisBatch = Boolean(response.canUndoAnalysisBatch);- restoreLibraryReturnSnapshot();+ restoreLibraryReturnSnapshot(true);const displayedLibraryTitle = libraryTitleForLocale(settings.libraryTitle, currentLocale());elements.libraryTitle.textContent = displayedLibraryTitle;if (document.activeElement !== elements.libraryNameSetting) elements.libraryNameSetting.value = displayedLibraryTitle;@@ -1016,7 +1019,7 @@ async function refreshLibrary() {rebuildLibraryDerivedState();renderGallery();document.body.dataset.libraryState = "ready";- restoreLibraryScrollPosition();+ if (!elements.searchInput.value.trim()) restoreLibraryScrollPosition();const cacheGeneration = ++documentCacheGeneration;void loadDocumentDerivedCache(entries).then(() => {if (cacheGeneration !== documentCacheGeneration) return;@@ -1024,7 +1027,7 @@ async function refreshLibrary() {gallerySearchIndex = searchIndexForEntries(indexedGalleryEntries);updateCachedDocumentCards();if (elements.searchInput.value.trim()) scheduleSearchRender();- }).catch(() => undefined);+ }).catch(() => undefined).finally(() => restoreLibraryScrollPosition());if (elements.managerDialog.open) renderManager();if (elements.visionBatchDialog.open) renderVisionBatchDialog();if (elements.settingsDialog.open && activeSettingsTab === "tasks") renderBatchManager();@@ -1133,6 +1136,7 @@ function scheduleSearchRender() {searchRenderFrame = requestAnimationFrame(() => {searchRenderFrame = 0;renderGalleryResults({ refreshNavigation: false });+ restoreLibraryScrollPosition();});}@@ -2916,6 +2920,7 @@ function saveLibraryReturnSnapshot() {try {sessionStorage.setItem(LIBRARY_RETURN_STORAGE_KEY, serializeLibraryReturnSnapshot({collectionId: selectedCollectionId,+ unassignedViewActive,contentId: selectedContentId,facetNodeIds: [...selectedFacets.values()].flatMap((nodeIds) => [...nodeIds]),pendingOnly: elements.pendingFilter.checked,@@ -2927,16 +2932,8 @@ function saveLibraryReturnSnapshot() {}}-function restoreLibraryReturnSnapshot() {- if (libraryReturnRestored) return;- libraryReturnRestored = true;- let snapshot = null;- try {- snapshot = parseLibraryReturnSnapshot(sessionStorage.getItem(LIBRARY_RETURN_STORAGE_KEY));- } catch {- }- if (!snapshot) return;- unassignedViewActive = false;+function applyLibraryReturnSnapshot(snapshot) {+ unassignedViewActive = snapshot.unassignedViewActive;selectedCollectionId = organizerState.collections.some((item) => item.id === snapshot.collectionId)? snapshot.collectionId: "";@@ -2957,9 +2954,20 @@ function restoreLibraryReturnSnapshot() {function restoreLibraryScrollPosition() {if (!Number.isFinite(libraryReturnScrollY)) return;- const scrollY = libraryReturnScrollY;- libraryReturnScrollY = null;- requestAnimationFrame(() => requestAnimationFrame(() => window.scrollTo({ top: scrollY, left: 0, behavior: "auto" })));+ const generation = galleryGeneration;+ requestAnimationFrame(() => {+ if (generation !== galleryGeneration || !Number.isFinite(libraryReturnScrollY)) return;+ // Load enough of the case wall before scrolling; the first batch may be shorter+ // than the saved position. Exhausted results naturally clamp to the new end.+ const availableScroll = document.scrollingElement.scrollHeight - window.innerHeight;+ if (availableScroll < libraryReturnScrollY && renderedCount < visibleEntries.length) {+ renderNextBatch(generation);+ restoreLibraryScrollPosition();+ return;+ }+ window.scrollTo({ top: libraryReturnScrollY, left: 0, behavior: "auto" });+ libraryReturnScrollY = null;+ });}function openRequestedSettings() {diff --git a/navigation-state.js b/navigation-state.jsindex 93cc451..66d6978 100644--- a/navigation-state.js+++ b/navigation-state.js@@ -76,7 +76,12 @@ export function createLibraryReturnRestore({let restored = false;return function restoreWhenReady(isReady) {if (!isReady || restored) return false;- const snapshot = parseLibraryReturnSnapshot(storage?.getItem?.(key) ?? "");+ let snapshot;+ try {+ snapshot = parseLibraryReturnSnapshot(storage?.getItem?.(key) ?? "");+ } catch {+ return false;+ }if (!snapshot) return false;applySnapshot(snapshot);restored = true;@@ -97,5 +102,6 @@ function normalizeLibraryReturnSnapshot(value) {? value.sortMode: "added-desc";if (collectionId === null || contentId === null || facetNodeIds === null || pendingOnly === null || query === null || scrollY === null) return null;- return { collectionId, contentId, facetNodeIds, pendingOnly, query, scrollY, sortMode };+ const unassignedViewActive = !collectionId && value?.unassignedViewActive === true;+ return { collectionId, unassignedViewActive, contentId, facetNodeIds, pendingOnly, query, scrollY, sortMode };}diff --git a/search-index.js b/search-index.jsindex cab69ce..d22e452 100644--- a/search-index.js+++ b/search-index.js@@ -1,36 +1,17 @@import { normalizeFacetCatalog } from "./facets.js";import { entrySearchText } from "./library-model.js";import { entryMediaAssets } from "./media.js";-import { parseSearchQuery } from "./search-query.js";+import { matchesSearchDocument, parseSearchQuery, searchFieldsForEntry } from "./search-query.js";export function buildSearchIndex(entries = [], catalogValue, documentTextByAsset = new Map(), derivedMetadataByAsset = new Map()) {const catalog = normalizeFacetCatalog(catalogValue);const nodeById = new Map(catalog.nodes.map((node) => [node.id, node]));return entries.map((entry) => {const mediaAssets = entryMediaAssets(entry);- const sources = [entry.url, ...(entry.sourcePages ?? []).flatMap((source) => [source.url, source.title]),- ...mediaAssets.flatMap((asset) => [asset.sourceUrl, asset.sourceTitle, asset.reference?.url])];- const notes = [entry.text, ...(entry.timeNotes ?? []).map((note) => note.text)];- const tags = [- ...(entry.customLabels ?? []),- ...(entry.facetAssignments ?? []).filter((item) => item.status === "confirmed").flatMap((item) => {- const node = nodeById.get(item.nodeId);- return node ? [node.name, ...(node.aliases ?? [])] : [];- })- ];return {id: entry.id,fullText: clean([entrySearchText(entry, catalog, nodeById), ...mediaAssets.map((asset) => documentTextByAsset.get(asset.id))].filter(Boolean).join("\n")),- sources: clean(sources.join("\n")),- notes: clean(notes.join("\n")),- tags: clean(tags.join("\n")),- colors: mediaAssets.flatMap((asset) =>- asset.palette?.colors ?? derivedMetadataByAsset.get(asset.id)?.palette?.colors ?? []- ).map(normalizeColor),- kinds: new Set(mediaAssets.map((asset) => asset.kind)),- hasMedia: mediaAssets.length > 0,- isNote: !mediaAssets.length && Boolean(String(entry.text ?? "").trim()),- savedDate: validDatePrefix(entry.savedAt)+ ...searchFieldsForEntry(entry, nodeById, derivedMetadataByAsset)};});}@@ -38,48 +19,7 @@ export function buildSearchIndex(entries = [], catalogValue, documentTextByAssetexport function searchIndexedEntries(index = [], queryValue = "") {const query = parseSearchQuery(queryValue);if (!query.terms.length && !query.filters.length) return new Set(index.map((item) => item.id));- return new Set(index.filter((document) =>- query.terms.every((term) => document.fullText.includes(term)) &&- query.filters.every((filter) => matchesFilter(document, filter))- ).map((item) => item.id));-}--function matchesFilter(document, filter) {- const value = filter.value;- if (filter.name === "type" || filter.name === "has") {- if (value === "media") return document.hasMedia;- if (value === "note") return document.isNote;- return document.kinds.has(normalizeKind(value));- }- if (filter.name === "source") return document.sources.includes(value);- if (filter.name === "note") return document.notes.includes(value);- if (filter.name === "tag") return document.tags.includes(value);- if (filter.name === "color") {- const wanted = normalizeColor(value);- return document.colors.some((color) => color.includes(wanted));- }- if (filter.name === "date") return matchesDate(document.savedDate, value);- return false;-}--function matchesDate(savedDate, query) {- if (!savedDate) return false;- if (!query.includes("..")) return savedDate.startsWith(query);- const [start, end] = query.split("..", 2);- return (!start || savedDate >= start) && (!end || savedDate <= end);-}--function validDatePrefix(value) {- const timestamp = Date.parse(value);- return Number.isFinite(timestamp) ? new Date(timestamp).toISOString().slice(0, 10) : "";-}--function normalizeKind(value) {- return ({ 图片: "image", 图像: "image", 视频: "video", 文档: "document", pdf: "document" })[value] || value;-}--function normalizeColor(value) {- return String(value ?? "").toLocaleLowerCase("en-US").replace(/^#/, "");+ return new Set(index.filter(document => matchesSearchDocument(document, query)).map(item => item.id));}function clean(value) {diff --git a/search-query.js b/search-query.jsindex a63c4d6..dc90779 100644--- a/search-query.js+++ b/search-query.js@@ -1,4 +1,4 @@-import { normalizeEntryMedia } from "./media.js";+import { entryMediaAssets } from "./media.js";import { normalizeFacetCatalog } from "./facets.js";const OPERATORS = new Set(["type", "source", "tag", "color", "date", "note", "has"]);@@ -17,60 +17,78 @@ export function parseSearchQuery(value = "") {}export function matchesSearchQuery(entryValue, queryValue, catalogValue, fullText = "") {+ const catalog = normalizeFacetCatalog(catalogValue);+ const nodeById = new Map(catalog.nodes.map(node => [node.id, node]));+ return matchesSearchDocument({+ ...searchFieldsForEntry(entryValue, nodeById),+ fullText: searchText(fullText)+ }, queryValue);+}++export function searchFieldsForEntry(entry, nodeById, derivedMetadataByAsset = new Map()) {+ const mediaAssets = entryMediaAssets(entry);+ const sources = [entry.url, ...(entry.sourcePages ?? []).flatMap(source => [source.url, source.title]),+ ...mediaAssets.flatMap(asset => [asset.sourceUrl, asset.sourceTitle, asset.reference?.url])];+ const notes = [entry.text, ...(entry.timeNotes ?? []).map(note => note.text)];+ const tags = [+ ...(entry.customLabels ?? []),+ ...(entry.facetAssignments ?? []).filter(item => item.status === "confirmed").flatMap(item => {+ const node = nodeById.get(item.nodeId);+ return node ? [node.name, ...(node.aliases ?? [])] : [];+ })+ ];+ const timestamp = Date.parse(entry.savedAt);+ return {+ sources: searchText(sources.join("\n")),+ notes: searchText(notes.join("\n")),+ tags: searchText(tags.join("\n")),+ colors: mediaAssets.flatMap(asset =>+ asset.palette?.colors ?? derivedMetadataByAsset.get(asset.id)?.palette?.colors ?? []+ ).map(normalizeSearchColor),+ kinds: new Set(mediaAssets.map(asset => asset.kind)),+ hasMedia: mediaAssets.length > 0,+ isNote: !mediaAssets.length && Boolean(String(entry.text ?? "").trim()),+ savedDate: Number.isFinite(timestamp) ? new Date(timestamp).toISOString().slice(0, 10) : ""+ };+}++export function matchesSearchDocument(document, queryValue = "") {const query = typeof queryValue === "string" ? parseSearchQuery(queryValue) : queryValue;- const entry = normalizeEntryMedia(entryValue);- const searchable = String(fullText).toLocaleLowerCase("zh-CN");- if (query.terms.some((term) => !searchable.includes(term))) return false;- return query.filters.every((filter) => matchesFilter(entry, filter, catalogValue));+ return query.terms.every(term => document.fullText.includes(term)) &&+ query.filters.every(filter => matchesFilter(document, filter));}-function matchesFilter(entry, filter, catalogValue) {+function matchesFilter(document, filter) {const value = filter.value;if (filter.name === "type" || filter.name === "has") {- if (value === "media") return entry.mediaAssets.length > 0;- if (value === "note") return !entry.mediaAssets.length && Boolean(clean(entry.text));- return entry.mediaAssets.some((asset) => asset.kind === normalizeKind(value));- }- if (filter.name === "source") {- return [entry.url, ...(entry.sourcePages ?? []).flatMap((source) => [source.url, source.title]),- ...entry.mediaAssets.flatMap((asset) => [asset.sourceUrl, asset.sourceTitle, asset.reference?.url])]- .some((item) => clean(item).toLocaleLowerCase("zh-CN").includes(value));- }- if (filter.name === "note") {- return [entry.text, ...(entry.timeNotes ?? []).map((note) => note.text)]- .some((item) => clean(item).toLocaleLowerCase("zh-CN").includes(value));+ if (value === "media") return document.hasMedia;+ if (value === "note") return document.isNote;+ return document.kinds.has(normalizeKind(value));}+ if (filter.name === "source") return document.sources.includes(value);+ if (filter.name === "note") return document.notes.includes(value);+ if (filter.name === "tag") return document.tags.includes(value);if (filter.name === "color") {- const wanted = value.replace(/^#/, "");- return entry.mediaAssets.flatMap((asset) => asset.palette?.colors ?? [])- .some((color) => clean(color).toLocaleLowerCase("en-US").replace(/^#/, "").includes(wanted));- }- if (filter.name === "date") return matchesDate(entry.savedAt, value);- if (filter.name === "tag") {- const catalog = normalizeFacetCatalog(catalogValue);- const nodeById = new Map(catalog.nodes.map((node) => [node.id, node]));- const labels = [- ...(entry.customLabels ?? []),- ...(entry.facetAssignments ?? []).filter((item) => item.status === "confirmed")- .flatMap((item) => {- const node = nodeById.get(item.nodeId);- return node ? [node.name, ...(node.aliases ?? [])] : [];- })- ];- return labels.some((label) => clean(label).toLocaleLowerCase("zh-CN").includes(value));+ const wanted = normalizeSearchColor(value);+ return document.colors.some(color => color.includes(wanted));}+ if (filter.name === "date") return matchesDate(document.savedDate, value);return false;}-function matchesDate(savedAt, query) {- const timestamp = Date.parse(savedAt);- if (!Number.isFinite(timestamp)) return false;- if (!query.includes("..")) return new Date(timestamp).toISOString().slice(0, 10).startsWith(query);- const [startValue, endValue] = query.split("..", 2);- const start = startValue ? Date.parse(startValue) : Number.NEGATIVE_INFINITY;- const end = endValue ? Date.parse(`${endValue}T23:59:59.999Z`) : Number.POSITIVE_INFINITY;- return (Number.isFinite(start) || start === Number.NEGATIVE_INFINITY) &&- (Number.isFinite(end) || end === Number.POSITIVE_INFINITY) && timestamp >= start && timestamp <= end;+function matchesDate(savedDate, query) {+ if (!savedDate) return false;+ if (!query.includes("..")) return savedDate.startsWith(query);+ const [start, end] = query.split("..", 2);+ return (!start || savedDate >= start) && (!end || savedDate <= end);+}++function normalizeSearchColor(value) {+ return searchText(value).replace(/^#/, "");+}++function searchText(value) {+ return String(value ?? "").toLocaleLowerCase("zh-CN");}function normalizeKind(value) {diff --git a/test/composer-retrieval.test.js b/test/composer-retrieval.test.jsindex 7fa5b3a..801d8ca 100644--- a/test/composer-retrieval.test.js+++ b/test/composer-retrieval.test.js@@ -115,3 +115,21 @@ test("one-click retrieval finds the distinctive subject inside a natural-languagassert.deepEqual(sources.map((item) => item.entryId).sort(), ["case", "guide"]);});++test("natural-language retrieval keeps explicit derived-color filters when there is no exact phrase match", () => {+ const entries = [+ { id: "blue", text: "雨夜角色", classification: { pathIds: [CONTENT_IDS.promptImage] },+ mediaAssets: [{ id: "blue-image", kind: "image", storageMode: "managed" }] },+ { id: "red", text: "雨夜角色", classification: { pathIds: [CONTENT_IDS.promptImage] },+ mediaAssets: [{ id: "red-image", kind: "image", storageMode: "managed" }] }+ ];+ const metadata = new Map([+ ["blue-image", { palette: { colors: ["#123456"] } }],+ ["red-image", { palette: { colors: ["#aa0000"] } }]+ ]);+ const sources = retrieveComposerSources({+ entries, query: "请参考雨夜角色 color:123", contentRoles: ["case"], targetType: "image",+ characterBudget: 2000, searchIndex: buildSearchIndex(entries, undefined, new Map(), metadata)+ });+ assert.deepEqual(sources.map(item => item.entryId), ["blue"]);+});diff --git a/test/composer_generation_e2e.py b/test/composer_generation_e2e.pyindex 1f59956..e4a06ad 100644--- a/test/composer_generation_e2e.py+++ b/test/composer_generation_e2e.py@@ -106,6 +106,8 @@ def main() -> None:jimeng_character["mediaAssets"] = [{"id": "character-image", "kind": "image", "usage": "content", "storageMode": "managed", "mimeType": "image/png", "width": 1, "height": 1, "byteSize": 68}]jimeng_character["primaryMediaId"] = "character-image"retrieved_case = base_entry("retrieval-case", "内部案例标题", "雾夜角色穿银色披风,轮廓清晰。", "content:prompt:image")+ retrieved_case["mediaAssets"] = [{"id": "retrieval-color-image", "kind": "image", "usage": "content", "storageMode": "managed", "mimeType": "image/png", "width": 1, "height": 1}]+ retrieved_case["primaryMediaId"] = "retrieval-color-image"retrieved_guide = base_entry("retrieval-guide", "内部教程标题", "雾夜角色布光教程:先确定轮廓光,再控制环境雾。", "content:tutorial")with extension_session("prompt-director-composer-") as session:setup = session.open_page("collector.html")@@ -159,11 +161,14 @@ def main() -> None:)setup.evaluate("""async () => {- const {saveMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));+ const {saveMediaBlob, saveDerivedMetadata} = await import(chrome.runtime.getURL('media-store.js'));const data = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';const bytes = Uint8Array.from(atob(data), character => character.charCodeAt(0));const blob = new Blob([bytes], {type: 'image/png'});await saveMediaBlob('composition-image', blob, {checkCapacity: false});+ await saveMediaBlob('retrieval-color-image', blob, {checkCapacity: false});+ // Synthetic palette tests indexing, not pixel color extraction.+ await saveDerivedMetadata('retrieval-color-image', {palette: {colors: ['#123456'], version: 1}});await saveMediaBlob('character-image', blob, {checkCapacity: false});}""")@@ -433,6 +438,24 @@ def main() -> None:expect(composer.locator("#composer-assembly-content")).to_contain_text("实际终态:completed")composer.locator("#composer-assembly-close").click()+ library = session.open_page("library.html", wait_until="networkidle")+ library.locator("#search-input").fill("color:123")+ expect(library.locator("#case-list > .case-card")).to_have_count(1)+ expect(library.locator("#case-list > .case-card")).to_have_attribute("data-entry-id", "retrieval-case")+ library.close()+ for color, expected_count in [("123", 1), ("abcdef", 0)]:+ composer.locator("#composer-new").click()+ composer.locator("#composer-library-search").click()+ composer.locator("#composer-instruction").fill(f"用私人资料补充雾夜角色 color:{color}")+ composer.locator("#composer-action").click()+ expect(composer.locator(".composer-message.prompt .composer-message-text")).to_have_text("东方庭院,柔和逆光。")+ color_payload = json.loads(requests[-1]["messages"][-1]["content"])+ assert len(color_payload["retrievedSources"]) == expected_count, color_payload+ if expected_count:+ assert "雾夜角色穿银色披风" in json.dumps(color_payload["retrievedSources"], ensure_ascii=False)+ color_session = completed_session(composer)+ assert color_session["retrievalSnapshot"]["sourceCount"] == expected_count, color_session+composer.locator("#composer-new").click()composer.locator("#composer-instruction").fill("协议降级测试")degraded_requests_before = len(requests)diff --git a/test/library_browse_return_e2e.py b/test/library_browse_return_e2e.pynew file mode 100644index 0000000..f14e93b--- /dev/null+++ b/test/library_browse_return_e2e.py@@ -0,0 +1,69 @@+from __future__ import annotations++from playwright.sync_api import expect++from e2e_support import base_entry, extension_session+++def main() -> None:+ entries = [base_entry(+ f"browse-{index:03d}", f"浏览参考 {index:03d}",+ f"雨夜创作参考 {index:03d}。保留画面、人物和场景。", "content:prompt:image", index % 60+ ) for index in range(180)]+ project_id = "collection:browse"+ with extension_session("prompt-director-browse-return-", viewport={"width": 1000, "height": 700}) as session:+ setup = session.open_page("collector.html")+ session.seed_storage(setup, {+ "schemaVersion": 28, "entries": entries,+ "organizerState": {"version": 1, "collections": [{+ "id": project_id, "name": "浏览项目", "entryIds": [entry["id"] for entry in entries[:84]],+ "parentId": None, "order": 0, "visibility": "library"+ }]}+ })+ library = session.open_page("library.html", wait_until="networkidle")+ for unassigned in [True, False]:+ if unassigned:+ library.locator("#workspace-unassigned").click()+ else:+ library.locator(f'[data-collection-id="{project_id}"] .project-filter').click()+ library.locator("#search-input").fill("雨夜")+ library.locator("#gallery-sort").select_option("title")+ # 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()+ library.locator("#case-list > .case-card").last.scroll_into_view_if_needed()+ 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("#start-compose").click()+ library.wait_for_url("**/composer.html*")+ saved = library.evaluate("JSON.parse(sessionStorage.getItem('promptDirector.libraryReturn'))")+ assert saved["scrollY"] > 700, saved+ library.locator(".composer-library-exit").click()+ library.wait_for_url("**/library.html")+ expect(library.locator("#workspace-unassigned")).to_have_attribute("aria-current", "page" if unassigned else "false")+ expect(library.locator("#library-title")).to_have_text("未归项目" if unassigned else "浏览项目")+ expect(library.locator("#search-input")).to_have_value("雨夜")+ expect(library.locator("#gallery-sort")).to_have_value("title")+ library.wait_for_function("target => Math.abs(scrollY - target) <= 2", arg=saved["scrollY"])+ 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("#start-compose").click()+ library.wait_for_url("**/composer.html*")+ await_result = library.evaluate("""async () => {+ const {organizerState} = await chrome.storage.local.get('organizerState');+ await chrome.storage.local.set({organizerState: {...organizerState, collections: []}});+ return true;+ }""")+ assert await_result is True+ library.locator(".composer-library-exit").click()+ library.wait_for_url("**/library.html")+ expect(library.locator("#workspace-library")).to_have_attribute("aria-current", "page")+ expect(library.locator("#workspace-unassigned")).to_have_attribute("aria-current", "false")+ expect(library.locator("#search-input")).to_have_value("雨夜")+ print({"unassigned_return": True, "project_return": True, "deep_scroll_return": True, "deleted_project_return": True})+++if __name__ == "__main__":+ main()diff --git a/test/navigation-state.test.js b/test/navigation-state.test.jsindex 6840763..839cb33 100644--- a/test/navigation-state.test.js+++ b/test/navigation-state.test.js@@ -104,6 +104,7 @@ test("library return snapshots serialize canonical collection, facets, query, anassert.deepEqual(JSON.parse(serialized), {collectionId: "collection:7",+ unassignedViewActive: false,contentId: "content:prompt:image",facetNodeIds: ["facet:2", "facet:1"],pendingOnly: true,@@ -149,6 +150,7 @@ test("library return restore waits for initialization readiness and only appliesassert.equal(restore(true), true);assert.deepEqual(applied, [{collectionId: "collection:1",+ unassignedViewActive: false,contentId: "",facetNodeIds: ["facet:1"],pendingOnly: false,@@ -170,6 +172,7 @@ test("old library return snapshots gain safe default sorting", () => {scrollY: 0})), {collectionId: "",+ unassignedViewActive: false,contentId: "",facetNodeIds: [],pendingOnly: false,@@ -192,3 +195,35 @@ test("removed oldest-first snapshots fall back to recent-first", () => {}));assert.equal(snapshot.sortMode, "added-desc");});++test("returning from creation preserves the unassigned workspace alongside its filters", () => {+ const snapshot = parseLibraryReturnSnapshot(serializeLibraryReturnSnapshot({+ collectionId: "", unassignedViewActive: true, contentId: "content:prompt:image",+ facetNodeIds: ["style:film"], pendingOnly: false, query: "雨夜", scrollY: 2800,+ sortMode: "title", caseOrderManagementActive: true+ }));+ assert.equal(snapshot.unassignedViewActive, true);+ assert.equal(snapshot.query, "雨夜");+ assert.equal(snapshot.scrollY, 2800);+ assert.equal(snapshot.sortMode, "title");+ assert.equal("caseOrderManagementActive" in snapshot, false);+});++test("a saved project takes precedence over a contradictory unassigned flag", () => {+ const snapshot = parseLibraryReturnSnapshot(serializeLibraryReturnSnapshot({+ collectionId: "collection:1", unassignedViewActive: true, contentId: "",+ facetNodeIds: [], pendingOnly: false, query: "", scrollY: 0+ }));+ assert.equal(snapshot.collectionId, "collection:1");+ assert.equal(snapshot.unassignedViewActive, false);+});++test("unavailable session storage does not block opening the library", () => {+ const applied = [];+ const restore = createLibraryReturnRestore({+ storage: { getItem() { throw new Error("storage unavailable"); } },+ applySnapshot: snapshot => applied.push(snapshot)+ });+ assert.equal(restore(true), false);+ assert.deepEqual(applied, []);+});diff --git a/test/run_e2e.py b/test/run_e2e.pyindex 19cf9e7..4c613c2 100644--- a/test/run_e2e.py+++ b/test/run_e2e.py@@ -13,6 +13,7 @@ SCRIPTS = ["capture_and_cross_page_e2e.py","library_core_e2e.py","library_navigation_e2e.py",+ "library_browse_return_e2e.py","curated_workflow_e2e.py","curated_skills_install_e2e.py","curated_video_workflow_e2e.py",@@ -72,6 +73,7 @@ SCRIPTS = [CASE_MANAGEMENT_SCRIPTS = ["library_navigation_e2e.py",+ "library_browse_return_e2e.py","historical_zip_salvage_e2e.py","video_detail_layout_e2e.py","library_detail_actions_e2e.py",diff --git a/test/search-query.test.js b/test/search-query.test.jsindex 46b1d89..6a9de2d 100644--- a/test/search-query.test.js+++ b/test/search-query.test.js@@ -2,6 +2,7 @@ import test from "node:test";import assert from "node:assert/strict";import { filterEntries } from "../library-model.js";import { parseSearchQuery } from "../search-query.js";+import { buildSearchIndex, searchIndexedEntries } from "../search-index.js";const catalog = {facets: [{ id: "style", name: "风格", color: "#000", status: "active", order: 0 }],@@ -30,3 +31,18 @@ test("free words remain local full-text search alongside operators", () => {assert.equal(filterEntries([entry], { query: "雨夜 type:video" }, catalog).length, 1);assert.equal(filterEntries([entry], { query: "晴天 type:video" }, catalog).length, 0);});++test("library indexing and direct conditions agree for combined and excluding filters", () => {+ const index = buildSearchIndex([entry], catalog);+ for (const [query, expected] of [+ ["type:视频 source:x.com tag:cinematic color:#123 date:2026-08 note:加速 has:media", ["case-1"]],+ ["date:2026-08-01..2026-08-02", ["case-1"]],+ ["date:..2026-08-01", ["case-1"]],+ ["date:2026-08-02..", []],+ ["color:abc", []], ["tag:不存在", []], ["type:图片", []], ["has:note", []],+ ["source:missing.invalid", []], ["note:静止", []]+ ]) {+ assert.deepEqual([...searchIndexedEntries(index, query)], expected, query);+ assert.deepEqual(filterEntries([entry], { query }, catalog).map(item => item.id), expected, query);+ }+});