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

472 KB
Raw Blame
import { skillRevision } from "./skill-operations.js";
import { sameUndoState } from './undo-state.js';
import { normalizeAnalysisScope, selectAnalysisScope, sameAnalysisTargets } from "./analysis-scope.js";
import { createDedupeMediaVerifier } from './dedupe-media-verifier.js';
import { createAgentCapturePreview } from './agent-capture-preview.js';
import { CAPTURE_OPERATION_SPECS } from './capture-operation-specs.js';
import { runCaptureAssistant } from './capture-assistant.js';
import { assistantChatSession, assistantChatView, assistantChatViews, assistantChatContent } from './assistant-chat-session.js';
import { COMPOSER_DRAFTS_KEY, assistantDraftUpdate } from './composer-session-drafts.js';
import { restoreCaptureSessions } from './capture-assistant-sessions.js';
import { createComposerToolProgress } from './composer-tool-progress.js';
import { readAssistantCaseMedia } from './assistant-case-media.js';
import { captureChatAssetIds, readCaptureChatAttachment, resolveCaptureLocalMedia, resolveCaptureChatFile } from './capture-chat-attachments.js';
import { createCaseDedupeOperations } from './case-dedupe-operations.js';
import { createCaptureSaveTasks, CAPTURE_SAVE_TASK_KEY, rebaseCaptureEntries } from './capture-save-tasks.js';
import { jsonBytes, startPhase, timingEnabled } from "./perf-trace.js";
import { editedLabels } from "./label-edits.js";
import { manageLayoutPreset } from './layout-presets.js';
import { createCaptureSaveProgress } from './capture-save-progress.js';
import { WORKSPACE_OPERATION_SPECS } from './workspace-operation-specs.js';
import { applyCompletedImageResult, applyCompletedVideoResult } from './media-analysis-results.js';
import { handleComposerLibraryHost } from './composer-library-host.js';
import { createOriginalFileDragHost } from './original-file-drag.js';
import {createExternalAnalysisBatches} from './external-analysis-batches.js';
import {ANALYSIS_BATCH_SPECS, ANALYSIS_RESULT_FIELDS} from './analysis-batch-specs.js';
import { skillPackageLimits } from './creative-skill-package.js';
import { createSkillWriter } from './skill-writer.js';
import { createSkillOperations } from './skill-operations.js';
import { assertCaseFilesReadable } from './case-file-status.js';
import { getLibraryStorage, createLibraryCommitter, CASE_LIBRARY_REVISION_KEY } from "./library-storage.js";
import { needsFolderOwnershipMigration, planFolderOwnership } from './library-folder-ownership.js';
import { operationBudget, stagingByteBudget, RESOURCE_POLICY } from './resource-policy.js';
import { createProjectOperations } from "./project-operations.js";
import { createBrowserLibraryIdentity } from "./library-identity.js";
import { validateProjectOperation } from "./project-operation-specs.js";
import { collectVideoPagePayload, normalizeVideoPagePayload } from "./video-page-capture.js";
import { collectDouyinVideoPayload } from './douyin-video-capture.js';
import { installVideoDiscovery, addDiscoveredVideos } from "./video-discovery.js";
import { pickPageContent, validateSelectedCaptureRectangles } from "./page-content-picker.js";
import { CAPTURE_SAVED_TEXT_KEY, createTextCandidate } from "./capture-text-candidate.js";
import { planImageGenerationPrompts, generationPromptConfirmation } from "./image-generation-ingestion.js";
import { readImageGenerationInfo, embeddedMediaPrompts } from "./image-generation-info.js";
import { waitForDownload } from "./download-completion.js";
import { splitArticleCases } from "./article-case-groups.js";
import { collectGenericCaptureDetails } from "./generic-capture-details.js";
import { groupGenericCapture } from "./generic-capture-groups.js";
import { createAgentConnection } from "./agent-connection.js";
import { createAgentTasks } from "./agent-tasks.js";
import { createAgentLibrary } from "./agent-library.js";
import { createCaseLibraryReader } from "./case-library-state.js";
import { projectLibraryViewState, enrichContentMeanings } from "./library-view-state.js";
import { LIBRARY_VIEW_SUMMARY_KEY, LIBRARY_VIEW_SUMMARY_SOURCES, completeLibraryViewSummary, composerSessionSummaries } from './library-view-summary.js';
import { createAgentWorkspace } from "./agent-workspace.js";
import { createWorkspaceScreenshot, WORKSPACE_SCREENSHOT_SPEC } from './workspace-screenshot.js';
import { createCaseTrashOperations } from './case-trash-operations.js';
import { AGENT_CASE_ACTION_SPECS } from './agent-case-action-specs.js';
import { createReferenceSelection } from "./reference-selection.js";
import { createCaseOperations } from "./case-operations.js";
import { CASE_OPERATION_SPECS, CASE_SEARCH_PROPERTIES } from './case-operation-specs.js';
import { createAgentTransfers } from "./agent-transfers.js";
import { reusableAgentFile } from './agent-transfer-reuse.js';
import { saveAgentMaterial } from "./agent-save.js";
import { captureAgentUrl } from "./agent-capture.js";
import { agentError, AGENT_PROTOCOL_VERSION, AGENT_CHUNK_BYTES } from "./agent-protocol.js";
import { collectFeishuDocument } from "./feishu-document-capture.js";
import { saveComposerToolDraft, preserveSavedToolDrafts } from './composer-tool-drafts.js';
import { renderPageCaptureRegionPreview, clearPageCapturePageState } from "./page-capture-highlight.js";
import { collectLibTvPublicPayload, normalizeLibTvPublicPayload } from "./libtv-capture.js";
import { createCaseEditor, touchEntry, stringListsEqual, userVisibleEntryEqual } from "./case-editor.js";
import { showPageToast } from "./capture-region.js";
import { analysisRequestCounts } from "./analysis-retry-policy.js";
import { articleDocumentText, finalizeArticleDocumentAssets } from "./article-document.js";
import {
  classifyContent,
  classifyCapturedContent,
  classifyImportedMedia,
  confirmClassification,
  createSourceRule
} from "./classifier.js";
import { casesLostByMigration, 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,
  SCHEMA_VERSION,
  contentRoleForEntry,
  contentTypeForRole,
  createContentType,
  isValidContentPath,
  normalizeTaxonomy,
  removeContentTypeWithTransfer,
  updateContentType
} from "./taxonomy.js";
import {
  applyFacetChange,
  createFacetNode,
  normalizeFacetCatalog,
  previewFacetChange,
  recoverFullyArchivedFacets,
  restoreArchivedFacets,
  restoreArchivedNodes,
  uniqueNames
} from "./facets.js";
import { appendFacetUndo, facetUndoCount, undoFacetHistory } from "./facet-history.js";
import { removeCaseTags } from './case-tags.js';
import {
  acceptAnalysisCandidate,
  applyAnalysisCandidates,
  applyAnalysisImport,
  applyTextAnalysisTags,
  rejectAnalysisCandidate,
  undoVisionAnalysis,
  setManualAssignment
} from "./analysis-candidates.js";
import {
  ANALYSIS_PROMPT_VERSION,
  analysisProfileFingerprint,
  analysisTaxonomyPrompt,
  analyzeTextDetailedWithDeepSeek,
  publicAiSettings,
  summarizeVisualSetWithAi
} from "./deepseek.js";
import {
  compileVisualSetSummaryInstruction,
  normalizeVisualSetSummaryV1,
  prepareVisualSetSummary
} from "./visual-analysis.js";
import { createAiProviderModule } from "./ai-provider-module.js";
import {
  analysisBatchSummary,
  analysisRebuildRecovery,
  backfillLegacyAnalysisMeta,
  bindAnalysisItemAttempt,
  cancelAnalysisBatch,
  claimAnalysisItems,
  createAnalysisBatchUndo,
  createAnalysisBatchJob,
  createVideoBatchJob,
  createVisionBatchJob,
  failAnalysisItem,
  failUnfinishedAnalysisItems,
  finalizeAnalysisRebuild,
  finalizePartialAnalysisRebuild,
  normalizeAnalysisBatchJob,
  pauseAnalysisBatch,
  previewAnalysisBatch,
  previewVideoBatch,
  previewVisionBatch,
  reconcileVisionBatchResults,
  recoverInterruptedAnalysisBatch,
  restoreAnalysisBatchUndo,
  sealAnalysisBatchUndo,
  resumeAnalysisBatch,
  retryFailedAnalysisItems,
  stageAnalysisRebuildResults,
  succeedAnalysisItem,
  textFingerprint,
  textAnalysisResultIsCurrent
} from "./analysis-batch.js";
import { canonicalTextAnalysisInput } from "./analysis-input.js";
import { buildAutomaticVisionJob } from "./automatic-vision.js";
import { coalesceAnalysisRequest, runScheduledAnalysisWithRetries, scheduleAnalysis } from "./analysis-scheduler.js";
import {
  completeAnalysisAttempt,
  failAnalysisAttempt,
  retryAnalysisAttempt,
  startAnalysisAttempt,
  stopAnalysisTask,
  updateAnalysisTaskProgress
} from "./analysis-tasks.js";
import {
  analysisTaskById,
  createOrJoinAnalysisTask,
  detachAnalysisTaskConsumer,
  normalizeAnalysisTaskRegistry,
  recoverInterruptedAnalysisTasks,
  replaceAnalysisTask
} from "./analysis-task-registry.js";
import { findPersistedVisionAnalysis } from "./vision-analysis-cache.js";
import {
  analysisRevisionMeta,
  entryTextRevision,
  markEntryTextChanged
} from "./analysis-revision.js";
import { applyDetailOrganizationMappings, applyFixedAnalysisTags } from "./tag-taxonomy.js";
import {
  buildEntry,
  defaultSettingsForLocale,
  findDuplicate,
  normalizeSettings,
  screenshotStorageKey
} from "./lib.js";
import {
  deleteScreenshotBlob,
  discardScreenshotReplacementBackup,
  getScreenshotBlob,
  undoScreenshotReplacement,
  saveScreenshotBlob
} from "./image-store.js";
import {
  savePortableAssetBlob,
  deleteMediaBlob,
  deleteMediaBlobs,
  getAllDerivedMetadata,
  getDerivedMedia,
  getDerivedMetadata,
  getMediaBlob,
  saveDerivedMetadata,
  saveMediaBlob
} from "./media-store.js";
import { deleteLocalAssetHandles } from "./local-asset-store.js";
import {
  LOCAL_ASSET_REFERENCE_RECORD_TYPE,
  chunkedBlobFingerprint,
  createExactMediaDuplicateIndex,
  sha256Blob
} from "./local-media.js";
import { tempReferenceAssetIds, unreadReferenceImageAssets } from "./temp-references.js";
import { planTrashCleanup, retainedTrashCleanupAssets, TRASH_HISTORY_KEYS, TRASH_CLEANUP_KEY } from './trash-cleanup.js';
import { createStagedMediaRegistry, resolveStageDocument } from './staged-media.js';
import {
  addStagedAsset,
  collectRetainedLocalAssetIds,
  normalizeImportStagingState,
  removeStagedAsset,
  stagedAssetById,
  stagedAssetMediaRecord
} from "./import-staging.js";
import {
  cancelImportJob,
  createImportJob,
  finishImportItem,
  markImportJobAnalysisQueued,
  normalizeImportJobsState,
  retryImportJob,
  startImportJob,
  undoImportJob
} from "./import-jobs.js";
import {
  createCreativeSkill,
  deleteCreativeSkill,
  normalizeCreativeSkillsState,
  restoreCreativeSkillVersion,
  saveCreativeSkillVersion,
  protectedSkillVersionIds,
  skillPackageAssetIds
} from "./creative-skills.js";
import { commitSkillWithCover } from "./skill-cover-save.js";
import {
  addEntryMedia,
  addTimeNote,
  currentVideoReconstruction,
  entryMediaAssets,
  normalizeEntryMedia,
  setCaseCover,
  removeEntryMedia,
  removeTimeNote,
  setPrimaryMedia,
  updateLocalAssetReferenceMetadata
} from "./media.js";
import {
  cancelLibraryMaintenance,
  completeLibraryMaintenanceItem,
  createLibraryMaintenanceJob,
  extendLibraryMaintenanceJob,
  libraryMaintenanceSummary,
  mergeLibraryMaintenanceProgress,
  nextLibraryMaintenanceItem,
  normalizeLibraryMaintenanceJob,
  pauseLibraryMaintenance,
  resumeLibraryMaintenance,
  retryLibraryMaintenanceFailures
} from "./library-maintenance.js";
import {
  commitMetadataThenDeleteImages
} from "./image-transaction.js";
import { assertCreatedEntryUndoSafe, createEntrySaveUndo, normalizeLastSaveUndo, restoreScreenshotSaveEntry } from "./save-history.js";
import {
  selectLibraryPackage,
  selectProjectPackage
} from "./library-package.js";
import {
  LIBRARY_TRANSFER_MODES,
  LIBRARY_TRANSFER_SOURCES,
  planLibraryTransfer,
  planLibraryTransferBatch,
  previewLibraryTransferBatch
} from "./library-transfer.js";
import {
  claimLibraryImportTransaction,
  failLibraryImportTransaction,
  normalizeLibraryImportTransactionsState,
  succeedLibraryImportTransaction
} from "./library-import-transaction.js";
import {
  createLibraryReplacementRecoveryPoint,
  normalizeLibraryReplacementRecoveryPoint,
  obsoleteRecoveryAssetIds,
  swapLibraryReplacementRecoveryPoint
} from "./library-recovery-point.js";
import { createUndoConfirmations, replacementImpact } from "./library-undo-preview.js";
import { mergeCuratedLibraryPackage } from "./curated-import.js";
import { prepareCuratedSubmissionState } from "./curated-submission.js";
import {
  createCollection,
  collectionEntryIds,
  collectionPathLabel,
  moveCollection,
  assertCollectionStructureCurrent,
  moveEntriesBetweenCollections,
  normalizeOrganizerState,
  removeEntriesFromOrganizer,
  reorderCollections,
  replaceCollectionEntries,
  renameCollection,
  setEntriesCollection,
  setCollectionVisibility
} from "./organizer.js";
import {
  listTrashItems,
  moveCollectionWithEntriesToTrash,
  moveCollectionsToTrash,
  moveEntriesToTrash,
  moveMediaToTrash,
  normalizeTrashState,
  restoreTrashItems
} from "./trash.js";
import { normalizeUiPreferences, resolveLocale, updateLayoutPreferences } from "./preferences.js";
import { translateForLocale } from "./i18n.js";
import { libraryFromNewerVersion, newerLibraryError } from "./library-version-guard.js";
import { normalizeShortcutOverrides, shortcutBindings, shortcutConflict } from './keyboard-shortcuts.js';
import { CHROME_WEB_STORE_URL } from "./product-links.js";
import { PALETTE_VERSION, hasCurrentPalette } from "./palette.js";
import {
  COMPOSER_METHOD_VERSION,
  appendDiagnosticEvent,
  createComposerSession,
  failComposerAssemblySnapshot,
  isMeaningfulComposerSession,
  normalizeComposerAiProfile,
  normalizeComposerSessions,
  normalizeComposerSettings,
  resetComposerAgentInstruction,
  sessionSummary,
  resetComposerTaskMethod,
  setComposerFailure,
  updateComposerAgentInstruction,
  updateComposerTaskMethod
} from "./composer.js";
import {
  activeCreativeJob,
  createCreativeJob,
  creativeJobById,
  interruptActiveCreativeJobs,
  normalizeCreativeJobsState,
  requestCreativeJobStop,
  retryCreativeJob,
  settleCreativeJobStop,
  updateCreativeJob
} from "./creative-jobs.js";
import { handleContextMenuCapture, syncContextMenus } from "./context-menus.js";
import {
  createCaptureDraft,
  draftParts,
  draftSourcePages,
  draftText,
  sourceContextForUrl
} from "./capture-draft.js";
import { createCaptureWorkspace } from "./capture-workspace.js";
import { RESTRICTED_PAGE_MESSAGE } from "./capture-permissions.js";
import {
  applyPageCaptureSelections,
  combinePageCaptureCandidates,
  collectPageCaptureSnapshot,
  readPageCaptureInjectionResult,
  PAGE_CAPTURE_ADAPTERS,
  PAGE_CAPTURE_PLATFORM_ADAPTERS,
  normalizePageCaptureBatch,
  normalizePageCaptureCandidate,
  pageCaptureMediaFetchCandidates,
  resolvePageCaptureImage
} from "./page-capture.js";
import {
  collectPageCaptureSitePayload,
  installPageCaptureSiteObserver,
  normalizePageCaptureSitePayload
} from "./page-capture-site-adapters.js";
import { boundedMediaBlobFromResponse, fetchBoundedMedia, isSupportedDocumentMimeType, mediaDownloadFailure } from "./bounded-media.js";
import { enrichPinterestCandidates, readPinterestHtml } from "./pinterest-capture.js";
import { downloadPageCaptureVideo } from "./page-capture-video.js";
import { resolveCapturedVideoOriginal } from './captured-video-original.js';
import { downloadNativeVideo, nativeVideoStatus } from './native-video.js';
import { createVideoComponentSetup, VIDEO_SETUP_ALARM } from './video-component-setup.js';
import { createDownloadAhead } from "./capture-download-ahead.js";
import { createCaptureAssetIndex } from "./capture-asset-index.js";
import { resolveXVideoSources } from "./x-video-capture.js";
import { readPageCaptureSupplement } from "./capture-supplement.js";
import { PAGE_CAPTURE_VIDEO_FRAME_RULES, resolvePageCaptureVideoFrames } from "./page-capture-frames.js";
import { pageCaptureMediaReceipt, planPageCaptureRepair, mergePageCaptureRepair, capturedMediaPrompts, samePageCaptureSource } from "./page-capture-repair.js";
import { collectPageCaptureDownloads } from "./page-capture-downloads.js";
import {
  discardPageSessionMedia,
  PAGE_SESSION_MEDIA_CHUNK_BYTES,
  preparePageSessionMedia,
  readPageSessionMediaChunk
} from "./page-session-media.js";
import { PAGE_CAPTURE_LIMITS, PAGE_CAPTURE_QUALITY_LIMITS, LIBRARY_TRANSFER_LIMITS } from "./resource-limits.js";
import { publicAiServiceProfiles } from "./ai-service-profiles.js";
import {
  applyConnectionModelAssignments,
  availableAiModelsForTask,
  availableAiProvidersForTask,
  mergeAiProviderRegistry,
  modelConcurrencyLimit,
  normalizeAiTaskAssignments,
  publicAiProviderRegistry
} from "./ai-provider-registry.js";
import {
  AI_RUNTIME_PROTOCOL_VERSION,
  aiConfigurationFromStorage,
  aiConfigurationNeedsStorageUpdate,
  normalizeAiPreferences,
  projectAiRuntime,
  resolveTextTaskSettings,
  resolveVideoAnalysisTask,
  resolveVisionTaskSettings,
  videoAnalysisRouteMatches
} from "./ai-runtime.js";
import {
  chatCompletionsVideoSourcePlan,
  VIDEO_ANALYSIS_REQUEST_TIMEOUT_MS,
  VIDEO_RECONSTRUCTION_CONTRACT_VERSION
} from "./video-analysis.js";
import { detectMediaReferenceProvider, officialMediaEmbedUrl } from "./media-reference-resolver.js";
import {
  createCompoundCase,
  normalizeCompoundCases,
  removeEntriesFromCompoundCases,
  splitCompoundCase,
  updateCompoundCase
} from "./compound-cases.js";
import {
  addEntryVisual,
  normalizeEntryVisuals,
  primaryVisual,
  setPrimaryVisual,
  updateEntryVisual
} from "./visuals.js";
import {
  VISION_ANALYSIS_VERSION,
  evaluateCreativeOutputWithVision,
  analyzeImageWithVision,
  blobToDataUrl,
  createVisionRequestBudget,
  imageFingerprint,
  publicVisionSettings,
  visionAnalysisProfileFingerprint
} from "./vision.js";
import {
  activateCreativeResultContext,
  addCreativeOutput,
  applyCreativeEvaluation,
  createCreativeRun,
  normalizeActiveCreativeResult,
  normalizeCreativeExperimentSettings,
  normalizeCreativeRuns,
  recordCreativeSignal,
  removeCreativeOutput,
  updateCreativeJudgment
} from "./creative-runs.js";
import { mergeCreativeExperimentPackage } from "./creative-experiment-package.js";
import {
  markSyncMetaDirty,
  normalizeSyncMeta,
  normalizeSyncSettings,
  syncErrorDetails
} from "./sync-model.js";
import {
  createOrUnlockSyncVault,
  openSyncVaultWithKey
} from "./sync-vault.js";
import { createManualSyncController } from "./manual-sync.js";
import {
  clearSyncPrivateState,
  getSyncCryptoKey,
  getSyncDirectoryHandle,
  getStagedSyncDirectoryHandle,
  saveSyncConnection,
  saveSyncCryptoKey
} from "./sync-store.js";
import {
  createExtensionUpdateLifecycle,
  EXTENSION_UPDATE_STATUS_CHANGED
} from "./extension-update.js";

const STORAGE_KEYS = Object.freeze({
  schemaVersion: "schemaVersion",
  entries: "entries",
  trashState: "trashState",
  compoundCases: "compoundCases",
  settings: "settings",
  taxonomy: "taxonomy",
  facetCatalog: "facetCatalog",
  classificationRules: "classificationRules",
  migrationBackup: "migrationBackup",
  upgradeBackup: "upgradeBackup",
  folderOwnershipBackup: "folderOwnershipBackup",
  classificationResetBackup: "classificationResetBackup",
  facetMigrationBackup: "creativeFacetMigrationBackupV5",
  facetUndo: "facetUndo",
  aiProviderRegistry: "aiProviderRegistry",
  aiTaskAssignments: "aiTaskAssignments",
  aiPreferences: "aiPreferences",
  visionAnalysisUndo: "visionAnalysisUndo",
  automaticVisionBatchJob: "automaticVisionBatchJob",
  batchJob: "batchJob",
  analysisTasks: "analysisTasks",
  libraryImportTransactions: "libraryImportTransactions",
  libraryReplacementRecoveryPoint: "libraryReplacementRecoveryPoint",
  libraryMaintenanceJob: "libraryMaintenanceJob",
  legacyAnalysisBatchJob: "analysisBatchJob",
  analysisBatchUndo: "analysisBatchUndo",
  analysisRebuildStaging: "analysisRebuildStaging",
  organizerState: "organizerState",
  uiPreferences: "uiPreferences",
  composerSettings: "composerSettings",
  composerSessions: "composerSessions",
  creativeExperimentSettings: "creativeExperimentSettings",
  creativeRuns: "creativeRuns",
  creativeJobs: "creativeJobs",
  importJobs: "importJobs",
  importStaging: "importStaging",
  creativeSkills: "creativeSkills",
  activeCreativeResult: "activeCreativeResult",
  lastSaveUndo: "lastSaveUndo",
  captureDraft: "captureDraft",
  syncSettings: "syncSettings",
  syncMeta: "syncMeta"
});
const SYNCED_STORAGE_KEYS = new Set([
  STORAGE_KEYS.entries,
  STORAGE_KEYS.trashState,
  STORAGE_KEYS.compoundCases,
  STORAGE_KEYS.settings,
  STORAGE_KEYS.taxonomy,
  STORAGE_KEYS.facetCatalog,
  STORAGE_KEYS.classificationRules,
  STORAGE_KEYS.organizerState,
  STORAGE_KEYS.composerSettings,
  STORAGE_KEYS.composerSessions,
  STORAGE_KEYS.creativeExperimentSettings,
  STORAGE_KEYS.creativeRuns,
  STORAGE_KEYS.creativeSkills
]);
const libraryStorage = getLibraryStorage();
const OFFSCREEN_DOCUMENT_PATH = "offscreen.html";
let writeQueue = Promise.resolve();
let trashCleanupProgress = null;
let captureWriteQueue = Promise.resolve();
let stateMigration = null;
let creatingOffscreenDocument = null;
let visionAnalysisInFlight = false;
const aiProviderModule = createAiProviderModule();
const extensionUpdateLifecycle = createExtensionUpdateLifecycle({
  runtime: chrome.runtime,
  getInstallation: () => chrome.management.getSelf(),
  storage: chrome.storage.local,
  fetchFn: (...args) => fetch(...args),
  notify: (status) => chrome.runtime.sendMessage({
    type: EXTENSION_UPDATE_STATUS_CHANGED,
    status
  }).catch(() => undefined)
});
let activePageCapture = null;
let syncApplyInProgress = false;
const commitLocalChanges = createLibraryCommitter({ storage: libraryStorage, syncedKeys: SYNCED_STORAGE_KEYS,
  syncMetaKey: STORAGE_KEYS.syncMeta, markDirty: markSyncMetaDirty, isSyncApplying: () => syncApplyInProgress });
const undoConfirmations = createUndoConfirmations(libraryStorage);
const caseEditor = createCaseEditor({ commitCase: (entryId, transform) => commitLocalChanges.updateCase(entryId, transform) });
const stagedMedia = createStagedMediaRegistry({
  storage: libraryStorage,
  activeDocuments: async () => (await chrome.runtime.getContexts({})).map(context => context.documentId || context.contextId),
  cleanup: async (assetIds, protectedIds, localReferenceIds) => {
    const retained = retainedTrashCleanupAssets(await readTrashCleanupState(),
      [...protectedIds, ...activeCaptureAssetIds, ...await agentTransfers.retainedIds()]);
    await deleteMediaBlobs(assetIds.filter(id => !retained.has(id)));
    await deleteLocalAssetHandles(localReferenceIds.filter(id => !retained.has(id)));
  }
});
const manualSyncController = createManualSyncController({
  readState,
  readMeta: async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.syncMeta);
    return stored[STORAGE_KEYS.syncMeta];
  },
  readMedia: getMediaBlob,
  writeMedia: savePortableAssetBlob,
  deleteMedia: deleteMediaBlob,
  commit: commitManualSyncResult,
  onProgress: notifySyncProgress,
  onStatus: notifySyncProgress
});
let maintenanceRunnerActive = false;
let maintenanceRunnerTimer = 0;
let automaticVisionRunnerActive = false;
let automaticVisionRunnerTimer = 0;
let analysisBatchRunnerActive = false;
let analysisBatchRunnerTimer = 0;
let importRunnerActive = false;
let importRunnerTimer = 0;
const analysisTaskRunners = new Map();
const LIBRARY_MAINTENANCE_ALARM = "prompt-director-library-maintenance";
const AUTOMATIC_VISION_ALARM = "prompt-director-automatic-vision";
const ANALYSIS_BATCH_ALARM = "prompt-director-analysis-batch";
const ANALYSIS_TASK_ALARM = "prompt-director-analysis-task";
const IMPORT_JOB_ALARM = "prompt-director-local-import";
const ANALYSIS_TASK_STORAGE_LOCK = "promptdirector-analysis-task-storage";
const MAINTENANCE_SLICE_TARGET_MS = 250;
const captureRuntime = createCaptureWorkspace({
  chromeApi: chrome,
  storage: libraryStorage,
  captureDraftStorageKey: STORAGE_KEYS.captureDraft,
  uiPreferencesStorageKey: STORAGE_KEYS.uiPreferences,
  ensureOffscreenDocument,
  deleteVisual: deleteScreenshotBlob,
  resolveSourceContext: resolveCaptureSourceContext
});

const activeCaptureAssetIds = new Set();
const captureSaveTasks = createCaptureSaveTasks({ storage: libraryStorage,
  cleanup: ids => enqueue(() => deleteUnreferencedMedia(ids)),
  notify: message => chrome.runtime.sendMessage(message),
  execute: (message, progress) => runCaptureSave(message, progress)
});
const videoComponentSetup = createVideoComponentSetup({ storage: libraryStorage,
  inspect: nativeVideoStatus, platform: () => chrome.runtime.getPlatformInfo(),
  homepage: chrome.runtime.getManifest().homepage_url, downloads: chrome.downloads, alarms: chrome.alarms,
  resume: () => captureSaveTasks.resumeVideo(),
  notify: state => chrome.runtime.sendMessage({ type: 'VIDEO_COMPONENT_SETUP_CHANGED', state }).catch(() => {})
});

const readCaseLibraryState = createCaseLibraryReader({ storage: libraryStorage, readFullState: readState });
const skillOperations = createSkillOperations({ loadState: () => enqueue(() => libraryStorage.get(STORAGE_KEYS.creativeSkills)), readBlob: getMediaBlob });
const agentLibrary = createAgentLibrary({
  loadState: () => enqueue(readCaseLibraryState),
  readBlob: async id => await getMediaBlob(id) || await getScreenshotBlob(id),
  readDerived: getDerivedMedia, readDerivedMetadata: getAllDerivedMetadata,
  libraryUrl: chrome.runtime.getURL("library.html")
});
const projectOperations = createProjectOperations({ loadState: readState, loadReadState: readCaseLibraryState, storage: libraryStorage, commit: commitLocalChanges, enqueue });
const caseOperations = createCaseOperations({ loadState: readState, loadReadState: readCaseLibraryState, storage: libraryStorage, commit: commitLocalChanges, enqueue });
const workspaceScreenshot = createWorkspaceScreenshot({ chromeApi: chrome });
const caseTrashOperations = createCaseTrashOperations({ loadState: readState, storage: libraryStorage, commit: commitLocalChanges, enqueue });
const caseDedupeOperations = createCaseDedupeOperations({ loadState: readState, storage: libraryStorage, commit: commitLocalChanges, enqueue });
const verifyDedupeMedia = createDedupeMediaVerifier({ storage: libraryStorage, readBlob: getMediaBlob, commit: commitLocalChanges, enqueue });
const libraryIdentity = createBrowserLibraryIdentity({ storage: libraryStorage,
  getLegacyId: async () => (await agentConnection.prepare()).instanceId });
const externalAnalysisBatches = createExternalAnalysisBatches({storage:libraryStorage,loadState:readState,
  commit:commitLocalChanges,enqueue,readBlob:async id=>await getMediaBlob(id)||await getScreenshotBlob(id),
  getLibraryId:async()=>(await libraryIdentity.read()).libraryId});
const referenceSelection = createReferenceSelection({ storage: libraryStorage, loadState: readCaseLibraryState,
  readDerived: getDerivedMedia, getLibraryId: async () => (await libraryIdentity.read()).libraryId, enqueue });
const agentWorkspace = createAgentWorkspace({ chromeApi: chrome, readCase: input => caseOperations.read(input),
  readSelection: input => referenceSelection.read(input),
  readTemporary: async id => {
    const record = await agentTransfers.get(id);
    if (record.state !== 'ready' || !['video', 'image'].includes(record.prepared?.asset?.kind)) throw agentError('invalid_review_media', '请先传入可审阅的图片或视频');
    return { assetId: record.assetId, name: record.name, kind: record.prepared.asset.kind,
      byteSize: record.byteSize, sha256: record.sha256, mimeType: record.mimeType, transferId: record.id, feedback: record.reviewFeedback || { revision: 0, notes: [], frames: [] } };
  } });
const agentTransfers = createAgentTransfers({
  storage: libraryStorage, readBlob: getMediaBlob, writeBlob: savePortableAssetBlob, deleteBlob: deleteMediaBlob,
  cleanup: deleteUnreferencedMedia,
  reuse: async record => reusableAgentFile(record, await readCaseLibraryState(), getMediaBlob),
  protectedIds: async () => [...collectRetainedLocalAssetIds(await readState()), ...captureChatAssetIds((await libraryStorage.get('captureAssistantDialog')).captureAssistantDialog)],
  prepare: async record => {
    await ensureOffscreenDocument();
    const response = await chrome.runtime.sendMessage({ target: "offscreen", type: "PREPARE_AGENT_FILE", record });
    if (!response?.ok) throw new Error(response?.message || "文件准备失败");
    return response.prepared;
  }
});
const skillWriter = createSkillWriter({ storage: libraryStorage, transfers: agentTransfers,
  readBlob: getMediaBlob, commit: commitLocalChanges, enqueue, cleanup: deleteUnreferencedMedia });
const agentCapturePreview = createAgentCapturePreview({ storage: libraryStorage, chromeApi: chrome,
  collect: collectPageCaptureTab, commit: commitPageCapture,
  readSavedText: async caseId => {
    let result = await agentLibrary.read({ caseId, part: 'body', length: AGENT_CHUNK_BYTES / 4 }), text = result.content;
    while (result.nextOffset !== null) {
      result = await agentLibrary.read({ caseId, part: 'body', length: AGENT_CHUNK_BYTES / 4, offset: result.nextOffset, expectedRevision: result.revision });
      text += result.content;
    }
    return text;
  },
  resolveLocalMedia: media => resolveCaptureLocalMedia(media, agentTransfers, { loadState: readCaseLibraryState }),
  readImage: async media => media.localAssetId ? await getMediaBlob(media.localAssetId) || await getScreenshotBlob(media.localAssetId)
    : fetchBoundedMedia(media.url, { kind: 'image', maxBytes: LIBRARY_TRANSFER_LIMITS.maxImageBytes, maxPixels: LIBRARY_TRANSFER_LIMITS.maxImagePixels }),
  loadState: () => libraryStorage.get(STORAGE_KEYS.organizerState),
  getLibraryId: async () => (await libraryIdentity.read()).libraryId });
const captureAssistantControllers = new Map();
const agentTasks = createAgentTasks({ storage: libraryStorage,
  getLibraryId: async () => (await libraryIdentity.read()).libraryId,
  // This browser library may adopt its receipts predating library IDs.
  allowLegacyTasks: true,
  execute: async (operation, input, requestId, scope) => {
    if (operation === 'capture_assist') {
      const controller = captureAssistantControllers.get(requestId) || new AbortController(); captureAssistantControllers.set(requestId, controller);
      try {
        await scope.assertCurrent();
        const contextRuntime = createComposerToolProgress({ storage: libraryStorage, sessionId: input.sessionId, userMessageId: requestId });
        return await runCaptureAssistant(input, { runtime: await getComposerAiRuntime(), signal: controller.signal, sessionRuntime: contextRuntime,
          readAttachment: transferId => readCaptureChatAttachment(transferId, { transfers: agentTransfers, readBlob: getMediaBlob, loadState: readCaseLibraryState, readDerived: getDerivedMedia }),
          readMedia: input => readAssistantCaseMedia(input, { loadState: readCaseLibraryState, readBlob: getMediaBlob }),
          call: async (name, args) => { await scope.assertCurrent(); return executeAgentOperation(name,
            name === 'save_capture' ? { ...args, captureAssistantRequestId: requestId } : args); },
          onDelta: (_delta, text) => { void chrome.runtime.sendMessage({ type: 'CAPTURE_ASSIST_CHANGED', requestId, text }).catch(() => {}); },
          onPreview: preview => { void chrome.runtime.sendMessage({ type: 'CAPTURE_ASSIST_CHANGED', requestId, preview }).catch(() => {}); },
          onStatus: message => { void chrome.runtime.sendMessage({ type: 'CAPTURE_ASSIST_CHANGED', requestId, message }).catch(() => {}); } });
      } finally { captureAssistantControllers.delete(requestId); }
    }
    await scope.assertCurrent();
    if (['prepare_capture', 'update_capture', 'save_capture'].includes(operation)) {
      scope.report({ state: 'queued', progress: { phase: 'queued' } });
      return enqueueCapture(async () => {
        await scope.assertCurrent();
        scope.report({ state: 'running', progress: { phase: operation === 'save_capture' ? 'preparing'
          : operation === 'prepare_capture' ? 'reading-page' : 'updating-preview' } });
        const controller = input.captureAssistantRequestId ? captureAssistantControllers.get(input.captureAssistantRequestId) : null;
        const progress = operation === 'save_capture' ? createCaptureSaveProgress({ requestId,
          send: message => {
            scope.report({ progress: message.progress, sequence: message.sequence });
            if (controller) return chrome.runtime.sendMessage({ ...message, requestId: input.captureAssistantRequestId });
          } }) : undefined;
        if (progress) {
          progress.signal = controller?.signal;
          progress.retain = async ids => { ids.forEach(id => activeCaptureAssetIds.add(id)); };
          progress.commit = async () => {
            await scope.assertCurrent();
            if (!controller) return;
            controller.signal.throwIfAborted(); controller.committing = true;
            void chrome.runtime.sendMessage({ type: 'CAPTURE_ASSIST_CHANGED', requestId: input.captureAssistantRequestId, committing: true }).catch(() => {}); };
        }
        try { return await agentCapturePreview.execute(operation, input, requestId, scope, progress); }
        finally { progress?.close(); activeCaptureAssetIds.clear(); }
      });
    }
    if (operation === "capture") return enqueueCapture(async () => {
      await scope.assertCurrent();
      try {
        return await captureAgentUrl(input, requestId, {
          chromeApi: chrome, loadState: readState, collect: collectPageCaptureTab,
          commit: async (batch, metadata) => {
            await scope.assertCurrent();
            return commitPageCapture(batch, metadata);
          }
        });
      } finally { activeCaptureAssetIds.clear(); }
    });
    if (operation === "save_material") return saveMaterial(input, requestId, scope);
    throw agentError("unknown_operation", "未知写入操作。");
  }
});
function saveMaterial(input, requestId, scope) {
  return enqueue(() => agentTransfers.lock(async () => {
    await scope?.assertCurrent();
    return saveAgentMaterial(input, requestId, {
      loadState: readState, storage: libraryStorage, transfers: agentTransfers, buildEntry, readBlob: getMediaBlob,
      getInstanceId: async () => (await agentConnection.snapshot()).instanceId,
      classify: (entry, state) => classifyContent(entry, state.classificationRules, state.taxonomy),
      place: organizerAfterCapturePlacement, commit: async (update, options) => {
        await scope?.assertCurrent();
        return commitLocalChanges(update, options);
      }, notify: notifySaved, schemaVersion: SCHEMA_VERSION
    });
  }));
}
const agentConnection = createAgentConnection({ chromeApi: chrome, execute: dispatchAgentOperation });
void agentConnection.start();

const workspaceActivityLabels = {
  search: '查询案例', read_case: '读取案例', read_case_details: '读取案例详情', read_media: '读取原件',
  edit_case: '修改案例', organize_case: '整理案例', save_material: '回存成果', show_case: '打开案例', open_workspace: '打开工作页面',
  control_workspace: '操作工作页面', read_workspace_context: '读取选择', read_workspace_content: '读取参考',
  capture: '采集资料', save_skill: '保存创作方法', create_project: '创建项目', update_project: '修改项目'
};
async function publishWorkspaceActivity(operation, state, error) {
  const label = workspaceActivityLabels[operation];
  if (!label) return;
  try { await chrome.runtime.sendMessage({ type: 'AGENT_WORKSPACE_ACTIVITY', label, state, message: error?.message }); }
  catch { /* No library page is open; the operation's own receipt is authoritative. */ }
}
async function dispatchAgentOperation(operation, input = {}) {
  await publishWorkspaceActivity(operation, 'running');
  try {
    const result = await executeAgentOperation(operation, input);
    await publishWorkspaceActivity(operation, ['queued', 'running', 'opening'].includes(result?.state) ? 'accepted' : 'completed');
    if (operation === 'get_task' && ['completed', 'failed'].includes(result.state)) await publishWorkspaceActivity(result.operation, result.state);
    return result;
  } catch (error) { await publishWorkspaceActivity(operation, 'failed', error); throw error; }
}
// Developer timing only: an isolated test browser can time read-only Agent queries without a connector.
const AGENT_PROBE_OPERATIONS = new Set(["search", "describe_case_query", "read_case_details"]);
globalThis.promptDirectorAgentProbe = async (operation, input = {}) => {
  if (!timingEnabled() || !AGENT_PROBE_OPERATIONS.has(operation)) throw new Error("Agent 计时探针仅在开发计时开启时用于只读查询");
  const done = startPhase("agent", `probe:${operation}`);
  try { return await executeAgentOperation(operation, input); } finally { done(); }
};

async function executeAgentOperation(operation, input) {
  switch (operation) {
    case "status": return { ...(await agentConnection.snapshot()), protocolVersion: AGENT_PROTOCOL_VERSION,
      extensionVersion: chrome.runtime.getManifest().version, searchGuidance: { systemLanguage: chrome.i18n.getUILanguage(), languages: [...new Set([chrome.i18n.getUILanguage().split(/[-_]/u)[0], 'en'])], expansion: 'calling_agent', querySemantics: 'terms_and_alternatives_or', pluginApiCalls: false }, analysisResultVersion: 2, analysisResultFields: ANALYSIS_RESULT_FIELDS, skillPackageLimits: skillPackageLimits(),
      caseOperationFeatures: Object.fromEntries(CASE_OPERATION_SPECS.filter(spec => spec.name !== 'read_case_details').map(spec => [spec.name, spec.name === 'edit_case' ? Object.keys(spec.parameters.properties.patch.properties) : spec.parameters.properties.action.enum])),
      captureReadParts: CAPTURE_OPERATION_SPECS.find(spec => spec.name === 'read_capture').parameters.properties.part.enum,
      workspaceSyncVersion: 6, sourceProtectionVersion: 1, capabilities: [...CAPTURE_OPERATION_SPECS.map(spec => spec.name), WORKSPACE_SCREENSHOT_SPEC.name, ...AGENT_CASE_ACTION_SPECS.map(spec => spec.name), ...WORKSPACE_OPERATION_SPECS.map(spec => spec.name), ...ANALYSIS_BATCH_SPECS.map(spec=>spec.name), "save_skill", "restore_skill", "list_skills", "read_skill", "read_skill_file", "read_projects", "create_project", "update_project", "describe_case_query", "search", "read_case", "read_media", "capture", "save_material", "get_task", "read_case_details", "edit_case", "organize_case", "read_workspace_context", "read_workspace_content", "resolve_reference", "show_case"], materialFields: ["projectRevision", "sourceReferences", "previousCreation", "creative", "customLabels", "classificationPathIds", "sourceFacts", "timeNotes"], workspaceContentParts: ["instruction", "reference", "selection"], workspaceProjectionVersion: 2, projectLookup: ["name", "path", "query"], materialReceiptVersion: 2, taskWaitMaxMs: 15000, caseTextReadVersion: 2, caseQueryVersion: 1, searchFilters: Object.keys(CASE_SEARCH_PROPERTIES) };
    case "manage_analysis_batch":
    case "list_analysis_batches":
    case "read_analysis_batch":
    case "submit_analysis_results":
    case "submit_analysis_result": return externalAnalysisBatches.execute(operation,input);
    case "save_skill":
    case "restore_skill": return skillWriter.execute(operation, input);
    case "list_skills":
    case "read_skill":
    case "read_skill_file": return skillOperations.execute(operation, input);
    case "read_projects": return projectOperations.read(input);
    case "create_project":
    case "update_project": return projectOperations.execute(operation, input);
    case "resolve_reference": return referenceSelection.resolve(input);
    case "read_workspace_context":
    case "read_workspace_content": return agentWorkspace.read(input);
    case "show_case": return agentWorkspace.show(input);
    case 'open_workspace': return agentWorkspace.open(input);
    case "capture_workspace": return workspaceScreenshot.capture(input);
    case 'read_review_media':
    case 'read_live_workspace':
    case 'wait_workspace_changes':
    case 'control_workspace': return agentWorkspace.live(operation, input);
    case "read_case_details": return caseOperations.read(input);
    case "trash_case": return caseTrashOperations.execute(input);
    case "edit_case":
    case "organize_case": return caseOperations.execute(operation, input);
    case "describe_case_query": return agentLibrary.describeQuery();
    case "search": return agentLibrary.search(input);
    case "read_case": return agentLibrary.read(input);
    case "read_media": return agentLibrary.media(input);
    case 'read_capture': {
      // Freezing new originals changes the preview revision. Serialize those
      // reads and directory checkpoints with selection/save; ordinary live
      // context and source pagination stay read-only.
      const freezesSource = ['source', 'supplement'].includes(input.part) && !input.offset || input.refresh || input.part === 'modules';
      return freezesSource ? enqueueCapture(() => agentCapturePreview.read(input)) : agentCapturePreview.read(input);
    }
    case "capture":
    case 'prepare_capture':
    case 'update_capture':
    case 'save_capture':
    case "save_material": {
      const { requestId, ...args } = input;
      return agentTaskLinks(await agentTasks.submit(operation, args, requestId));
    }
    case "get_task": {
      return agentTaskLinks(await agentTasks.inspect(input.requestId, input));
    }
    case "begin_transfer": return enqueue(() => agentTransfers.begin(input));
    case "append_transfer": return agentTransfers.append(input);
    case "finish_transfer": return agentTransfers.finish(input);
    case "abort_transfer": return agentTransfers.abort(input);
    default: throw agentError("unknown_operation", "连接器不支持这个业务操作。");
  }
}

function agentTaskLinks(receipt) {
  if (receipt.result?.results) receipt.result.results = receipt.result.results.map(item => ({ ...item,
    ...(item.entryId ? { openUrl: chrome.runtime.getURL(`library.html?case=${encodeURIComponent(item.entryId)}`) } : {}) }));
  return receipt;
}

chrome.runtime.onInstalled.addListener((details) => {
  enqueue(async () => {
    await extensionUpdateLifecycle.handleInstalled(details);
    await restrictLocalStorageAccess();
    await syncContextMenus();
    await chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: false });

    const state = await readState();
    await commitLocalChanges({ [STORAGE_KEYS.settings]: state.settings }, { markSyncDirty: false });
    await migrateLegacyScreenshots(state.entries);
  }).catch((error) => console.error("PromptDirector installation setup failed", error));
});

chrome.runtime.onUpdateAvailable.addListener((details) => {
  extensionUpdateLifecycle.handleUpdateAvailable(details)
    .catch((error) => console.error("PromptDirector update availability handling failed", error));
});

chrome.runtime.onStartup.addListener(() => {
  extensionUpdateLifecycle.handleStartup()
    .catch((error) => console.error("PromptDirector development update check failed", error));
});

restrictLocalStorageAccess().catch((error) => console.error("PromptDirector storage access restriction failed", error));
syncContextMenus().catch((error) => console.error("PromptDirector context menu sync failed", error));
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: false }).catch((error) => console.error("PromptDirector side panel setup failed", error));
chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === VIDEO_SETUP_ALARM) videoComponentSetup.check().catch(error => console.warn('视频组件安装接续未完成', error));
  if (alarm.name === 'agent-temporary-maintenance') {
    enqueue(() => agentTransfers.prune()).catch(error => console.warn('临时传输回收未完成', error));
    enqueue(() => withTrashCleanupProgress(resumeTrashCleanup)).catch(error => console.warn('永久删除文件清理未完成', error));
    enqueue(() => stagedMedia.sweep()).catch(error => console.warn('临时文件清理未完成', error));
  }
  if (alarm.name === LIBRARY_MAINTENANCE_ALARM) scheduleLibraryMaintenanceRunner();
  if (alarm.name === AUTOMATIC_VISION_ALARM) scheduleAutomaticVisionRunner();
  if (alarm.name === ANALYSIS_BATCH_ALARM) scheduleAnalysisBatchRunner();
  if (alarm.name === IMPORT_JOB_ALARM) scheduleImportRunner();
});
chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === ANALYSIS_TASK_ALARM) return runQueuedAnalysisTasks();
});
videoComponentSetup.restore().catch(error => console.warn('视频组件安装恢复未完成', error));
scheduleLibraryMaintenanceRunner();
chrome.alarms.create('agent-temporary-maintenance', { periodInMinutes: RESOURCE_POLICY.temporaryIdleMs / (24 * 60_000) }).catch(error => console.warn('临时传输维护未安排', error));
enqueue(() => agentTransfers.prune()).catch(error => console.warn('临时传输回收未完成', error));
enqueue(() => withTrashCleanupProgress(resumeTrashCleanup)).catch(error => console.warn('永久删除文件清理未完成', error));
enqueue(() => stagedMedia.sweep()).catch(error => console.warn('临时文件清理未完成', error));
chrome.tabs.onRemoved.addListener(() => { enqueue(() => stagedMedia.sweep()).catch(error => console.warn('临时文件清理未完成', error)); });
chrome.tabs.onUpdated.addListener((_tabId, change) => {
  if (change.status === 'complete') enqueue(() => stagedMedia.sweep()).catch(error => console.warn('临时文件清理未完成', error));
});
scheduleAutomaticVisionRunner();
recoverCreativeJobs().catch((error) => console.error("PromptDirector creative job recovery failed", error));
enqueue(recoverImportJobs).catch((error) => console.error("PromptDirector local import recovery failed", error));
enqueue(async () => {
  await recoverAnalysisTasks();
  await recoverVideoBatchExecutionState();
  scheduleAnalysisBatchRunner();
}).catch((error) => console.error("PromptDirector analysis task recovery failed", error));

chrome.contextMenus.onClicked.addListener((info, tab) => {
  handleContextMenuCapture(info, tab, {
    chromeApi: chrome,
    enqueueCapture,
    dispatch: (action, payload) => captureRuntime.dispatch(action, payload),
    showResult: showResultToast,
    formatError: userMessage,
    reportSidePanelError: (error) => console.error("PromptDirector side panel open failed", error)
  });
});

chrome.commands.onCommand.addListener(async (command) => {
  if (command !== "save-selection") return;
  const response = await enqueueCapture(() => captureRuntime.dispatch("add-active-selection"));
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (tab?.windowId) await chrome.sidePanel.open({ windowId: tab.windowId }).catch(() => undefined);
  await showResultToast(tab?.id, response.message, !response.ok);
});

const discoveredVideosForTab = installVideoDiscovery(chrome);

chrome.action.onClicked.addListener((tab) => {
  if (!Number.isInteger(tab?.windowId)) return;
  chrome.sidePanel.open({ windowId: tab.windowId })
    .then(() => chrome.runtime.sendMessage({ type: "OPEN_PAGE_CAPTURE", windowId: tab.windowId }).catch(() => undefined))
    .catch((error) => console.error("PromptDirector toolbar side panel open failed", error));
});

const originalFileDrag = createOriginalFileDragHost(chrome, getMediaBlob);
const syncOriginalFileDrag = () => originalFileDrag.sync().catch(error => console.error('PromptDirector file drop setup failed', error));
chrome.permissions.onAdded.addListener(syncOriginalFileDrag);
chrome.permissions.onRemoved.addListener(syncOriginalFileDrag);
void syncOriginalFileDrag();
chrome.runtime.onConnect.addListener((port) => {
  if (originalFileDrag.connect(port)) return;
  if (port.name !== "capture-region") return;
  port.onMessage.addListener(() => undefined);
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (['AGENT_READ_WORKSPACE', 'AGENT_LIVE_WORKSPACE', 'AGENT_WORKSPACE_ACTIVITY'].includes(message?.type)) return false;
  if (message?.target === "offscreen") return false;
  const interaction = {
    sidePanelOpening: openCreativeResultSidePanel(message, sender),
    sender
  };
  const done = startPhase("background", `message:${String(message?.type || "unknown")}`);
  handleMessage(message, interaction)
    .then(sendResponse)
    .catch((error) => sendResponse({ ok: false, message: userMessage(error) }))
    .finally(done);
  return true;
});

function openCreativeResultSidePanel(message, sender) {
  if (message?.type !== "ACTIVATE_CREATIVE_RESULT") return null;
  const windowId = sender?.tab?.windowId;
  if (!Number.isInteger(windowId)) return Promise.resolve(false);
  return chrome.sidePanel.open({ windowId })
    .then(() => true)
    .catch((error) => {
      console.error("PromptDirector creative result side panel open failed", error);
      return false;
    });
}

async function handleMessage(message, interaction = {}) {
  switch (message?.type) {
    case 'REGISTER_STAGED_MEDIA':
    case 'RELEASE_STAGED_MEDIA': {
      const sender = interaction.sender;
      const documentId = await resolveStageDocument(chrome, sender, message.operationId, libraryStorage);
      return enqueue(async () => {
        if (message.type === 'REGISTER_STAGED_MEDIA') await stagedMedia.register(message.operationId, documentId, message.assetIds, message.localReferenceIds);
        else await stagedMedia.release(message.operationId, documentId);
        return { ok: true };
      });
    }

    case 'GET_LIBRARY_IDENTITY': {
      if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL(''))) throw new Error('资料库身份只能从插件工作空间读取');
      return { ok: true, identity: await libraryIdentity.read() };
    }
    case 'START_CAPTURE_ASSIST':
    case 'GET_CAPTURE_ASSIST_TASK':
    case 'CANCEL_CAPTURE_ASSIST':
    case 'SHOW_CAPTURE_ASSIST_CASE':
    case 'GET_CAPTURE_ASSIST_PREVIEW': {
      if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL('collector.html'))) {
        throw agentError('unauthorized', '采集助手只能从采集侧边栏操作');
      }
      if (message.type === 'SHOW_CAPTURE_ASSIST_CASE') return { ok: true, ...await agentWorkspace.show({ caseId: message.caseId }) };
      if (message.type === 'START_CAPTURE_ASSIST') {
        if (typeof message.input?.instruction !== 'string' || !message.input.instruction.trim()) throw new Error('请输入要求');
        if (/^https?:/iu.test(message.input.sourceUrl || '') && (!Number.isInteger(message.input.tabId) || (await chrome.tabs.get(message.input.tabId)).url !== message.input.sourceUrl)) throw new Error('当前页面已改变,请重试');
        if (captureAssistantControllers.size) {
          const [requestId, active] = captureAssistantControllers.entries().next().value;
          if (requestId === message.requestId) return { ok: true, task: await agentTasks.submit('capture_assist', message.input, requestId) };
          return { ok: false, code: 'capture_busy', requestId, sessionId: active.sessionId, message: '已有采集助手任务正在运行,请先等待或停止' };
        }
        const controller = new AbortController(); controller.sessionId = message.input.sessionId; captureAssistantControllers.set(message.requestId, controller);
        try {
          const task = await agentTasks.submit('capture_assist', message.input, message.requestId);
          if (!['queued', 'running'].includes(task.state)) captureAssistantControllers.delete(message.requestId);
          return { ok: true, task };
        } catch (error) { captureAssistantControllers.delete(message.requestId); throw error; }
      }
      if (message.type === 'GET_CAPTURE_ASSIST_PREVIEW') return agentCapturePreview.view(message.input);
      let task;
      try { task = await agentTasks.inspect(message.requestId, { waitMs: message.waitMs ?? 0 }); }
      catch (error) { return { ok: false, code: error.code, message: userMessage(error) }; }
      if (task.operation !== 'capture_assist') throw new Error('这不是采集助手任务');
      if (!['queued', 'running'].includes(task.state)) captureAssistantControllers.delete(message.requestId);
      if (message.type === 'CANCEL_CAPTURE_ASSIST') {
        const controller = captureAssistantControllers.get(message.requestId);
        if (controller && !controller.committing) controller.abort(new Error('采集助手已停止,已有预览保留'));
      }
      return { ok: true, task };
    }
    case "GET_REFERENCE_SELECTION":
    case "SET_REFERENCE_SELECTION": {
      if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL(""))) {
        throw new Error("参考选择只能从插件工作空间操作");
      }
      return { ok: true, selection: message.type === "GET_REFERENCE_SELECTION"
        ? await referenceSelection.get() : await referenceSelection.update(message.input) };
    }
    case "SKILL_OPERATION": {
      if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL(""))) {
        throw new Error("Skill操作只能从插件工作空间调用");
      }
      return { ok: true, data: await (["save_skill", "restore_skill"].includes(message.operation)
        ? skillWriter.execute(message.operation, message.input) : skillOperations.execute(message.operation, message.input)) };
    }
    case 'COMPOSER_SKILL_TRANSFER': {
      if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL(''))) {
        throw agentError('unauthorized', 'Skill文件只能从插件工作空间传入');
      }
      if (!['begin_transfer', 'append_transfer', 'finish_transfer'].includes(message.operation)) throw agentError('invalid_input', '未知Skill文件操作');
      if (message.operation === 'begin_transfer') {
        if (message.input?.purpose !== 'skill-file') throw agentError('invalid_input', '这里只接收Skill文件');
      } else if ((await agentTransfers.get(message.input?.id)).purpose !== 'skill-file') {
        throw agentError('invalid_input', '这里只接收Skill文件');
      }
      return { ok: true, data: await dispatchAgentOperation(message.operation, message.input) };
    }
    case 'REVIEW_TRANSFER': {
      if (interaction.sender?.id !== chrome.runtime.id || interaction.sender?.url?.split(/[?#]/u)[0] !== chrome.runtime.getURL('library.html')) throw agentError('unauthorized', '审片操作只能从案例库调用');
      if (!['begin_transfer', 'append_transfer', 'finish_transfer', 'abort_transfer'].includes(message.operation)) throw agentError('invalid_input', '未知审片文件操作');
      const result = await dispatchAgentOperation(message.operation, message.input);
      if (message.operation !== 'finish_transfer') return result;
      const record = await agentTransfers.get(message.input.id);
      if (!['video', 'image'].includes(record.prepared?.asset?.kind)) throw agentError('invalid_review_media', '请选择图片或视频');
      return { assetId: record.assetId, name: record.name, kind: record.prepared.asset.kind, byteSize: record.byteSize,
        sha256: record.sha256, mimeType: record.mimeType, transferId: record.id, feedback: record.reviewFeedback || { revision: 0, notes: [], frames: [] } };
    }
    case 'REVIEW_LOCAL_FILE': {
      if (interaction.sender?.id !== chrome.runtime.id || interaction.sender?.url?.split(/[?#]/u)[0] !== chrome.runtime.getURL('library.html')) throw agentError('unauthorized', '审片操作只能从案例库调用');
      const record = await agentTransfers.stageLocal(message.input || {});
      if (!['video', 'image'].includes(record.prepared?.asset?.kind)) throw agentError('invalid_review_media', '请选择图片或视频');
      return { assetId: record.assetId, name: record.name, kind: record.prepared.asset.kind, byteSize: record.byteSize,
        sha256: record.sha256, mimeType: record.mimeType, transferId: record.id, feedback: record.reviewFeedback || { revision: 0, notes: [], frames: [] } };
    }
    case 'CAPTURE_LOCAL_FILE': {
      if (interaction.sender?.id !== chrome.runtime.id || interaction.sender?.url?.split(/[?#]/u)[0] !== chrome.runtime.getURL('collector.html')) throw agentError('unauthorized', '本机采集文件只能从采集侧栏传入');
      const record = await agentTransfers.stageLocal(message.input || {});
      if (!['image', 'video', 'document', 'attachment'].includes(record.prepared?.asset?.kind)) throw agentError('invalid_input', '请选择图片、视频或文档');
      return { ok: true, transferId: record.id, asset: record.prepared.asset, poster: record.prepared.poster };
    }
    case 'REVIEW_FEEDBACK': {
      if (interaction.sender?.id !== chrome.runtime.id || interaction.sender?.url?.split(/[?#]/u)[0] !== chrome.runtime.getURL('library.html')) throw agentError('unauthorized', '审片备注只能从案例库调用');
      return { ok: true, feedback: await agentTransfers.updateReview(message.input) };
    }
    case "SAVE_REVIEW_MATERIAL": {
      if (interaction.sender?.id !== chrome.runtime.id || interaction.sender?.url?.split(/[?#]/u)[0] !== chrome.runtime.getURL('library.html')) throw agentError('unauthorized', '审片保存只能从案例库页面调用');
      const { requestId, transferId, transferIds, reviewRevisions, title, project } = message.input || {};
      validateProjectOperation('save_material', { requestId, title, text: '', ...(project ? { project } : {}) });
      const ids = transferIds ?? [transferId];
      if (!Array.isArray(ids) || !ids.length || ids.some(id => typeof id !== 'string' || !id.trim()) || new Set(ids).size !== ids.length) throw agentError('invalid_input', '缺少有效临时样片身份');
      const records = await Promise.all(ids.map(id => agentTransfers.get(id)));
      for (const record of records) {
        if (record.purpose || !['image', 'video'].includes(record.prepared?.asset?.kind) && record.state !== 'committed') throw agentError('invalid_review_media', '只能保存已准备好的审片媒体');
        if (reviewRevisions && reviewRevisions[record.id] !== (record.reviewFeedback?.revision || 0)) throw agentError('review_conflict', '审阅反馈已变化,请重新读取');
      }
      return saveMaterial({ title, text: '', kind: 'collected', transferIds: [...ids, ...records.flatMap(record => (record.reviewFeedback?.frames || []).map(frame => frame.transferId))],
        timeNotes: records.flatMap(record => (record.reviewFeedback?.notes || []).map(({ createdAt, ...note }) => note)),
        reviewRevisions: Object.fromEntries(records.map(record => [record.id, record.reviewFeedback?.revision || 0])), ...(project ? { project } : {}) }, requestId);
    }
    case "CASE_OPERATION": {
      if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL(""))) {
        throw new Error("案例操作只能从插件工作空间调用");
      }
      if (ANALYSIS_BATCH_SPECS.some(spec=>spec.name===message.operation)) return externalAnalysisBatches.execute(message.operation,message.input);
      if (message.operation === "read_projects") return projectOperations.read(message.input);
      if (["create_project", "update_project"].includes(message.operation)) return projectOperations.execute(message.operation, message.input);
      if (message.operation === "save_material") {
        validateProjectOperation(message.operation, message.input);
        const { requestId, ...input } = message.input;
        return saveMaterial(input, requestId);
      }
      if (message.operation === "read_case_details") return caseOperations.read(message.input);
      if (message.operation === "trash_case") return caseTrashOperations.execute(message.input);
      if (!["edit_case", "organize_case"].includes(message.operation)) throw new Error("未知案例操作");
      return caseOperations.execute(message.operation, message.input);
    }
    case "PREPARE_AGENT_CONNECTION":
    case "GET_AGENT_CONNECTION":
    case "SET_AGENT_CONNECTION": {
      if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL(""))) {
        throw new Error("Agent 连接只能在插件设置中管理");
      }
      return { ok: true, connection: message.type === "SET_AGENT_CONNECTION"
        ? await agentConnection.setEnabled(message.enabled === true)
        : message.type === "PREPARE_AGENT_CONNECTION" ? await agentConnection.prepare() : await agentConnection.snapshot() };
    }
    case "GET_STATE": {
      return enqueue(async () => ({ ok: true, ...publicLibraryState(await readState()) }));
    }
    case "PREPARE_LIBRARY_VIEW_STATE": {
      return enqueue(async () => {
        const state = message.summaryOnly ? {} : await readState();
        await libraryStorage.update([...LIBRARY_VIEW_SUMMARY_SOURCES], stored => ({
          [LIBRARY_VIEW_SUMMARY_KEY]: completeLibraryViewSummary(stored)
        }));
        if (message.creativeSummary) await libraryStorage.update('composerSessions', stored => ({
          composerSessionSummaries: composerSessionSummaries(normalizeComposerSessions(stored.composerSessions))
        }));
        return { ok: true, restoredArchivedFacetCount: state.restoredArchivedFacetCount };
      });
    }
    case "GET_LIBRARY_VIEW_STATUS": {
      const stored = await libraryStorage.get(STORAGE_KEYS.syncSettings);
      return { ok: true, syncStatus: await publicSyncStatus(stored[STORAGE_KEYS.syncSettings]) };
    }
    case "GET_CASE_LIBRARY_STATE": {
      if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL(""))) {
        throw new Error("案例读取只能从插件工作空间调用");
      }
      return enqueue(async () => ({ ok: true, ...await readCaseLibraryState() }));
    }
    case "GET_FOLDER_BACKUP_STATE":
      return enqueue(async () => ({ ok: true, ...folderBackupState(await readState()) }));
    case "GET_CAPTURE_WORKSPACE":
      return captureWorkspace();
    case "GET_LIBRARY_ASSET_RETENTION":
      return enqueue(async () => {
        const ids = Array.isArray(message.assetIds) ? message.assetIds : [];
        const stored = await libraryStorage.get(STORAGE_KEYS.libraryImportTransactions);
        const transactions = normalizeLibraryImportTransactionsState(stored[STORAGE_KEYS.libraryImportTransactions]);
        if (transactions.items.some(item => item.status === "pending")) {
          return { ok: true, assetIds: ids };
        }
        const retained = referencedMediaAssetIds(await readState());
        for (const id of await agentTransfers.retainedIds()) retained.add(id);
        return { ok: true, assetIds: ids.filter(id => retained.has(id)) };
      });
    case "GET_DATA_SAFETY_STATUS":
      return enqueue(async () => dataSafetyStatus(await readState()));
    case "PREVIEW_LIBRARY_UNDO":
      return enqueue(() => previewLibraryUndo(message));
    case "RESTORE_LIBRARY_REPLACEMENT_POINT":
      return enqueue(async () => restoreLibraryReplacementPoint(await readState(), message));
    case "GET_SYNC_RUN_STATUS":
      return Promise.resolve({ ok: true, syncStatus: manualSyncController.status() });
    case "CANCEL_SYNC": {
      const cancelRequested = manualSyncController.cancel();
      return Promise.resolve({
        ok: true,
        cancelRequested,
        message: cancelRequested ? "正在停止本次同步" : "当前没有正在运行的同步"
      });
    }
    case "GET_EXTENSION_UPDATE_STATUS":
      return extensionUpdateLifecycle.getStatus()
        .then((status) => ({ ok: true, status }));
    case "CHECK_EXTENSION_UPDATE":
      return extensionUpdateLifecycle.check()
        .then((status) => ({
          ok: status.checkStatus !== "error",
          status,
          message: status.lastError
        }));
    case "APPLY_EXTENSION_UPDATE":
      return extensionUpdateLifecycle.apply();
    case "CONNECT_SYNC_FOLDER":
      return enqueue(async () => connectSyncFolder(message.password, message.directoryId));
    case "UNLOCK_SYNC_VAULT":
      return enqueue(async () => unlockSyncVault(message.password));
    case "SYNC_NOW":
      return enqueue(async () => performManualSynchronization((input) => manualSyncController.start(input)));
    case "DISCONNECT_SYNC_FOLDER":
      return enqueue(async () => disconnectSyncFolder());
    case "UPDATE_CAPTURE_DRAFT":
      return enqueueCapture(async () => captureRuntime.dispatch("persist-draft", { draft: message.draft }));
    case "UPDATE_CAPTURE_DRAFT_METADATA":
      return enqueueCapture(async () => captureRuntime.dispatch("persist-draft-metadata", { patch: message.patch }));
    case "ADD_ACTIVE_SELECTION_TO_DRAFT":
      return enqueueCapture(async () => captureRuntime.dispatch("add-active-selection", { tabId: message.tabId }));
    case "TRY_ACTIVE_SELECTION_TO_DRAFT":
      return enqueueCapture(async () => captureRuntime.dispatch("try-active-selection"));
    case "ADD_CLIPBOARD_TEXT_TO_DRAFT":
      return enqueueCapture(async () => captureRuntime.dispatch("add-clipboard-text", { text: message.text }));
    case "CAPTURE_ACTIVE_TAB_TO_DRAFT":
      return enqueueCapture(async () => captureRuntime.dispatch("capture-active-tab", { tabId: message.tabId }));
    case "CAPTURE_VISIBLE_VISUALS_TO_DRAFT":
      return enqueueCapture(async () => captureRuntime.dispatch("capture-visible-visuals", { tabId: message.tabId }));
    case "START_SMART_VISUAL_SELECTION":
      return enqueueCapture(async () => captureRuntime.dispatch("start-visible-visual-selection", { tabId: message.tabId }));
    case "CONFIRM_SMART_VISUAL_SELECTION":
      return enqueueCapture(async () => captureRuntime.dispatch("confirm-visible-visual-selection", { sessionId: message.sessionId }));
    case "CANCEL_SMART_VISUAL_SELECTION":
      return enqueueCapture(async () => captureRuntime.dispatch("cancel-visible-visual-selection", { sessionId: message.sessionId }));
    case "CANCEL_REGION_CAPTURE":
      return captureRuntime.dispatch("cancel-region-capture", { sessionId: message.sessionId });
    case "GET_DISCOVERED_VIDEOS":
      return { ok: true, resources: await discoveredVideosForTab(Number(message.tabId)) };
    case "PICK_PAGE_CONTENT": {
      const tab = await chrome.tabs.get(Number(message.tabId));
      await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: clearPageCapturePageState, args: [{ removeRegionMarkers: false, removePreview: true, removeEditor: true }] });
      const [picked] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: pickPageContent, args: [{ commentLimit: 30, timeoutMs: PAGE_CAPTURE_LIMITS.navigationTimeoutMs,
        cancelLabel: translateForLocale("取消选取", resolveLocale((await libraryStorage.get("uiPreferences")).uiPreferences, chrome.i18n.getUILanguage())) }] });
      if (!picked?.result?.html) return { ok: false, cancelled: true };
      const [captured] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: collectPageCaptureSnapshot,
        args: [{ serializeErrors: true, sessionId: crypto.randomUUID(), manualContentHtml: picked.result.html,
          selectedContentMarker: picked.result.selectedContentMarker,
          selectionTemplate: picked.result.selectionTemplate, maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate }] });
      const snapshot = await addVisiblePageCaptureFallbacks(readPageCaptureInjectionResult(captured), tab, { selectedOnly: true });
      return { ok: true, supplement: picked.result.supplement, batch: { ...snapshot, tabId: tab.id } };
    }
    case "READ_PAGE_CAPTURE_DETAILS":
      return enqueueCapture(() => readGenericPageCaptureDetails(message));
    case "START_PAGE_CAPTURE":
      return enqueueCapture(async () => startPageCapture(message.mode, message.targetCount, message.requestId, message.selectionTemplate));
    case "READ_PAGE_CAPTURE_SUPPLEMENT":
      return { ok: true, supplement: await readPageCaptureSupplement(message.supplement, chrome, { sourceTabId: message.sourceTabId, sourceUrl: message.sourceUrl }) };
    case "CANCEL_PAGE_CAPTURE":
      return cancelPageCapture(message.sessionId);
    case "PREVIEW_PAGE_CAPTURE_REGION":
      return previewPageCaptureRegion(message.tabId, message.preview);
    case "CLEAR_PAGE_CAPTURE_MARKERS":
      return clearPageCaptureMarkers(message.tabId, message.removeRegionMarkers !== false);
    case 'START_CAPTURE_SAVE':
      if (!['COMMIT_PAGE_CAPTURE', 'COMMIT_CAPTURE_DRAFT'].includes(message.input?.type)) throw new Error('不支持的保存任务');
      return captureSaveTasks.start(message.input);
    case 'GET_CAPTURE_SAVE_TASK': return { ok: true, task: await captureSaveTasks.get() };
    case 'CANCEL_CAPTURE_SAVE': return captureSaveTasks.cancel(message.id);
    case 'DISCARD_CAPTURE_SAVE':
      if (typeof message.id !== 'string' || !message.id) throw new Error('缺少保存任务');
      await captureSaveTasks.discard(message.id);
      return { ok: true };
    case 'ACK_CAPTURE_SAVE': await captureSaveTasks.acknowledge(message.id, message.remainingBatch); return { ok: true };
    case "COMMIT_PAGE_CAPTURE":
      return captureSaveTasks.run(message);
    case "PAGE_CAPTURE_VIEWPORT_FALLBACKS":
      return capturePageCaptureViewportFallbacks(message, interaction.sender);
    case "SMART_VISUAL_SELECTION_CHANGED":
    case "SMART_VISUAL_SELECTION_ENDED":
    case "REGION_CAPTURE_CHANGED":
      return { ok: true };
    case "CAPTURE_CREATIVE_OUTPUTS":
      return captureAndCommitCreativeOutputs(message);
    case "UPDATE_CAPTURE_FRAGMENT":
      return enqueueCapture(async () => captureRuntime.dispatch("update-fragment", {
        fragmentId: message.fragmentId,
        text: message.text
      }));
    case "REMOVE_CAPTURE_FRAGMENT":
      return enqueueCapture(async () => captureRuntime.dispatch("remove-fragment", { fragmentId: message.fragmentId }));
    case "CLEAR_SAVED_CAPTURE_FRAGMENTS":
      return enqueueCapture(async () => captureRuntime.dispatch("clear-saved-fragments", { fragmentIds: message.fragmentIds }));
    case "REORDER_CAPTURE_FRAGMENTS":
      return enqueueCapture(async () => captureRuntime.dispatch("reorder-fragments", { ids: message.ids }));
    case "REMOVE_CAPTURE_VISUAL":
      return enqueueCapture(async () => captureRuntime.dispatch("remove-visual", { visualId: message.visualId }));
    case "REORDER_CAPTURE_VISUALS":
      return enqueueCapture(async () => captureRuntime.dispatch("reorder-visuals", { ids: message.ids }));
    case "SET_CAPTURE_PRIMARY_VISUAL":
      return enqueueCapture(async () => captureRuntime.dispatch("set-primary-visual", { visualId: message.visualId }));
    case "CANCEL_CAPTURE_DRAFT":
      return enqueueCapture(async () => { await captureSaveTasks.discard(); return captureRuntime.dispatch("cancel"); });
    case "COMMIT_CAPTURE_DRAFT":
      return captureSaveTasks.run(message);
    case "START_CAPTURE_FOR_CASE":
      return enqueueCapture(async () => startCaptureForCase(message.caseId, message.partEntryId));
    case "CREATE_COMPOUND_CASE":
      return enqueue(async () => createCompoundCaseAction(message));
    case "UPDATE_COMPOUND_CASE":
      return enqueue(async () => updateCompoundCaseAction(message));
    case "SPLIT_COMPOUND_CASE":
      return enqueue(async () => splitCompoundCaseAction(message.compoundCaseId));
    case "SET_ENTRY_PRIMARY_VISUAL":
      return enqueue(async () => setEntryPrimaryVisual(message.entryId, message.visualId));
    case "DELETE_ENTRY_VISUAL":
      return enqueue(async () => deleteEntryVisual(message.entryId, message.visualId));
    case "ADD_UPLOADED_VISUAL":
      return enqueue(async () => addUploadedVisual(message.entryId, message.visual, message.generationPromptChoices));
    case "SET_ENTRY_COVER":
      return enqueue(async () => setEntryCover(message.entryId, message.assetId, message.asset));
    case "SET_ENTRY_PRIMARY_MEDIA":
      return enqueue(async () => setEntryPrimaryMedia(message.entryId, message.assetId));
    case "DELETE_ENTRY_MEDIA":
      return enqueue(async () => deleteEntryMedia(message.entryId, message.assetId));
    case "ADD_UPLOADED_MEDIA":
      return enqueue(async () => addUploadedMedia(message.entryId, message.asset, message.posterAsset, message.generationPromptChoices));
    case "DISCARD_UNREFERENCED_MEDIA":
      return enqueue(async () => { await deleteUnreferencedMedia(message.assetIds); return { ok: true }; });
    case "CREATE_MEDIA_CASE":
      return enqueue(async () => createMediaCase(message.asset, message.posterAsset, message.title, message.text, message.generationPromptChoices));
    case "CREATE_MEDIA_REFERENCE":
      return enqueue(async () => createMediaReferenceCase(message.asset, message.posterAsset, message.title, message));
    case "CREATE_QUICK_NOTE":
      return enqueue(async () => createQuickNote(message.title, message.text, message));
    case "ADD_TIME_NOTE":
      return enqueue(async () => addEntryTimeNote(message.entryId, message.note));
    case "ADD_VIDEO_KEYFRAME":
      return enqueue(async () => addVideoKeyframe(message.entryId, message.asset, message.note));
    case "DELETE_TIME_NOTE":
      return enqueue(async () => deleteEntryTimeNote(message.entryId, message.noteId));
    case "EXPORT_MARKDOWN":
    case "EXPORT_ARCHIVE":
      return enqueue(async () => exportArchive(await readState(), message.entryIds, message.directory === true));
    case "EXPORT_PROJECT":
      return enqueue(async () => exportProjectArchive(await readState(), message.collectionId, message.directory === true));
    case "EXPORT_CURATED_SUBMISSION":
      return enqueue(async () => exportCuratedSubmission(await readState(), message));
    case "EXPORT_CREATIVE_EXPERIMENTS":
      return enqueue(async () => exportCreativeExperiments(await readState()));
    case "PREVIEW_CREATIVE_EXPERIMENT_IMPORT":
      return enqueue(async () => previewCreativeExperimentImport(await readState(), message.experiments));
    case "APPLY_CREATIVE_EXPERIMENT_IMPORT":
      return enqueue(async () => applyCreativeExperimentImport(await readState(), message));
    case "PREVIEW_LIBRARY_IMPORT":
      return enqueue(async () => previewLibraryImport(await readState(), message.library, {
        preserveLibraryConfiguration: message.preserveLibraryConfiguration === true,
        sourceType: message.sourceType,
        mode: message.mode,
        conflictResolutions: message.conflictResolutions,
        importReport: message.importReport,
        resourceIndex: message.resourceIndex
      }));
    case "APPLY_LIBRARY_IMPORT":
      return enqueue(async () => applyLibraryImport(await readState(), message));
    case "PREVIEW_LIBRARY_IMPORT_BATCH":
      return enqueue(async () => previewLibraryImportBatch(await readState(), message));
    case "APPLY_LIBRARY_IMPORT_BATCH":
      return enqueue(async () => applyLibraryImportBatch(await readState(), message));
    case "PREVIEW_CURATED_IMPORT":
      return enqueue(async () => previewCuratedImport(await readState(), message));
    case "APPLY_CURATED_IMPORT":
      return enqueue(async () => applyCuratedImport(await readState(), message));
    case "UPDATE_SETTINGS":
      return enqueue(async () => {
        const state = await readState();
        const settings = normalizeSettings(message.settings);
        await commitLocalChanges({ [STORAGE_KEYS.settings]: settings });
        return {
          ok: true,
          message: "设置已保存,下次导出 ZIP 时生效",
          count: state.entries.length,
          settings
        };
      });
    case 'UPDATE_KEYBOARD_SHORTCUTS':
      return enqueue(async () => {
        const shortcuts = normalizeShortcutOverrides(message.shortcuts);
        if (shortcutConflict(shortcutBindings(shortcuts))) throw new Error('按键重复,请调整后保存');
        const stored = await libraryStorage.get(STORAGE_KEYS.uiPreferences);
        const uiPreferences = normalizeUiPreferences({ ...stored[STORAGE_KEYS.uiPreferences], shortcuts });
        await commitLocalChanges({ [STORAGE_KEYS.uiPreferences]: uiPreferences });
        return { ok: true };
      });
    case "UPDATE_UI_PREFERENCES":
      return enqueue(async () => {
        const stored = await libraryStorage.get(STORAGE_KEYS.uiPreferences);
        const uiPreferences = normalizeUiPreferences({ ...stored[STORAGE_KEYS.uiPreferences], ...message.preferences,
          customTagColors: { ...stored[STORAGE_KEYS.uiPreferences]?.customTagColors, ...message.preferences?.customTagColors },
          sidebarLayout: { ...stored[STORAGE_KEYS.uiPreferences]?.sidebarLayout, ...message.preferences?.sidebarLayout },
          layoutPresets: stored[STORAGE_KEYS.uiPreferences]?.layoutPresets,
          activeLayoutId: stored[STORAGE_KEYS.uiPreferences]?.activeLayoutId,
          floatingPanelPositions: stored[STORAGE_KEYS.uiPreferences]?.floatingPanelPositions ?? message.preferences?.floatingPanelPositions,
          shortcuts: stored[STORAGE_KEYS.uiPreferences]?.shortcuts ?? message.preferences?.shortcuts });
        await commitLocalChanges({ [STORAGE_KEYS.uiPreferences]: uiPreferences });
        return { ok: true, uiPreferences };
      });
    case 'GET_NATIVE_VIDEO_STATUS':
      return { ok: true, ...(await nativeVideoStatus()) };
    case 'START_VIDEO_COMPONENT_SETUP':
      return { ok: true, state: await videoComponentSetup.start({ restart: message.restart === true, viaAgent: message.viaAgent === true }) };
    case 'CONTINUE_VIDEO_COMPONENT_SETUP':
      return { ok: true, state: await videoComponentSetup.continue() };
    case 'GET_VIDEO_COMPONENT_SETUP': {
      return { ok: true, state: await videoComponentSetup.refresh() };
    }
    case 'UPDATE_LAYOUT_PREFERENCES':
      return enqueue(async () => {
        const stored = await libraryStorage.get(STORAGE_KEYS.uiPreferences);
        const previous = stored[STORAGE_KEYS.uiPreferences];
        const uiPreferences = message.action
          ? manageLayoutPreset(previous, { ...message, id: message.action === 'create' ? crypto.randomUUID() : message.id })
          : updateLayoutPreferences(previous, message.preferences, message.reset === true);
        await commitLocalChanges({ [STORAGE_KEYS.uiPreferences]: uiPreferences });
        return { ok: true, uiPreferences };
      });
    case 'UPDATE_FLOATING_PANEL_POSITION':
      return enqueue(async () => {
        const stored = await libraryStorage.get(STORAGE_KEYS.uiPreferences);
        const uiPreferences = normalizeUiPreferences(stored[STORAGE_KEYS.uiPreferences]);
        if (message.position === null && /^[a-z][a-zA-Z0-9]*$/.test(message.key)) delete uiPreferences.floatingPanelPositions[message.key];
        else {
          const next = normalizeUiPreferences({ floatingPanelPositions: { [message.key]: message.position } }).floatingPanelPositions;
          if (!Object.hasOwn(next, message.key)) throw new Error('浮层位置无效');
          uiPreferences.floatingPanelPositions[message.key] = next[message.key];
        }
        await commitLocalChanges({ [STORAGE_KEYS.uiPreferences]: uiPreferences });
        return { ok: true, uiPreferences };
      });
    case "UPDATE_AI_PROVIDER_CONFIGURATION":
      return enqueue(async () => updateAiProviderConfiguration(message));
    case "VERIFY_AI_IMAGE_GENERATION_CREDENTIAL":
      return enqueue(async () => verifyAiImageGenerationCredential(message));
    case "DISCOVER_AI_PROVIDER_MODELS":
      return discoverAiProviderModels(message.providerId, message.force === true);
    case "PREVIEW_AI_PROVIDER_MODELS":
      return previewAiProviderModels(message);
    case "GET_AI_TASK_RUNTIME":
      return enqueue(async () => getAiTaskRuntime(message.taskId, message.allowUnconfigured === true, message.assignment));
    case "GET_COMPOSER_AI_RUNTIME":
      return enqueue(async () => getComposerAiRuntime());
    case "GET_COMPOSER_SESSION":
      return enqueue(async () => getComposerSession(message.sessionId));
    case "GET_ASSISTANT_CHATS":
      return enqueue(async () => getAssistantChats(message.activeId, message.includeDiagnostics === true));
    case "UPSERT_ASSISTANT_CHAT":
      return enqueue(async () => {
        if (message.draftOnly) return saveAssistantDraft(message.chat);
        const previous = (await getComposerSession(message.chat.id)).session;
        const result = await upsertComposerSession(assistantChatSession(message.chat, previous), {activate:message.activate});
        if (!result.ok) return result;
        const {id,chatRevision,updatedAt,title} = result.session;
        return {ok:true,session:{id,chatRevision,updatedAt,title}};
      });
    case "START_CREATIVE_JOB":
      return enqueue(async () => startCreativeJobAction(message.request, message.jobId));
    case "GET_CREATIVE_JOB":
      return enqueue(async () => getCreativeJobAction(message.jobId));
    case "CANCEL_CREATIVE_JOB":
      return cancelCreativeJobAction(message.jobId);
    case "RETRY_CREATIVE_JOB":
      return enqueue(async () => retryCreativeJobAction(message.jobId));
    case "UPDATE_CREATIVE_JOB_PROGRESS":
      return enqueue(async () => updateCreativeJobProgress(message));
    case "GET_CREATIVE_JOB_EXECUTION_STATE":
      return creativeJobExecutionState();
    case "COMPLETE_CREATIVE_JOB":
      return enqueue(async () => completeCreativeJobAction(message));
    case "FAIL_CREATIVE_JOB":
      return enqueue(async () => failCreativeJobAction(message));
    case "START_IMPORT_JOB":
      return enqueue(async () => startImportJobAction(message));
    case "GET_IMPORT_JOB":
      return enqueue(async () => getImportJobAction(message.jobId));
    case "CANCEL_IMPORT_JOB":
      return enqueue(async () => cancelImportJobAction(message.jobId));
    case "RETRY_IMPORT_JOB":
      return enqueue(async () => retryImportJobAction(message.jobId));
    case "UNDO_IMPORT_JOB":
      return enqueue(async () => undoImportJobAction(message.jobId, message.confirmationToken));
    case "ADD_TEMP_REFERENCES":
      return enqueue(async () => addTempReferencesAction(message));
    case "REMOVE_TEMP_REFERENCE":
      return enqueue(async () => removeTempReferenceAction(message));
    case "SAVE_TEMP_REFERENCE_AS_CASE":
      return enqueue(async () => saveTempReferenceAsCaseAction(message));
    case "START_OR_JOIN_ANALYSIS_TASK":
      return startOrJoinAnalysisTaskAction(message);
    case "GET_ANALYSIS_TASK":
      return enqueue(async () => getAnalysisTaskAction(message.taskId));
    case "GET_ENTRY_VIDEO_ANALYSIS_TASK":
      return enqueue(async () => getEntryVideoAnalysisTaskAction(message.entryId, message.assetId));
    case "DETACH_ANALYSIS_CONSUMER":
      return enqueue(async () => detachAnalysisConsumerAction(message));
    case "STOP_ANALYSIS_TASK":
      return stopAnalysisTaskAction(message);
    case "RETRY_ANALYSIS_TASK":
      return retryAnalysisTaskAction(message);
    case "UPDATE_VIDEO_ANALYSIS_PROGRESS":
      return persistAnalysisTaskProgress(message.taskId, message.attemptId, message.phase, message);
    case "COMPLETE_VIDEO_ANALYSIS":
      return completeVideoAnalysisAction(message);
    case "FAIL_VIDEO_ANALYSIS":
      return failVideoAnalysisAction(message);
    case "SAVE_COMPOSER_TOOL_DRAFT":
      return enqueue(async () => saveComposerToolDraftAction(message));
    case "COMPOSER_LIBRARY_HOST":
      if (interaction.sender?.id !== chrome.runtime.id || !interaction.sender?.url?.startsWith(chrome.runtime.getURL(""))) {
        throw new Error("创作台资料工具只能从插件工作空间调用");
      }
      // A worker cannot deliver runtime messages to itself. Reuse the same
      // dispatcher and sender validation without nesting the host in enqueue.
      return handleComposerLibraryHost(message, libraryStorage, {
        sendMessage: nested => handleMessage(nested, interaction)
      });
    case "CREATE_CREATIVE_SKILL":
      return enqueue(async () => createCreativeSkillAction(message));
    case "SAVE_CREATIVE_SKILL_VERSION":
      return enqueue(async () => saveCreativeSkillVersionAction(message));
    case "RESTORE_CREATIVE_SKILL_VERSION":
      return enqueue(async () => restoreCreativeSkillVersionAction(message));
    case "DELETE_CREATIVE_SKILL":
      return enqueue(async () => deleteCreativeSkillAction(message.skillId));
    case "UPDATE_COMPOSER_SETTINGS":
      return enqueue(async () => updateComposerSettings(message));
    case "UPSERT_COMPOSER_SESSION":
      return enqueue(async () => upsertComposerSession(message.session));
    case "DELETE_COMPOSER_SESSION":
      return enqueue(async () => deleteComposerSession(message.sessionId));
    case "SAVE_COMPOSER_RESULT":
      return enqueue(async () => saveComposerResult(message));
    case "ACTIVATE_CREATIVE_RESULT":
      return enqueue(async () => activateCreativeResult(message, interaction.sidePanelOpening));
    case "CLEAR_ACTIVE_CREATIVE_RESULT":
      return enqueue(async () => {
        await commitLocalChanges({ [STORAGE_KEYS.activeCreativeResult]: null });
        return { ok: true };
      });
    case "COMMIT_CREATIVE_OUTPUTS":
      return commitExistingCreativeOutputs();
    case "REGISTER_GENERATED_OUTPUTS":
      return enqueue(async () => registerGeneratedOutputs(message));
    case "UPDATE_CREATIVE_EXPERIMENT_SETTINGS":
      return enqueue(async () => updateCreativeExperimentSettings(message.settings));
    case "SAVE_CREATIVE_OUTPUT_TO_LIBRARY":
      return enqueue(async () => saveCreativeOutputToLibrary(message));
    case "RECORD_CREATIVE_SIGNAL":
      return enqueue(async () => updateCreativeSignal(message));
    case "UPDATE_CREATIVE_JUDGMENT":
      return enqueue(async () => updateCreativeJudgmentAction(message));
    case "DELETE_CREATIVE_OUTPUT":
      return enqueue(async () => deleteCreativeOutput(message));
    case "ANALYZE_CREATIVE_OUTPUT":
      return analyzeCreativeOutput(message.runId, message.visualId);
    case "ANALYZE_ENTRY_IMAGE":
      try {
        return await analyzeEntryImage(
          message.entryId,
          message.visualId,
          message.outputLocale,
          message.batchJobId,
          message.bypassCache === true,
          message.assignment,
          "interactive"
        );
      } catch (error) {
        return {
          ok: false,
          message: userMessage(error),
          status: Number(error?.status) || 0,
          usage: error?.usage,
          attempts: error?.attempts
        };
      }
    case "ANALYZE_ENTRY_VISUAL_SET":
      return analyzeEntryVisualSet(message);
    case "UPDATE_VIDEO_RECONSTRUCTION_PROMPT":
      return enqueue(async () => updateVideoReconstructionPrompt(message));
    case "UPDATE_VISION_RECONSTRUCTION_PROMPT":
      return enqueue(async () => updateVisionReconstructionPrompt(message.entryId, message.visualId, message.reconstructionPrompt));
    case "UPDATE_ENTRY_ARTICLE_TEXT":
      return enqueue(async () => updateCaseArticle(message));
    case "UPDATE_ENTRY_TEXT":
      return enqueue(async () => updateCaseText(message));
    case "UPDATE_ENTRY_MEDIA_PROMPT":
      return enqueue(async () => updateEntryMediaPromptAction(message));
    case "APPLY_ENTRY_MEDIA_PROMPT_SUGGESTIONS":
      return enqueue(async () => applyEntryMediaPromptSuggestions(message));
    case "UPDATE_ENTRY_TITLE":
      return enqueue(async () => updateCaseTitle(message));
    case "UPDATE_ENTRY_CUSTOM_LABELS":
      return enqueue(async () => updateEntryCustomLabels(message));
    case "UPDATE_LOCAL_ASSET_REFERENCE":
      return enqueue(async () => updateLocalAssetReferenceAction(message));
    case "BATCH_ADD_CUSTOM_LABELS":
      return enqueue(async () => batchAddCustomLabels(message));
    case "BATCH_REMOVE_CASE_TAGS":
      return enqueue(async () => batchRemoveCaseTags(message));
    case "BATCH_SET_CLASSIFICATION":
      return enqueue(async () => batchSetClassification(message));
    case "BATCH_SET_PROJECT":
      return enqueue(async () => batchSetProject(message));
    case "CREATE_COLLECTION_FROM_SELECTION":
      return enqueue(async () => createCollectionFromSelection(message));
    case "UNDO_VISION_ANALYSIS":
      return enqueue(async () => undoEntryVisionAnalysis(message.entryId));
    case "UNDO_LAST":
      return enqueue(async () => undoLastSave());
    case "DELETE_ENTRY":
      return enqueue(async () => deleteEntry(message.entryId));
    case "PREVIEW_CASE_DEDUPE":
      return caseDedupeOperations.preview(message.groups);
    case "APPLY_CASE_DEDUPE":
      return caseDedupeOperations.execute(message.input);
    case "VERIFY_DEDUPE_MEDIA":
      return verifyDedupeMedia(message);
    case "BATCH_MOVE_TO_TRASH":
      return enqueue(async () => moveEntryBatchToTrash(message.entryIds));
    case "DELETE_COLLECTION_WITH_ENTRIES":
      return enqueue(async () => deleteCollectionWithEntries(message));
    case "GET_TRASH_CLEANUP_STATUS":
      return { ok: true, progress: trashCleanupProgress };
    case "GET_TRASH_ITEMS":
      return enqueue(async () => getTrashItems(message));
    case "RESTORE_TRASH_ITEMS":
      return enqueue(async () => restoreSelectedTrashItems(message));
    case "PERMANENT_DELETE_TRASH_ITEMS":
      return enqueue(() => withTrashCleanupProgress(() => permanentlyDeleteTrashItems(message)));
    case "EMPTY_TRASH":
      return enqueue(() => withTrashCleanupProgress(emptyTrashAction));
    case "CONFIRM_CLASSIFICATION":
      return enqueue(async () => updateClassification(message));
    case "RENAME_CONTENT_TYPE":
      return enqueue(async () => updateContentTypeName(message));
    case "CREATE_CONTENT_TYPE":
      return enqueue(async () => createLibraryContentType(message));
    case "UPDATE_CONTENT_TYPE":
      return enqueue(async () => updateLibraryContentType(message));
    case "SET_CONTENT_TYPE_VISIBILITY":
      return enqueue(async () => updateLibraryContentTypeVisibility(message));
    case "DELETE_CONTENT_TYPE":
      return enqueue(async () => deleteLibraryContentType(message));
    case "CREATE_FACET_NODE":
      return enqueue(async () => createFacetTag(message));
    case "APPLY_DETAIL_TAG_ORGANIZATION":
      return enqueue(async () => applyDetailTagOrganization(message));
    case "SET_ENTRY_FACET":
      return enqueue(async () => updateEntryFacet(message));
    case "CREATE_COLLECTION":
    case "RENAME_COLLECTION":
    case "DELETE_COLLECTION":
    case "REORDER_COLLECTIONS":
    case "MOVE_COLLECTION":
    case "REPLACE_COLLECTION_ENTRIES":
    case "SET_COLLECTION_VISIBILITY":
      return enqueue(async () => updateOrganizer(message));
    case "ACCEPT_ANALYSIS_CANDIDATE":
      return enqueue(async () => decideAnalysisCandidate(message, true));
    case "REJECT_ANALYSIS_CANDIDATE":
      return enqueue(async () => decideAnalysisCandidate(message, false));
    case "APPLY_ENTRY_ANALYSIS_RESULT":
      return enqueue(async () => applyEntryAnalysisResult(message));
    case "PREVIEW_ANALYSIS_BATCH":
      return enqueue(async () => previewDeepSeekBatch(message.outputLocale, message.mode, message.entryIds, message.scope, message.includeChanged));
    case "CREATE_ANALYSIS_BATCH":
      return enqueue(async () => createDeepSeekBatch(message.outputLocale, message.mode, message.entryIds, message.expectedEntryIds, message.scope, message.includeChanged, message.expectedItems));
    case "GET_ANALYSIS_BATCH_STATUS":
      return getDeepSeekBatchStatus(message.jobId);
    case "PAUSE_ANALYSIS_BATCH":
      return enqueue(async () => updateDeepSeekBatch("pause", message.jobId));
    case "RESUME_ANALYSIS_BATCH":
      return enqueue(async () => updateDeepSeekBatch("resume", message.jobId));
    case "CANCEL_ANALYSIS_BATCH":
      return enqueue(async () => updateDeepSeekBatch("cancel", message.jobId));
    case "RETRY_ANALYSIS_FAILURES":
      return enqueue(async () => updateDeepSeekBatch("retry", message.jobId));
    case "APPLY_STAGED_ANALYSIS_REBUILD":
      return enqueue(async () => applyStagedAnalysisRebuild(message.jobId));
    case "UNDO_ANALYSIS_BATCH":
      return enqueue(async () => undoDeepSeekBatch(message.jobId, message.confirmationToken));
    case "PREVIEW_VISION_BATCH":
      return enqueue(async () => previewVisionBatchTask(message));
    case "CREATE_VISION_BATCH":
      return enqueue(async () => createVisionBatchTask(message));
    case "PREVIEW_VIDEO_BATCH":
      return enqueue(async () => previewVideoBatchTask(message));
    case "CREATE_VIDEO_BATCH":
      return enqueue(async () => createVideoBatchTask(message));
    case "PAUSE_VISION_BATCH":
      return enqueue(async () => updateVisionBatch("pause", message.jobId));
    case "RESUME_VISION_BATCH":
      return enqueue(async () => updateVisionBatch("resume", message.jobId));
    case "CANCEL_VISION_BATCH":
      return enqueue(async () => updateVisionBatch("cancel", message.jobId));
    case "RETRY_VISION_BATCH_FAILURES":
      return enqueue(async () => updateVisionBatch("retry", message.jobId, {
        itemKeys: message.itemKeys,
        confirmDuplicateCharge: message.confirmDuplicateCharge
      }));
    case "IMPORT_ANALYSIS_CANDIDATES":
      return enqueue(async () => importAnalysisCandidates(message.payload));
    case "PREVIEW_FACET_CHANGE":
      return enqueue(async () => previewFacetUpdate(message.change));
    case "APPLY_FACET_CHANGE":
      return enqueue(async () => applyFacetUpdate(message.preview));
    case "RESTORE_ARCHIVED_FACETS":
      return enqueue(async () => restoreFacetDimensions(message.facetIds));
    case "RESTORE_ARCHIVED_NODES":
      return enqueue(async () => restoreFacetTags(message.nodeIds));
    case "PREVIEW_REANALYZE":
    case "PREVIEW_LIBRARY_MAINTENANCE":
      return enqueue(async () => previewLibraryMaintenance());
    case "APPLY_REANALYZE":
    case "START_LIBRARY_MAINTENANCE":
      return enqueue(async () => startLibraryMaintenance());
    case "GET_LIBRARY_MAINTENANCE_STATUS":
      return libraryMaintenanceStatus();
    case "PAUSE_LIBRARY_MAINTENANCE":
      return enqueue(async () => updateLibraryMaintenance("pause"));
    case "RESUME_LIBRARY_MAINTENANCE":
      return enqueue(async () => updateLibraryMaintenance("resume"));
    case "CANCEL_LIBRARY_MAINTENANCE":
      return enqueue(async () => updateLibraryMaintenance("cancel"));
    case "RETRY_LIBRARY_MAINTENANCE":
      return enqueue(async () => updateLibraryMaintenance("retry"));
    case "UNDO_FACET_UPDATE":
      return enqueue(async () => undoFacetUpdate(message.confirmationToken));
    default:
      return { ok: false, message: "未知操作" };
  }
}

async function captureWorkspace() {
  const draft = await captureRuntime.getDraft();
  const stored = await libraryStorage.get([
    STORAGE_KEYS.entries,
    STORAGE_KEYS.compoundCases,
    STORAGE_KEYS.taxonomy,
    STORAGE_KEYS.classificationRules,
    STORAGE_KEYS.organizerState,
    STORAGE_KEYS.activeCreativeResult
  ]);
  const activeCreativeResult = normalizeActiveCreativeResult(stored[STORAGE_KEYS.activeCreativeResult]);
  const activeSession = activeCreativeResult ? (await getComposerSession(activeCreativeResult.sessionId)).session : null;
  const state = {
    entries: Array.isArray(stored[STORAGE_KEYS.entries]) ? stored[STORAGE_KEYS.entries] : [],
    taxonomy: normalizeTaxonomy(stored[STORAGE_KEYS.taxonomy]),
    classificationRules: Array.isArray(stored[STORAGE_KEYS.classificationRules]) ? stored[STORAGE_KEYS.classificationRules] : [],
    organizerState: normalizeOrganizerState(stored[STORAGE_KEYS.organizerState]),
    activeCreativeResult,
    composerSessions: activeSession ? [activeSession] : []
  };
  const compound = normalizeCompoundCases(stored[STORAGE_KEYS.compoundCases], state.entries)
    .find((item) => item.id === draft.targetCaseId);
  const targetEntry = draft.targetCaseId
    ? state.entries.find((entry) => entry.id === draft.targetCaseId) ?? (compound ? {
      id: compound.id,
      title: compound.title,
      classification: draft.contentTypeId ? { pathIds: [draft.contentTypeId] } : undefined
    } : null)
    : null;
  const suggested = targetEntry?.classification ?? captureDraftClassification(draft, state);
  const partContentTypes = Object.fromEntries(draftParts(draft).map((part) => {
    const classification = classifyCapturedContent({
      text: part.text, title: part.sourceTitle, url: part.sourceUrl, visuals: part.visuals, mediaPrompts: embeddedMediaPrompts(part.visuals), sourceFacts: sourceFactsForCaptureContext(part.sourceContext)
    }, state.classificationRules, state.taxonomy);
    const id = classification?.pathIds?.[0] || "";
    const contentType = state.taxonomy.nodes.find((item) => item.id === id);
    const name = contentType?.name || "待确认";
    return [part.sourceUrl || "source:unknown", { id, name, customized: contentType?.customized === true }];
  }));
  return {
    ok: true,
    draft,
    targetEntry,
    suggestedContentTypeId: suggested?.pathIds?.[0] || "",
    classificationContext: { taxonomy: state.taxonomy, rules: state.classificationRules },
    contentTypes: state.taxonomy.nodes.map((item) => ({ id: item.id, name: item.name, customized: item.customized === true })),
    collections: state.organizerState.collections.map((item) => ({
      id: item.id,
      name: item.name,
      parentId: item.parentId,
      order: item.order
    })),
    saveTask: await captureSaveTasks.get(),
    partContentTypes,
    activeCreativeResult: state.activeCreativeResult,
    activeCreativePrompt: activeCreativePromptSummary(state.activeCreativeResult, state.composerSessions),
    count: state.entries.length
  };
}

async function startPageCapture(mode = "loaded", targetCountValue = 0, requestId = "", selectionTemplate = null) {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab?.id || !/^https?:/iu.test(tab.url || "")) {
    return { ok: false, message: RESTRICTED_PAGE_MESSAGE };
  }
  await clearPageCaptureMarkers(tab.id, true).catch(() => undefined);
  const sessionId = crypto.randomUUID();
  const listMode = mode === "list";
  const targetCount = listMode
    ? Number(targetCountValue)
    : 0;
  if (listMode && (!Number.isSafeInteger(targetCount) || targetCount < 1)) {
    return { ok: false, message: "请输入正整数目标案例数" };
  }
  activePageCapture = { sessionId, tabId: tab.id, cancelled: false, maxCandidates: listMode ? targetCount : PAGE_CAPTURE_LIMITS.maxCandidates };
  await chrome.runtime.sendMessage({ type: "PAGE_CAPTURE_CHANGED", sessionId, requestId, phase: mode === "whole" || listMode ? "scanning" : "starting" }).catch(() => undefined);
  const originalUrl = tab.url;
  let result = null;
  let stopReason = "";
  try {
    if (!listMode) {
      result = { result: await collectPageCaptureTab(tab, {
        sessionId, requestId,
        mode: mode === "whole" ? "whole" : "loaded",
        genericGroupingRequested: mode === "article" || mode === "media",
        maxCandidates: mode === "loaded" ? PAGE_CAPTURE_QUALITY_LIMITS.maxRegionCandidates : PAGE_CAPTURE_LIMITS.maxCandidates
      }) };
    } else {
      const candidates = new Map();
      let currentTab = tab;
      let adapter = "";
      const visitedUrls = new Set();
      for (let pageIndex = 0; pageIndex < targetCount && !activePageCapture?.cancelled; pageIndex += 1) {
        visitedUrls.add(currentTab.url);
        const snapshot = await collectPageCaptureTab(currentTab, { sessionId, requestId, mode: "whole", maxCandidates: targetCount, listMode: true, selectionTemplate });
        if (!adapter) adapter = snapshot.adapter;
        else if (snapshot.adapter !== adapter) {
          stopReason = "layout-changed";
          break;
        }
        const before = candidates.size;
        const pageCandidates = (snapshot.candidates || []).flatMap(candidate => {
          const groups = splitArticleCases(candidate);
          return groups.length ? groups : [candidate];
        });
        for (const candidate of pageCandidates) {
          const key = `${candidate.canonicalUrl || ""}\n${candidate.sourceFacts?.itemId || ""}\n${candidate.title || ""}`;
          if (!candidates.has(key)) candidates.set(key, candidate);
          if (candidates.size >= targetCount) break;
        }
        if (candidates.size >= targetCount) {
          stopReason = "target-reached";
          break;
        }
        // A manual template belongs to the selected live document. Keep its successful
        // candidates instead of navigating away and invalidating the selection.
        if (selectionTemplate) {
          stopReason = "manual-template-page";
          break;
        }
        const nextUrl = await findNextPageCaptureListUrl(currentTab.id, currentTab.url);
        if (activePageCapture?.cancelled) {
          stopReason = "cancelled";
          break;
        }
        if (!nextUrl || visitedUrls.has(nextUrl) || candidates.size === before) {
          stopReason = candidates.size === before ? "no-new-items" : "no-next-page";
          break;
        }
        try {
          await chrome.tabs.update(currentTab.id, { url: nextUrl });
          await waitForPageCaptureTab(currentTab.id, nextUrl);
          currentTab = await chrome.tabs.get(currentTab.id);
        } catch {
          stopReason = "pagination-failed";
          break;
        }
      }
      if (activePageCapture?.cancelled) stopReason = "cancelled";
      result = { result: {
        id: sessionId,
        sourceUrl: originalUrl,
        adapter,
        candidates: [...candidates.values()].slice(0, targetCount),
        capturedAt: new Date().toISOString()
      } };
    }
  } finally {
    if (listMode) {
      try {
        const current = await chrome.tabs.get(tab.id);
        if (current.url !== originalUrl) {
          await chrome.tabs.update(tab.id, { url: originalUrl });
          await waitForPageCaptureTab(tab.id, originalUrl);
        }
      } catch {
      }
    }
    if (activePageCapture?.sessionId === sessionId) activePageCapture = null;
  }
  if ((mode === "article" || mode === "media") && result?.result?.adapter === "generic") {
    const grouping = mode === "media" ? "media" : "sections";
    const groups = (result.result.candidates || []).flatMap(candidate => groupGenericCapture(candidate, grouping));
    result.result = { ...result.result, candidates: groups, captureMode: "list", saveMode: "multiple", genericGrouping: grouping };
  } else if (mode === "article") {
    const groups = (result?.result?.candidates || []).flatMap(splitArticleCases);
    if (!groups.length) return { ok: false, message: "未识别到可靠的多个案例边界,请保留整篇文章或手动选择内容" };
    result.result = {...result.result, candidates:groups, captureMode:"list", saveMode:"multiple", articleSplit:true};
  }
  const batch = normalizePageCaptureBatch({
    ...result?.result,
    ...(listMode ? {
      captureMode: "list",
      saveMode: "",
      targetCount,
      stopReason: stopReason || ((result?.result?.candidates?.length || 0) >= targetCount ? "target-reached" : "no-new-items"),
      candidates: (result?.result?.candidates || []).slice(0, targetCount)
    } : {}),
    tabId: tab.id,
    status: "preview"
  });
  if (!batch.candidates.length) {
    const jimengHome = /^https:\/\/jimeng\.jianying\.com\/ai-tool\/home(?:\/|$)/iu.test(tab.url);
    return {
      ok: false,
      message: jimengHome
        ? "即梦主页作品信息尚未完整取得,请刷新页面后再次扫描"
        : "当前网页没有识别到可保存的正文、作品或媒体"
    };
  }
  return {
    ok: true,
    message: batch.stopReason === "manual-template-page"
      ? `已按手选范围识别本页 ${batch.candidates.length} 项内容,请确认后保存;其他页面需重新选取`
      : `已识别 ${batch.candidates.length} 项网页内容,请确认后保存`,
    batch
  };
}

async function readGenericPageCaptureDetails(message) {
  const tab = await chrome.tabs.get(message.tabId);
  const sessionId = crypto.randomUUID(), requestId = message.requestId;
  const requests = Array.isArray(message.requests) ? message.requests : [];
  if (!requests.length) return { ok: true, details: [] };
  activePageCapture = { sessionId, tabId: tab.id, cancelled: false };
  await chrome.runtime.sendMessage({ type: "PAGE_CAPTURE_CHANGED", sessionId, requestId, phase: "details", detailDone: 0, detailTotal: requests.length }).catch(() => undefined);
  try {
    const [result] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: collectGenericCaptureDetails,
      args: [requests, { sessionId, requestId, concurrency: RESOURCE_POLICY.mediaDownloadConcurrency,
        timeoutMs: PAGE_CAPTURE_LIMITS.navigationTimeoutMs, maxBytes: operationBudget().maxTextBytes }] });
    return { ok: true, details: result?.result || requests.map(request => ({ url: request.url, error: "详情尚未读取" })) };
  } finally { if (activePageCapture?.sessionId === sessionId) activePageCapture = null; }
}

async function collectPageCaptureTab(tab, options) {
  let feishuDocument = null;
  if (/^https:\/\/(?:[^/]+\.)?feishu\.cn\//iu.test(tab.url) && !options.editedRegion) {
    const [documentResult] = await chrome.scripting.executeScript({
      target: { tabId: tab.id }, func: collectFeishuDocument,
      args: [{ sessionId: options.sessionId, timeoutMs: PAGE_CAPTURE_LIMITS.navigationTimeoutMs }]
    });
    feishuDocument = documentResult?.result || null;
  }
  let siteData = await readPageCaptureSiteData(tab, { maxCandidates: options.maxCandidates });
  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 && 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],
        buttonSelector: adapter.fields.downloadButtons, maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate,
        maxBytes: operationBudget().maxTextBytes, maxPayloadBytes: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters,
        timeoutMs: PAGE_CAPTURE_LIMITS.navigationTimeoutMs,
        extensions: ["md", "markdown", "txt", "pdf", "html", "htm", "rtf", "skill"] }]
    });
    downloads = downloadResult?.result || { items: [], failures: 1 };
  }
  if (activePageCapture?.sessionId === options.sessionId && activePageCapture.cancelled) return { candidates: [] };
  await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ["vendor/document-ingestion/Readability.js"]
  });
  const [injected] = await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: collectPageCaptureSnapshot,
    args: [{
      serializeErrors: true,
      sessionId: options.sessionId,
      adapters: PAGE_CAPTURE_ADAPTERS,
      platformAdapters: PAGE_CAPTURE_PLATFORM_ADAPTERS,
      mode: options.mode,
      maxCandidates: options.maxCandidates,
      maxRegionCandidates: PAGE_CAPTURE_QUALITY_LIMITS.maxRegionCandidates,
      feishuDocument,
      maxMedia: Math.max(PAGE_CAPTURE_LIMITS.maxMediaPerCandidate, feishuDocument?.mediaCount || 0),
      maxScrollSteps: PAGE_CAPTURE_LIMITS.maxScrollSteps,
      listMode: options.listMode === true,
      genericGroupingRequested: options.genericGroupingRequested === true,
      selectionTemplate: options.selectionTemplate,
      mediaTimeoutMs: PAGE_CAPTURE_LIMITS.navigationTimeoutMs,
      maxInlinePixelDataCharacters: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters,
      maxCanvasPixels: operationBudget().maxImagePixels,
      editedRegion: options.editedRegion || null,
      downloads,
      videoFrameRules: PAGE_CAPTURE_VIDEO_FRAME_RULES,
      siteData
    }]
  });
  let snapshot = readPageCaptureInjectionResult(injected);
  if (siteData?.pageKind === "feed") {
    siteData = await readPageCaptureSiteData(tab, { installObserver: false, maxCandidates: options.maxCandidates }) || siteData;
    snapshot = { ...snapshot, candidates: siteData.candidates, siteStatus: siteData.completeness };
  }
  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);
}

async function findNextPageCaptureListUrl(tabId, currentUrlValue) {
  try {
    const [result] = await chrome.scripting.executeScript({
      target: { tabId },
      func: () => {
        const direct = document.querySelector('a[rel~="next"]');
        const paginationLinks = [...document.querySelectorAll('nav[aria-label*="pagination" i] a[href],[role="navigation"] a[href],[class*="pagination"] a[href]')];
        const next = direct || paginationLinks.find((link) => /^(?:next|下一页|下页|后页|›|»|→)$/iu.test(String(link.textContent || link.getAttribute("aria-label") || link.title || "").trim()));
        return next?.href || "";
      }
    });
    const nextUrl = new URL(result?.result || "", currentUrlValue);
    const currentUrl = new URL(currentUrlValue);
    return nextUrl.origin === currentUrl.origin && nextUrl.href !== currentUrl.href ? nextUrl.href : "";
  } catch {
    return "";
  }
}

async function waitForPageCaptureTab(tabId, expectedUrl) {
  const current = await chrome.tabs.get(tabId);
  if (current.status === "complete" && current.url === expectedUrl) return;
  await new Promise((resolve, reject) => {
    const timeout = setTimeout(() => {
      chrome.tabs.onUpdated.removeListener(onUpdated);
      reject(new Error("列表翻页超时"));
    }, PAGE_CAPTURE_LIMITS.navigationTimeoutMs);
    const onUpdated = (updatedTabId, changeInfo, updatedTab) => {
      if (updatedTabId !== tabId || changeInfo.status !== "complete" || updatedTab.url !== expectedUrl) return;
      clearTimeout(timeout);
      chrome.tabs.onUpdated.removeListener(onUpdated);
      resolve();
    };
    chrome.tabs.onUpdated.addListener(onUpdated);
  });
}

async function readPageCaptureSiteData(tab, { installObserver = true, maxCandidates = PAGE_CAPTURE_LIMITS.maxCandidates } = {}) {
  if (!tab?.id || !/^https?:/iu.test(tab.url || "")) return null;
  try {
    if (/^(?:www\.)?(?:youtube\.com|bilibili\.com|douyin\.com)$/u.test(new URL(tab.url).hostname)) {
      const douyin = new URL(tab.url).hostname.endsWith('douyin.com');
      let [video] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, world: "MAIN", func: douyin ? collectDouyinVideoPayload : collectVideoPagePayload });
      // Active capture only: browser load completion can precede the player's
      // React commit. Stop if navigation changes instead of binding stale data.
      const deadline = Date.now() + PAGE_CAPTURE_LIMITS.navigationTimeoutMs;
      while (douyin && video?.result && !video.result.resolved && Date.now() < deadline) {
        if (activePageCapture?.cancelled) break;
        await new Promise(resolve => setTimeout(resolve, 200));
        if ((await chrome.tabs.get(tab.id)).url !== tab.url) throw new Error('采集期间网页已切换,请重新读取当前作品');
        [video] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, world: 'MAIN', func: collectDouyinVideoPayload });
      }
      const payload = normalizeVideoPagePayload(video?.result, tab.url);
      if (payload) return payload;
    }
    if (installObserver) {
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        world: "MAIN",
        func: installPageCaptureSiteObserver,
        args: [{
          maxCandidates,
          maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate
        }]
      });
    }
    const [sitePayloadResult] = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      world: "MAIN",
      func: /(^|\.)liblib\.tv$/u.test(new URL(tab.url).hostname) ? collectLibTvPublicPayload : collectPageCaptureSitePayload,
      args: [{
        maxCandidates,
        maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate,
        maxTextCharacters: LIBRARY_TRANSFER_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: LIBRARY_TRANSFER_LIMITS.maxLibraryJsonBytes }), tab.url);
    }
    return sitePayloadResult?.result?.adapter === "libtv" ? normalizeLibTvPublicPayload(sitePayloadResult.result) : normalizePageCaptureSitePayload(sitePayloadResult?.result, tab.url);
  } catch (error) {
    console.warn("Page capture site extraction failed:", error?.message || String(error));
    return null;
  }
}

async function resolveCaptureSourceContext(tab) {
  const siteData = await readPageCaptureSiteData(tab);
  const candidates = Array.isArray(siteData?.candidates)
    ? siteData.candidates
    : siteData?.sourceFacts ? [siteData] : [];
  if (!candidates.length) return null;
  let workId = "";
  try {
    const lastPart = new URL(tab.url).pathname.split("/").filter(Boolean).at(-1) || "";
    if (/^\d{8,32}$/u.test(lastPart)) workId = lastPart;
  } catch {
  }
  const candidate = candidates.find((item) => item.sourceFacts?.itemId === workId) || (candidates.length === 1 ? candidates[0] : null);
  if (!candidate) return null;
  return {
    canonicalUrl: candidate.canonicalUrl,
    displayTitle: candidate.displayTitle || candidate.title,
    completeness: candidate.completeness,
    sourceFacts: candidate.sourceFacts
  };
}

async function addVisiblePageCaptureFallbacks(snapshot, tab, { selectedOnly = false } = {}) {
  const positions = [];
  const candidates = (Array.isArray(snapshot?.candidates) ? snapshot.candidates : []).map((candidate, candidateIndex) => ({
    ...candidate,
    media: (Array.isArray(candidate?.media) ? candidate.media : []).map((media, mediaIndex) => {
      if (media.kind === "image" && media.fallbackRect && !media.dataUrl && (!selectedOnly || media.captureMethod === 'pixel-fallback')) positions.push({ candidateIndex, mediaIndex, selection: media.fallbackRect });
      return media;
    })
  }));
  if (!positions.length || !Number.isInteger(tab.windowId)) return { ...snapshot, candidates };
  try {
    const [current] = await chrome.tabs.query({ active: true, windowId: tab.windowId });
    if (current?.id !== tab.id) {
      if (selectedOnly) throw new Error('所选网页已经切换,请重新选择;当前草稿保留');
      return { ...snapshot, candidates };
    }
    const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, { format: "png" });
    if (selectedOnly) {
      const [capturedTab] = await chrome.tabs.query({ active: true, windowId: tab.windowId });
      if (capturedTab?.id !== tab.id) throw new Error('所选网页已经切换,请重新选择;当前草稿保留');
      const [checked] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: validateSelectedCaptureRectangles,
        args: [positions.map(item => item.selection), true] });
      if (!checked?.result) throw new Error('所选画面位置已经变化,请重新选择;当前草稿保留');
    }
    await ensureOffscreenDocument();
    const response = await chrome.runtime.sendMessage({
      target: "offscreen",
      type: "CROP_PAGE_CAPTURE_PREVIEWS",
      dataUrl,
      selections: positions.map((item) => item.selection),
      maxDataUrlCharacters: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters
    });
    if (!response?.ok || response.dataUrls?.length !== positions.length || selectedOnly && response.dataUrls.some(value => !value)) {
      if (selectedOnly) throw new Error(response?.message || '所选画面截图失败,请重试;当前草稿保留');
      return { ...snapshot, candidates };
    }
    response.dataUrls.forEach((pixelData, index) => {
      if (!pixelData) return;
      const position = positions[index];
      candidates[position.candidateIndex].media[position.mediaIndex] = {
        ...candidates[position.candidateIndex].media[position.mediaIndex],
        dataUrl: pixelData,
        previewDataUrl: pixelData
      };
    });
  } catch (error) {
    if (selectedOnly) {
      const failedIds = new Set(positions.map(item => candidates[item.candidateIndex].media[item.mediaIndex].id));
      const remaining = candidates.map(candidate => ({ ...candidate, completeness: 'partial',
        sourceFacts: { ...candidate.sourceFacts, status: 'partial' },
        media: candidate.media.filter(media => !failedIds.has(media.id)),
        articleDocument: { ...candidate.articleDocument, blocks: (candidate.articleDocument?.blocks || []).filter(block => !failedIds.has(block.assetId)) }
      })).filter(candidate => candidate.contentText || candidate.media.length);
      if (!remaining.length) throw error;
      return { ...snapshot, candidates: remaining, error: error.message };
    }
  }
  return { ...snapshot, candidates };
}

async function capturePageCaptureViewportFallbacks(message, sender) {
  if (!activePageCapture || message?.sessionId !== activePageCapture.sessionId || sender?.tab?.id !== activePageCapture.tabId) {
    return { ok: false, message: "整页扫描会话已经结束" };
  }
  const selections = (Array.isArray(message?.selections) ? message.selections : []).slice(0, activePageCapture.maxCandidates);
  if (!selections.length || !Number.isInteger(sender.tab.windowId)) return { ok: true, dataUrls: [] };
  const [activeTab] = await chrome.tabs.query({ active: true, windowId: sender.tab.windowId });
  if (activeTab?.id !== sender.tab.id) return { ok: false, message: "扫描页面已不在前台" };
  const dataUrl = await chrome.tabs.captureVisibleTab(sender.tab.windowId, { format: "png" });
  await ensureOffscreenDocument();
  return chrome.runtime.sendMessage({
    target: "offscreen",
    type: "CROP_PAGE_CAPTURE_PREVIEWS",
    dataUrl,
    selections,
    maxDataUrlCharacters: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters
  });
}

async function cancelPageCapture(sessionIdValue) {
  const sessionId = String(sessionIdValue ?? "").trim();
  if (!activePageCapture || sessionId && sessionId !== activePageCapture.sessionId) return { ok: false, message: "整页扫描已经结束" };
  activePageCapture.cancelled = true;
  try {
    const response = await chrome.tabs.sendMessage(activePageCapture.tabId, {
      type: "PROMPTDIRECTOR_PAGE_CAPTURE", sessionId: activePageCapture.sessionId, action: "cancel"
    });
    return response?.ok ? { ok: true, message: "正在停止整页扫描,并恢复原滚动位置" } : { ok: false, message: "网页扫描器没有响应" };
  } catch {
    return { ok: false, message: "扫描页面已经关闭或刷新" };
  }
}

async function previewPageCaptureRegion(tabIdValue, preview) {
  const tabId = Number(tabIdValue);
  if (!Number.isInteger(tabId)) return { ok: false, message: "采集页面已经关闭" };
  try {
    const [result] = await chrome.scripting.executeScript({
      target: { tabId },
      func: renderPageCaptureRegionPreview,
      args: [preview || {}]
    });
    return result?.result?.ok
      ? { ok: true }
      : { ok: false, message: "原网页暂时无法高亮定位,请在采集预览中核对内容" };
  } catch {
    return { ok: false, message: "无法在当前网页显示区域高亮" };
  }
}

async function clearPageCaptureMarkers(tabIdValue, removeRegionMarkers = true) {
  const tabId = Number(tabIdValue);
  if (!Number.isInteger(tabId)) return { ok: false, message: "采集页面已经关闭" };
  try {
    await chrome.scripting.executeScript({
      target: { tabId },
      func: clearPageCapturePageState,
      args: [{ removeRegionMarkers, removePreview: true, removeEditor: true }]
    });
    return { ok: true };
  } catch {
    return { ok: false, message: "采集页面已经关闭或刷新" };
  }
}

async function runCaptureSave(message, progress) {
  return enqueueCapture(async () => {
    const retain = progress.retain, release = progress.release;
    progress.retain = async ids => { ids.forEach(id => activeCaptureAssetIds.add(id)); await retain(ids); };
    progress.release = async ids => { ids.forEach(id => activeCaptureAssetIds.delete(id)); await release(ids); };
    try {
      progress.stage('preparing');
      if (message.type === 'COMMIT_PAGE_CAPTURE') return await commitPageCapture(message.batch, message, progress);
      return await enqueue(() => commitCaptureDraft(message.duplicateAction, message, progress));
    } finally { activeCaptureAssetIds.clear(); }
  });
}

// A capture may reuse an identical original owned by another case. Protect it
// (and its poster) for the rest of this save, before confirming it still exists,
// so trash emptying during the remaining downloads cannot delete it. Only the
// in-memory guard is used: crash recovery deletes persisted capture IDs.
async function reusableCaptureAsset(asset) {
  activeCaptureAssetIds.add(asset.id);
  if (asset.posterAssetId) activeCaptureAssetIds.add(asset.posterAssetId);
  return Boolean(await getMediaBlob(asset.id));
}

function pageCaptureDocumentDownloadOptions(media) {
  return {
    kind: media.kind,
    expectedMimeType: media.mimeType,
    maxBytes: LIBRARY_TRANSFER_LIMITS.maxFileBytes,
    timeoutMs: 60_000,
    accept: "application/zip,application/pdf,text/markdown,text/plain,text/html,application/rtf,text/rtf,application/x-rtf"
  };
}

async function fetchPageCaptureImage(url, { onProgress, signal }) {
  let metadata = null;
  const blob = await fetchBoundedMedia(url, {
    onProgress, signal,
    kind: "image",
    revalidateCache: true,
    maxBytes: LIBRARY_TRANSFER_LIMITS.maxImageBytes,
    maxPixels: LIBRARY_TRANSFER_LIMITS.maxImagePixels,
    timeoutMs: 60_000,
    accept: "image/avif,image/webp,image/png,image/jpeg,image/gif",
    onMetadata: (value) => { metadata = value; }
  });
  return { blob, metadata };
}

// The plain network download each item would start first, so it can begin while earlier items are
// written. Items restored from a save checkpoint, local files and page-session fallbacks are not
// fetched ahead; they keep their existing path.
function pageCaptureDownloadPlan(media, candidate, progress, videoOnlineOnly = false) {
  if (media.localTransferId) return null;
  const cached = key => progress.mediaCached?.(key) === true;
  if (["document", "attachment"].includes(media.kind)) {
    const supported = media.kind === "attachment"
      ? /\.skill$/iu.test(media.filename) && media.mimeType === "application/zip"
      : isSupportedDocumentMimeType(media.mimeType);
    if (!supported || media.downloadDataUrl || !media.url || cached(`document:${candidate.id}:${media.id}:${media.url}`)) return null;
    return { key: `document:${media.url}`, start: options => fetchBoundedMedia(media.url, { ...pageCaptureDocumentDownloadOptions(media), ...options }) };
  }
  if (media.kind === "video") {
    if (videoOnlineOnly || media.videoStreams) return null;
    if (!media.url || cached(`video:${candidate.id}:${media.id}:${media.url}`)) return null;
    return { key: `video:${media.url}`, start: options => downloadPageCaptureVideo(media.url, {
      ...options, mimeType: media.mimeType, declaredVideo: ["site-original", "video-element"].includes(media.sourceKind) }) };
  }
  if (media.localAssetId || cached(`image:${candidate.id}:${media.id}:${media.url || "pixels"}`)) return null;
  const [url] = pageCaptureMediaFetchCandidates(media);
  return url ? { key: `image:${url}`, start: options => fetchPageCaptureImage(url, options) } : null;
}

async function commitPageCapture(batchValue, metadata = {}, progress = createCaptureSaveProgress(), durableReceipt) {
  const captureMetadata = createCaptureDraft(metadata);
  let batch = normalizePageCaptureBatch(batchValue);
  if (Number.isInteger(batch.tabId) && batch.candidates.some((candidate) => candidate.media.some((media) => media.fallbackRect && !media.dataUrl))) {
    try {
      const tab = await chrome.tabs.get(batch.tabId);
      batch = normalizePageCaptureBatch(await addVisiblePageCaptureFallbacks(batch, tab));
    } catch {
    }
  }
  let selected = applyPageCaptureSelections(batch);
  if (batch.captureMode === "list" && batch.saveMode === "combined" && selected.length) {
    const combined = combinePageCaptureCandidates(selected, {
      title: batch.combinedTitle,
      canonicalUrl: batch.sourceUrl
    });
    selected = combined ? [combined] : [];
  }
  if (!selected.length) return { ok: false, message: "请至少选择一项网页内容" };
  const mediaCount = selected.reduce((count, candidate) => count + candidate.media.length, 0);
  let mediaOffset = 0;
  const state = await enqueue(() => readState());
  const videoOnlineOnly = state.uiPreferences?.videoOnlineOnly === true;
  // Saved previews and picker fragments share the same source resolution as
  // whole-page/MCP capture. Match selected X media by poster and post ownership.
  if (!videoOnlineOnly) for (let index = 0; index < selected.length; index++) {
    progress.signal?.throwIfAborted();
    const candidate = selected[index];
    const snapshot = await resolveXVideoSources({ candidates: [candidate] },
      { id: batch.tabId, url: candidate.canonicalUrl }, chrome, { allowTabReload: false, allowTemporaryTab: true,
        cancelled: () => Boolean(progress.signal?.aborted) });
    selected[index] = snapshot.candidates[0];
  }
  const loadMedia = (key, load) => progress.media ? progress.media(key, load) : load();
  const results = [];
  let entries = [...state.entries];
  const savedAssets = createCaptureAssetIndex();
  const savedAssetIds = [];
  const captureFiles = new Map();
  const copySources = new Set();
  const targetEntryIds = new Set(state.organizerState.collections.find(item => item.id === captureMetadata.collectionId)?.entryIds || []);
  const projectScoped = Boolean(captureMetadata.collectionId || captureMetadata.newCollectionName);
  let metadataCommitted = false;
  try {
    for (const candidate of selected) {
      progress.signal?.throwIfAborted();
      const matches = entries.filter(entry => samePageCaptureSource(entry, candidate));
      // A project copy owns its edits. Repair that copy before considering the
      // original in another project; foreign matches are copied at commit time.
      const duplicate = (projectScoped && matches.find(entry => targetEntryIds.has(entry.id)
        || !state.entries.some(original => original.id === entry.id))) || matches[0];
      if (projectScoped && duplicate && !targetEntryIds.has(duplicate.id)
        && state.entries.some(original => original.id === duplicate.id)) copySources.add(duplicate.id);
      const repair = duplicate ? await planPageCaptureRepair(duplicate, candidate, async id => Boolean(await getMediaBlob(id))) : null;
      const refreshedClassification = duplicate ? classifyCapturedContent({ ...duplicate, sourceFacts: candidate.sourceFacts }, state.classificationRules, state.taxonomy) : null;
      const classificationChanged = duplicate && JSON.stringify(duplicate.classification?.pathIds) !== JSON.stringify(refreshedClassification.pathIds);
      if (duplicate && !repair.pending.length && !repair.obsoleteReferences.size && !repair.promptsChanged && !repair.textAdditions.length && duplicate.sourceFacts?.pageType === candidate.pageType && !classificationChanged) {
        results.push({ candidateId: candidate.id, status: "duplicate", entryId: duplicate.id, title: duplicate.title,
          contentTypeId: duplicate.classification?.pathIds?.[0] || "",
          ...pageCaptureMediaReceipt(candidate, repair.assetIds) });
        mediaOffset += candidate.media.length;
        continue;
      }
      const mediaAssets = [];
      const articleAssetIds = new Map(repair?.assetIds);
      const warnings = candidate.extraction?.scope === 'selection' && batch.error ? [batch.error] : [];
      const failedMediaIds = new Set();
      if (candidate.extraction?.pendingMediaCount) {
        warnings.push(`正文仍有 ${candidate.extraction.pendingMediaCount} 项媒体未加载,已保存当前可用内容,请回到来源页面核对`);
      }
      const candidateMedia = repair?.pending || candidate.media;
      const downloadAhead = createDownloadAhead({ signal: progress.signal });
      downloadAhead.plan(candidateMedia.map(media => pageCaptureDownloadPlan(media, candidate, progress, videoOnlineOnly)));
      try {
      for (const [mediaIndex, media] of candidateMedia.entries()) {
        progress.signal?.throwIfAborted();
        downloadAhead.advance(mediaIndex);
        const context = { kind: media.kind, index: mediaOffset + candidate.media.findIndex(item => item.id === media.id) + 1, count: mediaCount };
        const onProgress = value => progress.update(value);
        progress.stage('preparing', context);
        if (media.localTransferId) {
          try {
          const record = await resolveCaptureChatFile(media.localTransferId, { transfers: agentTransfers, loadState: readCaseLibraryState, touch: false });
          if (record.assetId !== media.localAssetId || record.prepared.asset.kind !== media.kind) throw new Error('本机文件已变化或不可用,请重新选择');
          const blob = await getMediaBlob(record.assetId);
          if (!blob || blob.size !== record.byteSize) throw new Error('本机原件未取得,已有预览保留');
          await progress.retain?.([record.assetId, ...(record.prepared.poster ? [record.prepared.poster.id] : [])]);
          mediaAssets.push({ ...record.prepared.asset, sourceTitle: media.filename || record.name,
            sourceUrl: candidate.canonicalUrl, originalWorkUrl: candidate.canonicalUrl });
          if (record.prepared.poster) mediaAssets.push({ ...record.prepared.poster, usage: 'poster', derivedFromAssetId: record.assetId });
          articleAssetIds.set(media.id, record.assetId); captureFiles.set(record.id, { record, candidateId: candidate.id });
          warnings.push(...record.prepared.warnings);
          } catch (error) {
            progress.signal?.throwIfAborted();
            failedMediaIds.add(media.id); warnings.push(`${media.filename || media.alt || candidate.title}:${userMessage(error)}`);
          }
          continue;
        }
        if (["document", "attachment"].includes(media.kind)) {
          if (!(media.kind === "attachment" ? /\.skill$/iu.test(media.filename) && media.mimeType === "application/zip" : isSupportedDocumentMimeType(media.mimeType))) {
            warnings.push(`${media.filename || media.alt || media.url}:已保留来源链接,未知或高风险文件不会自动下载`);
            continue;
          }
          const assetId = repair?.matched.get(media.id)?.id || crypto.randomUUID();
          try {
            const documentOptions = { ...pageCaptureDocumentDownloadOptions(media), onProgress, signal: progress.signal };
            progress.stage(media.downloadDataUrl ? 'transfer' : 'download', context);
            const blob = await loadMedia(`document:${candidate.id}:${media.id}:${media.url}`, async () => media.downloadDataUrl
              ? await boundedMediaBlobFromResponse(await fetch(media.downloadDataUrl), documentOptions)
              : await (downloadAhead.take(`document:${media.url}`, onProgress) ?? fetchBoundedMedia(media.url, documentOptions)));
            progress.stage('verify', context);
            const contentHash = await sha256Blob(blob);
            const [existing] = savedAssets.withHash(entries, contentHash);
            if (existing && await reusableCaptureAsset(existing)) {
              if (!mediaAssets.some((asset) => asset.id === existing.id)) mediaAssets.push({ ...existing,
                sourceUrl: media.url, sourceTitle: media.filename || media.sourceTitle || media.alt || candidate.title,
                sourceAuthor: media.sourceAuthor || candidate.sourceFacts.author,
                originalWorkUrl: media.originalWorkUrl || candidate.canonicalUrl
              });
              articleAssetIds.set(media.id, existing.id);
              continue;
            }
            progress.stage('writing', context);
            await progress.retain?.([assetId]);
            await (media.kind === "attachment" ? savePortableAssetBlob : saveMediaBlob)(assetId, blob);
            savedAssetIds.push(assetId);
            const documentAsset = {
              id: assetId,
              kind: media.kind,
              storageMode: "managed",
              sourceUrl: media.url,
              sourceTitle: media.filename || media.sourceTitle || media.alt || candidate.title,
              ...(media.kind === "attachment" ? { sourceFormat: "skill" } : {}),
              sourceAuthor: media.sourceAuthor || candidate.sourceFacts.author,
              originalWorkUrl: media.originalWorkUrl || candidate.canonicalUrl,
              mimeType: blob.type,
              byteSize: blob.size,
              contentHash,
              extractedTextFormat: ["text/markdown", "text/html", "application/rtf", "text/rtf", "application/x-rtf"].includes(blob.type) ? "markdown" : "plain",
              capturedAt: new Date().toISOString(),
              reviewStatus: "verified"
            };
            mediaAssets.push(documentAsset);
            articleAssetIds.set(media.id, documentAsset.id);
          } catch (error) {
          progress.signal?.throwIfAborted();
            progress.signal?.throwIfAborted();
            failedMediaIds.add(media.id);
            warnings.push(`${media.filename || media.alt || media.url}:本地副本未保存,已保留来源链接(${userMessage(error)})`);
          }
          continue;
        }
        if (media.kind === "video") {
          const referenceUrl = officialMediaEmbedUrl(media.url) ? media.url
            : candidate.media.filter(item => item.kind === "video").length === 1 && officialMediaEmbedUrl(candidate.canonicalUrl)
              ? candidate.canonicalUrl : media.originalWorkUrl || media.url || candidate.canonicalUrl;
          const provider = detectMediaReferenceProvider(referenceUrl);
          const playbackMode = officialMediaEmbedUrl(referenceUrl, provider) ? "embed" : "source";
          const videoAsset = {
            id: repair?.matched.get(media.id)?.id || crypto.randomUUID(),
            kind: "video",
            storageMode: "reference",
            sourceUrl: referenceUrl,
            sourceTitle: media.sourceTitle || candidate.title,
            sourceAuthor: media.sourceAuthor || candidate.sourceFacts.author,
            originalWorkUrl: media.originalWorkUrl || candidate.canonicalUrl,
            width: media.width,
            height: media.height,
            capturedAt: new Date().toISOString(),
            playbackCapability: playbackMode === "embed" ? "embedded" : "external",
            reference: { url: referenceUrl, provider, playbackMode,
              ...(media.streamUrl ? { streamUrl: media.streamUrl } : {}),
              ...(/^https?:/iu.test(media.url) && ["site-original", "video-element"].includes(media.sourceKind)
                ? { playbackUrl: media.url } : {}) },
            reviewStatus: "verified"
          };
          try {
            progress.stage('download', context);
            const blob = videoOnlineOnly ? null : await loadMedia(`video:${candidate.id}:${media.id}:${media.url}`, () => resolveCapturedVideoOriginal(media, candidate, {
              signal: progress.signal, onProgress,
              download: (url, options) => downloadAhead.take(`video:${url}`, onProgress) ?? downloadPageCaptureVideo(url, options),
              downloadNative: downloadNativeVideo,
              ...(batch.sessionMediaAllowed !== false ? { downloadSession: async url => (await fetchSelectedPageSessionMedia(batch, candidate, url, 'video', progress, context)).blob } : {})
            }));
            if (blob) {
              progress.stage('verify', context);
              const contentHash = await sha256Blob(blob);
              const managedVideo = (asset) => asset.kind === "video" && asset.storageMode === "managed" && asset.contentHash === contentHash;
              const existing = savedAssets.withHash(entries, contentHash).find(managedVideo) ?? mediaAssets.find(managedVideo);
              if (existing && await reusableCaptureAsset(existing)) {
                if (!mediaAssets.some((asset) => asset.id === existing.id)) mediaAssets.push({ ...existing,
                sourceUrl: media.url, sourceTitle: media.filename || media.sourceTitle || media.alt || candidate.title,
                sourceAuthor: media.sourceAuthor || candidate.sourceFacts.author,
                originalWorkUrl: media.originalWorkUrl || candidate.canonicalUrl
              });
                const poster = savedAssets.withId(entries, existing.posterAssetId);
                if (poster && !mediaAssets.some(asset => asset.id === poster.id)) mediaAssets.push({ ...poster,
                  usage: 'poster', derivedFromAssetId: existing.id });
                articleAssetIds.set(media.id, existing.id);
                continue;
              }
              progress.stage('writing', context);
              await progress.retain?.([videoAsset.id]);
              await saveMediaBlob(videoAsset.id, blob);
              savedAssetIds.push(videoAsset.id);
              Object.assign(videoAsset, {
                storageMode: "managed", sourceUrl: media.url, mimeType: blob.type, byteSize: blob.size,
                contentHash, playbackCapability: "unknown"
              });
              delete videoAsset.reference;
              try {
                progress.stage('poster', context);
                const prepared = await enqueue(() => prepareStoredVideoPoster(videoAsset));
                Object.assign(videoAsset, prepared.metadata);
                if (prepared.poster) {
                  await progress.retain?.([prepared.poster.id]);
                  savedAssetIds.push(prepared.poster.id);
                  mediaAssets.push(prepared.poster);
                  videoAsset.posterAssetId = prepared.poster.id;
                } else warnings.push(`${media.alt || candidate.title}:视频已保存,封面暂未生成`);
              } catch (error) {
          progress.signal?.throwIfAborted();
            progress.signal?.throwIfAborted();
                warnings.push(`${media.alt || candidate.title}:视频已保存,封面生成失败(${userMessage(error)})`);
              }
            }
          } catch (error) {
          progress.signal?.throwIfAborted();
            progress.signal?.throwIfAborted();
            if (error.code === 'video_component_required') throw error;
            failedMediaIds.add(media.id);
            warnings.push(`${media.alt || candidate.title}:视频原件未保存(${userMessage(error)})`);
          }
          if (!videoOnlineOnly && videoAsset.storageMode !== 'managed') continue;
          if (!videoAsset.posterAssetId && media.posterUrl) {
            try {
              const posterContext = { ...context, kind: 'poster' };
              progress.stage('download', posterContext);
              const posterBlob = await loadMedia(`poster:${candidate.id}:${media.id}:${media.posterUrl}`, () => fetchBoundedMedia(media.posterUrl, {
                onProgress, signal: progress.signal,
                kind: "image", maxBytes: LIBRARY_TRANSFER_LIMITS.maxImageBytes,
                revalidateCache: true,
                maxPixels: LIBRARY_TRANSFER_LIMITS.maxImagePixels, timeoutMs: 60_000
              }).catch(async error => {
                progress.signal?.throwIfAborted();
              if (batch.sessionMediaAllowed === false) throw error;
                try { return (await fetchSelectedPageSessionMedia(batch, candidate, media.posterUrl, 'image', progress, posterContext)).blob; }
                catch (sessionError) { throw new Error(`${userMessage(error)};${userMessage(sessionError)}`); }
              }));
              const posterId = crypto.randomUUID();
              progress.stage('writing', posterContext);
              await progress.retain?.([posterId]);
              await saveMediaBlob(posterId, posterBlob);
              savedAssetIds.push(posterId);
              mediaAssets.push({ id: posterId, kind: "image", usage: "poster", storageMode: "managed",
                derivedFromAssetId: videoAsset.id, sourceUrl: media.posterUrl,
                sourceTitle: candidate.title, mimeType: posterBlob.type, byteSize: posterBlob.size,
                capturedAt: videoAsset.capturedAt, reviewStatus: "verified" });
              videoAsset.posterAssetId = posterId;
            } catch (error) {
          progress.signal?.throwIfAborted();
            progress.signal?.throwIfAborted();
              warnings.push(`${media.alt || candidate.title}:来源封面未保存(${userMessage(error)})`);
            }
          }
          mediaAssets.push(videoAsset);
          articleAssetIds.set(media.id, videoAsset.id);
          continue;
        }
        const assetId = repair?.matched.get(media.id)?.id || crypto.randomUUID();
        try {
          const localBlob = media.localAssetId ? await getScreenshotBlob(media.localAssetId) : null;
          if (media.localAssetId && !localBlob) throw new Error("待补充的本地图片已不可用,请重新选择");
          const resolved = await loadMedia(`image:${candidate.id}:${media.id}:${media.url || media.localAssetId || "pixels"}`, async () => localBlob ? { blob: localBlob, sourceUrl: media.url, captureMethod: "source" }
            : await resolvePageCaptureImage(media, {
            signal: progress.signal, sessionMediaAllowed: batch.sessionMediaAllowed,
            fetchMedia: async (url) => {
              progress.stage('download', context);
              return downloadAhead.take(`image:${url}`, onProgress) ?? fetchPageCaptureImage(url, { onProgress, signal: progress.signal });
            },
            fetchSessionMedia: async (url) => fetchSelectedPageSessionMedia(batch, candidate, url, 'image', progress, context),
            decodeDataUrl: dataUrlToImageBlob
          }));
          const blob = resolved.blob;
          if (resolved.usedReducedImage) warnings.push(`${media.alt || candidate.title}:原图不可用,已保存网站提供的较小图片`);
          progress.stage('verify', context);
          const contentHash = await sha256Blob(blob);
          const existing = mediaAssets.find((asset) => asset.contentHash === contentHash) ?? savedAssets.withHash(entries, contentHash)[0];
          if (existing && await reusableCaptureAsset(existing)) {
            if (!mediaAssets.some((asset) => asset.id === existing.id)) mediaAssets.push({ ...existing,
                sourceUrl: resolved.sourceUrl || media.url, sourceTitle: media.filename || media.sourceTitle || media.alt || candidate.title,
                sourceAuthor: media.sourceAuthor || candidate.sourceFacts.author,
                originalWorkUrl: media.originalWorkUrl || candidate.canonicalUrl
              });
            articleAssetIds.set(media.id, existing.id);
            continue;
          }
          progress.stage('writing', context);
          await progress.retain?.([assetId]);
          await saveMediaBlob(assetId, blob);
          savedAssetIds.push(assetId);
          const generationInfo = await readImageGenerationInfo(blob);
          if (generationInfo?.warnings.length) warnings.push(...generationInfo.warnings);
          const imageAsset = {
            ...(generationInfo ? { generationInfo } : {}),
            id: assetId,
            kind: "image",
            storageMode: "managed",
            sourceUrl: resolved.sourceUrl || media.url || candidate.canonicalUrl,
            sourceTitle: media.sourceTitle || media.alt || candidate.title,
            sourceAuthor: media.sourceAuthor || candidate.sourceFacts.author,
            originalWorkUrl: media.originalWorkUrl || candidate.canonicalUrl,
            mimeType: blob.type,
            byteSize: blob.size,
            width: resolved.metadata?.width || media.width,
            height: resolved.metadata?.height || media.height,
            contentHash,
            captureMethod: resolved.captureMethod || media.captureMethod,
            capturedAt: new Date().toISOString(),
            reviewStatus: "verified"
          };
          mediaAssets.push(imageAsset);
          articleAssetIds.set(media.id, imageAsset.id);
          if (resolved.usedPixelFallback) warnings.push(`${media.alt || candidate.title}:原图不可用,已保存页面可见画面`);
        } catch (error) {
          progress.signal?.throwIfAborted();
          failedMediaIds.add(media.id);
          warnings.push(`${media.alt || media.url || candidate.title}:${userMessage(error)}`);
        }
      }
      } finally {
        downloadAhead.close();
      }
      mediaOffset += candidate.media.length;
      if (warnings.length) console.debug("PromptDirector capture diagnostics", { candidateId: candidate.id, warnings: [...new Set(warnings)] });
      const captureFacts = { ...candidate.sourceFacts,
        status: warnings.length ? "partial" : candidate.sourceFacts.status };
      if (duplicate) {
        const repaired = mergePageCaptureRepair(duplicate, { ...candidate, sourceFacts: captureFacts }, repair, mediaAssets, articleAssetIds);
        const existingAssetIds = new Set((duplicate.mediaAssets ?? []).map(asset => asset.id));
        const entry = normalizeEntryMedia({ ...repaired,
          mediaPrompts: [...(repaired.mediaPrompts ?? []), ...embeddedMediaPrompts(mediaAssets.filter(asset => !existingAssetIds.has(asset.id)), repaired.mediaPrompts)],
          classification: classifyCapturedContent(repaired, state.classificationRules, state.taxonomy)
        });
        entries = entries.map(item => item.id === entry.id ? entry : item);
        results.push({ candidateId: candidate.id, status: warnings.length ? "partial" : "saved", repaired: true, entryId: entry.id, title: entry.title, warnings,
          ...pageCaptureMediaReceipt(candidate, articleAssetIds, failedMediaIds) });
        continue;
      }
      // A selected work's description alone is not a saved video case. Keep the
      // full draft for retry; explicit text-only saves still have no video here.
      if (candidate.pageType === 'video' && candidate.media.some(media => media.kind === 'video')
        && failedMediaIds.size && !mediaAssets.some(asset => asset.usage !== 'poster')) {
        results.push({ candidateId: candidate.id, status: 'failed', title: candidate.title, warnings,
          ...pageCaptureMediaReceipt(candidate, articleAssetIds, failedMediaIds) });
        continue;
      }
      const articleText = articleDocumentText(candidate.articleDocument);
      const base = buildEntry({
        text: articleText || candidate.contentText || (candidate.sourceFacts.originalPromptAvailable === false ? "" : candidate.excerpt),
        title: candidate.title,
        url: candidate.canonicalUrl,
        allowEmptyText: mediaAssets.length > 0
      });
      if (!base.text && !mediaAssets.length) {
        results.push({ candidateId: candidate.id, status: "failed", title: candidate.title, warnings: [...warnings, "没有可保存的正文或媒体"] });
        continue;
      }
      const mediaPrompts = capturedMediaPrompts(candidate, articleAssetIds);
      mediaPrompts.push(...embeddedMediaPrompts(mediaAssets, mediaPrompts));
      const entry = normalizeEntryMedia({
        ...base,
        schemaVersion: SCHEMA_VERSION,
        mediaPrompts,
        articleDocument: finalizeArticleDocumentAssets(candidate.articleDocument, articleAssetIds),
        sourceFacts: captureFacts,
        sourcePages: [{ url: candidate.canonicalUrl, title: candidate.title }],
        mediaAssets,
        primaryMediaId: (candidate.pageType === "video"
          ? mediaAssets.find((asset) => asset.kind === "video")
          : mediaAssets.find((asset) => asset.kind === "image" && asset.usage !== "poster"))?.id
          || mediaAssets.find((asset) => asset.usage !== "poster")?.id || "",
        classification: classifyCapturedContent({ ...base, sourceFacts: candidate.sourceFacts, mediaAssets, mediaPrompts }, state.classificationRules, state.taxonomy),
        customLabels: [], metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
        rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
      });
      entries.push(entry);
      results.push({ candidateId: candidate.id, status: warnings.length ? "partial" : "saved", entryId: entry.id, title: entry.title, warnings,
        ...pageCaptureMediaReceipt(candidate, articleAssetIds, failedMediaIds) });
    }
    const explicitClassification = captureMetadata.contentTypeExplicit && isValidContentPath(state.taxonomy, [captureMetadata.contentTypeId]);
    const explicitOrganization = captureMetadata.collectionId || captureMetadata.newCollectionName || captureMetadata.customLabelsExplicit;
    const affectedIds = results.filter(item => ["saved", "partial"].includes(item.status)
      || item.status === "duplicate" && (explicitClassification || explicitOrganization)).map(item => item.entryId);
    if (!affectedIds.length) {
      return { ok: true, message: "所选内容均已存在或无法保存", results };
    }
    entries = entries.map(entry => !affectedIds.includes(entry.id) ? entry : {
      ...entry,
      customLabels: uniqueNames([...(entry.customLabels || []), ...captureMetadata.customLabels]),
      classification: explicitClassification
        ? { pathIds: [captureMetadata.contentTypeId], status: "confirmed", source: "manual", reason: "保存前人工确认" }
        : entry.classification
    });
    const promptConflicts = [];
    for (let index = 0; index < entries.length; index++) {
      const entry = entries[index];
      if (!affectedIds.includes(entry.id)) continue;
      const oldIds = new Set((state.entries.find(item => item.id === entry.id)?.mediaAssets ?? []).map(asset => asset.id));
      const promptPlan = await planImageGenerationPrompts(entry, entry.mediaAssets.filter(asset => !oldIds.has(asset.id)), metadata.generationPromptChoices);
      entries[index] = promptPlan.entry;
      promptConflicts.push(...promptPlan.conflicts);
    }
    if (promptConflicts.length) {
      progress.stage('confirm');
      await progress.release?.(savedAssetIds);
      await deleteUnreferencedMedia(savedAssetIds);
      return generationPromptConfirmation(promptConflicts);
    }
    let organizerState;
    await enqueue(async () => {
      progress.signal?.throwIfAborted();
      const latest = await readState();
      entries = rebaseCaptureEntries(state.entries, entries, latest.entries, affectedIds,
        (existing, entry) => samePageCaptureSource(existing, { canonicalUrl: entry.url, contentText: entry.text, sourceFacts: entry.sourceFacts }));
      if (captureMetadata.contentTypeExplicit && !isValidContentPath(latest.taxonomy, [captureMetadata.contentTypeId])) {
        throw new Error('分类在下载期间已变化,请重新选择');
      }
      // Reject a changed target membership before writing a repair into a case
      // that the user moved elsewhere while media was being downloaded.
      if (captureMetadata.collectionId && affectedIds.some(id => targetEntryIds.has(id)
        && !latest.organizerState.collections.find(item => item.id === captureMetadata.collectionId)?.entryIds.includes(id))) {
        throw new Error('案例项目在下载期间已变化,待保存内容已保留,请重试');
      }
      const copiedIds = affectedIds.filter(id => copySources.has(id));
      const preparedCopies = new Map(entries.filter(entry => copiedIds.includes(entry.id)).map(entry => [entry.id, entry]));
      // Rebase above checks the original for concurrent edits. Restore it before
      // the shared copy planner runs, then apply the repair only to the new copy.
      entries = entries.map(entry => preparedCopies.has(entry.id) ? latest.entries.find(item => item.id === entry.id) : entry);
      organizerState = organizerAfterCapturePlacement(latest.organizerState, entries,
        affectedIds.filter(id => !copySources.has(id)), captureMetadata);
      const targetId = captureMetadata.collectionId || (captureMetadata.newCollectionName
        ? organizerState.collections.find(collection => !latest.organizerState.collections.some(prior => prior.id === collection.id))?.id : '');
      const copyPlan = copiedIds.length ? planCaseCopies({ entries, organizerState, compoundCases: latest.compoundCases }, copiedIds, targetId) : null;
      if (copyPlan) {
        const repairs = new Map();
        for (const copy of copyPlan.copies) for (const [sourceId, copyId] of Object.entries(copy.entryIdMap)) {
          if (preparedCopies.has(sourceId)) repairs.set(copyId, preparedCopies.get(sourceId));
          for (const result of results) if (result.entryId === sourceId) result.entryId = copyId;
        }
        const oldIds = new Set(latest.entries.map(entry => entry.id));
        const preserved = new Map(entries.map(entry => [entry.id, entry]));
        entries = copyPlan.state.entries.map(entry => repairs.has(entry.id)
          ? { ...repairs.get(entry.id), id: entry.id, copyOrigin: entry.copyOrigin, caseInstanceId: entry.caseInstanceId }
          : oldIds.has(entry.id) ? preserved.get(entry.id) : entry);
        organizerState = copyPlan.state.organizerState;
      }
      // Commit project copies with their actual receipt IDs. Deferring ownership
      // migration until the next read leaves Open case pointing at the source.
      const folderPlan = needsFolderOwnershipMigration({ organizerState })
        ? planFolderOwnership({ entries, organizerState, compoundCases: copyPlan?.state.compoundCases || latest.compoundCases }) : null;
      if (folderPlan) { entries = folderPlan.state.entries; organizerState = folderPlan.state.organizerState; }
      for (const copy of (folderPlan?.copies || []).filter(item => item.collectionId === targetId)) {
        for (const result of results) result.entryId = copy.entryIdMap[result.entryId] || result.entryId;
      }
      await progress.commit?.();
      progress.stage('writing');
      const files = Object.fromEntries([...captureFiles.values()].flatMap(({ record, candidateId }) => {
        const result = results.find(item => item.candidateId === candidateId && item.entryId);
        return result ? [[agentTransfers.key(record.id), { ...record, state: 'committed', entryId: result.entryId, prepared: null, chunks: 0 }]] : [];
      }));
      // The durable receipt carries the classification actually committed,
      // including duplicates and project copies, rather than model arguments.
      const receiptTypes = new Map(results.filter(result => result.entryId).map(result => [result.entryId, '']));
      for (const entry of entries) if (receiptTypes.has(entry.id)) receiptTypes.set(entry.id, entry.classification?.pathIds?.[0] || '');
      for (const result of results) if (result.entryId) result.contentTypeId = receiptTypes.get(result.entryId);
      await commitLocalChanges({ [STORAGE_KEYS.entries]: entries, [STORAGE_KEYS.organizerState]: organizerState,
        ...(folderPlan?.changed || copyPlan ? { [STORAGE_KEYS.compoundCases]: folderPlan?.state.compoundCases || copyPlan.state.compoundCases } : {}), ...files,
        ...(durableReceipt ? { [durableReceipt.key]: durableReceipt.value({ ok: true, results, collectionId: targetId || '' }) } : {}) });
    });
    metadataCommitted = true;
    const postCommitWarnings = [];
    try { await notifySaved(entries.length); }
    catch (error) { postCommitWarnings.push(`保存成功,但状态提示更新失败:${userMessage(error)}`); }
    const savedCount = results.filter((item) => ["saved", "partial"].includes(item.status)).length;
    const duplicateCount = results.filter((item) => item.status === "duplicate").length;
    return {
      ok: true,
      message: `已保存 ${savedCount} 项${duplicateCount ? `,跳过 ${duplicateCount} 项重复内容` : ""}${postCommitWarnings.length ? `;${postCommitWarnings.join(";")}` : ""}`,
      results,
      collectionId: captureMetadata.collectionId || (captureMetadata.newCollectionName
        ? organizerState.collections.find(collection => !state.organizerState.collections.some(prior => prior.id === collection.id))?.id || "" : ""),
      warnings: postCommitWarnings
    };
  } catch (error) {
    if (!metadataCommitted) {
      await progress.release?.(savedAssetIds);
      await deleteUnreferencedMedia(savedAssetIds).catch(() => undefined);
    }
    throw error;
  }
}

async function fetchSelectedPageSessionMedia(batch, candidate, value, kind = "image", progress, context = {}) {
  if (batch.sessionMediaAllowed === false) throw new Error("没有获得页面媒体读取权限");
  const maxBytes = await stagingByteBudget();
  const timeoutMs = operationBudget().maxDurationMs;
  const signal = progress?.signal ? AbortSignal.any([progress.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
  if (!Number.isInteger(batch?.tabId)) throw new Error("原网页标签页已经不可用");
  const tab = await chrome.tabs.get(batch.tabId);
  let currentOrigin;
  let capturedOrigin;
  try {
    currentOrigin = new URL(tab.url).origin;
    capturedOrigin = new URL(batch.sourceUrl || candidate.canonicalUrl).origin;
  } catch {
    throw new Error("原网页地址已经不可用");
  }
  if (currentOrigin !== capturedOrigin) throw new Error("原网页已经跳转,未使用页面登录状态读取媒体");
  const allowedUrls = pageCaptureMediaFetchCandidatesForSession(candidate, value);
  if (!allowedUrls.includes(value)) throw new Error("页面媒体地址不在已选择内容中");
  const token = crypto.randomUUID();
  const discard = () => chrome.scripting.executeScript({ target: { tabId: batch.tabId }, world: 'MAIN',
    func: discardPageSessionMedia, args: [{ token }] }).catch(() => undefined);
  signal.throwIfAborted();
  signal.addEventListener('abort', discard, { once: true });
  try {
    progress?.stage('page', context);
    const [preparedResult] = await chrome.scripting.executeScript({
      target: { tabId: batch.tabId },
      world: "MAIN",
      func: preparePageSessionMedia,
      args: [{
        token,
        url: value,
        allowedUrls,
        maxBytes,
        chunkBytes: Math.min(maxBytes, PAGE_SESSION_MEDIA_CHUNK_BYTES),
        timeoutMs
      }]
    });
    signal.throwIfAborted();
    const prepared = preparedResult?.result;
    if (prepared?.token === token && prepared.ok === false && prepared.error) {
      const error = new Error(prepared.error.message || '页面媒体读取失败');
      error.name = prepared.error.name;
      throw mediaDownloadFailure(error, prepared.error);
    }
    if (!prepared || prepared.token !== token || !Number.isSafeInteger(prepared.chunkCount) || prepared.chunkCount <= 0) {
      throw new Error("页面没有返回有效媒体");
    }
    const chunks = [];
    let totalBytes = 0;
    progress?.stage('transfer', { ...context, receivedBytes: 0, totalBytes: prepared.totalBytes });
    for (let index = 0; index < prepared.chunkCount; index += 1) {
      signal.throwIfAborted();
      const [chunkResult] = await chrome.scripting.executeScript({
        target: { tabId: batch.tabId },
        world: "MAIN",
        func: readPageSessionMediaChunk,
        args: [{ token, index }]
      });
      const binary = globalThis.atob(String(chunkResult?.result || ""));
      const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
      totalBytes += bytes.byteLength;
      if (totalBytes > maxBytes) throw new Error("页面媒体超过本次暂存预算");
      chunks.push(new Blob([bytes]));
      progress?.update({ receivedBytes: totalBytes, totalBytes: prepared.totalBytes });
    }
    if (totalBytes !== prepared.totalBytes) throw new Error("页面媒体传输不完整");
    let metadata = null;
    progress?.stage('verify', context);
    const blob = await boundedMediaBlobFromResponse(new Response(new Blob(chunks), {
      headers: { "content-type": String(prepared.contentType || "application/octet-stream") }
    }), {
      kind,
      maxBytes,
      signal,
      maxPixels: LIBRARY_TRANSFER_LIMITS.maxImagePixels,
      onMetadata: (value) => { metadata = value; }
    });
    return { blob, metadata };
  } finally {
    signal.removeEventListener('abort', discard);
    await discard();
  }
}

function pageCaptureMediaFetchCandidatesForSession(candidate, selectedUrl) {
  const urls = new Set();
  for (const media of candidate?.media || []) {
    for (const url of [...pageCaptureMediaFetchCandidates(media), media.posterUrl].filter(Boolean)) urls.add(url);
  }
  return urls.has(selectedUrl) ? [...urls] : [];
}

async function startCaptureForCase(caseId, partEntryId = "") {
  const current = await captureRuntime.getDraft();
  if (current.fragments.length || current.visuals.length || current.targetCaseId) {
    return { ok: false, message: "当前还有未保存草稿,请先保存或丢弃" };
  }
  const state = await readState();
  const compound = normalizeCompoundCases(state.compoundCases, state.entries).find((item) => item.id === String(caseId ?? ""));
  const entryId = String(partEntryId || (compound ? compound.memberEntryIds[0] : caseId) || "");
  const entry = findEntry(state, entryId);
  const draft = createCaptureDraft({
    targetCaseId: compound?.id || entry.id,
    targetPartEntryId: partEntryId ? entry.id : "",
    title: compound?.title || entry.title,
    contentTypeId: entry.classification?.pathIds?.[0] || "",
    customLabels: entry.customLabels
  });
  await commitLocalChanges({ [STORAGE_KEYS.captureDraft]: draft });
  return { ok: true, message: `正在为“${compound?.title || entry.title}”继续采集`, draft, sourceUrl: entry.url };
}

async function createCompoundCaseAction(message) {
  const state = await readState();
  const result = createCompoundCase(state.compoundCases, state.entries, {
    id: message.compoundCaseId,
    title: message.title,
    memberEntryIds: message.memberEntryIds,
    coverVisualId: message.coverVisualId,
    customLabels: message.customLabels
  });
  await commitLocalChanges({ [STORAGE_KEYS.compoundCases]: result.compoundCases });
  return { ok: true, message: "案例已组合,可随时拆分", compoundCase: result.compoundCase };
}

async function updateCompoundCaseAction(message) {
  const state = await readCaseLibraryState();
  const labelsEdited = message.customLabels !== undefined || Array.isArray(message.addLabels) || Array.isArray(message.removeLabels);
  const current = state.compoundCases.find(item => item.id === message.compoundCaseId);
  const result = updateCompoundCase(state.compoundCases, state.entries, message.compoundCaseId, {
    title: message.title,
    memberEntryIds: message.memberEntryIds,
    coverVisualId: message.coverVisualId,
    customLabels: labelsEdited ? editedLabels(current?.customLabels, message) : undefined
  });
  await commitLocalChanges({ [STORAGE_KEYS.compoundCases]: result.compoundCases });
  return {
    ok: true,
    message: result.split ? "成员不足两个,已恢复为独立案例" : "组合内容已更新",
    compoundCase: result.compoundCase
  };
}

async function splitCompoundCaseAction(compoundCaseId) {
  const state = await readState();
  const result = splitCompoundCase(state.compoundCases, state.entries, compoundCaseId);
  await commitLocalChanges({ [STORAGE_KEYS.compoundCases]: result.compoundCases });
  return { ok: true, message: `已拆分为 ${result.memberEntryIds.length} 个独立案例`, memberEntryIds: result.memberEntryIds };
}

async function setEntryPrimaryVisual(entryId, visualId) {
  const state = await readCaseLibraryState();
  const current = findEntry(state, entryId);
  const next = setPrimaryVisual(current, visualId);
  const updated = next.primaryVisualId === current.primaryVisualId ? next : touchEntry(next);
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: "主图已更新", entry: updated };
}

async function deleteEntryVisual(entryId, visualId) {
  return moveEntryMediaToTrash(entryId, visualId, {
    missingMessage: "没有找到这张截图",
    successMessage: "截图已移入回收站,案例文字和其他截图保持不变"
  });
}

async function addUploadedVisual(entryId, visualValue, choices = {}) {
  const state = await readState();
  const current = findEntry(state, entryId);
  const visualId = String(visualValue?.id ?? "").trim();
  if (!visualId || !await getScreenshotBlob(visualId)) throw new Error("没有读取到待添加的图片");
  if (current.mediaAssets?.some(asset => asset.id === visualId)) return { ok: true, duplicate: true, message: "图片已在案例中", entry: current };
  let updated = touchEntry(addEntryVisual(current, {
    ...visualValue, id: visualId, sourceUrl: current.url, sourceTitle: current.title,
    capturedAt: new Date().toISOString(), reviewStatus: "verified"
  }));
  if (!current.mediaAssets?.some(asset => asset.id === visualId)) {
    updated = normalizeEntryVisuals({ ...updated, mediaPrompts: [...(updated.mediaPrompts ?? []), ...embeddedMediaPrompts([{ ...visualValue, kind: "image" }], updated.mediaPrompts)] });
  }
  const promptPlan = await planImageGenerationPrompts(updated, current.mediaAssets?.some(item => item.id === visualValue.id) ? [] : [visualValue], choices);
  if (promptPlan.conflicts.length) return generationPromptConfirmation(promptPlan.conflicts);
  updated = promptPlan.entry;
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: `图片已加入案例 · 共 ${updated.visuals.length} 张`, entry: updated };
}

async function setEntryCover(entryId, assetId, uploadedAsset) {
  const state = await readState();
  let current = findEntry(state, entryId);
  if (uploadedAsset) {
    if (uploadedAsset.kind !== "image" || !uploadedAsset.id || !await getMediaBlob(uploadedAsset.id)) throw new Error("没有读取到封面图片");
    current = addEntryMedia(current, { ...uploadedAsset, usage: "poster", storageMode: "managed" });
    assetId = uploadedAsset.id;
  }
  const updated = touchEntry(setCaseCover(current, assetId));
  await commitLocalChanges({ [STORAGE_KEYS.entries]: state.entries.map(entry => entry.id === entryId ? updated : entry) });
  return { ok: true, message: "封面已更新", entry: updated };
}

async function setEntryPrimaryMedia(entryId, assetId) {
  const state = await readState();
  const current = findEntry(state, entryId);
  const next = setPrimaryMedia(current, assetId);
  const updated = next.primaryMediaId === current.primaryMediaId ? next : touchEntry(next);
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: "主要媒体已更新", entry: updated };
}

async function deleteEntryMedia(entryId, assetId) {
  return moveEntryMediaToTrash(entryId, assetId, {
    missingMessage: "没有找到这个媒体",
    successMessage: "媒体已移入回收站,案例文字和其他资料保持不变"
  });
}

async function moveEntryMediaToTrash(entryId, assetId, messages) {
  const state = await readState();
  const current = normalizeEntryMedia(findEntry(state, entryId));
  const asset = current.mediaAssets.find((item) => item.id === String(assetId ?? ""));
  if (!asset) return { ok: false, message: messages.missingMessage };
  const moved = moveMediaToTrash({
    entries: state.entries,
    trashState: state.trashState
  }, current.id, [asset.id]);
  const entries = touchEntries(moved.entries, [current.id]);
  const updated = entries.find((entry) => entry.id === current.id);
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: entries,
    [STORAGE_KEYS.trashState]: moved.trashState
  });
  return {
    ok: true,
    message: messages.successMessage,
    movedItemIds: moved.movedItemIds,
    entry: updated,
    trashState: moved.trashState
  };
}

async function updateLocalAssetReferenceAction(message = {}) {
  const state = await readState();
  const current = findEntry(state, String(message.entryId ?? "").trim());
  const updated = updateLocalAssetReferenceMetadata(current, message.assetId, {
    sourceTitle: message.sourceTitle,
    relativePath: message.relativePath,
    sourceFormat: message.sourceFormat,
    mimeType: message.mimeType,
    byteSize: message.byteSize,
    sourceLastModified: message.sourceLastModified
  });
  const entry = touchEntry(updated.entry);
  const entries = state.entries.map((item) => item.id === entry.id ? entry : item);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return {
    ok: true,
    message: "本机源文件链接已更新",
    entry,
    asset: entry.mediaAssets.find((item) => item.id === updated.asset.id)
  };
}

async function prepareStoredVideoPoster(asset) {
  await ensureOffscreenDocument();
  const response = await chrome.runtime.sendMessage({
    target: "offscreen", type: "PREPARE_STORED_VIDEO_POSTER", assetId: asset.id,
    timeoutMs: PAGE_CAPTURE_LIMITS.navigationTimeoutMs
  });
  if (!response?.ok) throw new Error(response?.message || "视频封面生成失败");
  return response;
}

async function addUploadedMedia(entryId, assetValue, posterValue = null, choices = {}) {
  const state = await readState();
  const current = findEntry(state, entryId);
  const assetId = String(assetValue?.id ?? "").trim();
  const storageMode = assetValue?.storageMode === "reference" ? "reference" : "managed";
  if (!assetId || (storageMode === "managed" && !await getMediaBlob(assetId))) {
    throw new Error("没有读取到待添加的媒体文件");
  }
  if (current.mediaAssets?.some(asset => asset.id === assetId)) return { ok: true, duplicate: true, message: "资料已在案例中", entry: current };
  if (assetValue?.derivedFromAssetId && !current.mediaAssets.some(asset => asset.id === assetValue.derivedFromAssetId && asset.kind === 'video')) throw new Error('截图来源视频不属于当前案例');
  let updated = addEntryMedia(current, {
    ...assetValue,
    id: assetId,
    storageMode,
    sourceUrl: assetValue?.sourceUrl || current.url,
    sourceTitle: assetValue?.sourceTitle || current.title,
    capturedAt: new Date().toISOString(),
    reviewStatus: "verified"
  });
  if (posterValue?.id) {
    if (!await getMediaBlob(posterValue.id)) throw new Error("没有读取到视频封面");
    updated = addEntryMedia(updated, { ...posterValue, usage: "poster", derivedFromAssetId: assetId, storageMode: "managed" });
  }
  if (!current.mediaAssets?.some(asset => asset.id === assetId)) {
    updated = normalizeEntryMedia({ ...updated, mediaPrompts: [...(updated.mediaPrompts ?? []), ...embeddedMediaPrompts([assetValue], updated.mediaPrompts)] });
  }
  updated = touchEntry(updated);
  const promptPlan = await planImageGenerationPrompts(updated, current.mediaAssets?.some(item => item.id === assetValue.id) ? [] : [assetValue], choices);
  if (promptPlan.conflicts.length) return generationPromptConfirmation(promptPlan.conflicts);
  updated = promptPlan.entry;
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  const contentCount = updated.mediaAssets.filter((item) => item.usage !== "poster").length;
  return { ok: true, message: `资料已加入案例 · 共 ${contentCount} 项`, entry: updated };
}

async function createMediaCase(assetValue, posterValue, titleValue, textValue = "", choices = {}) {
  const assetId = String(assetValue?.id ?? "").trim();
  if (!assetId || !await getMediaBlob(assetId)) throw new Error("没有读取到待保存的媒体文件");
  const state = await readState();
  const prior = state.entries.find(entry => entry.mediaAssets?.some(asset => asset.id === assetId));
  if (prior) return { ok: true, duplicate: true, message: "资料已保存", entry: prior };
  const base = buildEntry({ text: textValue, title: titleValue, url: "", allowEmptyText: true });
  const mediaAssets = [{ ...assetValue, id: assetId, storageMode: "managed", capturedAt: new Date().toISOString(), reviewStatus: "verified" }];
  if (posterValue?.id) {
    if (!await getMediaBlob(posterValue.id)) throw new Error("没有读取到视频封面");
    mediaAssets.push({ ...posterValue, usage: "poster", derivedFromAssetId: assetId, storageMode: "managed" });
  }
  const classification = classifyImportedMedia({ ...base, mediaAssets }, state.taxonomy);
  let entry = normalizeEntryMedia({
    ...base,
    schemaVersion: SCHEMA_VERSION,
    mediaAssets,
    primaryMediaId: assetId,
    mediaPrompts: embeddedMediaPrompts(mediaAssets),
    classification,
    customLabels: [], metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
    rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
  });
  const promptPlan = await planImageGenerationPrompts(entry, mediaAssets, choices, textValue);
  if (promptPlan.conflicts.length) return generationPromptConfirmation(promptPlan.conflicts);
  entry = { ...promptPlan.entry, classification: classifyImportedMedia(promptPlan.entry, state.taxonomy) };
  const entries = [...state.entries, entry];
  await retireLastSaveUndo();
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: entries,
    [STORAGE_KEYS.lastSaveUndo]: createEntrySaveUndo(entry)
  });
  await enqueueAutomaticLibraryMaintenance([entry]);
  await notifySaved(entries.length);
  if (assetValue?.kind === "image") await queueAutomaticVisionAnalysis([entry.id]);
  return { ok: true, message: "资料已保存", entry };
}

async function createMediaReferenceCase(assetValue, posterValue, titleValue, organization = {}) {
  const state = await readState();
  const sourceUrl = String(assetValue?.reference?.url || assetValue?.sourceUrl || "").trim();
  const base = buildEntry({ text: "", title: titleValue, url: sourceUrl, allowEmptyText: true });
  const mediaAssets = [{ ...assetValue, storageMode: "reference", sourceUrl, capturedAt: new Date().toISOString(), reviewStatus: "verified" }];
  if (posterValue?.id) {
    if (!await getMediaBlob(posterValue.id)) throw new Error("没有读取到视频封面");
    mediaAssets.push({ ...posterValue, usage: "poster", derivedFromAssetId: assetValue?.id, storageMode: "managed" });
  }
  const entry = normalizeEntryMedia({
    ...base,
    schemaVersion: SCHEMA_VERSION,
    mediaAssets,
    primaryMediaId: assetValue?.id,
    classification: classifyContent({ ...base, mediaAssets }, state.classificationRules, state.taxonomy),
    customLabels: uniqueNames(organization.customLabels), metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
    rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
  });
  const entries = [...state.entries, entry];
  const organizerState = organizerAfterCapturePlacement(state.organizerState, entries, [entry.id], organization);
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: entries,
    [STORAGE_KEYS.organizerState]: organizerState
  });
  await notifySaved(entries.length);
  return { ok: true, message: "视频来源已保存;不能嵌入的平台会打开原网页", entry };
}

async function createQuickNote(titleValue, textValue, organization = {}) {
  const state = await readState();
  const entry = buildEntry({ text: textValue, title: titleValue, url: "" });
  entry.schemaVersion = SCHEMA_VERSION;
  entry.classification = classifyImportedMedia({ ...entry, sourceKind: "quick_note" }, state.taxonomy);
  entry.customLabels = uniqueNames(organization.customLabels);
  const entries = [...state.entries, entry];
  const organizerState = organizerAfterCapturePlacement(state.organizerState, entries, [entry.id], organization);
  await retireLastSaveUndo();
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: entries,
    [STORAGE_KEYS.organizerState]: organizerState,
    [STORAGE_KEYS.lastSaveUndo]: createEntrySaveUndo(entry)
  });
  await notifySaved(entries.length);
  return { ok: true, message: "快速笔记已保存", entry };
}

async function addEntryTimeNote(entryId, noteValue) {
  const state = await readCaseLibraryState();
  const current = findEntry(state, entryId);
  const updated = touchEntry(addTimeNote(current, noteValue));
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: "时间点笔记已保存", entry: updated };
}

async function addVideoKeyframe(entryId, assetValue, noteValue) {
  const state = await readState();
  const current = normalizeEntryMedia(findEntry(state, entryId));
  const frameId = String(assetValue?.id ?? "").trim();
  if (!frameId || !await getMediaBlob(frameId)) throw new Error("没有读取到关键帧图片");
  let updated = addEntryMedia(current, {
    ...assetValue,
    id: frameId,
    kind: "image",
    storageMode: "managed",
    capturedAt: new Date().toISOString(),
    reviewStatus: "verified"
  });
  if (noteValue) updated = addTimeNote(updated, { ...noteValue, frameAssetId: frameId });
  updated = touchEntry(updated);
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: noteValue ? "当前画面和时间点笔记已保存" : "截图已保存", entry: updated };
}

async function deleteEntryTimeNote(entryId, noteId) {
  const state = await readCaseLibraryState();
  const current = findEntry(state, entryId);
  const next = removeTimeNote(current, noteId);
  const updated = (next.timeNotes ?? []).length === (current.timeNotes ?? []).length ? next : touchEntry(next);
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: "时间点笔记已删除", entry: updated };
}

async function commitCaptureDraft(duplicateAction = "", placementValue = {}, progress = createCaptureSaveProgress()) {
  progress.stage('verify');
  const draft = await captureRuntime.getDraft();
  if (!draft.fragments.length && !draft.visuals.length) return { ok: false, message: "草稿里还没有可保存的文字或截图", draft };
  const state = await readState();
  const targetCompound = normalizeCompoundCases(state.compoundCases, state.entries)
    .find((compound) => compound.id === draft.targetCaseId) ?? null;
  const placement = capturePlacement(draft, placementValue);
  if (targetCompound) return commitCaptureIntoCompound(draft, draftParts(draft), state, targetCompound, placement, placementValue.generationPromptChoices, progress);
  const text = draftText(draft);
  const sourcePages = mergeSourcePages(draftSourcePages(draft), draft.visuals.map((visual) => {
    const context = sourceContextForUrl(draft, visual.sourceUrl);
    return { url: visual.sourceUrl, title: context?.displayTitle || visual.sourceTitle };
  }));
  const firstVisual = draft.visuals[0];
  const sourceUrl = sourcePages[0]?.url || firstVisual?.sourceUrl || "";
  const sourceContext = sourceContextForUrl(draft, sourceUrl);
  const sourceFacts = sourceFactsForCaptureContext(sourceContext);
  const sourceTitle = draft.title || sourceContext?.displayTitle || sourcePages[0]?.title || firstVisual?.sourceTitle || "未命名案例";
  const candidateBase = buildEntry({ text, title: sourceTitle, url: sourceUrl, allowEmptyText: draft.visuals.length > 0 });
  const explicitTarget = draft.targetCaseId
    ? state.entries.find((entryValue) => entryValue.id === draft.targetCaseId) ?? null
    : null;
  if (draft.targetCaseId && !explicitTarget) throw new Error("要继续采集的案例已经不存在");
  const duplicate = !explicitTarget && text ? findDuplicate(state.entries, candidateBase) : null;
  if (duplicate && !["merge", "new"].includes(duplicateAction)) {
    return { ok: false, duplicate: true, existing: { id: duplicate.id, title: duplicate.title }, draft };
  }
  const target = explicitTarget ?? (duplicateAction === "merge" ? duplicate : null);
  let entry;
  let created = false;
  if (target) {
    entry = normalizeEntryVisuals(target);
    const nextText = text && !entry.text.includes(text) ? [entry.text, text].filter(Boolean).join("\n\n") : entry.text;
    entry = {
      ...markEntryTextChanged(entry, nextText),
      sourcePages: mergeSourcePages(entry.sourcePages, sourcePages),
      ...(sourceFacts ? { sourceFacts } : {}),
      customLabels: draft.customLabelsExplicit ? uniqueNames(draft.customLabels) : uniqueNames(entry.customLabels)
    };
    if (draft.contentTypeExplicit && isValidContentPath(state.taxonomy, [draft.contentTypeId])) {
      entry.classification = {
        pathIds: [draft.contentTypeId],
        status: "confirmed",
        source: "manual",
        reason: "保存前人工确认"
      };
    }
    const newVisuals = draft.visuals.filter(asset => !entry.mediaAssets.some(item => item.id === asset.id));
    for (const visual of newVisuals) entry = addEntryVisual(entry, visual);
    entry = normalizeEntryVisuals({ ...entry, mediaPrompts: [...(entry.mediaPrompts ?? []), ...embeddedMediaPrompts(newVisuals, entry.mediaPrompts)] });
    entry.classification = classifyCapturedContent(entry, state.classificationRules, state.taxonomy);
    if (draft.primaryVisualExplicit && draft.primaryVisualId) entry = setPrimaryVisual(entry, draft.primaryVisualId);
  } else {
    created = true;
    entry = normalizeEntryVisuals({
      ...candidateBase,
      schemaVersion: SCHEMA_VERSION,
      title: sourceTitle,
      sourcePages,
      ...(sourceFacts ? { sourceFacts } : {}),
      visuals: draft.visuals,
      mediaPrompts: embeddedMediaPrompts(draft.visuals),
      primaryVisualId: draft.primaryVisualId,
      classification: draft.contentTypeExplicit && isValidContentPath(state.taxonomy, [draft.contentTypeId])
        ? { pathIds: [draft.contentTypeId], status: "confirmed", source: "manual", reason: "保存前人工确认" }
        : captureDraftClassification(draft, state),
      customLabels: uniqueNames(draft.customLabels),
      metadataLabels: [],
      facetAssignments: [], analysisCandidates: [], analysisBreakdown: [], rejectedCandidateKeys: [],
      negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
    });
  }
  const promptPlan = await planImageGenerationPrompts(entry, draft.visuals.filter(asset => !target?.mediaAssets?.some(item => item.id === asset.id)), placementValue.generationPromptChoices);
  if (promptPlan.conflicts.length) { progress.stage('confirm'); return generationPromptConfirmation(promptPlan.conflicts); }
  entry = promptPlan.entry;
  let entries = target
    ? state.entries.map((item) => item.id === entry.id ? entry : item)
    : [...state.entries, entry];
  const organizerState = organizerAfterCapturePlacement(state.organizerState, entries, [entry.id], placement);
  const existingEntryIds = new Set(state.entries.map((item) => item.id));
  const touchedEntryIds = new Set([
    ...(target ? [entry.id] : []),
    ...changedProjectEntryIds(state.organizerState, organizerState).filter((id) => existingEntryIds.has(id))
  ]);
  entries = touchEntries(entries, [...touchedEntryIds]);
  entry = entries.find((item) => item.id === entry.id) ?? entry;
  const nextDraft = createCaptureDraft();
  await progress.commit?.();
  progress.stage('writing');
  await retireLastSaveUndo();
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: entries,
    [STORAGE_KEYS.organizerState]: organizerState,
    ...await captureCommitState(draft, nextDraft),
    ...(created ? { [STORAGE_KEYS.lastSaveUndo]: createEntrySaveUndo(entry) } : {})
  });
  await notifySaved(entries.length);
  return { ok: true, message: target ? "内容已加入明确选择的案例" : "多段文字和截图已保存为新案例", entry, draft: nextDraft };
}

async function commitCaptureIntoCompound(draft, parts, state, targetCompound, placement = {}, choices = {}, progress = createCaptureSaveProgress()) {
  let entries = [...state.entries];
  let compounds = normalizeCompoundCases(state.compoundCases, entries);
  const memberIds = [...targetCompound.memberEntryIds];
  const updatedExistingIds = new Set();
  for (const [index, part] of parts.entries()) {
    progress.stage('verify', { index: index + 1, count: parts.length });
    const partTarget = findCapturePartTarget({
      entries,
      memberIds,
      part,
      preferredEntryId: index === 0 ? draft.targetPartEntryId : ""
    });
    if (partTarget) {
      const updated = mergeCapturePartIntoEntry(partTarget, part, draft, state);
      entries = entries.map((entry) => entry.id === updated.id ? updated : entry);
      updatedExistingIds.add(updated.id);
      continue;
    }
    const created = createEntryFromCapturePart(part, draft, state, {
      title: memberIds.length || index ? part.sourceTitle : draft.title || part.sourceTitle
    });
    entries.push(created);
    memberIds.push(created.id);
  }

  const promptConflicts = [];
  for (let index = 0; index < entries.length; index++) {
    if (!memberIds.includes(entries[index].id)) continue;
    const oldIds = new Set((state.entries.find(item => item.id === entries[index].id)?.mediaAssets ?? []).map(asset => asset.id));
    const plan = await planImageGenerationPrompts(entries[index], (entries[index].mediaAssets ?? []).filter(asset => !oldIds.has(asset.id)), choices);
    entries[index] = plan.entry;
    promptConflicts.push(...plan.conflicts);
  }
  if (promptConflicts.length) { progress.stage('confirm'); return generationPromptConfirmation(promptConflicts); }
  const updated = updateCompoundCase(compounds, entries, targetCompound.id, { memberEntryIds: memberIds });
  compounds = updated.compoundCases;
  const compoundCase = updated.compoundCase;
  const organizerState = organizerAfterCapturePlacement(state.organizerState, entries, compoundCase.memberEntryIds, placement);
  const existingEntryIds = new Set(state.entries.map((entry) => entry.id));
  for (const entryId of changedProjectEntryIds(state.organizerState, organizerState)) {
    if (existingEntryIds.has(entryId)) updatedExistingIds.add(entryId);
  }
  entries = touchEntries(entries, [...updatedExistingIds]);

  const nextDraft = createCaptureDraft();
  await progress.commit?.();
  progress.stage('writing');
  await retireLastSaveUndo();
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: entries,
    [STORAGE_KEYS.compoundCases]: compounds,
    [STORAGE_KEYS.organizerState]: organizerState,
    ...await captureCommitState(draft, nextDraft)
  });
  await notifySaved(entries.length);
  return {
    ok: true,
    message: `内容已加入组合案例 · 共 ${compoundCase.memberEntryIds.length} 个部分`,
    entry: compoundCase,
    compoundCase,
    draft: nextDraft
  };
}

function capturePlacement(draft, value = {}) {
  const hasCollectionId = Object.hasOwn(value, "collectionId");
  const hasNewCollectionName = Object.hasOwn(value, "newCollectionName");
  return {
    collectionId: String(hasCollectionId ? value.collectionId : draft.collectionId ?? "").trim(),
    newCollectionName: String(hasNewCollectionName ? value.newCollectionName : draft.newCollectionName ?? "").trim()
  };
}

function organizerAfterCapturePlacement(organizerValue, entries, entryIds, placement = {}) {
  let organizerState = normalizeOrganizerState(organizerValue, entries.map((entry) => entry.id));
  let collectionId = String(placement.collectionId ?? "").trim();
  const newCollectionName = String(placement.newCollectionName ?? "").trim();
  if (collectionId && newCollectionName) throw new Error("请选择已有项目或新建项目,不要同时填写");
  if (newCollectionName) {
    const created = createCollection(organizerState, newCollectionName);
    organizerState = created.state;
    collectionId = created.item.id;
  }
  if (!collectionId) return organizerState;
  const target = organizerState.collections.find((collection) => collection.id === collectionId);
  if (!target) throw new Error("保存目标项目已经不存在,请重新选择");
  target.entryIds = [...new Set([...target.entryIds, ...entryIds])];
  return normalizeOrganizerState(organizerState, entries.map((entry) => entry.id));
}

async function captureCommitState(draft, nextDraft) {
  const texts = [...draft.fragments.map(fragment => fragment.text), draftText(draft)];
  const candidates = await Promise.all(texts.map(text => createTextCandidate({ clipboard: text })));
  return {
    [STORAGE_KEYS.captureDraft]: nextDraft,
    [CAPTURE_SAVED_TEXT_KEY]: [...new Set(candidates.filter(Boolean).map(candidate => candidate.textFingerprint))]
  };
}

function findCapturePartTarget({ entries, memberIds, part, preferredEntryId }) {
  if (preferredEntryId && memberIds.includes(preferredEntryId)) {
    const preferred = entries.find((entry) => entry.id === preferredEntryId) ?? null;
    if (preferred && (!part.sourceUrl || entryHasSource(preferred, part.sourceUrl))) return preferred;
  }
  if (!part.sourceUrl) return memberIds.length === 1 ? entries.find((entry) => entry.id === memberIds[0]) ?? null : null;
  return entries.find((entry) => memberIds.includes(entry.id) && entryHasSource(entry, part.sourceUrl)) ?? null;
}

function entryHasSource(entry, sourceUrl) {
  return entry.url === sourceUrl || (entry.sourcePages ?? []).some((source) => source.url === sourceUrl);
}

function mergeCapturePartIntoEntry(entryValue, part, draft, state) {
  let entry = normalizeEntryVisuals(entryValue);
  const nextText = part.text && !String(entry.text ?? "").includes(part.text)
    ? [entry.text, part.text].filter(Boolean).join("\n\n")
    : entry.text;
  entry = {
    ...markEntryTextChanged(entry, nextText),
    sourcePages: mergeSourcePages(entry.sourcePages, [{ url: part.sourceUrl, title: part.sourceTitle }]),
    ...(sourceFactsForCaptureContext(part.sourceContext) ? { sourceFacts: sourceFactsForCaptureContext(part.sourceContext) } : {}),
    customLabels: draft.customLabelsExplicit ? uniqueNames(draft.customLabels) : uniqueNames(entry.customLabels)
  };
  if (draft.contentTypeExplicit && isValidContentPath(state.taxonomy, [draft.contentTypeId])) {
    entry.classification = { pathIds: [draft.contentTypeId], status: "confirmed", source: "manual", reason: "保存前人工确认" };
  }
  for (const visual of part.visuals) entry = addEntryVisual(entry, visual);
  if (part.visuals.some((visual) => visual.id === draft.primaryVisualId)) entry = setPrimaryVisual(entry, draft.primaryVisualId);
  return entry;
}

function createEntryFromCapturePart(part, draft, state, options = {}) {
  const sourceTitle = String(options.title || part.sourceTitle || "未命名案例").trim();
  const base = buildEntry({
    text: part.text,
    title: sourceTitle,
    url: part.sourceUrl,
    allowEmptyText: part.visuals.length > 0
  });
  return normalizeEntryVisuals({
    ...base,
    schemaVersion: SCHEMA_VERSION,
    sourcePages: mergeSourcePages([], [{ url: part.sourceUrl, title: part.sourceTitle }]),
    ...(sourceFactsForCaptureContext(part.sourceContext) ? { sourceFacts: sourceFactsForCaptureContext(part.sourceContext) } : {}),
    visuals: part.visuals,
    primaryVisualId: part.visuals.some((visual) => visual.id === draft.primaryVisualId)
      ? draft.primaryVisualId
      : part.visuals[0]?.id || "",
    classification: draft.contentTypeExplicit && isValidContentPath(state.taxonomy, [draft.contentTypeId])
      ? { pathIds: [draft.contentTypeId], status: "confirmed", source: "manual", reason: "保存前人工确认" }
      : classifyCapturedContent({ text: part.text, title: part.sourceTitle, url: part.sourceUrl, visuals: part.visuals, mediaPrompts: embeddedMediaPrompts(part.visuals), sourceFacts: sourceFactsForCaptureContext(part.sourceContext) }, state.classificationRules, state.taxonomy),
    customLabels: uniqueNames(draft.customLabels),
    metadataLabels: [],
    facetAssignments: [], analysisCandidates: [], analysisBreakdown: [], rejectedCandidateKeys: [],
    negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
  });
}

function sourceFactsForCaptureContext(context) {
  const facts = context?.sourceFacts;
  if (!facts || typeof facts !== "object" || !String(facts.provider || facts.itemId || facts.author || "").trim()) return null;
  return facts;
}

function captureDraftClassification(draft, state) {
  const text = draftText(draft);
  const firstSource = draftSourcePages(draft)[0];
  return classifyCapturedContent({
    text,
    sourceFacts: sourceFactsForCaptureContext(sourceContextForUrl(draft, firstSource?.url || draft.visuals[0]?.sourceUrl || "")),
    title: draft.title || firstSource?.title || draft.visuals[0]?.sourceTitle || "",
    url: firstSource?.url || draft.visuals[0]?.sourceUrl || "",
    visuals: draft.visuals,
    mediaPrompts: embeddedMediaPrompts(draft.visuals)
  }, state.classificationRules, state.taxonomy);
}

function mergeSourcePages(leftValue, rightValue) {
  const seen = new Set();
  return [...(Array.isArray(leftValue) ? leftValue : []), ...(Array.isArray(rightValue) ? rightValue : [])].flatMap((item) => {
    const url = String(item?.url ?? "").trim();
    if (!url || seen.has(url)) return [];
    seen.add(url);
    return [{ url, title: String(item?.title ?? "").trim() }];
  });
}

async function undoLastSave() {
  const state = await readState();
  const undo = normalizeLastSaveUndo(state.lastSaveUndo);
  if (!undo) return { ok: false, message: "没有可安全撤回的保存操作" };

  if (undo.type === "delete_created_entry") {
    const removed = state.entries.find((item) => item.id === undo.entryId);
    if (!removed) {
      await libraryStorage.remove(STORAGE_KEYS.lastSaveUndo);
      return { ok: false, message: "这次保存已经不存在,撤回记录已清理" };
    }
    assertCreatedEntryUndoSafe(removed, undo);
    const moved = moveEntriesToTrash({
      entries: state.entries,
      trashState: state.trashState,
      organizerState: state.organizerState,
      compoundCases: state.compoundCases
    }, [removed.id]);
    if (moved.movedItemIds.length !== 1) throw new Error("回收站已有同编号案例,未执行撤回");
    const visionAnalysisUndo = await visionUndoWithout(removed.id);
    await commitLocalChanges({
      [STORAGE_KEYS.entries]: moved.entries,
      [STORAGE_KEYS.trashState]: moved.trashState,
      [STORAGE_KEYS.compoundCases]: moved.compoundCases,
      [STORAGE_KEYS.organizerState]: moved.organizerState,
      [STORAGE_KEYS.visionAnalysisUndo]: visionAnalysisUndo
    });
    await libraryStorage.remove(STORAGE_KEYS.lastSaveUndo);
    return { ok: true, message: "已撤回刚才保存的案例,可在回收站恢复", removed, count: moved.entries.length };
  }

  const current = state.entries.find((item) => item.id === undo.entryId);
  if (!current) {
    await discardSaveUndoBackup(undo).catch(() => undefined);
    await libraryStorage.remove(STORAGE_KEYS.lastSaveUndo);
    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 libraryStorage.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) {
    restoredScreenshot = await undoScreenshotReplacement(current.id, { backupEntryId: undo.backupEntryId });
  } else {
    await deleteScreenshotBlob(current.id);
  }
  const entries = state.entries.map((item) => item.id === updated.id ? updated : item);
  try {
    await commitLocalChanges(
      { [STORAGE_KEYS.entries]: entries },
      { dirtyAssetIds: [current.id] }
    );
  } catch (error) {
    if (replacedScreenshot) await saveScreenshotBlob(current.id, replacedScreenshot).catch(() => undefined);
    if (restoredScreenshot) {
      await saveScreenshotBlob(undo.backupEntryId, restoredScreenshot).catch(() => undefined);
    }
    throw error;
  }
  await libraryStorage.remove(STORAGE_KEYS.lastSaveUndo);
  return { ok: true, message: "已恢复原案例更新前的截图与图片分析", entry: updated, count: entries.length };
}

async function deleteEntry(entryId) {
  const state = await readState();
  const entry = findEntry(state, entryId);
  return moveEntryBatchToTrash([entry.id], state);
}

async function deleteCollectionWithEntries(message) {
  const state = await readState();
  const organizerState = normalizeOrganizerState(state.organizerState, state.entries.map((entry) => entry.id));
  const collection = organizerState.collections.find((item) => item.id === String(message.collectionId ?? "").trim());
  if (!collection) throw new Error("项目不存在");
  if (String(message.confirmationName ?? "").trim() !== collection.name) throw new Error("项目名称不匹配,未执行删除");
  if (!collectionEntryIds(organizerState, collection.id, { subtree: true }).length) {
    throw new Error("这个项目及其子项目没有可删除的案例");
  }
  const moved = moveCollectionWithEntriesToTrash({
    entries: state.entries,
    trashState: state.trashState,
    organizerState,
    compoundCases: state.compoundCases
  }, collection.id);
  const visionAnalysisUndo = await visionUndoWithoutEntries(new Set(moved.movedEntryIds));
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: moved.entries,
    [STORAGE_KEYS.trashState]: moved.trashState,
    [STORAGE_KEYS.compoundCases]: moved.compoundCases,
    [STORAGE_KEYS.organizerState]: moved.organizerState,
    [STORAGE_KEYS.visionAnalysisUndo]: visionAnalysisUndo
  });
  return {
    ok: true,
    message: `项目“${collection.name}”及其中 ${moved.movedEntryIds.length} 个案例已移入回收站`,
    movedEntryCount: moved.movedEntryIds.length,
    movedItemIds: moved.movedItemIds,
    ...publicDomainState({
      ...state,
      entries: moved.entries,
      trashState: moved.trashState,
      organizerState: moved.organizerState,
      compoundCases: moved.compoundCases
    })
  };
}


async function moveEntryBatchToTrash(entryIdsValue, stateValue) {
  const state = stateValue ?? await readState();
  const activeIds = new Set(state.entries.map((entry) => entry.id));
  const entryIds = uniqueNames(entryIdsValue).filter((entryId) => activeIds.has(entryId));
  if (!entryIds.length) return { ok: false, message: "没有找到可移入回收站的案例" };
  const moved = moveEntriesToTrash({
    entries: state.entries,
    trashState: state.trashState,
    organizerState: state.organizerState,
    compoundCases: state.compoundCases
  }, entryIds);
  const visionAnalysisUndo = await visionUndoWithoutEntries(new Set(entryIds));
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: moved.entries,
    [STORAGE_KEYS.trashState]: moved.trashState,
    [STORAGE_KEYS.organizerState]: moved.organizerState,
    [STORAGE_KEYS.compoundCases]: moved.compoundCases,
    [STORAGE_KEYS.visionAnalysisUndo]: visionAnalysisUndo
  });
  return {
    ok: true,
    message: moved.movedItemIds.length === 1
      ? "案例已移入回收站"
      : `${moved.movedItemIds.length} 个案例已移入回收站`,
    movedEntryIds: entryIds,
    movedItemIds: moved.movedItemIds,
    ...publicDomainState({ ...state, ...moved })
  };
}

async function getTrashItems(message = {}) {
  const stored = await libraryStorage.get(STORAGE_KEYS.trashState);
  const trashState = normalizeTrashState(stored[STORAGE_KEYS.trashState]);
  const items = listTrashItems(trashState, { kind: message.kind });
  return { ok: true, items, count: items.length, trashState };
}

async function restoreSelectedTrashItems(message = {}) {
  const state = await readState();
  const restored = restoreTrashItems({
    entries: state.entries,
    trashState: state.trashState,
    organizerState: state.organizerState,
    compoundCases: state.compoundCases
  }, message.itemIds, { collectionReplacements: message.collectionReplacements });
  if (!restored.restoredItemIds.length) {
    return {
      ok: false,
      message: restored.unresolved[0]?.reason || "没有找到可恢复的内容",
      unresolved: restored.unresolved,
      trashState: restored.trashState
    };
  }
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: restored.entries,
    [STORAGE_KEYS.trashState]: restored.trashState,
    [STORAGE_KEYS.organizerState]: restored.organizerState,
    [STORAGE_KEYS.compoundCases]: restored.compoundCases
  });
  const unresolvedMessage = restored.unresolved.length ? `;另有 ${restored.unresolved.length} 项因关系冲突未恢复` : "";
  const warningMessage = restored.warnings?.length ? `;${restored.warnings[0].reason}` : "";
  return {
    ok: true,
    message: `已恢复 ${restored.restoredItemIds.length} 项${unresolvedMessage}${warningMessage}`,
    restoredItemIds: restored.restoredItemIds,
    unresolved: restored.unresolved,
    warnings: restored.warnings ?? [],
    ...publicDomainState({ ...state, ...restored })
  };
}

async function permanentlyDeleteTrashItems(message = {}) {
  reportTrashCleanupProgress("checking");
  const state = await readTrashCleanupState();
  return commitTrashCleanup(planTrashCleanup(state, message.itemIds ?? [], await trashCleanupActiveAssetIds()));
}

async function emptyTrashAction() {
  reportTrashCleanupProgress("checking");
  const state = await readTrashCleanupState();
  // The cleanup planner validates snapshots; collecting IDs needs no deep copy.
  const ids = (state.trashState?.items ?? []).map(item => String(item?.id ?? "").trim());
  return commitTrashCleanup(planTrashCleanup(state, ids, await trashCleanupActiveAssetIds()));
}

async function withTrashCleanupProgress(task) {
  try { return await task(); }
  finally { reportTrashCleanupProgress(null); }
}

function reportTrashCleanupProgress(phase) {
  trashCleanupProgress = phase ? { phase } : null;
  void chrome.runtime.sendMessage({ type: "TRASH_CLEANUP_PROGRESS", progress: trashCleanupProgress }).catch(() => undefined);
}

async function readTrashCleanupState() {
  const keys = ['schemaVersion', 'entries', 'trashState', 'creativeRuns', 'creativeSkills',
    'composerSessions', 'creativeJobs', 'importStaging', ...TRASH_HISTORY_KEYS];
  const version = (await libraryStorage.get('schemaVersion')).schemaVersion;
  if (version !== SCHEMA_VERSION) await readState();
  // No view models, AI settings or duplicate recovery reads for physical cleanup.
  return libraryStorage.getSnapshot(keys);
}

async function trashCleanupActiveAssetIds() {
  return [...activeCaptureAssetIds, ...await agentTransfers.retainedIds(), ...await stagedMedia.retainedIds()];
}

async function commitTrashCleanup(taken) {
  if (!taken.takenItems.length) return { ok: false, message: "回收站中没有可永久删除的内容" };
  const stored = await libraryStorage.get(TRASH_CLEANUP_KEY);
  const previous = stored[TRASH_CLEANUP_KEY] ?? {};
  const pending = {
    mediaIds: [...new Set([...(previous.mediaIds ?? []), ...taken.cleanup.mediaIds])],
    localReferenceIds: [...new Set([...(previous.localReferenceIds ?? []), ...taken.cleanup.localReferenceIds])],
    screenshotEntryIds: [...new Set([...(previous.screenshotEntryIds ?? []), ...taken.cleanup.screenshotEntryIds])]
  };
  // Commit deletion intent with metadata: interruption cannot orphan the cleanup work.
  // This journal stores IDs only; it cannot restore a permanently deleted case.
  reportTrashCleanupProgress("committing");
  await commitLocalChanges({ ...taken.changes, [TRASH_CLEANUP_KEY]: pending });
  const cleanup = await resumeTrashCleanup();
  return {
    ...cleanup,
    message: cleanup.ok ? `已永久删除 ${taken.takenItems.length} 项` : cleanup.message,
    permanentlyDeletedItemIds: taken.takenItems.map(item => item.id),
    trashState: taken.trashState
  };
}

async function resumeTrashCleanup() {
  const stored = await libraryStorage.get(TRASH_CLEANUP_KEY);
  const pending = stored[TRASH_CLEANUP_KEY];
  if (!pending) return { ok: true, deletedMediaCount: 0 };
  reportTrashCleanupProgress("checking");
  const state = await readTrashCleanupState();
  const retained = retainedTrashCleanupAssets(state, await trashCleanupActiveAssetIds());
  const mediaIds = pending.mediaIds.filter(id => !retained.has(id));
  const localReferenceIds = pending.localReferenceIds.filter(id => !retained.has(id));
  const entryIds = new Set(state.entries.map(entry => entry.id));
  const screenshotEntryIds = pending.screenshotEntryIds.filter(id => !entryIds.has(id));
  try {
    reportTrashCleanupProgress("deleting");
    await deleteMediaBlobs(mediaIds);
    // Linked originals stay at their user-owned location; remove only the local handle.
    await deleteLocalAssetHandles(localReferenceIds);
    if (screenshotEntryIds.length) await libraryStorage.remove(screenshotEntryIds.map(screenshotStorageKey));
    reportTrashCleanupProgress("finishing");
    await libraryStorage.remove(TRASH_CLEANUP_KEY);
    return { ok: true, deletedMediaCount: mediaIds.length, failedMediaCount: 0 };
  } catch (error) {
    console.warn('永久删除文件清理未完成', error);
    return { ok: false, failedMediaCount: mediaIds.length,
      message: "案例已永久删除,但文件清理未完成;下次启动插件时会继续释放空间" };
  }
}

function enqueue(task) {
  const operation = writeQueue.then(task, task);
  writeQueue = operation.catch(() => undefined);
  return operation;
}

function withAnalysisTaskStorageLock(task) {
  if (globalThis.navigator?.locks?.request) {
    return navigator.locks.request(ANALYSIS_TASK_STORAGE_LOCK, task);
  }
  return task();
}

function enqueueCapture(task) {
  const operation = captureWriteQueue.then(task, task);
  captureWriteQueue = operation.catch(() => undefined);
  return operation;
}

async function restrictLocalStorageAccess() {
  if (typeof chrome.storage?.local?.setAccessLevel !== "function") return;
  await chrome.storage.local.setAccessLevel({ accessLevel: "TRUSTED_CONTEXTS" });
}

async function retireLastSaveUndo(options = {}) {
  const stored = await libraryStorage.get(STORAGE_KEYS.lastSaveUndo);
  const undo = normalizeLastSaveUndo(stored[STORAGE_KEYS.lastSaveUndo]);
  const preserveCurrentFixedBackup = undo?.type === "restore_replaced_screenshot" &&
    undo.entryId === options.preserveBackupEntryId &&
    undo.backupEntryId === `backup:${undo.entryId}`;
  if (undo?.type === "restore_replaced_screenshot" && !preserveCurrentFixedBackup) {
    await discardSaveUndoBackup(undo).catch(() => undefined);
  }
  await libraryStorage.remove(STORAGE_KEYS.lastSaveUndo);
}

async function discardSaveUndoBackup(undoValue) {
  const undo = normalizeLastSaveUndo(undoValue);
  if (undo?.type !== "restore_replaced_screenshot") return;
  await discardScreenshotReplacementBackup(undo.entryId, { backupEntryId: undo.backupEntryId });
}

// Only the library records a migration rewrites. Other recovery copies are not nested inside, so a
// backup per upgrade does not grow with every version.
const MIGRATION_BACKUP_KEYS = Object.freeze(["schemaVersion", "entries", "trashState", "compoundCases", "taxonomy",
  "facetCatalog", "classificationRules", "organizerState", "settings", "tagCatalog"]);
function migrationBackupSnapshot(stored) {
  return {
    fromSchemaVersion: Number.isInteger(stored.schemaVersion) ? stored.schemaVersion : null,
    toSchemaVersion: SCHEMA_VERSION,
    createdAt: new Date().toISOString(),
    state: structuredClone(Object.fromEntries(MIGRATION_BACKUP_KEYS.filter(key => stored[key] !== undefined).map(key => [key, stored[key]])))
  };
}

async function readState() {
  const doneReading = startPhase("background", "readState");
  const stored = await libraryStorage.get([...Object.values(STORAGE_KEYS), "tagCatalog"]);
  doneReading({ bytes: () => jsonBytes(stored) });
  // Checked before any repair or migration write: a newer library is left exactly as it is.
  if (libraryFromNewerVersion(stored)) throw newerLibraryError();
  const aiConfiguration = aiConfigurationFromStorage(stored);
  const aiStorageOutdated = aiConfigurationNeedsStorageUpdate(stored, aiConfiguration);
  if (aiStorageOutdated) {
    await commitLocalChanges({
      [STORAGE_KEYS.aiProviderRegistry]: aiConfiguration.registry,
      [STORAGE_KEYS.aiTaskAssignments]: aiConfiguration.assignments,
      [STORAGE_KEYS.aiPreferences]: aiConfiguration.preferences
    });
    stored[STORAGE_KEYS.aiProviderRegistry] = aiConfiguration.registry;
    stored[STORAGE_KEYS.aiTaskAssignments] = aiConfiguration.assignments;
    stored[STORAGE_KEYS.aiPreferences] = aiConfiguration.preferences;
  }
  const shouldMigrate = needsMigration(stored);
  if (stateMigration) {
    await stateMigration;
    return readState();
  }
  const migration = shouldMigrate ? migrateLibraryState(stored) : null;
  const lostCaseIds = migration ? casesLostByMigration(stored, migration.state) : [];
  if (lostCaseIds.length) {
    // Nothing has been written yet; the library stays exactly as stored until a fixed version runs.
    throw Object.assign(new Error(`升级检查发现 ${lostCaseIds.length} 个案例会丢失,已停止升级;资料没有改动`),
      { code: "MIGRATION_WOULD_LOSE_CASES", lostEntryIds: lostCaseIds.slice(0, 20) });
  }
  let state = migration?.state ?? {
    schemaVersion: SCHEMA_VERSION,
    entries: stored[STORAGE_KEYS.entries],
    trashState: stored[STORAGE_KEYS.trashState],
    compoundCases: stored[STORAGE_KEYS.compoundCases],
    taxonomy: stored[STORAGE_KEYS.taxonomy],
    facetCatalog: stored[STORAGE_KEYS.facetCatalog],
    classificationRules: stored[STORAGE_KEYS.classificationRules],
    organizerState: stored[STORAGE_KEYS.organizerState],
    settings: stored[STORAGE_KEYS.settings]
  };
  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;
    }
    // Every schema upgrade also keeps the library exactly as it was before that upgrade, replacing
    // the copy from the previous upgrade; the first-ever backup above is never replaced, and
    // repairs within one version keep the existing upgrade copy.
    const upgrading = !Number.isInteger(stored.schemaVersion) || stored.schemaVersion < SCHEMA_VERSION;
    if (upgrading || !stored[STORAGE_KEYS.upgradeBackup]) update[STORAGE_KEYS.upgradeBackup] = migrationBackupSnapshot(stored);
    if (migration.resetPerformed && !stored[STORAGE_KEYS.facetMigrationBackup]) {
      update[STORAGE_KEYS.facetMigrationBackup] = migration.backup;
    }
    if (migration.resetPerformed && !stored[STORAGE_KEYS.classificationResetBackup]) {
      update[STORAGE_KEYS.classificationResetBackup] = migration.backup;
    }
    stateMigration = commitLocalChanges(update);
    try { await stateMigration; }
    finally { stateMigration = null; }
    await libraryStorage.remove("tagCatalog");
  }
  // A new required content type can arrive within the same data schema. Repair
  // only the small type catalog; do not remigrate cases or reset custom types.
  const currentTaxonomy = normalizeTaxonomy(state.taxonomy);
  if (!sameUndoState(currentTaxonomy, state.taxonomy)) {
    state = { ...state, taxonomy: currentTaxonomy };
    await commitLocalChanges({ [STORAGE_KEYS.taxonomy]: currentTaxonomy });
  }
  const recoveredVocabulary = recoverFullyArchivedFacets(state.facetCatalog);
  if (recoveredVocabulary.restoredFacetIds.length) {
    state = { ...state, facetCatalog: recoveredVocabulary.catalog };
    await commitLocalChanges({ [STORAGE_KEYS.facetCatalog]: state.facetCatalog });
    await libraryStorage.remove(STORAGE_KEYS.facetUndo);
    stored[STORAGE_KEYS.facetUndo] = null;
  }
  const composerSessions = normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions]);
  if (!sameUndoState(stored[STORAGE_KEYS.composerSessions] ?? [], composerSessions)) {
    await libraryStorage.update('composerSessions', latest => ({ composerSessions: normalizeComposerSessions(latest.composerSessions) }));
  }
  const creativeRuns = normalizeCreativeRuns(stored[STORAGE_KEYS.creativeRuns]);
  const creativeJobs = normalizeCreativeJobsState(stored[STORAGE_KEYS.creativeJobs]);
  const importStaging = normalizeImportStagingState(stored[STORAGE_KEYS.importStaging]);
  const creativeSkills = normalizeCreativeSkillsState(stored[STORAGE_KEYS.creativeSkills]);
  const creativeExperimentSettings = normalizeCreativeExperimentSettings(stored[STORAGE_KEYS.creativeExperimentSettings]);
  const activeCreativeResult = normalizeActiveCreativeResult(stored[STORAGE_KEYS.activeCreativeResult]);
  const syncSettings = normalizeSyncSettings(stored[STORAGE_KEYS.syncSettings]);
  if (!stored[STORAGE_KEYS.batchJob] && stored[STORAGE_KEYS.legacyAnalysisBatchJob]) {
    const migratedBatch = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.legacyAnalysisBatchJob]);
    if (migratedBatch) {
      stored[STORAGE_KEYS.batchJob] = migratedBatch;
      await commitLocalChanges({ [STORAGE_KEYS.batchJob]: migratedBatch });
    }
    await libraryStorage.remove(STORAGE_KEYS.legacyAnalysisBatchJob);
  }
  const normalizedCreativeStorage = {
    [STORAGE_KEYS.creativeRuns]: creativeRuns,
    [STORAGE_KEYS.creativeJobs]: creativeJobs,
    [STORAGE_KEYS.creativeExperimentSettings]: creativeExperimentSettings,
    [STORAGE_KEYS.activeCreativeResult]: activeCreativeResult
  };
  const creativeNormalizationUpdate = Object.fromEntries(
    Object.entries(normalizedCreativeStorage)
      .filter(([key, value]) => JSON.stringify(stored[key]) !== JSON.stringify(value))
  );
  if (Object.keys(creativeNormalizationUpdate).length) {
    await commitLocalChanges(creativeNormalizationUpdate, { markSyncDirty: false });
  }
  return {
    ...projectLibraryViewState({ ...stored, ...state }, {
      aiConfiguration,
      uiLanguage: chrome.i18n.getUILanguage(),
      syncStatus: await publicSyncStatus(syncSettings),
      restoredArchivedFacetCount: recoveredVocabulary.restoredFacetIds.length
    }),
    composerSessions,
    composerSessionSummaries: composerSessions.map(sessionSummary),
    creativeRuns,
    creativeJobs,
    importStaging,
    creativeSkills,
    activeCreativeResult,
    folderOwnershipBackup: stored[STORAGE_KEYS.folderOwnershipBackup],
    libraryReplacementRecoveryPoint: normalizeLibraryReplacementRecoveryPoint(stored[STORAGE_KEYS.libraryReplacementRecoveryPoint]),
    migrationBackupExists: Boolean(stored[STORAGE_KEYS.facetMigrationBackup] || stored[STORAGE_KEYS.migrationBackup] || shouldMigrate),
    facetUndo: stored[STORAGE_KEYS.facetUndo] ?? null,
    lastSaveUndo: normalizeLastSaveUndo(stored[STORAGE_KEYS.lastSaveUndo])
  };
}

async function saveComposerToolDraftAction(message) {
  const keys = [STORAGE_KEYS.composerSessions, STORAGE_KEYS.creativeSkills, STORAGE_KEYS.entries];
  const stored = await libraryStorage.get(keys);
  const state = { composerSessions: normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions]),
    creativeSkills: stored[STORAGE_KEYS.creativeSkills], entries: stored[STORAGE_KEYS.entries] };
  const result = saveComposerToolDraft(state, message);
  await commitLocalChanges({ [STORAGE_KEYS.composerSessions]: result.composerSessions,
    [STORAGE_KEYS.creativeSkills]: result.creativeSkills, [STORAGE_KEYS.entries]: result.entries });
  return {ok:true, session:result.composerSessions.find(item=>item.id===message.sessionId)};
}

async function createCreativeSkillAction(message) {
  const stored = await libraryStorage.get(STORAGE_KEYS.creativeSkills);
  const result = createCreativeSkill(stored[STORAGE_KEYS.creativeSkills], message.skill);
  await commitSkillCoverResult(result, message.cover);
  return { ok: true, message: "Skill 已保存", creativeSkills: result.state, skill: result.skill };
}

async function saveCreativeSkillVersionAction(message) {
  const stored = await libraryStorage.get(['creativeSkills', 'composerSessions', 'creativeRuns', 'creativeJobs']);
  const current = normalizeCreativeSkillsState(stored.creativeSkills).items.find(skill => skill.id === message.skillId);
  if (message.expectedRevision && await skillRevision(current) !== message.expectedRevision) throw new Error("Skill 已变化,请重新打开后再编辑");
  const result = saveCreativeSkillVersion(stored[STORAGE_KEYS.creativeSkills], message.skillId, message.version, { protectedVersionIds: protectedSkillVersionIds(stored) });
  await commitSkillCoverResult(result, message.cover);
  await deleteUnreferencedMedia(normalizeCreativeSkillsState(stored[STORAGE_KEYS.creativeSkills]).items.flatMap(skillPackageAssetIds)).catch(error => console.warn("Skill资源清理未完成", error));
  return { ok: true, message: message.version?.coverOnly ? "Skill 已保存" : "Skill 新版本已保存", creativeSkills: result.state, skill: result.skill };
}

async function commitSkillCoverResult(result, cover) {
  return commitSkillWithCover(result, cover, {
    readBlob: getMediaBlob,
    saveBlob: savePortableAssetBlob,
    commit: state => commitLocalChanges({ [STORAGE_KEYS.creativeSkills]: state }),
    cleanup: deleteUnreferencedMedia,
    decode: async blob => { const bitmap = await createImageBitmap(blob); bitmap.close(); },
    onCleanupError: error => console.warn("Skill 封面资源清理未完成", error)
  });
}

async function restoreCreativeSkillVersionAction(message) {
  const stored = await libraryStorage.get(['creativeSkills', 'composerSessions', 'creativeRuns', 'creativeJobs']);
  const before = normalizeCreativeSkillsState(stored[STORAGE_KEYS.creativeSkills]).items.find(item => item.id === message.skillId);
  const source = before?.versions.find(item => item.id === message.versionId);
  const filesKnown = source?.id === before?.currentVersionId || Array.isArray(source?.packageFiles);
  const result = restoreCreativeSkillVersion(stored[STORAGE_KEYS.creativeSkills], message.skillId, message.versionId, { protectedVersionIds: protectedSkillVersionIds(stored) });
  await commitLocalChanges({ [STORAGE_KEYS.creativeSkills]: result.state });
  await deleteUnreferencedMedia(normalizeCreativeSkillsState(stored[STORAGE_KEYS.creativeSkills]).items.flatMap(skillPackageAssetIds)).catch(error => console.warn("Skill资源清理未完成", error));
  return { ok: true, message: filesKnown ? "已将所选版本恢复为新的当前版本" : "已恢复文字版本;此旧版本没有文件记录,当前包文件保留", creativeSkills: result.state, skill: result.skill };
}

async function deleteCreativeSkillAction(skillId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.creativeSkills);
  const result = deleteCreativeSkill(stored[STORAGE_KEYS.creativeSkills], skillId);
  await commitLocalChanges({ [STORAGE_KEYS.creativeSkills]: result.state });
  await deleteUnreferencedMedia(skillPackageAssetIds(result.skill)).catch(error => console.warn("Skill 资源清理未完成", error));
  return { ok: true, message: "Skill 已删除", creativeSkills: result.state };
}

async function getComposerSession(sessionId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.composerSessions);
  const value = (Array.isArray(stored[STORAGE_KEYS.composerSessions]) ? stored[STORAGE_KEYS.composerSessions] : []).find(item => item.id === sessionId);
  const session = value && createComposerSession(value);
  return session ? { ok: true, session } : { ok: false, message: "没有找到这份创作草稿" };
}

async function saveAssistantDraft(chat) {
  let response;
  await libraryStorage.update([COMPOSER_DRAFTS_KEY, 'assistantChatViews', 'composerSessionSummaries', 'syncMeta'], stored => {
    const result = assistantDraftUpdate(stored, chat, new Date().toISOString());
    response = result.response;
    return result.update ? { ...result.update, ...(!syncApplyInProgress ? {syncMeta:markSyncMetaDirty(stored.syncMeta)} : {}) } : {};
  });
  return response;
}

async function getAssistantChats(activeId, includeDiagnostics = false) {
  if (!includeDiagnostics) {
    let stored = await libraryStorage.get(['assistantChatViews', 'captureAssistantDialog']);
    if (stored.captureAssistantDialog?.schema === 'shared-chat') {
      if (stored.assistantChatViews?.version !== 1) {
        // One-time projection for existing installs; build under the writer
        // lock so a concurrent chat edit cannot publish an obsolete view.
        await libraryStorage.update('composerSessions', latest => ({assistantChatViews: assistantChatViews(latest.composerSessions)}));
        stored = await libraryStorage.get('assistantChatViews');
      }
      const chats = [...stored.assistantChatViews.chats].sort((a,b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
      const recent = chats.slice(0,5), active = chats.find(chat => chat.id === activeId);
      if (active && !recent.includes(active)) recent.splice(4,1,active);
      return {ok:true,chats:recent};
    }
  }
  const stored = await libraryStorage.get(['composerSessions', 'captureAssistantDialog']);
  let sessions = normalizeComposerSessions(stored.composerSessions);
  if (stored.captureAssistantDialog?.schema !== 'shared-chat') {
    const old = restoreCaptureSessions(stored.captureAssistantDialog || {});
    const migrated = [...old.history,...old.conversations].map(chat => assistantChatSession(chat)).filter(isMeaningfulComposerSession);
    if (migrated.length) {
      const {libraryId} = await libraryIdentity.read();
      const keys = migrated.map(session => `captureAssistantRuntime:${libraryId}:${session.id}`);
      const contexts = await libraryStorage.get(keys);
      migrated.forEach((session,index) => {
        const context = contexts[keys[index]];
        if (context) Object.assign(session,{toolContext:context.toolContext || [],toolContinuations:context.toolContinuations || {},toolSkillVersionIds:context.toolSkillVersionIds || []});
        session.chatRevision = Math.max(1,session.chatRevision);
      });
    }
    await libraryStorage.update(['composerSessions','captureAssistantDialog','syncMeta'], latest => {
      sessions = normalizeComposerSessions(latest.composerSessions);
      if (latest.captureAssistantDialog?.schema === 'shared-chat') return {};
      sessions = normalizeComposerSessions([...sessions,...migrated.filter(session => !sessions.some(current => current.id === session.id))]);
      return {composerSessions:sessions,captureAssistantDialog:{schema:'shared-chat',pages:old.pages,activeId:old.activeId,activeUrl:old.activeUrl},
        ...(!syncApplyInProgress ? {syncMeta:markSyncMetaDirty(latest.syncMeta)} : {})};
    });
  }
  const recent = sessions.slice(0, 5);
  const active = sessions.find(session => session.id === activeId);
  if (active && !recent.includes(active)) recent.splice(4, 1, active);
  return { ok: true, chats: recent.map(session => assistantChatView(session, {includeDiagnostics})) };
}

async function startCreativeJobAction(request, jobId) {
  const hasVideo = (request?.session?.referenceSnapshots ?? []).some((reference) =>
    (reference.assetRefs ?? []).some((asset) => asset.kind === "video"));
  if (!["create_image", "create_video"].includes(request?.session?.outputMode) && !hasVideo) {
    return { ok: false, message: "后台持久任务用于媒体创作与视频对话" };
  }
  const stored = await libraryStorage.get([
    STORAGE_KEYS.creativeJobs,
    STORAGE_KEYS.composerSessions
  ]);
  const created = createCreativeJob(stored[STORAGE_KEYS.creativeJobs], request, { id: jobId });
  const sessions = upsertSessionList(stored[STORAGE_KEYS.composerSessions], created.job.request.session);
  await commitLocalChanges({
    [STORAGE_KEYS.creativeJobs]: created.state,
    [STORAGE_KEYS.composerSessions]: sessions
  });
  try {
    await dispatchCreativeJob(created.job);
  } catch (error) {
    await failCreativeJobAction({
      jobId: created.job.id,
      error: { kind: "service", message: userMessage(error), retryable: true }
    });
    return { ok: false, message: userMessage(error), job: creativeJobById(created.state, created.job.id) };
  }
  return { ok: true, message: "创作任务已在后台开始", job: created.job };
}

async function getCreativeJobAction(jobId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.creativeJobs);
  const creativeJobs = normalizeCreativeJobsState(stored[STORAGE_KEYS.creativeJobs]);
  const job = String(jobId ?? "").trim()
    ? creativeJobById(creativeJobs, jobId)
    : activeCreativeJob(creativeJobs) ?? creativeJobs.items.at(-1) ?? null;
  return { ok: true, job, creativeJobs };
}

async function retryCreativeJobAction(jobId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.creativeJobs);
  const retried = retryCreativeJob(stored[STORAGE_KEYS.creativeJobs], jobId);
  await commitLocalChanges({ [STORAGE_KEYS.creativeJobs]: retried.state });
  try {
    await dispatchCreativeJob(retried.job);
  } catch (error) {
    await failCreativeJobAction({
      jobId: retried.job.id,
      error: { kind: "service", message: userMessage(error), retryable: true }
    });
    return { ok: false, message: userMessage(error), job: retried.job };
  }
  return { ok: true, message: "创作任务已重新开始", job: retried.job };
}

async function updateCreativeJobProgress(message) {
  const stored = await libraryStorage.get([
    STORAGE_KEYS.creativeJobs,
    STORAGE_KEYS.composerSessions
  ]);
  const current = creativeJobById(stored[STORAGE_KEYS.creativeJobs], message.jobId);
  if (!current || !["queued", "running"].includes(current.status)) {
    return { ok: false, message: "创作任务已经结束" };
  }
  const creativeJobs = updateCreativeJob(stored[STORAGE_KEYS.creativeJobs], current.id, {
    status: "running",
    phase: message.phase,
    actualStages: message.actualStages,
    executionState: current.executionState === "stop_requested" ? "stop_requested" : "running",
    providerMayHaveAccepted: message.providerMayHaveAccepted === true,
    ...(message.remoteVideo ? { remoteVideo: message.remoteVideo } : {})
  });
  const update = { [STORAGE_KEYS.creativeJobs]: creativeJobs };
  if (message.session) {
    const session = createComposerSession(message.session);
    if (session.id !== current.sessionId) return { ok: false, message: "创作任务与对话不匹配" };
    update[STORAGE_KEYS.composerSessions] = upsertSessionList(stored[STORAGE_KEYS.composerSessions], session);
  }
  await commitLocalChanges(update);
  return { ok: true, job: creativeJobById(creativeJobs, current.id) };
}

async function creativeJobExecutionState() {
  const stored = await libraryStorage.get([
    STORAGE_KEYS.entries,
    STORAGE_KEYS.compoundCases,
    STORAGE_KEYS.facetCatalog,
    STORAGE_KEYS.composerSettings,
    STORAGE_KEYS.aiProviderRegistry,
    STORAGE_KEYS.aiTaskAssignments,
    STORAGE_KEYS.aiPreferences
  ]);
  const aiRuntime = projectAiRuntime(aiConfigurationFromStorage(stored));
  return {
    ok: true,
    aiRuntimeProtocolVersion: AI_RUNTIME_PROTOCOL_VERSION,
    entries: stored[STORAGE_KEYS.entries],
    compoundCases: stored[STORAGE_KEYS.compoundCases],
    facetCatalog: stored[STORAGE_KEYS.facetCatalog],
    composerSettings: stored[STORAGE_KEYS.composerSettings],
    aiSettings: aiRuntime.aiSettings,
    visionSettings: aiRuntime.visionSettings,
    aiServiceProfiles: aiRuntime.aiServiceProfiles,
    aiTaskAssignments: aiRuntime.aiTaskAssignments
  };
}

async function completeCreativeJobAction(message) {
  const stored = await libraryStorage.get([
    STORAGE_KEYS.creativeJobs,
    STORAGE_KEYS.composerSessions,
    STORAGE_KEYS.creativeRuns
  ]);
  const current = creativeJobById(stored[STORAGE_KEYS.creativeJobs], message.jobId);
  if (!current || current.status !== "running") return { ok: false, message: "创作任务已经结束" };
  const session = createComposerSession(message.session);
  if (session.id !== current.sessionId) return { ok: false, message: "创作任务与对话不匹配" };
  const visuals = Array.isArray(message.visuals) ? message.visuals : [];
  for (const visual of visuals) {
    const id = String(visual?.id ?? "").trim();
    const video = visual?.kind === "video" || String(visual?.mimeType ?? "").startsWith("video/");
    const blob = id ? video ? await getMediaBlob(id) : await getScreenshotBlob(id) : null;
    if (!blob || !blob.type.startsWith(video ? "video/" : "image/") || !blob.size) {
      return { ok: false, message: `有一项生成${video ? "视频" : "图片"}没有完整写入本地存储` };
    }
  }

  let creativeRuns = normalizeCreativeRuns(stored[STORAGE_KEYS.creativeRuns]);
  if (visuals.length) {
    const promptVersionId = session.promptVersions.at(-1)?.id;
    if (!promptVersionId) return { ok: false, message: "生成媒体缺少对应的提示词版本" };
    let run = creativeRuns.find((item) => item.sessionId === session.id && item.promptVersionId === promptVersionId);
    if (run) {
      for (const visual of visuals) run = addCreativeOutput(run, visual, undefined, message.generation);
      creativeRuns = [run, ...creativeRuns.filter((item) => item.id !== run.id)];
    } else {
      run = createCreativeRun({ sessionId: session.id, promptVersionId }, session, visuals, undefined, message.generation);
      creativeRuns = [run, ...creativeRuns];
    }
    creativeRuns = normalizeCreativeRuns(creativeRuns);
  }
  const creativeJobs = updateCreativeJob(stored[STORAGE_KEYS.creativeJobs], current.id, {
    status: "completed",
    phase: "completed",
    error: null
  });
  await commitLocalChanges({
    [STORAGE_KEYS.creativeJobs]: creativeJobs,
    [STORAGE_KEYS.composerSessions]: upsertSessionList(stored[STORAGE_KEYS.composerSessions], session),
    [STORAGE_KEYS.creativeRuns]: creativeRuns
  });
  await cleanupCreativeJobMask(current);
  return { ok: true, job: creativeJobById(creativeJobs, current.id), creativeRuns };
}

async function failCreativeJobAction(message) {
  const stored = await libraryStorage.get([
    STORAGE_KEYS.creativeJobs,
    STORAGE_KEYS.composerSessions
  ]);
  const current = creativeJobById(stored[STORAGE_KEYS.creativeJobs], message.jobId);
  if (!current || !["queued", "running"].includes(current.status)) {
    return { ok: false, message: "创作任务已经结束" };
  }
  const details = normalizeCreativeJobFailure(message.error, current);
  const sessions = normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions]);
  const sourceSession = sessions.find((item) => item.id === current.sessionId) ?? current.request.session;
  let session = appendDiagnosticEvent(sourceSession, {
    phase: current.phase === "planning" ? "planning" : "streaming",
    status: "failed",
    detail: details.message
  });
  session = setComposerFailure(session, {
    userMessageId: current.userMessageId,
    phase: current.phase === "planning" ? "planning" : "streaming",
    kind: details.kind,
    message: `${details.message}。本轮内容已保留。`,
    retryable: details.retryable
  });
  session = createComposerSession({
    ...session,
    assemblySnapshot: failComposerAssemblySnapshot(session.assemblySnapshot, details)
  });
  const creativeJobs = updateCreativeJob(stored[STORAGE_KEYS.creativeJobs], current.id, {
    status: "failed",
    actualStages: details.actualStages,
    error: details
  });
  await commitLocalChanges({
    [STORAGE_KEYS.creativeJobs]: creativeJobs,
    [STORAGE_KEYS.composerSessions]: upsertSessionList(sessions, session)
  });
  if (details.referenceLimit && current.request.session?.outputMode === "create_image") {
    await rememberObservedReferenceLimit(details.referenceLimit).catch(() => undefined);
  }
  await cleanupCreativeJobMask(current);
  return { ok: true, job: creativeJobById(creativeJobs, current.id), session };
}

async function cancelCreativeJobAction(jobId) {
  const requested = await enqueue(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.creativeJobs);
    const current = creativeJobById(stored[STORAGE_KEYS.creativeJobs], jobId);
    if (!current) return null;
    if (!["queued", "running"].includes(current.status)) return current;
    const next = requestCreativeJobStop(stored[STORAGE_KEYS.creativeJobs], current.id);
    await commitLocalChanges({ [STORAGE_KEYS.creativeJobs]: next.state });
    return next.job;
  });
  if (!requested) return { ok: false, message: "没有找到对应的创作任务" };
  if (!["queued", "running"].includes(requested.status)) return { ok: true, job: requested };
  let runnerStopped = false;
  let providerMayHaveAccepted = requested.providerMayHaveAccepted;
  let providerCancelConfirmed = false;
  let runnerMessage = "";
  try {
    await ensureOffscreenDocument();
    const response = await chrome.runtime.sendMessage({
      target: "offscreen",
      type: "CANCEL_CREATIVE_JOB",
      jobId: requested.id
    });
    runnerStopped = response?.ok === true;
    providerMayHaveAccepted ||= response?.providerMayHaveAccepted === true;
    providerCancelConfirmed = response?.providerCancelConfirmed === true;
    runnerMessage = response?.message || "";
  } catch (error) {
    runnerMessage = userMessage(error);
  }
  return enqueue(async () => {
    const latest = await libraryStorage.get([
      STORAGE_KEYS.creativeJobs,
      STORAGE_KEYS.composerSessions
    ]);
    const active = creativeJobById(latest[STORAGE_KEYS.creativeJobs], requested.id);
    if (!active || !["queued", "running"].includes(active.status)) return { ok: true, job: active };
    const settled = settleCreativeJobStop(latest[STORAGE_KEYS.creativeJobs], active.id, {
      runnerStopped,
      providerMayHaveAccepted,
      providerCancelConfirmed
    });
    const creativeJobs = settled.state;
    const finalJob = settled.job;
    const sessions = normalizeComposerSessions(latest[STORAGE_KEYS.composerSessions]);
    const sourceSession = sessions.find((item) => item.id === active.sessionId) ?? active.request.session;
    let session = setComposerFailure(sourceSession, {
      userMessageId: active.userMessageId,
      phase: active.phase === "planning" ? "planning" : "streaming",
      kind: finalJob.executionState === "canceled" ? "stopped" : "interrupted",
      message: finalJob.error.message,
      retryable: finalJob.error.retryable
    });
    session = createComposerSession({
      ...session,
      assemblySnapshot: failComposerAssemblySnapshot(session.assemblySnapshot, {
        kind: finalJob.executionState === "canceled" ? "stopped" : "interrupted",
        actualStages: active.actualStages
      })
    });
    await commitLocalChanges({
      [STORAGE_KEYS.creativeJobs]: creativeJobs,
      [STORAGE_KEYS.composerSessions]: upsertSessionList(sessions, session)
    });
    if (finalJob.executionState === "canceled") await cleanupCreativeJobMask(active);
    return {
      ok: true,
      message: finalJob.executionState === "canceled"
        ? finalJob.error.message
        : `${finalJob.error.message}${runnerMessage && !runnerStopped ? `;后台执行器未响应:${runnerMessage}` : ""}`,
      job: finalJob
    };
  });
}

async function dispatchCreativeJob(job) {
  await ensureOffscreenDocument();
  const response = await chrome.runtime.sendMessage({ target: "offscreen", type: "RUN_CREATIVE_JOB", job });
  if (!response?.ok) throw new Error(response?.message || "后台创作任务启动失败");
}

function upsertSessionList(values, sessionValue) {
  const session = createComposerSession(sessionValue);
  const sessions = normalizeComposerSessions(values);
  preserveSavedToolDrafts(session, sessions.find(item => item.id === session.id));
  session.toolContinuations = sessions.find(item => item.id === session.id)?.toolContinuations || {};
  session.toolContext = sessions.find(item => item.id === session.id)?.toolContext || session.toolContext;
  session.toolSkillVersionIds = sessions.find(item => item.id === session.id)?.toolSkillVersionIds || [];
  return normalizeComposerSessions([session, ...sessions.filter((item) => item.id !== session.id)]);
}

function normalizeCreativeJobFailure(value, job) {
  const allowedKinds = new Set(["network", "timeout", "rate_limit", "service", "response", "reference_limit", "expired", "unknown", "storage"]);
  const kind = allowedKinds.has(value?.kind) ? value.kind : "unknown";
  const message = String(value?.message ?? "创作任务失败").trim() || "创作任务失败";
  return {
    kind,
    message,
    retryable: value?.retryable === true && job.request.imageEdit?.mode !== "local",
    referenceLimit: normalizeObservedReferenceLimit(value?.referenceLimit),
    actualStages: [...new Set((Array.isArray(value?.actualStages) ? value.actualStages : [])
      .map((item) => String(item ?? "").trim()).filter(Boolean))]
  };
}

function normalizeObservedReferenceLimit(value) {
  const maximum = Number(value?.maximum);
  const actual = Number(value?.actual);
  if (!Number.isInteger(maximum) || maximum < 0) return null;
  return { maximum, actual: Number.isInteger(actual) && actual >= 0 ? actual : null };
}

async function rememberObservedReferenceLimit(value) {
  const referenceLimit = normalizeObservedReferenceLimit(value);
  if (!referenceLimit) return;
  const configuration = await loadAiConfiguration();
  const assignment = configuration.assignments.imageGeneration;
  const profile = configuration.registry.providers[assignment?.providerId];
  const modelId = String(assignment?.model ?? "").trim();
  if (!profile || !modelId) return;
  const before = profile.discoveredModels.find((model) => model.id === modelId);
  const descriptor = {
    ...(before ?? {
      id: modelId,
      name: modelId,
      status: "available",
      confidence: "manual_unverified",
      source: "observed_error",
      tasks: ["imageGeneration"],
      inputModalities: ["text", "image"],
      outputModalities: ["image"],
      supportedParameters: [],
      supportedResolutions: [],
      supportedAspectRatios: []
    }),
    tasks: [...new Set([...(before?.tasks ?? []), "imageGeneration"])],
    referenceImages: {
      supported: true,
      maxItems: referenceLimit.maximum,
      source: "observed_error",
      observedAt: new Date().toISOString()
    }
  };
  const registry = mergeAiProviderRegistry(configuration.registry, { providers: {
    [profile.id]: {
      discoveredModels: [descriptor, ...profile.discoveredModels.filter((model) => model.id !== modelId)]
    }
  } });
  await persistAiConfiguration({ ...configuration, registry });
}

async function cleanupCreativeJobMask(job) {
  const maskAssetId = String(job?.request?.imageEdit?.maskAssetId ?? "").trim();
  if (maskAssetId) await deleteScreenshotBlob(maskAssetId).catch(() => undefined);
}

async function startImportJobAction(message) {
  const state = await readState();
  const collectionId = String(message.collectionId ?? "").trim();
  if (collectionId && !state.organizerState.collections.some((item) => item.id === collectionId)) {
    throw new Error("没有找到导入目标项目");
  }
  let staging = normalizeImportStagingState(state.importStaging);
  const incoming = Array.isArray(message.stagedAssets) ? message.stagedAssets : [];
  if (!incoming.length) throw new Error("请选择要导入的本机资料");
  const keepById = new Map((Array.isArray(message.items) ? message.items : [])
    .map((item) => [String(item?.stagedAssetId ?? "").trim(), item?.keepDuplicate === true]));
  const jobItems = [];
  const duplicateIndex = createExactMediaDuplicateIndex(state.entries, { readBlob: getMediaBlob });
  for (const value of incoming) {
    const assetId = String(value?.assetId ?? "").trim();
    const name = String(value?.name ?? "").trim();
    const isLocalReference = value?.storageMode === "reference" &&
      value?.recordType === LOCAL_ASSET_REFERENCE_RECORD_TYPE;
    if (isLocalReference) {
      const staged = addStagedAsset(staging, value);
      staging = staged.state;
      jobItems.push({ stagedAssetId: staged.asset.id, keepDuplicate: true });
      continue;
    }
    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 duplicateIndex.find(file);
    const staged = addStagedAsset(staging, {
      ...value,
      mimeType: blob.type || value?.mimeType,
      byteSize: blob.size,
      contentHash: duplicate.contentHash,
      duplicateAssetId: duplicate.duplicateAssetId
    });
    staging = staged.state;
    duplicateIndex.add({
      id: staged.asset.assetId,
      byteSize: staged.asset.byteSize,
      mimeType: staged.asset.mimeType,
      sourceTitle: staged.asset.name,
      contentHash: staged.asset.contentHash
    });
    jobItems.push({
      stagedAssetId: staged.asset.id,
      duplicateAssetId: staged.asset.duplicateAssetId,
      keepDuplicate: keepById.get(staged.asset.id) === true
    });
  }
  const created = createImportJob(state.importJobs, {
    collectionId,
    items: jobItems,
    options: {
      duplicateAction: "skip",
      autoAnalyze: message.options?.autoAnalyze === true,
      customLabels: uniqueNames(message.customLabels)
    }
  });
  const skippedCleanupIds = [];
  for (const item of created.job.items.filter((value) => value.status === "skipped")) {
    const staged = stagedAssetById(staging, item.stagedAssetId);
    if (!staged) continue;
    const removed = removeStagedAsset(staging, staged.id);
    staging = removed.state;
    skippedCleanupIds.push(...removed.removedAssetIds);
  }
  await commitLocalChanges({
    [STORAGE_KEYS.importJobs]: created.state,
    [STORAGE_KEYS.importStaging]: staging
  });
  await deleteUnreferencedMedia(skippedCleanupIds);
  await queueImportJobAnalysis(created.job);
  scheduleImportRunner();
  return { ok: true, message: "本机资料已加入后台导入", job: created.job };
}

async function getImportJobAction(jobId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.importJobs);
  const importJobs = normalizeImportJobsState(stored[STORAGE_KEYS.importJobs]);
  const id = String(jobId ?? "").trim();
  const job = id
    ? importJobs.items.find((item) => item.id === id) ?? null
    : importJobs.items.find((item) => ["queued", "running"].includes(item.status)) ?? importJobs.items.at(-1) ?? null;
  return { ok: true, job, importJobs };
}

async function cancelImportJobAction(jobId) {
  const stored = await libraryStorage.get([STORAGE_KEYS.importJobs, STORAGE_KEYS.importStaging]);
  const canceled = cancelImportJob(stored[STORAGE_KEYS.importJobs], jobId);
  let staging = normalizeImportStagingState(stored[STORAGE_KEYS.importStaging]);
  const cleanupIds = [];
  const localReferenceCleanupIds = [];
  for (const item of canceled.job.items.filter((value) => value.status === "skipped" && value.skipReason === "canceled")) {
    const staged = stagedAssetById(staging, item.stagedAssetId);
    if (!staged) continue;
    const removed = removeStagedAsset(staging, staged.id);
    staging = removed.state;
    cleanupIds.push(...removed.removedAssetIds);
    if (staged.recordType === LOCAL_ASSET_REFERENCE_RECORD_TYPE) localReferenceCleanupIds.push(staged.assetId);
  }
  await commitLocalChanges({
    [STORAGE_KEYS.importJobs]: canceled.state,
    [STORAGE_KEYS.importStaging]: staging
  });
  await deleteUnreferencedMedia(cleanupIds);
  const committedState = await readState();
  const retainedLocalAssetIds = collectRetainedLocalAssetIds({ ...committedState, importStaging: staging });
  await deleteLocalAssetHandles(localReferenceCleanupIds
    .filter((assetId) => !retainedLocalAssetIds.has(assetId)))
    .catch(error => console.warn("取消导入的本机引用清理未完成", error));
  return { ok: true, message: "已取消剩余导入项", job: canceled.job };
}

async function retryImportJobAction(jobId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.importJobs);
  const retried = retryImportJob(stored[STORAGE_KEYS.importJobs], jobId);
  await commitLocalChanges({ [STORAGE_KEYS.importJobs]: retried.state });
  scheduleImportRunner();
  return { ok: true, message: "失败项已重新加入后台导入", job: retried.job };
}

async function undoImportJobAction(jobId, confirmationToken) {
  const state = await readState();
  const undone = undoImportJob(state.importJobs, jobId);
  const targetIds = new Set(undone.createdEntryIds);
  const importedEntries = state.entries.filter((entry) => targetIds.has(entry.id));
  if (importedEntries.length !== targetIds.size || importedEntries.some((entry) => entry.importBatchId !== undone.job.importBatchId)) {
    throw new Error("导入案例已变化,未执行撤销");
  }
  const moved = moveEntriesToTrash({
    entries: state.entries,
    trashState: state.trashState,
    organizerState: state.organizerState,
    compoundCases: state.compoundCases
  }, undone.createdEntryIds);
  if (moved.movedItemIds.length !== targetIds.size) throw new Error("回收站已有同编号案例,未执行撤销");
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: moved.entries,
    [STORAGE_KEYS.trashState]: moved.trashState,
    [STORAGE_KEYS.organizerState]: moved.organizerState,
    [STORAGE_KEYS.compoundCases]: moved.compoundCases,
    [STORAGE_KEYS.importJobs]: undone.state
  }, { guard: confirmationToken ? undoConfirmations.guard("UNDO_IMPORT_JOB", confirmationToken, jobId) : undefined });
  return { ok: true, message: `已撤销本次导入的 ${importedEntries.length} 个案例,可在回收站恢复`, job: undone.job };
}

async function recoverImportJobs() {
  const stored = await libraryStorage.get(STORAGE_KEYS.importJobs);
  const recovered = normalizeImportJobsState(stored[STORAGE_KEYS.importJobs], { recoverRunning: true });
  if (stored[STORAGE_KEYS.importJobs]
      && JSON.stringify(stored[STORAGE_KEYS.importJobs]) !== JSON.stringify(recovered)) {
    await commitLocalChanges({ [STORAGE_KEYS.importJobs]: recovered });
  }
  if (recovered.items.some((job) => ["queued", "running"].includes(job.status) && job.items.some((item) => item.status === "queued"))) {
    scheduleImportRunner();
  }
}

function scheduleImportRunner() {
  if (importRunnerActive || importRunnerTimer) return;
  chrome.alarms.create(IMPORT_JOB_ALARM, { when: Date.now() + 1000 }).catch(() => undefined);
  importRunnerTimer = setTimeout(() => {
    importRunnerTimer = 0;
    void enqueue(runImportJobSlice).catch((error) => console.error("PromptDirector local import failed", error));
  }, 0);
}

async function runImportJobSlice() {
  if (importRunnerActive) return;
  importRunnerActive = true;
  try {
    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;
    await importStagedItems(state, active);
  } finally {
    importRunnerActive = false;
    const stored = await libraryStorage.get(STORAGE_KEYS.importJobs);
    const pending = normalizeImportJobsState(stored[STORAGE_KEYS.importJobs]).items.some((job) =>
      ["queued", "running"].includes(job.status) && job.items.some((item) => item.status === "queued"));
    if (pending) scheduleImportRunner();
    else await chrome.alarms.clear(IMPORT_JOB_ALARM).catch(() => undefined);
  }
}

// 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;
  }
  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({
    ...(imported.length ? {
      [STORAGE_KEYS.entries]: entries,
      [STORAGE_KEYS.organizerState]: organizerState
    } : {}),
    [STORAGE_KEYS.importJobs]: jobs,
    [STORAGE_KEYS.importStaging]: staging
  });
  if (imported.length) {
    await enqueueAutomaticLibraryMaintenance(imported);
    await notifySaved(entries.length);
  }
  await queueImportJobAnalysis(finished.job);
}

function importedEntryFromStagedAsset(state, staged, job, item) {
  const base = buildEntry({
    text: staged.contentText || "",
    title: staged.name,
    url: "",
    libraryAddedAt: item.libraryAddedAt || job.libraryAddedAt,
    allowEmptyText: true
  });
  const asset = stagedAssetMediaRecord(staged, { capturedAt: new Date().toISOString() });
  const mediaAssets = [asset];
  if (staged.posterAssetId) {
    mediaAssets.push({
      ...(staged.posterAsset ?? {}),
      id: staged.posterAssetId,
      kind: "image",
      usage: "poster",
      derivedFromAssetId: staged.assetId,
      storageMode: "managed",
      capturedAt: new Date().toISOString(),
      reviewStatus: "verified"
    });
  }
  return normalizeEntryMedia({
    ...base,
    importBatchId: item.importBatchId || job.importBatchId,
    schemaVersion: SCHEMA_VERSION,
    mediaAssets,
    mediaPrompts: embeddedMediaPrompts(mediaAssets),
    primaryMediaId: staged.assetId,
    classification: classifyImportedMedia({ ...base, mediaAssets, mediaPrompts: embeddedMediaPrompts(mediaAssets) }, state.taxonomy),
    customLabels: uniqueNames(job.options.customLabels), metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
    rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
  });
}

async function queueImportJobAnalysis(job) {
  if (!["completed", "failed", "canceled"].includes(job.status) || !job.options.autoAnalyze || job.analysisQueuedAt) return;
  const entryIds = job.items.filter((item) => item.status === "imported").map((item) => item.entryId).filter(Boolean);
  if (entryIds.length) await queueAutomaticVisionAnalysis(entryIds, { requireAutoImportSetting: false });
  const stored = await libraryStorage.get(STORAGE_KEYS.importJobs);
  const marked = markImportJobAnalysisQueued(stored[STORAGE_KEYS.importJobs], job.id);
  await commitLocalChanges({ [STORAGE_KEYS.importJobs]: marked.state });
}

async function addTempReferencesAction(message) {
  const sessionId = String(message.sessionId ?? "").trim();
  if (!sessionId) throw new Error("临时引用缺少创作会话编号");
  const stored = await libraryStorage.get(STORAGE_KEYS.composerSessions);
  const sessions = normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions]);
  const existing = sessions.find((item) => item.id === sessionId);
  if (message.session && String(message.session.id ?? "").trim() !== sessionId) throw new Error("临时引用与创作会话不匹配");
  const baseline = existing ?? (message.session ? createComposerSession(message.session) : null);
  if (!baseline || baseline.id !== sessionId) throw new Error("创作会话尚未保存,请重新打开创作台");
  const additions = Array.isArray(message.tempReferences) ? message.tempReferences : [];
  if (!additions.length) throw new Error("没有可添加的临时引用");
  const knownIds = new Set(baseline.referenceSnapshots.map((item) => item.entryId));
  for (const reference of additions) {
    const referenceId = String(reference?.entryId ?? "").trim();
    if (!referenceId.startsWith("temp-reference:") || reference?.sourceType !== "temporary") {
      throw new Error("临时引用格式无效");
    }
    if (knownIds.has(referenceId)) throw new Error("这项临时引用已经加入创作台");
    const assetIds = tempReferenceAssetIds(reference);
    if (!assetIds.length) throw new Error("临时引用没有可用媒体");
    for (const assetId of assetIds) {
      if (!await getMediaBlob(assetId)) throw new Error("临时引用媒体已经失效,请重新添加");
    }
    knownIds.add(referenceId);
  }
  const session = createComposerSession({
    ...baseline,
    referenceSnapshots: [...baseline.referenceSnapshots, ...additions]
  });
  const next = normalizeComposerSessions([session, ...sessions.filter((item) => item.id !== session.id)]);
  await commitLocalChanges({ [STORAGE_KEYS.composerSessions]: next });
  return { ok: true, session, summaries: next.map(sessionSummary) };
}

async function removeTempReferenceAction(message) {
  const sessionId = String(message.sessionId ?? "").trim();
  const tempReferenceId = String(message.tempReferenceId ?? "").trim();
  const stored = await libraryStorage.get(STORAGE_KEYS.composerSessions);
  const sessions = normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions]);
  const current = sessions.find((item) => item.id === sessionId);
  if (!current) throw new Error("没有找到这份创作草稿");
  const reference = current.referenceSnapshots.find((item) => item.entryId === tempReferenceId && item.sourceType === "temporary");
  if (!reference) throw new Error("没有找到这项临时引用");
  const session = createComposerSession({
    ...current,
    referenceSnapshots: current.referenceSnapshots.filter((item) => item.entryId !== tempReferenceId)
  });
  const next = normalizeComposerSessions([session, ...sessions.filter((item) => item.id !== session.id)]);
  await commitLocalChanges({ [STORAGE_KEYS.composerSessions]: next });
  await deleteUnreferencedMedia(tempReferenceAssetIds(reference));
  return { ok: true, session, summaries: next.map(sessionSummary) };
}

async function saveTempReferenceAsCaseAction(message) {
  const state = await readState();
  const sessionId = String(message.sessionId ?? "").trim();
  const tempReferenceId = String(message.tempReferenceId ?? "").trim();
  const current = state.composerSessions.find((item) => item.id === sessionId);
  if (!current) throw new Error("没有找到这份创作草稿");
  const reference = current.referenceSnapshots.find((item) => item.entryId === tempReferenceId && item.sourceType === "temporary");
  if (!reference) throw new Error("没有找到这项临时引用");
  const assetRefs = Array.isArray(reference.assetRefs) ? reference.assetRefs : [];
  if (!assetRefs.length) throw new Error("临时引用没有可保存的媒体");
  for (const asset of assetRefs) {
    if (!await getMediaBlob(asset.assetId)) throw new Error(`临时引用媒体已经失效:${asset.name || "未命名"}`);
  }
  const title = String(message.title ?? reference.title ?? assetRefs[0]?.name ?? "本机参考").trim();
  const base = buildEntry({ text: reference.referenceText || "", title, url: "", allowEmptyText: true });
  const mediaAssets = assetRefs.map((asset) => ({
    id: asset.assetId,
    kind: asset.kind,
    storageMode: "managed",
    mimeType: asset.mimeType,
    byteSize: asset.byteSize,
    sourceTitle: asset.name,
    capturedAt: new Date().toISOString(),
    reviewStatus: "verified"
  }));
  const entry = normalizeEntryMedia({
    ...base,
    schemaVersion: SCHEMA_VERSION,
    mediaAssets,
    primaryMediaId: mediaAssets[0].id,
    classification: classifyImportedMedia({ ...base, mediaAssets }, state.taxonomy),
    customLabels: [], metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
    rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
  });
  const libraryReference = {
    ...reference,
    entryId: entry.id,
    sourceType: "library",
    assetRefs: undefined
  };
  const session = createComposerSession({
    ...current,
    referenceSnapshots: current.referenceSnapshots.map((item) => item.entryId === tempReferenceId ? libraryReference : item)
  });
  const sessions = normalizeComposerSessions([session, ...state.composerSessions.filter((item) => item.id !== session.id)]);
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: [...state.entries, entry],
    [STORAGE_KEYS.composerSessions]: sessions
  });
  if (mediaAssets.some((asset) => asset.kind === "image")) await queueAutomaticVisionAnalysis([entry.id]);
  return { ok: true, message: "临时引用已保存为案例", entry, session, summaries: sessions.map(sessionSummary) };
}

async function startOrJoinAnalysisTaskAction(message) {
  const created = await enqueue(() => withAnalysisTaskStorageLock(async () => {
    const stored = await libraryStorage.get([STORAGE_KEYS.analysisTasks, STORAGE_KEYS.batchJob]);
    if (message.kind === "entry_video" && String(message.batchJobId ?? "").trim()) {
      const busy = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]).items.find((task) =>
        task.request?.kind === "entry_video"
        && ["queued", "running"].includes(task.status)
        && task.request.entryId === String(message.entryId ?? "").trim()
        && task.request.assetId === String(message.assetId ?? "").trim()
        && task.request.batchJobId !== String(message.batchJobId).trim());
      if (busy) return { state: stored[STORAGE_KEYS.analysisTasks], task: busy, created: false };
    }
    const result = createOrJoinAnalysisTask(stored[STORAGE_KEYS.analysisTasks], message, {
      taskId: `analysis-task:${crypto.randomUUID()}`
    });
    const changes = { [STORAGE_KEYS.analysisTasks]: result.state };
    if (message.kind === "entry_video" && String(message.batchJobId ?? "").trim()) {
      const batchJob = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], message.batchJobId, "video");
      changes[STORAGE_KEYS.batchJob] = bindAnalysisItemAttempt(
        batchJob,
        message.entryId,
        message.batchClaimId,
        { taskId: result.task.id }
      );
    }
    await commitLocalChanges(changes, { markSyncDirty: false });
    return result;
  }));
  if (created.created) scheduleAnalysisTaskRun(created.task.id);
  return analysisTaskResponse(created.task);
}

async function getAnalysisTaskAction(taskId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
  const task = analysisTaskById(stored[STORAGE_KEYS.analysisTasks], taskId);
  if (!task) return { ok: false, message: "没有找到分析任务" };
  return analysisTaskResponse(task);
}

async function getEntryVideoAnalysisTaskAction(entryIdValue, assetIdValue) {
  const entryId = String(entryIdValue ?? "").trim();
  const assetId = String(assetIdValue ?? "").trim();
  const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
  const state = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
  const task = state.items.slice().reverse().find((item) => item.request?.kind === "entry_video"
    && item.request.entryId === entryId && item.request.assetId === assetId);
  return task ? analysisTaskResponse(task) : { ok: true, task: null };
}

async function detachAnalysisConsumerAction(message) {
  const detached = await withAnalysisTaskStorageLock(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
    const result = detachAnalysisTaskConsumer(
      stored[STORAGE_KEYS.analysisTasks],
      message.taskId,
      message.consumerId,
      message.clientRequestId
    );
    await commitLocalChanges({ [STORAGE_KEYS.analysisTasks]: result.state }, { markSyncDirty: false });
    return result;
  });
  return analysisTaskResponse(detached.task);
}

async function stopAnalysisTaskAction(message) {
  let activeAttemptId = "";
  const stopped = await enqueue(() => withAnalysisTaskStorageLock(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
    const state = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
    const current = analysisTaskById(state, message.taskId);
    if (!current) throw new Error("没有找到分析任务");
    activeAttemptId = current.activeAttemptId;
    const task = stopAnalysisTask(current);
    const next = replaceAnalysisTask(state, task);
    await commitLocalChanges({ [STORAGE_KEYS.analysisTasks]: next }, { markSyncDirty: false });
    return task;
  }));
  analysisTaskRunners.get(stopped.id)?.controller.abort();
  if (stopped.request?.kind === "entry_video" && activeAttemptId) {
    await ensureOffscreenDocument();
    await chrome.runtime.sendMessage({
      target: "offscreen",
      type: "CANCEL_VIDEO_ANALYSIS",
      taskId: stopped.id,
      attemptId: activeAttemptId
    }).catch(() => undefined);
  }
  await notifyAnalysisTaskUpdated(stopped);
  return analysisTaskResponse(stopped);
}

async function retryAnalysisTaskAction(message) {
  if (message.confirmDuplicateCharge !== true) throw new Error("重新分析前必须确认可能再次计费");
  const retried = await enqueue(() => withAnalysisTaskStorageLock(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
    const state = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
    const current = analysisTaskById(state, message.taskId);
    if (!current) throw new Error("没有找到分析任务");
    const previousAttemptId = current.attempts.at(-1)?.id ?? "";
    if (String(message.previousAttemptId ?? "").trim() !== previousAttemptId) {
      throw new Error("分析任务已经变化,请刷新后再重试");
    }
    const task = retryAnalysisAttempt(current, {
      attemptId: `analysis-attempt:${crypto.randomUUID()}`,
      deadlineAt: current.request.kind === "entry_video"
        ? new Date(Date.now() + VIDEO_ANALYSIS_REQUEST_TIMEOUT_MS).toISOString()
        : "",
      confirmed: true
    });
    task.consumerIds = [...new Set([...task.consumerIds, String(message.consumerId ?? "").trim()].filter(Boolean))];
    task.clientRequestIds = [...new Set([...task.clientRequestIds, String(message.clientRequestId ?? "").trim()].filter(Boolean))];
    const next = replaceAnalysisTask(state, task);
    await commitLocalChanges({ [STORAGE_KEYS.analysisTasks]: next }, { markSyncDirty: false });
    return task;
  }));
  scheduleAnalysisTaskRun(retried.id, retried.activeAttemptId);
  return analysisTaskResponse(retried);
}

function scheduleAnalysisTaskRun(taskId, preparedAttemptId = "") {
  if (analysisTaskRunners.has(taskId)) return;
  chrome.alarms.create(ANALYSIS_TASK_ALARM, { when: Date.now() + 50 });
  void runAnalysisTask(taskId, preparedAttemptId);
}

async function runQueuedAnalysisTasks() {
  const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
  const state = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
  for (const task of state.items.filter((item) => item.status === "queued")) scheduleAnalysisTaskRun(task.id);
}

async function runAnalysisTask(taskId, preparedAttemptId = "") {
  if (analysisTaskRunners.has(taskId)) return;
  const claimed = await enqueue(() => withAnalysisTaskStorageLock(async () => {
    const stored = await libraryStorage.get([STORAGE_KEYS.analysisTasks, STORAGE_KEYS.batchJob]);
    const state = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
    const current = analysisTaskById(state, taskId);
    if (!current) return null;
    let task = current;
    if (task.status === "queued") {
      task = startAnalysisAttempt(task, {
        attemptId: `analysis-attempt:${crypto.randomUUID()}`,
        deadlineAt: task.request.kind === "entry_video"
          ? new Date(Date.now() + VIDEO_ANALYSIS_REQUEST_TIMEOUT_MS).toISOString()
          : ""
      });
    } else if (!preparedAttemptId || task.status !== "running" || task.activeAttemptId !== preparedAttemptId) {
      return null;
    }
    const next = replaceAnalysisTask(state, task);
    const changes = { [STORAGE_KEYS.analysisTasks]: next };
    if (task.request.kind === "entry_video" && task.request.batchJobId && task.request.batchClaimId) {
      const batchJob = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
      if (!batchJob || batchJob.id !== task.request.batchJobId || batchJob.kind !== "video") {
        throw new Error("批量视频任务已经变化,未发送请求");
      }
      changes[STORAGE_KEYS.batchJob] = bindAnalysisItemAttempt(
        batchJob,
        task.request.entryId,
        task.request.batchClaimId,
        { taskId: task.id, attemptId: task.activeAttemptId, requestId: task.activeAttemptId }
      );
    }
    await commitLocalChanges(changes, { markSyncDirty: false });
    return task;
  }));
  if (!claimed) return;
  if (claimed.request.kind === "entry_video") {
    try {
      await dispatchVideoAnalysisTask(claimed);
    } catch (error) {
      await failVideoAnalysisAction({
        taskId: claimed.id,
        attemptId: claimed.activeAttemptId,
        error: { message: userMessage(error), status: Number(error?.status) || 0 }
      });
    }
    return;
  }
  const controller = new AbortController();
  analysisTaskRunners.set(taskId, { attemptId: claimed.activeAttemptId, controller });
  let actionResult;
  try {
    actionResult = await analyzeTempReferencesAction({
      ...claimed.request,
      taskId: claimed.id,
      attemptId: claimed.activeAttemptId,
      priority: claimed.priority,
      signal: controller.signal
    });
  } catch (error) {
    actionResult = { ok: false, message: userMessage(error), status: Number(error?.status) || 0, usage: error?.usage };
  }
  let settled;
  try {
    settled = await enqueue(async () => {
      const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
      const state = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
      const current = analysisTaskById(state, taskId);
      if (!current || current.activeAttemptId !== claimed.activeAttemptId || current.status !== "running") return current;
      const task = actionResult?.ok
        ? completeAnalysisAttempt(current, { attemptId: claimed.activeAttemptId, result: actionResult })
        : failAnalysisAttempt(current, { attemptId: claimed.activeAttemptId, error: actionResult?.message || "图片分析失败" });
      const next = replaceAnalysisTask(state, task);
      await commitLocalChanges({ [STORAGE_KEYS.analysisTasks]: next }, { markSyncDirty: false });
      return task;
    });
  } finally {
    analysisTaskRunners.delete(taskId);
  }
  if (settled) await notifyAnalysisTaskUpdated(settled);
}

async function persistAnalysisTaskProgress(taskId, attemptId, phase, options = {}) {
  const task = await enqueue(() => withAnalysisTaskStorageLock(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
    const state = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
    const current = analysisTaskById(state, taskId);
    if (!current || current.activeAttemptId !== attemptId || current.status !== "running") return null;
    const updated = updateAnalysisTaskProgress(current, {
      attemptId,
      phase,
      requestBudget: options.requestBudget,
      requestId: options.requestId,
      diagnostic: options.diagnostic,
      providerMayHaveAccepted: options.providerMayHaveAccepted === true
    });
    await commitLocalChanges({
      [STORAGE_KEYS.analysisTasks]: replaceAnalysisTask(state, updated)
    }, { markSyncDirty: false });
    return updated;
  }));
  if (task) await notifyAnalysisTaskUpdated(task);
  return task
    ? { ok: true, task }
    : { ok: false, message: "本次视频分析已经停止,迟到进度未保存" };
}

async function recoverAnalysisTasks() {
  let activeAttemptIds = [];
  try {
    await ensureOffscreenDocument();
    const runner = await chrome.runtime.sendMessage({ target: "offscreen", type: "GET_VIDEO_ANALYSIS_RUNNER" });
    if (runner?.ok) activeAttemptIds = (Array.isArray(runner.runners) ? runner.runners : [])
      .map((item) => String(item?.attemptId ?? "").trim()).filter(Boolean);
  } catch {
    activeAttemptIds = [];
  }
  const recovered = await withAnalysisTaskStorageLock(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
    const current = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
    const next = recoverInterruptedAnalysisTasks(current, { activeAttemptIds });
    if (JSON.stringify(current) !== JSON.stringify(next)) {
      await commitLocalChanges({ [STORAGE_KEYS.analysisTasks]: next }, { markSyncDirty: false });
    }
    return next;
  });
  for (const task of recovered.items.filter((item) => item.executionState === "execution_state_unknown")) {
    await notifyAnalysisTaskUpdated(task);
  }
  for (const task of recovered.items.filter((item) => item.status === "queued")) scheduleAnalysisTaskRun(task.id);
}

async function recoverVideoBatchExecutionState() {
  const [stored, state] = await Promise.all([
    libraryStorage.get([STORAGE_KEYS.batchJob, STORAGE_KEYS.analysisTasks]),
    readState()
  ]);
  let job = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
  if (!job || job.kind !== "video" || !job.items.some((item) => item.status === "running")) return;
  const tasks = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]).items;
  const entryById = new Map(state.entries.map((entry) => [entry.id, normalizeEntryMedia(entry)]));
  let changed = false;
  let hasUnknownExecution = false;
  for (const item of job.items.filter((candidate) => candidate.status === "running")) {
    const task = item.taskId ? tasks.find((candidate) => candidate.id === item.taskId) : null;
    const identityMatches = Boolean(task
      && task.request?.kind === "entry_video"
      && task.request.batchJobId === job.id
      && task.request.batchClaimId === item.claimId
      && task.request.entryId === item.entryId
      && task.request.assetId === item.assetId
      && item.requestId
      && task.attempts.some((attempt) => attempt.id === item.requestId));
    const record = identityMatches
      ? entryById.get(item.entryId)?.videoAnalyses?.find((analysis) =>
          analysis.batchJobId === job.id && analysis.assetId === item.assetId && analysis.requestId === item.requestId)
      : null;
    if (record) {
      job = succeedAnalysisItem(job, item.entryId, item.claimId, {
        promptTokens: record.usage?.inputTokens,
        completionTokens: record.usage?.outputTokens,
        totalTokens: record.usage?.totalTokens
      }, undefined, { serviceRequests: 1, cost: record.cost ?? null });
      changed = true;
      continue;
    }
    if (identityMatches && ["queued", "running"].includes(task.status)) continue;
    job = failAnalysisItem(job, item.entryId, item.claimId, {
      message: "上次执行状态未知,未自动重试;服务商可能已收到请求",
      status: 0,
      attempts: { serviceRequests: identityMatches ? 1 : 0 }
    });
    changed = true;
    hasUnknownExecution = true;
  }
  if (!changed) return;
  if (hasUnknownExecution) job = { ...job, status: "paused", updatedAt: new Date().toISOString() };
  await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job }, { markSyncDirty: false });
  await ensureAnalysisBatchAlarm(job.status === "running");
}

async function analysisTaskAttemptIsActive(taskId, attemptId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
  const task = analysisTaskById(stored[STORAGE_KEYS.analysisTasks], taskId);
  return Boolean(task && task.status === "running" && task.executionState === "running" && task.activeAttemptId === attemptId);
}

function analysisTaskResponse(task) {
  const attempt = task?.activeAttemptId
    ? task.attempts.find((item) => item.id === task.activeAttemptId)
    : task?.attempts?.at(-1);
  return {
    ok: true,
    task,
    attemptId: attempt?.id ?? "",
    ...(attempt?.result ? { result: attempt.result } : {})
  };
}

async function notifyAnalysisTaskUpdated(task) {
  await chrome.runtime.sendMessage({ type: "ANALYSIS_TASK_UPDATED", ...analysisTaskResponse(task) }).catch(() => undefined);
}

async function analyzeTempReferencesAction(message) {
  try {
    const sessionId = String(message.sessionId ?? "").trim();
    const requestedIds = [...new Set((Array.isArray(message.tempReferenceIds) ? message.tempReferenceIds : [])
      .map((value) => String(value ?? "").trim()).filter(Boolean))];
    if (!sessionId || !requestedIds.length) return { ok: false, message: "没有可分析的临时图片" };
    const stored = await libraryStorage.get([
      STORAGE_KEYS.composerSessions,
      STORAGE_KEYS.facetCatalog,
      STORAGE_KEYS.entries
    ]);
    const sessions = normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions]);
    const session = sessions.find((item) => item.id === sessionId);
    if (!session) return { ok: false, message: "没有找到这份创作草稿" };
    const requested = new Set(requestedIds);
    const references = session.referenceSnapshots.filter((reference) =>
      (requested.has(reference.referenceId || reference.entryId) || requested.has(reference.entryId))
      && unreadReferenceImageAssets(reference).length
    );
    if ([...requested].some((id) => !references.some((reference) => reference.entryId === id || reference.referenceId === id))) {
      return { ok: false, message: "参考图片已经变化,请确认后重试" };
    }
    const configuration = await loadAiConfiguration();
    const locale = message.outputLocale === "en" ? "en" : "zh-CN";
    const settledReferences = await Promise.allSettled(references.map(async (reference) => {
      const imageAssets = unreadReferenceImageAssets(reference);
      const assetResults = await Promise.all(imageAssets.map(async (asset) => {
        if (message.signal?.aborted) throw new DOMException("图片分析已停止", "AbortError");
        const blob = await getTempReferenceVisionBlob(asset);
        if (!blob) throw new Error(`参考图片已经失效:${asset.name || "未命名图片"}`);
        const { result, fingerprint } = await analyzeVisionBlobWithScheduler({
          blob,
          catalog: stored[STORAGE_KEYS.facetCatalog],
          locale,
          configuration,
          entries: stored[STORAGE_KEYS.entries],
          signal: message.signal,
          priority: message.priority
        });
        return {
          result,
          description: result.description,
          requestCount: Math.max(0,
            (Number(result.attempts?.serviceRequests) || 0)
            + (Number(result.attempts?.outputCorrectionRequests) || 0)
          ),
          fingerprint: { assetId: asset.assetId, fingerprint },
          analysis: {
            assetId: asset.assetId,
            imageFingerprint: fingerprint,
            analysisImageFingerprint: fingerprint,
            analysisVersion: VISION_ANALYSIS_VERSION,
            analysisFingerprint: result.profileFingerprint,
            reconstructionPrompt: result.reconstructionPrompt
          }
        };
      }));
      return {
        referenceId: reference.referenceId || reference.entryId,
        entryId: reference.entryId,
        sourceType: reference.sourceType,
        assetResults,
        descriptions: assetResults.map((item) => item.description),
        requestCount: assetResults.reduce((total, item) => total + item.requestCount, 0),
        fingerprints: assetResults.map((item) => item.fingerprint),
        analyses: assetResults.map((item) => item.analysis)
      };
    }));
    const analyzed = settledReferences.flatMap((settled) => settled.status === "fulfilled" ? [settled.value] : []);
    const failures = settledReferences.flatMap((settled, index) => settled.status === "rejected"
      ? [{ referenceId: references[index].referenceId || references[index].entryId, message: userMessage(settled.reason) }]
      : []);
    if (!analyzed.length) throw new Error(failures[0]?.message || "参考图片分析失败");

    return await enqueue(async () => {
      if (message.taskId && !await analysisTaskAttemptIsActive(message.taskId, message.attemptId)) {
        return { ok: false, message: "这次图片分析已经停止或失效,结果没有写入" };
      }
      const latestStored = await libraryStorage.get(STORAGE_KEYS.composerSessions);
      const latestSessions = normalizeComposerSessions(latestStored[STORAGE_KEYS.composerSessions]);
      const latestSession = latestSessions.find((item) => item.id === sessionId);
      if (!latestSession) return { ok: false, message: "分析期间创作草稿已经变化,本次结果没有写入" };
      for (const item of analyzed) {
        const current = latestSession.referenceSnapshots.find((reference) =>
          (reference.referenceId || reference.entryId) === item.referenceId
          && unreadReferenceImageAssets(reference).length
        );
        if (!current) return { ok: false, message: "分析期间参考图片已经变化,本次结果没有写入" };
        const currentAssets = unreadReferenceImageAssets(current);
        for (const expected of item.fingerprints) {
          const asset = currentAssets.find((value) => value.assetId === expected.assetId);
          const blob = asset ? await getTempReferenceVisionBlob(asset) : null;
          if (!blob || await imageFingerprint(blob) !== expected.fingerprint) {
            return { ok: false, message: "分析期间参考图片已经变化,本次结果没有写入" };
          }
        }
      }
      let caseState = domainState(await readState());
      const undoStore = { ...((await libraryStorage.get(STORAGE_KEYS.visionAnalysisUndo))[STORAGE_KEYS.visionAnalysisUndo] ?? {}) };
      let casesChanged = false;
      for (const item of analyzed) {
        if (item.sourceType === "temporary") continue;
        for (const assetResult of item.assetResults) {
          const entry = caseState.entries.find((candidate) => candidate.id === item.entryId);
          const visual = entry && normalizeEntryVisuals(entry).visuals.find((candidate) => candidate.id === assetResult.fingerprint.assetId);
          const blob = visual && await getVisionImageBlob(visual.id);
          if (!entry || !visual || !blob || await imageFingerprint(blob) !== assetResult.fingerprint.fingerprint) {
            return { ok: false, message: "分析期间源案例或图片已经变化,本次结果没有写入" };
          }
          const applied = applyCompletedVisionResult(caseState, entry, visual, assetResult.result, {
            fingerprint: assetResult.fingerprint.fingerprint,
            catalogRevision: stored[STORAGE_KEYS.facetCatalog]?.revision,
            locale
          });
          caseState = applied.state;
          undoStore[entry.id] = applied.undo;
          casesChanged = true;
        }
      }
      const resultByReferenceId = new Map(analyzed.map((item) => [item.referenceId, item]));
      const updatedSession = createComposerSession({
        ...latestSession,
        referenceSnapshots: latestSession.referenceSnapshots.map((reference) => {
          const result = resultByReferenceId.get(reference.referenceId || reference.entryId);
          return result ? {
            ...reference,
            referenceKind: "vision",
            referenceText: result.descriptions.join("\n\n"),
            assets: [
              ...(reference.assets ?? []).filter((asset) => !result.analyses.some((analysis) => analysis.assetId === asset.assetId)),
              ...result.analyses
            ]
          } : reference;
        })
      });
      const next = normalizeComposerSessions([
        updatedSession,
        ...latestSessions.filter((item) => item.id !== updatedSession.id)
      ]);
      await commitLocalChanges({
        ...(casesChanged ? { ...storagePayload(caseState), [STORAGE_KEYS.visionAnalysisUndo]: undoStore } : {}),
        [STORAGE_KEYS.composerSessions]: next
      });
      return {
        ok: true,
        quality: failures.length ? "partial" : "complete",
        failedCount: failures.length,
        prerequisiteAnalysisRequests: analyzed.reduce((total, item) => total + item.requestCount, 0),
        failures,
        message: failures.length
          ? `已保存 ${analyzed.length} 项分析,另有 ${failures.length} 项失败,可直接重试`
          : `已完成 ${analyzed.length} 项临时图片分析`,
        session: updatedSession,
        summaries: next.map(sessionSummary)
      };
    });
  } catch (error) {
    return { ok: false, message: userMessage(error) };
  }
}

async function getTempReferenceVisionBlob(asset) {
  const blob = await getMediaBlob(asset.assetId) ?? await getScreenshotBlob(asset.assetId);
  if (!blob) return null;
  if (blob.type !== "image/gif") return blob;
  const derived = await getDerivedMedia(asset.assetId).catch(() => null);
  return derived?.thumbnail instanceof Blob ? derived.thumbnail : blob;
}

async function deleteUnreferencedMedia(assetIdsValue) {
  const candidates = new Set((Array.isArray(assetIdsValue) ? assetIdsValue : []).map(String).map((value) => value.trim()).filter(Boolean));
  if (!candidates.size) return;
  const state = await readState();
  const referenced = referencedMediaAssetIds(state);
  for (const id of captureChatAssetIds((await libraryStorage.get('captureAssistantDialog')).captureAssistantDialog)) referenced.add(id);
  await deleteMediaBlobs([...candidates].filter((assetId) => !referenced.has(assetId)));
}

function referencedMediaAssetIds(state) {
  const retained = collectRetainedLocalAssetIds(state);
  // Capture staging is protected while network work runs outside the write lock.
  for (const id of activeCaptureAssetIds) retained.add(id);
  return retained;
}

function temporaryAssetIdsFromSession(session) {
  return (Array.isArray(session?.referenceSnapshots) ? session.referenceSnapshots : [])
    .filter((reference) => reference?.sourceType === "temporary")
    .flatMap(tempReferenceAssetIds);
}

async function updateComposerSettings(message) {
  const stored = await libraryStorage.get(STORAGE_KEYS.composerSettings);
  let settings = normalizeComposerSettings(stored[STORAGE_KEYS.composerSettings]);
  const allowedActions = ["save_agent", "reset_agent", "save_task", "reset_task", "preferences"];
  const action = allowedActions.includes(message.action) ? message.action : "preferences";
  if (action === "save_agent") settings = updateComposerAgentInstruction(settings, message.text);
  if (action === "reset_agent") settings = resetComposerAgentInstruction(settings);
  if (action === "save_task") settings = updateComposerTaskMethod(settings, { taskKey: message.taskKey, text: message.text });
  if (action === "reset_task") settings = resetComposerTaskMethod(settings, message.taskKey);
  if (["auto", "zh-CN", "en"].includes(message.outputLanguage)) settings.outputLanguage = message.outputLanguage;
  if (message.lastTargetPlatform !== undefined) settings.lastTargetPlatform = String(message.lastTargetPlatform ?? "").trim();
  if (message.lastAiProfile !== undefined) settings.lastAiProfile = normalizeComposerAiProfile(message.lastAiProfile);
  if (message.productionReviewEnabled !== undefined) settings.productionReviewEnabled = message.productionReviewEnabled !== false;
  await commitLocalChanges({ [STORAGE_KEYS.composerSettings]: settings });
  const responseMessage = action.startsWith("reset_")
    ? "已采用当前版本默认内容"
    : action === "preferences" ? "创作偏好已保存" : "Agent 设置已保存";
  return { ok: true, message: responseMessage, composerSettings: settings };
}

async function upsertComposerSession(value, {activate = false} = {}) {
  let response;
  await libraryStorage.update(['composerSessions', 'syncMeta', ...(activate ? ['captureAssistantDialog'] : [])], stored => {
    // Other canonical chats are unchanged; do not clone their tool journals for a draft edit.
    const sessions = Array.isArray(stored.composerSessions) ? stored.composerSessions : [];
    const session = createComposerSession(value);
    const previous = sessions.find(item => item.id === session.id);
    if (!previous && session.assistantState && session.chatRevision > 0) {
      response = {ok:false,code:'chat_deleted',message:'对话已删除,请新建对话继续'}; return {};
    }
    const chatChanged = previous && assistantChatContent(session) !== assistantChatContent(previous);
    if ((session.assistantState || previous?.assistantState) && chatChanged && session.chatRevision !== previous.chatRevision) {
      response = { ok: false, code: 'chat_conflict', message: '对话已在其他页面更新,请重新读取后继续' }; return {};
    }
    if (session.assistantState) session.chatRevision = (previous?.chatRevision || 0) + (!previous?.assistantState || chatChanged ? 1 : 0);
    session.updatedAt = !previous || chatChanged ? new Date().toISOString() : previous.updatedAt;
    preserveSavedToolDrafts(session, previous);
    session.toolContinuations = previous?.toolContinuations || {};
    session.toolContext = previous?.toolContext || session.toolContext;
    session.toolSkillVersionIds = previous?.toolSkillVersionIds || [];
    if (!isMeaningfulComposerSession(session)) { response = { ok: false, message: '空白新对话不会保存到历史' }; return {}; }
    const next = [session, ...sessions.filter(item => item.id !== session.id)].sort((a,b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
    response = { ok: true, session, summaries: composerSessionSummaries(next) };
    return { composerSessions: next, ...(activate ? {captureAssistantDialog:{...stored.captureAssistantDialog,schema:'shared-chat',activeId:session.id,emptyChat:null}} : {}), ...(!syncApplyInProgress ? {syncMeta:markSyncMetaDirty(stored.syncMeta)} : {}) };
  });
  return response;
}

async function deleteComposerSession(sessionId) {
  let removedSession, response;
  await libraryStorage.update(['composerSessions','activeCreativeResult','syncMeta'], stored => {
    const sessions = normalizeComposerSessions(stored.composerSessions);
    removedSession = sessions.find(item => item.id === sessionId);
    if (!removedSession) { response = {ok:false,message:'没有找到这份创作草稿'}; return {}; }
    if (removedSession.assistantState?.requestId && captureAssistantControllers.has(removedSession.assistantState.requestId)) {
      response = {ok:false,message:'请先停止这个对话的任务,再删除'}; return {};
    }
    const next = sessions.filter(item => item.id !== sessionId);
    const active = normalizeActiveCreativeResult(stored.activeCreativeResult);
    response = {ok:true,message:'创作草稿已删除',summaries:next.map(sessionSummary)};
    return {composerSessions:next,...(active?.sessionId === sessionId ? {activeCreativeResult:null} : {}),
      ...(!syncApplyInProgress ? {syncMeta:markSyncMetaDirty(stored.syncMeta)} : {})};
  });
  if (!response.ok) return response;
  await deleteUnreferencedMedia(temporaryAssetIdsFromSession(removedSession));
  return response;
}

async function saveComposerResult(message) {
  const state = await readState();
  const stored = await libraryStorage.get(STORAGE_KEYS.composerSessions);
  const session = normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions]).find((item) => item.id === message.sessionId);
  if (!session) return { ok: false, message: "创作草稿已变化,请重新打开" };
  const version = session.promptVersions.find((item) => item.id === message.promptVersionId);
  if (!version) return { ok: false, message: "最终提示词尚未完整保存" };
  const title = String(message.title ?? version.title ?? session.title).trim() || "未命名提示词";
  const contentRole = session.targetType === "video" ? CONTENT_ROLES.promptVideo : CONTENT_ROLES.promptImage;
  const contentType = contentTypeForRole(state.taxonomy, contentRole);
  const entry = {
    ...buildEntry({ text: version.text, title, url: "" }),
    schemaVersion: SCHEMA_VERSION,
    classification: contentType
      ? { pathIds: [contentType.id], status: "confirmed", source: "composer", reason: "创作台保存" }
      : { pathIds: [], status: "needs_review", source: "composer", reason: "没有匹配当前创作用途的内容类型" },
    facetAssignments: [],
    analysisCandidates: [],
    analysisBreakdown: [],
    rejectedCandidateKeys: [],
    negativeTerms: [],
    legacyFacetCandidates: [],
    analysisPending: false,
    creationMeta: {
      sourceEntryIds: session.referenceSnapshots.map((item) => item.entryId),
      promptVersionId: version.id,
      methodVersion: version.methodVersion || COMPOSER_METHOD_VERSION,
      targetPlatform: session.targetPlatform,
      outputLanguage: version.outputLanguage || session.outputLanguage,
      createdAt: version.createdAt
    }
  };
  const entries = [...state.entries, entry];
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: "最终提示词已保存为新案例", entry };
}

async function activateCreativeResult(message, sidePanelOpening = null) {
  const stored = await libraryStorage.get(STORAGE_KEYS.composerSessions);
  const session = normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions])
    .find((item) => item.id === String(message.sessionId ?? "").trim());
  if (!session) return { ok: false, message: "创作草稿已变化,请重新打开" };
  if (session.targetType === "video") {
    await commitLocalChanges({ [STORAGE_KEYS.activeCreativeResult]: null });
    return { ok: false, message: "当前版本只支持关联图片生成结果" };
  }
  const activeCreativeResult = activateCreativeResultContext(session, message.promptVersionId);
  await commitLocalChanges({ [STORAGE_KEYS.activeCreativeResult]: activeCreativeResult });
  const panelOpened = sidePanelOpening ? await sidePanelOpening : false;
  return {
    ok: true,
    message: panelOpened
      ? "已打开侧边栏,可选择本次生成图片"
      : "已准备添加生成图片,但侧边栏未自动打开,请点击插件图标",
    panelOpened,
    activeCreativeResult
  };
}

async function captureAndCommitCreativeOutputs(message) {
  const transaction = await enqueueCapture(async () => {
    const captured = await dispatchCaptureMessage(message.captureType, message.tabId);
    if (!captured?.ok || !captured.added) {
      return { ...captured, captured, committed: null, draft: captured?.draft };
    }
    const committed = await enqueue(() => commitCreativeOutputsTransaction());
    return {
      ok: committed.ok,
      message: committed.message,
      draft: captured.draft,
      captured,
      committed
    };
  });
  if (!transaction.ok || !transaction.committed) return transaction;
  const committed = await analyzeCommittedCreativeOutputs(transaction.committed);
  return { ...transaction, message: committed.message, committed };
}

async function commitExistingCreativeOutputs() {
  const committed = await enqueueCapture(() => enqueue(() => commitCreativeOutputsTransaction()));
  return analyzeCommittedCreativeOutputs(committed);
}

async function registerGeneratedOutputs(message) {
  const state = await readState();
  const sessionId = String(message.sessionId ?? "").trim();
  const promptVersionId = String(message.promptVersionId ?? "").trim();
  const session = state.composerSessions.find((item) => item.id === sessionId);
  if (!session) return { ok: false, message: "对应的创作草稿已经不存在" };
  if (!session.promptVersions.some((item) => item.id === promptVersionId)) {
    return { ok: false, message: "生成图片与提示词版本不匹配" };
  }
  const visuals = Array.isArray(message.visuals) ? message.visuals : [];
  if (!visuals.length) return { ok: false, message: "没有收到可登记的生成图片" };
  for (const visual of visuals) {
    const id = String(visual?.id ?? "").trim();
    const blob = id ? await getScreenshotBlob(id) : null;
    if (!blob || !blob.type.startsWith("image/") || !blob.size) {
      return { ok: false, message: "有一张生成图片没有完整写入本地存储" };
    }
  }
  let creativeRuns = normalizeCreativeRuns(state.creativeRuns);
  let run = creativeRuns.find((item) => item.sessionId === sessionId && item.promptVersionId === promptVersionId);
  if (run) {
    for (const visual of visuals) run = addCreativeOutput(run, visual, undefined, message.generation);
    creativeRuns = [run, ...creativeRuns.filter((item) => item.id !== run.id)];
  } else {
    run = createCreativeRun({ sessionId, promptVersionId }, session, visuals, undefined, message.generation);
    creativeRuns = [run, ...creativeRuns];
  }
  creativeRuns = normalizeCreativeRuns(creativeRuns);
  await commitLocalChanges({ [STORAGE_KEYS.creativeRuns]: creativeRuns });
  return { ok: true, message: `已保存 ${visuals.length} 张生成图片`, runId: run.id, creativeRuns };
}

function dispatchCaptureMessage(type, tabId) {
  const actions = {
    ADD_ACTIVE_SELECTION_TO_DRAFT: "add-active-selection",
    CAPTURE_ACTIVE_TAB_TO_DRAFT: "capture-active-tab",
    CAPTURE_VISIBLE_VISUALS_TO_DRAFT: "capture-visible-visuals"
  };
  const action = actions[type];
  if (!action) throw new Error("不支持的创作结果采集操作");
  return captureRuntime.dispatch(action, { tabId });
}

async function commitCreativeOutputsTransaction() {
  const state = await readState();
  const context = state.activeCreativeResult;
  if (!context) return { ok: false, message: "没有等待接收结果的提示词,请先在创作台复制一版提示词" };
  const session = state.composerSessions.find((item) => item.id === context.sessionId);
  if (!session) return { ok: false, message: "对应的创作草稿已经不存在" };
  const draft = await captureRuntime.getDraft();
  if (draft.fragments.length) return { ok: false, message: "本次生成结果只接收图片,请先清空待保存文字" };
  if (!draft.visuals.length) return { ok: false, message: "请先选择或框选生成图片" };

  let runs = normalizeCreativeRuns(state.creativeRuns);
  let run = runs.find((item) =>
    item.sessionId === context.sessionId && item.promptVersionId === context.promptVersionId
  );
  if (run) {
    for (const visual of draft.visuals) run = addCreativeOutput(run, visual);
    runs = [run, ...runs.filter((item) => item.id !== run.id)];
  } else {
    run = createCreativeRun(context, session, draft.visuals);
    runs = [run, ...runs];
  }
  runs = normalizeCreativeRuns(runs);
  const visualIds = draft.visuals.map((item) => item.id);
  await commitLocalChanges({
    [STORAGE_KEYS.creativeRuns]: runs,
    [STORAGE_KEYS.captureDraft]: createCaptureDraft(),
    [STORAGE_KEYS.activeCreativeResult]: null
  });
  return {
    ok: true,
    message: `已关联 ${visualIds.length} 张生成结果`,
    runId: run.id,
    visualIds,
    creativeRuns: runs,
    autoAnalyze: state.creativeExperimentSettings.enabled && state.creativeExperimentSettings.autoAnalyze
  };
}

async function analyzeCommittedCreativeOutputs(committed) {
  if (!committed.ok || !committed.autoAnalyze) return committed;

  const failures = [];
  for (const visualId of committed.visualIds) {
    const result = await analyzeCreativeOutput(committed.runId, visualId);
    if (!result.ok) failures.push(result.message);
  }
  if (!failures.length) {
    return { ...committed, message: `${committed.message},高级视觉对照已完成` };
  }
  return {
    ...committed,
    message: `${committed.message};视觉对照未完成:${failures[0]}`,
    analysisWarning: failures[0]
  };
}

async function updateCreativeExperimentSettings(value) {
  const settings = normalizeCreativeExperimentSettings(value);
  if (settings.autoAnalyze) {
    const vision = resolveVisionTaskSettings("imageAnalysis", await loadAiConfiguration());
    if (!vision.consent || !vision[vision.activeProvider].apiKey) {
      throw new Error("自动视觉对照需要先完成图片视觉设置并确认截图发送范围");
    }
  }
  await commitLocalChanges({ [STORAGE_KEYS.creativeExperimentSettings]: settings });
  return {
    ok: true,
    message: settings.enabled
      ? settings.autoAnalyze ? "创作实验已开启,保存结果后会使用当前视觉服务分析" : "创作实验已开启"
      : "创作实验已关闭",
    creativeExperimentSettings: settings
  };
}

async function saveCreativeOutputToLibrary(message) {
  const state = await readState();
  const located = findCreativeOutput(state.creativeRuns, message.runId, message.visualId);
  if (!located) return { ok: false, message: "没有找到这张创作结果" };
  let posterAssetId = "";
  let metadataCommitted = false;
  try {
  let run = located.run;
  const output = located.output;
  const videoOutput = output.visual.kind === "video";
  const outputAssets = [output.visual];
  if (videoOutput) {
    const thumbnail = (await getDerivedMedia(output.visual.id).catch(() => null))?.thumbnail;
    if (thumbnail instanceof Blob) {
      const posterId = `poster:${output.visual.id}`;
      await saveMediaBlob(posterId, thumbnail);
      posterAssetId = posterId;
      outputAssets[0] = { ...output.visual, posterAssetId: posterId };
      outputAssets.push({
        id: posterId,
        kind: "image",
        usage: "poster",
        derivedFromAssetId: output.visual.id,
        storageMode: "managed",
        mimeType: thumbnail.type,
        byteSize: thumbnail.size,
        width: output.visual.width,
        height: output.visual.height,
        capturedAt: output.visual.capturedAt,
        reviewStatus: "verified"
      });
    }
  }
  const existing = state.entries.find((entry) =>
    entry.creationMeta?.promptVersionId === run.promptVersionId
  );
  let entry;
  let entries;
  if (existing) {
    entry = {
      ...existing,
      creationMeta: {
        ...existing.creationMeta,
        creativeRunId: run.id,
        promptVersionId: run.promptVersionId
      }
    };
    const newAssets = outputAssets.filter(asset => !existing.mediaAssets?.some(item => item.id === asset.id));
    for (const asset of newAssets) entry = addEntryMedia(entry, asset, { makePrimary: false });
    entry = normalizeEntryMedia({ ...entry, mediaPrompts: [...(entry.mediaPrompts ?? []), ...embeddedMediaPrompts(newAssets, entry.mediaPrompts)] });
    entries = state.entries.map((item) => item.id === existing.id ? entry : item);
  } else {
    entry = {
      ...buildEntry({ text: run.promptText, title: run.title || "创作结果", url: "" }),
      schemaVersion: SCHEMA_VERSION,
      classification: (() => {
        const contentType = contentTypeForRole(state.taxonomy, videoOutput ? CONTENT_ROLES.promptVideo : CONTENT_ROLES.promptImage);
        return contentType
          ? { pathIds: [contentType.id], status: "confirmed", source: "composer", reason: "创作结果回流" }
          : { pathIds: [], status: "needs_review", source: "composer", reason: `没有匹配${videoOutput ? "视频" : "图片"}创作用途的内容类型` };
      })(),
      facetAssignments: [],
      analysisCandidates: [],
      analysisBreakdown: [],
      rejectedCandidateKeys: [],
      negativeTerms: [],
      legacyFacetCandidates: [],
      analysisPending: false,
      mediaAssets: outputAssets,
      mediaPrompts: embeddedMediaPrompts(outputAssets),
      primaryMediaId: output.visual.id,
      creationMeta: {
        creativeRunId: run.id,
        promptVersionId: run.promptVersionId,
        methodVersion: run.methodVersion || COMPOSER_METHOD_VERSION,
        targetPlatform: run.targetPlatform,
        outputLanguage: run.outputLanguage,
        createdAt: run.createdAt
      }
    };
    entries = [...state.entries, normalizeEntryMedia(entry)];
  }
  const promptPlan = await planImageGenerationPrompts(entry, outputAssets.filter(asset => !existing?.mediaAssets?.some(item => item.id === asset.id)), message.generationPromptChoices);
  if (promptPlan.conflicts.length) return generationPromptConfirmation(promptPlan.conflicts);
  entry = promptPlan.entry;
  entries = entries.map(item => item.id === entry.id ? entry : item);
  run = recordCreativeSignal(run, output.visual.id, "saved_to_library");
  const creativeRuns = replaceCreativeRun(state.creativeRuns, run);
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: entries,
    [STORAGE_KEYS.creativeRuns]: creativeRuns
  });
  metadataCommitted = true;
  let warning = "";
  if (!videoOutput) {
    try { await queueAutomaticVisionAnalysis([entry.id]); }
    catch (error) { warning = `结果已保存,但自动画面分析没有加入队列:${userMessage(error)}`; }
  }
  return {
    ok: true,
    message: `${existing ? `结果${videoOutput ? "视频" : "图片"}已加入对应案例` : "结果与这版提示词已保存到灵感库"}${warning ? `;${warning}` : ""}`,
    entry,
    creativeRuns,
    ...(warning ? { warnings: [warning] } : {})
  };
  } catch (error) {
    if (posterAssetId && !metadataCommitted) await deleteUnreferencedMedia([posterAssetId]).catch(() => undefined);
    throw error;
  }
}

async function updateCreativeSignal(message) {
  const state = await readState();
  const located = findCreativeOutput(state.creativeRuns, message.runId, message.visualId);
  if (!located) return { ok: false, message: "没有找到这张创作结果" };
  const run = recordCreativeSignal(located.run, located.output.visual.id, message.signalType);
  const creativeRuns = replaceCreativeRun(state.creativeRuns, run);
  await commitLocalChanges({ [STORAGE_KEYS.creativeRuns]: creativeRuns });
  return { ok: true, creativeRuns };
}

async function updateCreativeJudgmentAction(message) {
  const state = await readState();
  const located = findCreativeOutput(state.creativeRuns, message.runId, message.visualId);
  if (!located) return { ok: false, message: "没有找到这项创作结果" };
  const run = updateCreativeJudgment(located.run, located.output.visual.id, message.judgment);
  const creativeRuns = replaceCreativeRun(state.creativeRuns, run);
  await commitLocalChanges({ [STORAGE_KEYS.creativeRuns]: creativeRuns });
  const judgment = run.outputs.find((item) => item.visual.id === located.output.visual.id)?.judgment ?? null;
  return {
    ok: true,
    message: judgment ? "本次人工判断已保存" : "本次人工判断已清空",
    creativeRuns,
    judgment
  };
}

async function deleteCreativeOutput(message) {
  const state = await readState();
  const located = findCreativeOutput(state.creativeRuns, message.runId, message.visualId);
  if (!located) return { ok: false, message: "没有找到这张创作结果" };
  const run = removeCreativeOutput(located.run, located.output.visual.id);
  const creativeRuns = replaceCreativeRun(state.creativeRuns, run);
  const retained = collectRetainedLocalAssetIds({ ...state, creativeRuns }).has(located.output.visual.id);
  if (located.output.visual.kind === "video") {
    await commitLocalChanges({ [STORAGE_KEYS.creativeRuns]: creativeRuns });
    if (!retained) await deleteMediaBlob(located.output.visual.id);
    return { ok: true, message: "生成结果已移除", creativeRuns };
  }
  await commitMetadataThenDeleteImages({
    imageIds: retained ? [] : [located.output.visual.id],
    deleteImage: deleteScreenshotBlob,
    commitMetadata: () => commitLocalChanges({ [STORAGE_KEYS.creativeRuns]: creativeRuns })
  });
  return { ok: true, message: "生成结果已移除", creativeRuns };
}

async function analyzeCreativeOutput(runId, visualId) {
  if (visionAnalysisInFlight) return { ok: false, message: "已有一张图片正在分析,请等待完成" };
  visionAnalysisInFlight = true;
  try {
    const state = await readState();
    if (!state.creativeExperimentSettings.enabled) {
      return { ok: false, message: "请先在分析设置中开启“创作实验(高级)”" };
    }
    const located = findCreativeOutput(state.creativeRuns, runId, visualId);
    if (!located) return { ok: false, message: "没有找到这张创作结果" };
    const blob = await getScreenshotBlob(located.output.visual.id);
    if (!blob) return { ok: false, message: "没有读取到这张生成结果" };
    const fingerprint = await imageFingerprint(blob);
    const privateSettings = resolveVisionTaskSettings("imageAnalysis", await loadAiConfiguration());
    const result = await evaluateCreativeOutputWithVision({
      imageDataUrl: await blobToDataUrl(blob),
      locale: located.run.outputLanguage === "en" ? "en" : "zh-CN",
      settings: privateSettings,
      target: creativeEvaluationTarget(located.run)
    });
    return await enqueue(async () => {
      const latest = await readState();
      const current = findCreativeOutput(latest.creativeRuns, runId, visualId);
      const currentBlob = await getScreenshotBlob(visualId);
      if (!current || !currentBlob || await imageFingerprint(currentBlob) !== fingerprint) {
        return { ok: false, message: "分析期间结果图片已经变化,本次对照没有写入" };
      }
      const run = applyCreativeEvaluation(current.run, visualId, {
        ...result,
        resultFingerprint: fingerprint,
        analyzedAt: new Date().toISOString()
      });
      const creativeRuns = replaceCreativeRun(latest.creativeRuns, run);
      await commitLocalChanges({ [STORAGE_KEYS.creativeRuns]: creativeRuns });
      return { ok: true, message: "视觉对照已完成", creativeRuns, evaluation: run.outputs.find((item) => item.visual.id === visualId)?.evaluation };
    });
  } catch (error) {
    return { ok: false, message: userMessage(error) };
  } finally {
    visionAnalysisInFlight = false;
  }
}

function activeCreativePromptSummary(context, sessions) {
  if (!context) return null;
  const session = sessions.find((item) => item.id === context.sessionId);
  const version = session?.promptVersions.find((item) => item.id === context.promptVersionId);
  if (!session || !version || session.targetType !== "image") return null;
  return {
    sessionId: session.id,
    promptVersionId: version.id,
    title: version.title || session.title,
    targetPlatform: session.targetPlatform
  };
}

function findCreativeOutput(runsValue, runIdValue, visualIdValue) {
  const run = normalizeCreativeRuns(runsValue).find((item) => item.id === String(runIdValue ?? "").trim());
  const output = run?.outputs.find((item) => item.visual.id === String(visualIdValue ?? "").trim());
  return run && output ? { run, output } : null;
}

function replaceCreativeRun(runsValue, run) {
  return normalizeCreativeRuns([run, ...normalizeCreativeRuns(runsValue).filter((item) => item.id !== run.id)]);
}

function creativeEvaluationTarget(run) {
  return {
    targetType: run.targetType,
    targetPlatform: run.targetPlatform || "通用",
    userRequest: run.briefSnapshot.filter((item) => item.role === "user").map((item) => item.content).join("\n"),
    finalPrompt: run.promptText,
    executionInstruction: run.executionInstruction
  };
}

async function updateClassification(message) {
  const state = await readState();
  if (!isValidContentPath(state.taxonomy, message.pathIds)) {
    return { ok: false, message: "内容分类路径无效" };
  }
  const current = findEntry(state, message.entryId);
  const recovery = await recoverPaletteAfterClassification(confirmClassification(current, message.pathIds, state.taxonomy));
  const updated = touchEntry(recovery.entry);
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  let classificationRules = state.classificationRules;
  if (message.rememberSource) {
    const rule = createSourceRule(current.url, message.pathIds, state.taxonomy);
    classificationRules = [
      ...state.classificationRules.filter((item) => item.hostname !== rule.hostname),
      rule
    ];
  }
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: entries,
    [STORAGE_KEYS.classificationRules]: classificationRules
  });
  const confirmationMessage = message.rememberSource ? "分类已确认,并记住此来源" : "内容分类已确认";
  return {
    ok: true,
    message: [confirmationMessage, recovery.paletteMessage].filter(Boolean).join(","),
    entry: updated,
    classificationRules
  };
}

async function recoverPaletteAfterClassification(entry) {
  const visual = primaryVisual(entry);
  if (!visual || visual.palette?.colors?.length) {
    return { entry };
  }
  try {
    await ensureOffscreenDocument();
    const result = await chrome.runtime.sendMessage({
      target: "offscreen", type: "ANALYZE_STORED_SCREENSHOT", entryId: visual.id
    });
    if (result?.ok && result.palette?.colors?.length) {
      return { entry: updateEntryVisual(entry, visual.id, (item) => ({ ...item, palette: result.palette })), paletteMessage: "色卡已从本地主图恢复" };
    }
    return { entry, paletteMessage: "本地截图暂时无法恢复色卡" };
  } catch {
    return { entry, paletteMessage: "本地截图暂时无法恢复色卡" };
  }
}

async function updateContentTypeName(message) {
  const state = await readState();
  const taxonomy = updateContentType(state.taxonomy, message.contentId, { name: message.name });
  await commitLocalChanges({ [STORAGE_KEYS.taxonomy]: taxonomy });
  return { ok: true, message: "内容类型显示名已更新,历史案例会同步显示新名称", taxonomy };
}

async function createLibraryContentType(message) {
  const state = await readState();
  const taxonomy = createContentType(state.taxonomy, {
    id: `content:${crypto.randomUUID()}`,
    name: message.name,
    role: message.role
  });
  await commitLocalChanges({ [STORAGE_KEYS.taxonomy]: taxonomy });
  return { ok: true, message: "内容类型已创建", taxonomy };
}

async function updateLibraryContentType(message) {
  const state = await readState();
  const taxonomy = updateContentType(state.taxonomy, message.contentId, {
    name: message.name,
    role: message.role
  });
  await commitLocalChanges({ [STORAGE_KEYS.taxonomy]: taxonomy });
  return { ok: true, message: "内容类型已更新,历史案例会继续使用这个分类", taxonomy };
}

async function updateLibraryContentTypeVisibility(message) {
  const state = await readState();
  const visibility = message.visibility === CONTENT_TYPE_VISIBILITY.categoryOnly
    ? CONTENT_TYPE_VISIBILITY.categoryOnly
    : CONTENT_TYPE_VISIBILITY.library;
  const taxonomy = updateContentType(state.taxonomy, message.contentId, { visibility });
  await commitLocalChanges({ [STORAGE_KEYS.taxonomy]: taxonomy });
  return {
    ok: true,
    message: visibility === CONTENT_TYPE_VISIBILITY.categoryOnly
      ? "这个内容类型现在仅在分类内显示"
      : "这个内容类型现在会显示在资料库中",
    taxonomy
  };
}

async function deleteLibraryContentType(message) {
  const state = await readState();
  const transferred = removeContentTypeWithTransfer(state, message.contentId, message.replacementId);
  await commitLocalChanges({
    [STORAGE_KEYS.entries]: transferred.entries,
    [STORAGE_KEYS.classificationRules]: transferred.classificationRules,
    [STORAGE_KEYS.taxonomy]: transferred.taxonomy
  });
  return {
    ok: true,
    message: transferred.movedCount
      ? `内容类型已删除,${transferred.movedCount} 条案例已转移`
      : "内容类型已删除",
    entries: transferred.entries,
    classificationRules: transferred.classificationRules,
    taxonomy: transferred.taxonomy
  };
}

async function createFacetTag(message) {
  const state = await readState();
  const before = domainState(state);
  const facetCatalog = createFacetNode(state.facetCatalog, {
    facetId: message.facetId,
    parentId: message.parentId || null,
    name: message.name,
    aliases: message.aliases,
    patterns: message.patterns
  });
  const next = { ...before, facetCatalog };
  await persistDomainState(next, before, { entriesChanged: false });
  return { ok: true, message: "创作标签已创建", facetCatalog, canUndoFacetUpdate: true };
}

async function applyDetailTagOrganization(message) {
  const state = await readState();
  const before = domainState(state);
  const applied = applyDetailOrganizationMappings(before, message.mappings);
  if (!applied.changedCount) {
    return { ok: true, message: "当前没有需要整理的三级标签组。", ...publicDomainState(before) };
  }
  const changedIds = userVisibleEntryChanges(before.entries, applied.state.entries);
  const nextState = { ...applied.state, entries: touchEntries(applied.state.entries, changedIds) };
  await persistDomainState(nextState, before);
  return {
    ok: true,
    message: `已整理 ${applied.changedCount} 个三级标签,其中合并 ${applied.mergedCount} 个;旧名称仍可搜索`,
    ...publicDomainState(nextState),
    canUndoFacetUpdate: true
  };
}

async function updateAiProviderConfiguration(message = {}) {
  const current = await loadAiConfiguration();
  const registry = mergeAiProviderRegistry(current.registry, message.registry);
  let assignments = normalizeAiTaskAssignments(message.assignments ?? current.assignments, registry);
  const connectionSelections = Array.isArray(message.connectionSelections)
    ? message.connectionSelections
    : message.connectionSelection ? [message.connectionSelection] : [];
  for (const selection of connectionSelections) {
    assignments = applyConnectionModelAssignments(assignments, selection, registry);
  }
  for (const [taskId, assignment] of Object.entries(assignments)) {
    const requested = Number(assignment?.concurrency);
    const limit = modelConcurrencyLimit(assignment?.providerId, assignment?.model, registry);
    if (Number.isInteger(requested) && Number.isInteger(limit) && requested > limit) {
      throw new Error(`${taskId} 的并发数 ${requested} 超过所选模型官方上限 ${limit}`);
    }
  }
  const configuration = {
    registry,
    assignments,
    preferences: normalizeAiPreferences(message.preferences ?? current.preferences)
  };
  await persistAiConfiguration(configuration);
  return aiConfigurationResponse(configuration, "AI 服务配置已保存");
}

async function verifyAiImageGenerationCredential(message = {}) {
  const providerId = String(message.providerId ?? "").trim();
  const configuration = providerId ? await loadAiConfiguration() : null;
  const profile = configuration?.registry?.providers?.[providerId];
  const endpoint = String(message.endpoint ?? profile?.imageGeneration?.endpoint ?? "").trim();
  const apiKey = String(message.apiKey ?? "").trim() || String(profile?.imageGeneration?.apiKey ?? "").trim();
  const model = String(message.model ?? profile?.models?.imageGeneration ?? profile?.imageGeneration?.model ?? "").trim();
  if (!endpoint || !apiKey || !model) throw new Error("图片生成 Key 校验缺少接口、Key 或模型");
  const result = await aiProviderModule.verifyModelAccess({
    id: "custom-media-image-credential-check",
    endpoint,
    apiKey,
    protocol: "images_generations"
  }, model);
  if (!result.available) {
    throw new Error(`当前保存的图片生成 API Key 的模型列表中没有 ${model}。米醋生图必须使用 vip_2_image(Image2)分组 Key;本次设置更改未保存,也没有发起生图请求。`);
  }
  return {
    ok: true,
    model,
    verification: result.verification,
    executionVerified: result.executionVerified,
    message: `模型目录中可见 ${model};这只证明目录可见,不代表米醋已授权该 Key 进入生图分组`
  };
}

async function previewAiProviderModels(message = {}) {
  const providerId = String(message.providerId ?? "").trim();
  const current = await loadAiConfiguration();
  const registry = mergeAiProviderRegistry(current.registry, message.registry);
  const profile = registry.providers[providerId];
  if (!profile) throw new Error("所选 AI 服务不存在");
  let result;
  try {
    result = await aiProviderModule.discoverModels({
      ...profile,
      models: {
        ...profile.models,
        ...assignedModelsForProvider(current.assignments, providerId)
      }
    }, { etag: "" });
  } catch (error) {
    throw new Error(discoveryErrorMessage(error, profile.apiKey), { cause: error });
  }
  const previewRegistry = mergeAiProviderRegistry(registry, { providers: {
    [providerId]: {
      discoveredModels: result.models,
      discovery: {
        discoveredAt: result.discoveredAt,
        source: result.source,
        etag: result.cache?.etag,
        cacheControl: result.cache?.cacheControl,
        error: ""
      }
    }
  } });
  return {
    ok: true,
    message: `${profile.label} 已读取 ${result.models.length} 个模型;保存前请选择分析模型`,
    provider: publicAiProviderRegistry(previewRegistry).providers[providerId]
  };
}

async function discoverAiProviderModels(providerIdValue, force = false) {
  const providerId = String(providerIdValue ?? "").trim();
  const configuration = await loadAiConfiguration();
  const profile = configuration.registry.providers[providerId];
  if (!profile) throw new Error("没有找到要刷新的 AI 厂商");
  if (!profile.endpoint || !profile.apiKey) throw new Error(`${profile.label} 需要先保存接口地址和 API Key`);
  let result;
  try {
    result = await aiProviderModule.discoverModels({
      ...profile,
      models: {
        ...profile.models,
        ...assignedModelsForProvider(configuration.assignments, providerId)
      }
    }, {
      etag: force ? "" : profile.discovery?.etag
    });
  } catch (error) {
    const visibleError = discoveryErrorMessage(error, profile.apiKey);
    await enqueue(async () => {
      const current = await loadAiConfiguration();
      const currentProfile = current.registry.providers[providerId];
      if (!sameProviderConnection(currentProfile, profile)) return;
      const registry = mergeAiProviderRegistry(current.registry, { providers: {
        [providerId]: {
          discovery: { ...currentProfile.discovery, error: visibleError }
        }
      } });
      await persistAiConfiguration({ ...current, registry });
    });
    throw new Error(visibleError, { cause: error });
  }
  return enqueue(async () => {
    const current = await loadAiConfiguration();
    const currentProfile = current.registry.providers[providerId];
    if (!sameProviderConnection(currentProfile, profile)) {
      throw new Error(`${profile.label} 的连接已在模型读取期间变更,请重新刷新`);
    }
    const registry = mergeAiProviderRegistry(current.registry, { providers: {
      [providerId]: {
        discoveredModels: result.models,
        discovery: {
          discoveredAt: result.discoveredAt,
          source: result.source,
          etag: result.cache?.etag,
          cacheControl: result.cache?.cacheControl,
          error: ""
        }
      }
    } });
    const next = { ...current, registry };
    await persistAiConfiguration(next);
    return aiConfigurationResponse(next, `${profile.label} 已发现 ${result.models.length} 个模型`);
  });
}

function assignedModelsForProvider(assignments = {}, providerId = "") {
  return Object.fromEntries(Object.entries(assignments).flatMap(([taskId, assignment]) =>
    assignment?.providerId === providerId && assignment.model ? [[taskId, assignment.model]] : []
  ));
}

function sameProviderConnection(current, requested) {
  return Boolean(current
    && current.endpoint === requested.endpoint
    && current.protocol === requested.protocol
    && current.apiKey === requested.apiKey);
}

function discoveryErrorMessage(error, apiKey) {
  const message = userMessage(error);
  const secret = String(apiKey ?? "").trim();
  return secret ? message.split(secret).join("[已隐藏 API Key]") : message;
}

async function loadAiConfiguration() {
  const stored = await libraryStorage.get([
    STORAGE_KEYS.aiProviderRegistry, STORAGE_KEYS.aiTaskAssignments, STORAGE_KEYS.aiPreferences
  ]);
  return aiConfigurationFromStorage(stored);
}

async function persistAiConfiguration(configuration) {
  await commitLocalChanges({
    [STORAGE_KEYS.aiProviderRegistry]: configuration.registry,
    [STORAGE_KEYS.aiTaskAssignments]: configuration.assignments,
    [STORAGE_KEYS.aiPreferences]: configuration.preferences
  });
}

function aiConfigurationResponse(configuration, message) {
  const runtime = projectAiRuntime(configuration);
  return {
    ok: true,
    message,
    aiProviderRegistry: publicAiProviderRegistry(configuration.registry),
    aiTaskAssignments: configuration.assignments,
    aiPreferences: configuration.preferences,
    aiSettings: publicAiSettings(runtime.aiSettings),
    visionSettings: publicVisionSettings(runtime.visionSettings),
    aiServiceProfiles: publicAiServiceProfiles(runtime.aiServiceProfiles)
  };
}

async function getAiTaskRuntime(taskIdValue, allowUnconfigured = false, assignmentOverride = null) {
  const taskId = canonicalAiTaskId(taskIdValue);
  const storedConfiguration = await loadAiConfiguration();
  const requestedProviderId = String(assignmentOverride?.providerId ?? "").trim();
  const requestedModel = String(assignmentOverride?.model ?? "").trim();
  const configuration = requestedProviderId || requestedModel ? {
    ...storedConfiguration,
    assignments: normalizeAiTaskAssignments({
      ...storedConfiguration.assignments,
      [taskId]: {
        providerId: requestedProviderId || storedConfiguration.assignments[taskId]?.providerId,
        model: requestedModel || storedConfiguration.assignments[taskId]?.model,
        concurrency: assignmentOverride?.concurrency ?? storedConfiguration.assignments[taskId]?.concurrency
      }
    }, storedConfiguration.registry)
  } : storedConfiguration;
  const assignment = configuration.assignments[taskId];
  const providerLabel = configuration.registry.providers[assignment?.providerId]?.label || assignment?.providerId;
  const common = {
    ok: true,
    aiRuntimeProtocolVersion: AI_RUNTIME_PROTOCOL_VERSION,
    taskId,
    assignment,
    providerLabel,
    runtimeDescriptor: aiTaskRuntimeDescriptor(taskId, configuration),
    availableProviders: aiTaskProviderOptions(taskId, configuration)
  };
  if (["textTags", "skillExtraction", "creativePlanning"].includes(taskId)) {
    return { ...common, aiSettings: resolveTextTaskSettings(taskId, configuration, { requireConfigured: !allowUnconfigured }) };
  }
  if (["imageAnalysis", "imageGeneration"].includes(taskId)) {
    return { ...common, visionSettings: resolveVisionTaskSettings(taskId, configuration, { requireConfigured: !allowUnconfigured }) };
  }
  if (taskId === "videoAnalysis") {
    if (allowUnconfigured && !assignment?.providerId) return { ...common, videoAnalysis: null };
    return { ...common, videoAnalysis: resolveVideoAnalysisTask(configuration) };
  }
  if (taskId === "videoGeneration") return { ...common, runtime: projectAiRuntime(configuration) };
  throw new Error("未知 AI 任务");
}

function aiTaskProviderOptions(taskId, configuration) {
  return availableAiProvidersForTask(taskId, configuration.registry).filter((provider) =>
    configuration.registry.providers[provider.id]?.consent === true
  ).map((provider) => {
    const profile = configuration.registry.providers[provider.id];
    const models = [...new Set([
      profile?.models?.[taskId],
      ...availableAiModelsForTask(taskId, profile).map((model) => model.id)
    ].filter(Boolean))];
    return { id: provider.id, label: provider.label, models };
  });
}

function aiTaskRuntimeDescriptor(taskId, configuration) {
  const assignment = configuration.assignments[taskId] ?? {};
  const profile = configuration.registry.providers[assignment.providerId] ?? {};
  const model = (profile.discoveredModels ?? []).find((item) => item.id === assignment.model);
  let endpointOrigin = "";
  try { endpointOrigin = new URL(profile.endpoint).origin; } catch {}
  const imageSupport = model?.inputModalities?.includes("image")
    ? true
    : model?.inputModalities?.length ? false : taskId === "imageAnalysis" ? null : false;
  return {
    providerId: assignment.providerId || "",
    providerLabel: profile.label || assignment.providerId || "",
    model: assignment.model || "",
    endpointOrigin,
    capabilities: {
      text: true,
      image: imageSupport,
      imageSource: model?.confidence || "unknown",
      maxImages: Number.isInteger(model?.referenceImages?.maxItems) ? model.referenceImages.maxItems : null
    }
  };
}

async function getComposerAiRuntime() {
  const configuration = await loadAiConfiguration();
  const runtime = projectAiRuntime(configuration);
  return {
    ok: true,
    aiRuntimeProtocolVersion: AI_RUNTIME_PROTOCOL_VERSION,
    ...runtime
  };
}

function canonicalAiTaskId(value) {
  const map = {
    "text-tags": "textTags", "skill-extraction": "skillExtraction", "creative-planning": "creativePlanning",
    "image-analysis": "imageAnalysis", "video-analysis": "videoAnalysis",
    "image-generation": "imageGeneration", "video-generation": "videoGeneration"
  };
  const id = String(value ?? "").trim();
  return map[id] || id;
}

function applyCompletedVisionResult(state, entry, visual, result, { fingerprint, catalogRevision, locale, batchJobId = "" }) {
  return applyCompletedImageResult(state, entry, visual, result, {
    imageFingerprint: fingerprint, profileFingerprint: result.profileFingerprint, catalogRevision, locale,
    providerType: result.providerType, model: result.model, usage: result.usage,
    cacheHit: result.cacheHit, attempts: result.attempts, batchJobId
  });
}

async function analyzeEntryImage(entryId, visualIdValue, outputLocale, batchJobIdValue = "", bypassCache = false, assignmentOverride = null, priority = "user_batch") {
    const state = await readState();
    const entry = findEntry(state, entryId);
    const visualId = String(visualIdValue ?? "").trim() || primaryVisual(entry)?.id;
    const visual = normalizeEntryVisuals(entry).visuals.find((item) => item.id === visualId);
    if (!visual) return { ok: false, message: "这条案例没有可分析的截图" };
    const blob = await getVisionImageBlob(visual.id);
    if (!blob) return { ok: false, message: "没有读取到这条案例的截图" };
    const loadedConfiguration = await loadAiConfiguration();
    const configuration = configurationForAssignment(loadedConfiguration, "imageAnalysis", assignmentOverride);
    const locale = outputLocale === "en" ? "en" : "zh-CN";
    const { result, fingerprint } = await analyzeVisionBlobWithScheduler({
      blob,
      catalog: state.facetCatalog,
      locale,
      measuredCanvas: { width: visual.width, height: visual.height },
      configuration,
      previousAnalysis: visual.visionAnalysis,
      entries: state.entries,
      bypassCache,
      priority
    });

    return await enqueue(async () => {
      const currentState = await readState();
      const current = findEntry(currentState, entry.id);
      const currentVisual = normalizeEntryVisuals(current).visuals.find((item) => item.id === visual.id);
      const currentBlob = await getVisionImageBlob(visual.id);
      if (!currentVisual || !currentBlob || await imageFingerprint(currentBlob) !== fingerprint) {
        return { ok: false, message: "分析期间截图已经变化,本次结果没有写入,请重新分析" };
      }
      const applied = applyCompletedVisionResult(domainState(currentState), current, currentVisual, result, {
        fingerprint, catalogRevision: state.facetCatalog.revision, locale: outputLocale,
        batchJobId: String(batchJobIdValue ?? "").trim()
      });
      const undoStore = {
        ...((await libraryStorage.get(STORAGE_KEYS.visionAnalysisUndo))[STORAGE_KEYS.visionAnalysisUndo] ?? {})
      };
      undoStore[current.id] = applied.undo;
      await commitLocalChanges({
        ...storagePayload(applied.state),
        [STORAGE_KEYS.visionAnalysisUndo]: undoStore
      });
      return {
        ok: true,
        message: result.tagDiagnostics?.rejectedCount
          ? `画面分析已保存,并写入 ${applied.appliedCount} 个检索标签;另有 ${result.tagDiagnostics.rejectedCount} 个不符合当前分类体系的可选标签未采用`
          : `画面分析已保存,并写入 ${applied.appliedCount} 个检索标签`,
        entry: applied.state.entries.find((item) => item.id === current.id),
        usage: result.usage,
        cacheHit: result.cacheHit,
        attempts: result.attempts,
        quality: "complete",
        ...publicDomainState(applied.state),
        visionUndoEntryIds: Object.keys(undoStore)
      };
    });
}

function configurationForAssignment(configuration, taskId, assignmentOverride) {
  const providerId = String(assignmentOverride?.providerId ?? "").trim();
  const model = String(assignmentOverride?.model ?? "").trim();
  if (!providerId && !model) return configuration;
  return {
    ...configuration,
    assignments: normalizeAiTaskAssignments({
      ...configuration.assignments,
      [taskId]: {
        ...configuration.assignments[taskId],
        providerId: providerId || configuration.assignments[taskId]?.providerId,
        model: model || configuration.assignments[taskId]?.model,
        concurrency: assignmentOverride?.concurrency ?? configuration.assignments[taskId]?.concurrency
      }
    }, configuration.registry)
  };
}

async function analyzeVisionBlobWithScheduler({ blob, catalog, locale, measuredCanvas, configuration, previousAnalysis, entries = [], bypassCache = false, priority = "user_batch", signal }) {
  signal?.throwIfAborted();
  const fingerprint = await imageFingerprint(blob);
  const assignment = configuration.assignments.imageAnalysis;
  const settings = resolveVisionTaskSettings("imageAnalysis", configuration);
  const profileFingerprint = await visionAnalysisProfileFingerprint(settings, locale);
  const cached = findPersistedVisionAnalysis(entries, {
    fingerprint,
    profileFingerprint,
    locale,
    catalogRevision: catalog?.revision
  });
  if (!bypassCache && cached?.quality === "complete") return {
    fingerprint,
    result: {
      ...cached,
      cacheHit: true,
      attempts: { serviceRequests: 0, outputCorrectionRequests: 0 },
      usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
    }
  };
  const schedulerKey = `${assignment.providerId}:${assignment.model}:imageAnalysis`;
  const requestMode = bypassCache ? "reanalyze" : "analyze";
  const requestKey = `${schedulerKey}:${fingerprint}:${profileFingerprint}:${locale}:${catalog?.revision ?? 0}:${requestMode}`;
  const requestBudget = createVisionRequestBudget();
  let coalesced = false;
  let result;
  try {
    result = await coalesceAnalysisRequest(requestKey, (requestSignal) => runScheduledAnalysisWithRetries({
      signal: requestSignal,
      requestBudget,
      key: schedulerKey,
      concurrency: assignment.concurrency,
      priority,
      task: async () => {
        return analyzeImageWithVision({
          imageDataUrl: await blobToDataUrl(blob),
          catalog,
          locale,
          measuredCanvas,
          previousAnalysis: null,
          settings,
          signal: requestSignal,
          requestBudget
        });
      }
    }), { signal, onCoalesced: () => { coalesced = true; } });
  } catch (error) {
    error.attempts = {
      serviceRequests: coalesced ? 0 : visionPrimaryRequestCount(requestBudget),
      outputCorrectionRequests: coalesced ? 0 : requestBudget.outputCorrectionRequests
    };
    throw error;
  }
  return {
    result: {
      ...result,
      cacheHit: result.cacheHit === true || coalesced,
      attempts: {
        serviceRequests: coalesced ? 0 : visionPrimaryRequestCount(requestBudget),
        outputCorrectionRequests: coalesced ? 0 : requestBudget.outputCorrectionRequests
      }
    },
    fingerprint
  };
}

function visionPrimaryRequestCount(requestBudget) {
  return Math.max(
    0,
    (Number(requestBudget?.providerCalls) || 0) - (Number(requestBudget?.outputCorrectionRequests) || 0)
  );
}

async function analyzeEntryVisualSet(message) {
  const state = await readState();
  const current = normalizeEntryMedia(findEntry(state, message.entryId));
  const locale = message.outputLocale === "en" ? "en" : "zh-CN";
  const selectedIds = new Set((Array.isArray(message.assetIds) ? message.assetIds : []).map((id) => String(id ?? "").trim()).filter(Boolean));
  const assets = current.mediaAssets.filter((asset) => asset.kind === "image" && asset.usage !== "poster" && (!selectedIds.size || selectedIds.has(asset.id)));
  const prepared = prepareVisualSetSummary(assets.map((asset) => ({
    assetId: asset.id,
    imageFingerprint: asset.contentHash,
    analysis: asset.visionAnalysis
  })), locale);
  if (!prepared.ready) return {
    ok: false,
    code: "missing_individual_analysis",
    missingAssetIds: prepared.missingAssetIds,
    message: `还有 ${prepared.missingAssetIds.length} 张图片缺少有效的独立分析,请先完成逐图分析`
  };
  const configuration = await loadAiConfiguration();
  const result = await summarizeVisualSetWithAi(prepared.input, resolveTextTaskSettings("creativePlanning", configuration), {
    instruction: compileVisualSetSummaryInstruction(locale)
  });
  const summary = normalizeVisualSetSummaryV1(result.value, assets.map((asset) => asset.id));
  const analysis = {
    id: `visual-set:${crypto.randomUUID()}`,
    ...summary,
    text: summary.reusablePrompt,
    mode: String(message.mode || "group"),
    batchIndex: Math.max(0, Number(message.batchIndex) || 0),
    batchCount: Math.max(1, Number(message.batchCount) || 1),
    provider: result.provider,
    model: result.model,
    usage: result.usage,
    createdAt: new Date().toISOString()
  };
  // The AI call can take minutes; append to the latest library state so edits,
  // captures and trash changes made meanwhile are never replaced.
  return enqueue(async () => {
    const latestState = await readState();
    const latest = normalizeEntryMedia(findEntry(latestState, current.id));
    const latestIds = new Set(latest.mediaAssets.map((asset) => asset.id));
    if (!assets.every((asset) => latestIds.has(asset.id))) {
      return { ok: false, message: "分析期间图片已经变化,本次结果没有写入,请重新分析" };
    }
    const updated = normalizeEntryMedia({ ...latest, visualSetAnalyses: [...latest.visualSetAnalyses, analysis] });
    const entries = latestState.entries.map((entry) => entry.id === latest.id ? updated : entry);
    await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
    return { ok: true, message: "整组图片关系分析已保存", entry: updated, analysis };
  });
}

async function dispatchVideoAnalysisTask(task) {
  const state = await readState();
  const entry = normalizeEntryMedia(findEntry(state, task.request.entryId));
  const assetId = String(task.request.assetId ?? "").trim() || entry.primaryMediaId;
  const asset = entry.mediaAssets.find((item) => item.id === assetId && item.kind === "video" && item.usage !== "poster");
  if (!asset) throw new Error("没有找到要分析的视频");
  const configuration = await loadAiConfiguration();
  const route = resolveVideoAnalysisTask(configuration);
  const requestRouteSnapshot = {
    providerId: task.request.routeProviderId,
    model: task.request.routeModel,
    protocol: task.request.protocol,
    endpoint: task.request.routeEndpoint,
    localVideo: task.request.localVideo,
    preferPublicVideoUrl: task.request.preferPublicVideoUrl,
    publicVideoUrl: task.request.publicVideoUrl
  };
  if (task.request.hasRouteSnapshot === true && !videoAnalysisRouteMatches(requestRouteSnapshot, route)) {
    throw new Error("视频分析服务的发送路径已经变化,未发送");
  }
  const sourceUrl = asset.reference?.url || asset.sourceUrl;
  const sourceKind = route.protocol === "chat_completions" || route.protocol === "openrouter"
    ? chatCompletionsVideoSourcePlan({
        providerLabel: route.providerLabel,
        hasLocalVideo: asset.storageMode === "managed",
        videoUrl: sourceUrl,
        videoMimeType: asset.mimeType,
        referenceProvider: asset.reference?.provider,
        referencePlaybackMode: asset.reference?.playbackMode,
        localVideo: route.localVideo,
        preferPublicVideoUrl: route.preferPublicVideoUrl,
        publicVideoUrl: route.publicVideoUrl
      }).sourceKind
    : asset.storageMode === "managed" ? "local-video" : "public-video-url";
  if (task.request.sourceKind && task.request.sourceKind !== sourceKind) {
    throw new Error("视频来源发送方式已经变化,未发送");
  }
  await ensureOffscreenDocument();
  const response = await chrome.runtime.sendMessage({
    target: "offscreen",
    type: "RUN_VIDEO_ANALYSIS",
    job: {
      taskId: task.id,
      attemptId: task.activeAttemptId,
      deadlineAt: task.deadlineAt,
      instruction: configuration.preferences.videoInstructionsByLocale?.[task.request.outputLocale]
        || configuration.preferences.videoInstructionsByLocale?.["zh-CN"],
      sourceKind,
      sourceFingerprint: task.request.sourceFingerprint,
      outputLocale: task.request.outputLocale,
      catalog: state.facetCatalog,
      asset: {
        id: asset.id,
        storageMode: asset.storageMode,
        mimeType: asset.mimeType,
        durationMs: asset.durationMs,
        width: asset.width,
        height: asset.height,
        sourceUrl: asset.sourceUrl,
        referenceUrl: asset.reference?.url,
        referenceProvider: asset.reference?.provider,
        referencePlaybackMode: asset.reference?.playbackMode
      },
      route: {
        providerId: route.providerId,
        concurrency: configuration.assignments.videoAnalysis.concurrency,
        providerLabel: route.providerLabel,
        protocol: route.protocol,
        endpoint: route.endpoint,
        apiKey: route.apiKey,
        model: route.model,
        maxOutputTokens: route.maxOutputTokens,
        localVideo: route.localVideo,
        preferPublicVideoUrl: route.preferPublicVideoUrl,
        publicVideoUrl: route.publicVideoUrl
      }
    }
  });
  if (!response?.ok) throw new Error(response?.message || "视频分析后台启动失败");
  return response;
}

async function completeVideoAnalysisAction(message) {
  const outcome = await enqueue(() => withAnalysisTaskStorageLock(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
    const registry = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
    const runningTask = analysisTaskById(registry, message.taskId);
    if (!runningTask || runningTask.status !== "running" || runningTask.activeAttemptId !== String(message.attemptId ?? "").trim()) {
      return { stale: true };
    }
    const analysis = message.analysis && typeof message.analysis === "object" ? message.analysis : {};
    if (!runningTask.deadlineAt || Date.now() >= Date.parse(runningTask.deadlineAt)) {
      throw new Error("视频分析已超过本次等待上限,迟到结果未保存");
    }
    let currentState = await readState();
    const current = normalizeEntryMedia(findEntry(currentState, runningTask.request.entryId));
    const asset = current.mediaAssets.find((item) => item.id === runningTask.request.assetId && item.kind === "video" && item.usage !== "poster");
    if (!asset) throw new Error("分析期间视频已被移除,本次结果没有写入");
    const expectedFingerprint = String(analysis.sourceFingerprint || runningTask.request.sourceFingerprint || "").trim();
    if (expectedFingerprint) {
      const currentBlob = asset.storageMode === "managed" ? await getMediaBlob(asset.id) : null;
      if (!currentBlob || await videoAssetFingerprint(currentBlob) !== expectedFingerprint) {
        throw new Error("分析期间视频文件已经变化,本次结果没有写入");
      }
    }
    const createdAt = new Date().toISOString();
    const record = {
      id: `video-analysis:${crypto.randomUUID()}`,
      assetId: asset.id,
      mode: "visual-reconstruction",
      prompt: analysis.prompt,
      sourceKind: analysis.sourceKind,
      provider: analysis.provider,
      model: analysis.model,
      usage: analysis.usage,
      cost: analysis.cost ?? null,
      routing: analysis.routing ?? null,
      requestId: runningTask.activeAttemptId,
      ...(runningTask.request.batchJobId ? { batchJobId: runningTask.request.batchJobId } : {}),
      createdAt,
      contractVersion: analysis.contractVersion,
      reconstructionPrompt: analysis.reconstructionPrompt,
      tags: analysis.tags,
      uncertainties: analysis.uncertainties,
      includeTags: true,
      analysisScope: analysis.analysisScope,
      finishReason: analysis.finishReason,
      userEdited: false
    };
    currentState = applyCompletedVideoResult(currentState, current, asset, record).state;
    const updated = currentState.entries.find(item => item.id === current.id);
    const savedRecord = currentVideoReconstruction(updated, asset.id);
    const actionResult = {
      ok: true,
      message: "AI 视频提示词已保存",
      entry: updated,
      analysis: savedRecord,
      requestBudget: analysis.requestBudget,
      result: { entryId: current.id, assetId: asset.id, analysisId: savedRecord.id }
    };
    const completedTask = completeAnalysisAttempt(runningTask, {
      attemptId: runningTask.activeAttemptId,
      result: actionResult
    });
    await commitLocalChanges({
      [STORAGE_KEYS.entries]: currentState.entries,
      [STORAGE_KEYS.facetCatalog]: currentState.facetCatalog,
      [STORAGE_KEYS.analysisTasks]: replaceAnalysisTask(registry, completedTask)
    });
    return { actionResult, completedTask, runningTask };
  }));
  if (outcome.stale) return { ok: false, message: "本次视频分析已经停止,迟到结果未保存" };
  await notifyAnalysisTaskUpdated(outcome.completedTask);
  if (outcome.runningTask.request.batchJobId) {
    await enqueue(() => settleVideoBatchTask(outcome.runningTask, outcome.actionResult));
  }
  return outcome.actionResult;
}

async function failVideoAnalysisAction(message) {
  const outcome = await enqueue(() => withAnalysisTaskStorageLock(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.analysisTasks);
    const registry = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
    const runningTask = analysisTaskById(registry, message.taskId);
    if (!runningTask || runningTask.status !== "running" || runningTask.activeAttemptId !== String(message.attemptId ?? "").trim()) {
      return { stale: true };
    }
    const actionResult = {
      ok: false,
      message: String(message.error?.message || "视频分析失败"),
      diagnostic: message.error?.diagnostic,
      requestBudget: message.error?.requestBudget,
      usage: message.error?.usage,
      status: Number(message.error?.status) || 0
    };
    const failedTask = failAnalysisAttempt(runningTask, {
      attemptId: runningTask.activeAttemptId,
      error: actionResult.message,
      diagnostic: message.error?.diagnostic,
      requestBudget: message.error?.requestBudget
    });
    await commitLocalChanges({
      [STORAGE_KEYS.analysisTasks]: replaceAnalysisTask(registry, failedTask)
    }, { markSyncDirty: false });
    return { actionResult, failedTask, runningTask };
  }));
  if (outcome.stale) return { ok: false, message: "本次视频分析已经结束,迟到状态已忽略" };
  await notifyAnalysisTaskUpdated(outcome.failedTask);
  if (outcome.runningTask.request.batchJobId) {
    await enqueue(() => settleVideoBatchTask(outcome.runningTask, outcome.actionResult));
  }
  return { ok: true, task: outcome.failedTask };
}

async function updateVideoReconstructionPrompt(message) {
  return caseEditor.videoReconstruction(message);
}

async function updateVisionReconstructionPrompt(entryId, visualIdValue, reconstructionPrompt) {
  return caseEditor.visionReconstruction({ entryId, visualId: visualIdValue, reconstructionPrompt });
}

async function updateEntryMediaPromptAction(message) {
  return caseEditor.mediaPrompt(message);
}

async function applyEntryMediaPromptSuggestions(message) {
  return caseEditor.mediaPromptSuggestions(message);
}

async function undoEntryVisionAnalysis(entryId) {
  const state = await readState();
  const stored = await libraryStorage.get(STORAGE_KEYS.visionAnalysisUndo);
  const undoStore = { ...(stored[STORAGE_KEYS.visionAnalysisUndo] ?? {}) };
  const undo = undoStore[entryId];
  if (!undo) return { ok: false, message: "这条案例没有可撤回的图片分析" };
  const current = findEntry(state, entryId);
  const visualId = String(undo.visualId ?? "").trim() || primaryVisual(current)?.id;
  const visual = normalizeEntryVisuals(current).visuals.find((item) => item.id === visualId);
  const temporaryState = domainState(state);
  temporaryState.entries = temporaryState.entries.map((entry) => entry.id === entryId
    ? { ...entry, visionAnalysis: visual?.visionAnalysis }
    : entry);
  const next = undoVisionAnalysis(temporaryState, undo);
  const undoneEntry = next.entries.find((entry) => entry.id === entryId);
  const restoredVision = undoneEntry.visionAnalysis;
  delete undoneEntry.visionAnalysis;
  const normalized = updateEntryVisual(undoneEntry, visualId, (item) => {
    const updated = { ...item };
    if (restoredVision) updated.visionAnalysis = restoredVision;
    else delete updated.visionAnalysis;
    return updated;
  });
  next.entries = next.entries.map((entry) => entry.id === entryId ? normalized : entry);
  delete undoStore[entryId];
  await commitLocalChanges({
    ...storagePayload(next),
    [STORAGE_KEYS.visionAnalysisUndo]: undoStore
  });
  return {
    ok: true,
    message: "已撤回本次图片分析",
    entry: next.entries.find((item) => item.id === entryId),
    ...publicDomainState(next),
    visionUndoEntryIds: Object.keys(undoStore)
  };
}

async function updateEntryFacet(message) {
  const state = await readState();
  const current = findEntry(state, message.entryId);
  const node = state.facetCatalog.nodes.find((item) => item.id === message.nodeId && item.status === "active");
  if (!node || node.facetId !== message.facetId) return { ok: false, message: "创作标签无效" };
  const next = setManualAssignment(current, node.facetId, node.id, message.selected !== false);
  const updated = userVisibleEntryEqual(current, next) ? next : touchEntry(next);
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: message.selected === false ? "标签已移除" : "创作标签已添加", entry: updated };
}

async function updateCaseArticle(message) {
  return caseEditor.article(message);
}

async function updateCaseText(message) {
  return caseEditor.text(message);
}

async function updateCaseTitle(message) {
  return caseEditor.title(message);
}

async function updateEntryCustomLabels(message) {
  return caseEditor.customLabels(message);
}

async function batchAddCustomLabels(message) {
  const state = await readCaseLibraryState();
  const requested = new Set(uniqueNames(message.entryIds));
  const labels = uniqueNames(message.customLabels);
  if (!labels.length) return { ok: false, message: "请输入要添加的标签" };
  let updatedCount = 0;
  const updatedAt = new Date().toISOString();
  const entries = state.entries.map((entry) => {
    if (!requested.has(entry.id)) return entry;
    const customLabels = uniqueNames([...(entry.customLabels ?? []), ...labels]);
    if (stringListsEqual(customLabels, entry.customLabels)) return entry;
    updatedCount += 1;
    return touchEntry({ ...entry, customLabels }, updatedAt);
  });
  if (!updatedCount) return { ok: true, message: "所选案例已经包含这些标签", updatedCount: 0, entries };
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: `已为 ${updatedCount} 个案例添加标签`, updatedCount, entries };
}

async function batchRemoveCaseTags(message) {
  const state = await readState();
  const before = domainState(state);
  const result = removeCaseTags(before, message.caseIds, message);
  if (!result.updatedCount) return { ok: true, message: '所选案例已无这些标签', updatedCount: 0 };
  const saved = await persistDomainState(result.state, before);
  return { ok: true, message: `已从 ${result.updatedCount} 个案例移除标签`, updatedCount: result.updatedCount,
    canUndoFacetUpdate: facetUndoCount(saved[STORAGE_KEYS.facetUndo]) > 0 };
}

async function batchSetClassification(message) {
  const state = await readState();
  const requested = new Set(uniqueNames(message.entryIds));
  if (!requested.size || !isValidContentPath(state.taxonomy, message.pathIds)) {
    return { ok: false, message: "请选择案例和有效的案例类型" };
  }
  const available = new Set(state.entries.map(entry => entry.id));
  if ([...requested].some(id => !available.has(id))) {
    return { ok: false, message: "部分案例已不存在,请刷新后重新选择" };
  }
  const entries = [];
  for (const entry of state.entries) {
    if (!requested.has(entry.id)) { entries.push(entry); continue; }
    entries.push(touchEntry(confirmClassification(entry, message.pathIds, state.taxonomy)));
  }
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: `已修改 ${requested.size} 个案例的分类`, updatedCount: requested.size };
}

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 = 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: "项目不存在" };
  }
  const beforeOrganizer = organizerState;
  if (mode === "move") {
    organizerState = moveEntriesBetweenCollections(
      organizerState,
      message.sourceCollectionId,
      message.collectionId,
      entryIds
    );
  } else {
    organizerState = setEntriesCollection(organizerState, message.collectionId, entryIds, mode !== "remove");
  }
  const changedEntryIds = changedProjectEntryIds(beforeOrganizer, organizerState);
  const updatedCount = changedEntryIds.length;
  const skippedCount = Math.max(0, requestedEntryIds.length - updatedCount);
  const unchangedCount = Math.max(0, entryIds.length - updatedCount);
  if (!updatedCount) {
    return {
      ok: true,
      message: `${mode === "remove" ? "所选案例原本不在这个项目中" : "所选案例已经在这个项目中"}${missingCount ? `;${missingCount} 个案例不存在` : ""}`,
      updatedCount,
      skippedCount,
      unchangedCount,
      missingCount,
      entries: state.entries,
      organizerState: beforeOrganizer
    };
  }
  const entries = touchEntries(state.entries, changedEntryIds);
  await commitLocalChanges({
    ...(changedEntryIds.length ? { [STORAGE_KEYS.entries]: entries } : {}),
    [STORAGE_KEYS.organizerState]: organizerState
  });
  return {
    ok: true,
    message: mode === "move"
      ? `已将 ${updatedCount} 个案例移动到项目`
      : mode === "remove"
        ? `已将 ${updatedCount} 个案例移出项目${unchangedCount ? `,${unchangedCount} 个原本不在该项目` : ""}${missingCount ? `;${missingCount} 个案例不存在` : ""}`
        : `已将 ${updatedCount} 个案例加入项目${unchangedCount ? `,${unchangedCount} 个已经在该项目` : ""}${missingCount ? `;${missingCount} 个案例不存在` : ""}`,
    updatedCount,
    skippedCount,
    unchangedCount,
    missingCount,
    entries,
    organizerState
  };
}

async function createCollectionFromSelection(message) {
  const state = await readState();
  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 beforeOrganizer = normalizeOrganizerState(state.organizerState, [...validIds]);
  const createdResult = createCollection(beforeOrganizer, message.name, message.parentId ?? null);
  let organizerState = createdResult.state;
  if (message.mode === "move") {
    organizerState = moveEntriesBetweenCollections(
      organizerState,
      message.sourceCollectionId,
      createdResult.item.id,
      entryIds
    );
  } else {
    organizerState = setEntriesCollection(organizerState, createdResult.item.id, entryIds, true);
  }
  const changedEntryIds = changedProjectEntryIds(beforeOrganizer, organizerState);
  const entries = touchEntries(state.entries, changedEntryIds);
  await commitLocalChanges({
    ...(changedEntryIds.length ? { [STORAGE_KEYS.entries]: entries } : {}),
    [STORAGE_KEYS.organizerState]: organizerState
  });
  return {
    ok: true,
    message: message.mode === "move" ? "项目已创建,案例已移动" : "项目已创建,案例已加入",
    created: createdResult.item,
    entries,
    organizerState
  };
}

async function updateOrganizer(message) {
  const state = await readState();
  let organizerState = normalizeOrganizerState(state.organizerState, state.entries.map((entry) => entry.id));
  const beforeOrganizer = organizerState;
  let trashState = normalizeTrashState(state.trashState);
  let created = null;
  if (message.type === "CREATE_COLLECTION") {
    const result = createCollection(organizerState, message.name, message.parentId);
    organizerState = result.state;
    created = result.item;
  } else if (message.type === "RENAME_COLLECTION") {
    organizerState = renameCollection(organizerState, message.collectionId, message.name);
  } else if (message.type === "DELETE_COLLECTION") {
    const moved = moveCollectionsToTrash({ organizerState, trashState }, [message.collectionId]);
    if (!moved.movedItemIds.length) throw new Error("项目不存在");
    organizerState = normalizeOrganizerState(moved.organizerState, state.entries.map((entry) => entry.id));
    trashState = moved.trashState;
  } else if (message.type === "REORDER_COLLECTIONS") {
    organizerState = reorderCollections(organizerState, message.collectionIds);
  } else if (message.type === "MOVE_COLLECTION") {
    if (message.undoing) assertCollectionStructureCurrent(organizerState, message.expectedStructure);
    organizerState = moveCollection(organizerState, message.collectionId, message.parentId, message.index);
  } else if (message.type === "REPLACE_COLLECTION_ENTRIES") {
    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);
  }
  const changedEntryIds = changedProjectEntryIds(beforeOrganizer, organizerState);
  const entries = touchEntries(state.entries, changedEntryIds);
  await commitLocalChanges({
    ...(changedEntryIds.length ? { [STORAGE_KEYS.entries]: entries } : {}),
    [STORAGE_KEYS.organizerState]: organizerState,
    ...(message.type === "DELETE_COLLECTION" ? { [STORAGE_KEYS.trashState]: trashState } : {})
  });
  return { ok: true, message: organizerMessage(message.type), entries, organizerState, trashState, created };
}

function organizerMessage(type) {
  return ({
    CREATE_COLLECTION: "项目已创建",
    RENAME_COLLECTION: "项目名称已保存",
    DELETE_COLLECTION: "项目已移入回收站,案例仍保留在资料库",
    REORDER_COLLECTIONS: "项目顺序已保存",
    MOVE_COLLECTION: "项目结构已保存",
    REPLACE_COLLECTION_ENTRIES: "项目案例已更新",
    SET_COLLECTION_VISIBILITY: "项目显示范围已更新"
  })[type] || "项目已更新";
}

async function decideAnalysisCandidate(message, accepted) {
  const state = await readState();
  const current = findEntry(state, message.entryId);
  if (accepted) {
    const next = acceptAnalysisCandidate(domainState(state), current.id, message.candidateId, message.edits);
    await persistDomainState(next, domainState(state));
    return { ok: true, message: "候选已确认,并归入可编辑词库", ...publicDomainState(next), canUndoFacetUpdate: true };
  }
  const updated = rejectAnalysisCandidate(current, message.candidateId);
  const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  return { ok: true, message: "候选已拒绝,同一候选不会重复出现", entry: updated };
}

async function applyEntryAnalysisResult(message) {
  const state = await readState();
  const entry = findEntry(state, message.entryId);
  const input = canonicalTextAnalysisInput(entry, message.assetId);
  if (message.textRevision && message.textRevision !== input.textRevision) {
    return { ok: false, message: "提示词原文已变化,本次分析结果没有写入" };
  }
  const currentFingerprint = await textFingerprint(input.text);
  if (message.fingerprint && message.fingerprint !== currentFingerprint) {
    return { ok: false, message: "提示词原文已变化,本次分析结果没有写入" };
  }
  const fingerprint = currentFingerprint;
  const applied = applyTextAnalysisTags(domainState(state), entry.id, message.tags);
  const updated = applied.state.entries.find((item) => item.id === entry.id);
  updated.analysisPending = false;
  updated.analyzedAt = new Date().toISOString();
  updated.analysisMeta = analysisMeta(message, fingerprint, updated.analyzedAt, updated);
  await persistDomainState(applied.state, domainState(state));
  return {
    ok: true,
    message: analysisResultMessage(applied),
    entry: updated,
    ...publicDomainState(applied.state),
    canUndoFacetUpdate: true
  };
}

async function previewDeepSeekBatch(outputLocale, mode = "incremental", entryIds, scopeValue, includeChanged) {
  const state = await readState();
  const scope = normalizeAnalysisScope(scopeValue);
  if (["rebuild", "reanalyze"].includes(mode) && (scope?.collectionId || scope?.entryIds || Array.isArray(scope?.contentTypeIds) || scope?.excludedCollectionIds.length)) {
    throw new Error("重建标签系统需要完整资料库;指定范围请使用重新分析全部");
  }
  const scopedEntries = selectAnalysisScope(state.entries, state.organizerState, scope);
  const stored = await libraryStorage.get([
    STORAGE_KEYS.batchJob,
    STORAGE_KEYS.analysisRebuildStaging,
    STORAGE_KEYS.analysisBatchUndo
  ]);
  const previous = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
  const previousSummary = analysisBatchSummary(previous);
  if (previous?.mode === "rebuild" && previousSummary?.counts.failed && !previous.partialApplied) {
    const recovery = analysisRebuildRecovery(previous, stored[STORAGE_KEYS.analysisRebuildStaging]);
    return {
      ok: false,
      message: recovery.recoverable
        ? `已有 ${recovery.stagedResultCount} 条重建结果安全暂存,请先继续完成剩余 ${previousSummary.counts.failed} 条`
        : "旧重建任务的暂存结果不完整,已阻止创建新的付费任务"
    };
  }
  const settings = resolveTextTaskSettings("textTags", await loadAiConfiguration(), { requireConfigured: false });
  const locale = outputLocale === "en" ? "en" : "zh-CN";
  const profileFingerprint = await analysisProfileFingerprint(settings, locale);
  const preview = await previewAnalysisBatch(scopedEntries, {
    analysisModel: settings.activeProvider === "compatible" ? settings.compatible.model : settings.analysisModel,
    profileFingerprint,
    mode,
    entryIds: mode === "selected" && scope ? scopedEntries.map(item => item.id) : Array.isArray(entryIds) ? entryIds : undefined,
    scope,
    includeChanged,
    fixedTaxonomyCharacters: analysisTaxonomyPrompt(state.facetCatalog, locale).length
  });
  return { ok: true, message: "批量分析预览已生成", preview: { ...preview, scope, includeChanged: includeChanged !== false } };
}

async function createDeepSeekBatch(outputLocale, mode = "incremental", entryIds, expectedEntryIds, scopeValue, includeChanged, expectedItems) {
  const state = await readState();
  const scope = normalizeAnalysisScope(scopeValue);
  if (["rebuild", "reanalyze"].includes(mode) && (scope?.collectionId || scope?.entryIds || Array.isArray(scope?.contentTypeIds) || scope?.excludedCollectionIds.length)) {
    throw new Error("重建标签系统需要完整资料库;指定范围请使用重新分析全部");
  }
  const scopedEntries = selectAnalysisScope(state.entries, state.organizerState, scope);
  const stored = await libraryStorage.get([
    STORAGE_KEYS.batchJob,
    STORAGE_KEYS.analysisRebuildStaging
  ]);
  const configuration = await loadAiConfiguration();
  const settings = resolveTextTaskSettings("textTags", configuration);
  if (!publicAiSettings(settings).configured) return { ok: false, message: "请先完成所选 AI 服务配置" };
  if (!settings.consent) return { ok: false, message: "请先确认:主动分析时会发送案例文字到所选 AI 服务" };
  const previous = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
  const previousSummary = analysisBatchSummary(previous);
  if (previous?.mode === "rebuild" && previousSummary?.counts.failed && !previous.partialApplied) {
    const recovery = analysisRebuildRecovery(previous, stored[STORAGE_KEYS.analysisRebuildStaging]);
    return {
      ok: false,
      message: recovery.recoverable
        ? `已有 ${recovery.stagedResultCount} 条重建结果安全暂存,请先继续完成剩余 ${previousSummary.counts.failed} 条`
        : "旧重建任务的暂存结果不完整,已阻止创建新的付费任务"
    };
  }
  if (previous && ["running", "paused"].includes(previous.status) &&
      previous.items.some((item) => ["pending", "running"].includes(item.status))) {
    return { ok: false, message: "已有未完成的批量任务,请继续或取消后再新建" };
  }
  const locale = outputLocale === "en" ? "en" : "zh-CN";
  const profileFingerprint = await analysisProfileFingerprint(settings, locale);
  const job = await createAnalysisBatchJob(scopedEntries, {
    analysisModel: settings.activeProvider === "compatible" ? settings.compatible.model : settings.analysisModel,
    outputLocale: locale,
    profileFingerprint,
    mode,
    entryIds: mode === "selected" && scope ? scopedEntries.map(item => item.id) : Array.isArray(entryIds) ? entryIds : undefined,
    scope,
    includeChanged,
    catalogRevision: state.facetCatalog.revision,
    fixedTaxonomyCharacters: analysisTaxonomyPrompt(state.facetCatalog, locale).length,
    concurrency: configuration.assignments.textTags.concurrency,
    providerId: configuration.assignments.textTags.providerId,
    outputProtocol: "json_object"
  });
  if (!sameAnalysisTargets(expectedItems, job.items)) {
    return { ok: false, previewChanged: true, message: "待分析案例已变化,请重新检查后确认费用" };
  }
  if (Array.isArray(expectedEntryIds)) {
    const expected = new Set(expectedEntryIds.map(String));
    if (job.items.length !== expected.size || job.items.some((item) => !expected.has(item.entryId))) {
      return { ok: false, previewChanged: true, message: "待分析案例已变化,请重新检查后确认费用" };
    }
  }
  const changes = { [STORAGE_KEYS.batchJob]: job };
  if (job.mode === "rebuild") {
    changes[STORAGE_KEYS.analysisRebuildStaging] = { version: 1, jobId: job.id, results: {} };
  } else {
    changes[STORAGE_KEYS.analysisBatchUndo] = createAnalysisBatchUndo(job, state);
  }
  await commitLocalChanges(changes);
  await ensureAnalysisBatchAlarm(true);
  scheduleAnalysisBatchRunner();
  return { ok: true, message: `已创建 ${job.items.length} 条批量分析任务`, analysisBatchJob: analysisBatchSummary(job) };
}

async function getDeepSeekBatchStatus(jobId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
  const job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], jobId, "text_tags");
  return { ok: true, analysisBatchJob: analysisBatchSummary(job) };
}

async function commitDeepSeekBatchItems(message) {
  const results = Array.isArray(message.results) ? message.results : [];
  if (!results.length) return { ok: false, message: "批量分析结果为空" };
  const stored = await libraryStorage.get([
    STORAGE_KEYS.batchJob,
    STORAGE_KEYS.analysisRebuildStaging,
    STORAGE_KEYS.analysisBatchUndo
  ]);
  let job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], message.jobId, "text_tags");
  const state = await readState();
  const expectedRevision = job.resultCatalogRevision ?? job.catalogRevision;
  if (state.facetCatalog.revision !== expectedRevision) {
    const paused = pauseAnalysisBatch(job);
    await commitLocalChanges({ [STORAGE_KEYS.batchJob]: paused });
    return { ok: false, message: "创作词库已变化,批量任务已暂停", analysisBatchJob: analysisBatchSummary(paused) };
  }
  if (job.mode === "rebuild") {
    return commitStagedRebuildResults(job, stored[STORAGE_KEYS.analysisRebuildStaging], state, results);
  }
  let working = domainState(state);
  let undo = stored[STORAGE_KEYS.analysisBatchUndo];
  for (const result of results) {
    requireClaim(job, result.entryId, result.claimId);
    if (result.error) {
      job = failAnalysisItem(job, result.entryId, result.claimId, result.error);
      continue;
    }
    const entry = working.entries.find((item) => item.id === result.entryId);
    if (!await textAnalysisResultIsCurrent(entry, result)) {
      job = failAnalysisItem(job, result.entryId, result.claimId, {
        message: "提示词原文已变化,请重新预览",
        status: 409
      });
      continue;
    }
    const applied = applyTextAnalysisTags(working, entry.id, result.tags);
    working = applied.state;
    const updated = working.entries.find((item) => item.id === entry.id);
    updated.analysisPending = false;
    updated.analyzedAt = new Date().toISOString();
    updated.analysisMeta = analysisMeta({
      ...result,
      profileFingerprint: job.profileFingerprint
    }, result.fingerprint, updated.analyzedAt, updated);
    job = succeedAnalysisItem(job, result.entryId, result.claimId, result.usage, working.facetCatalog.revision, result);
    if (Array.isArray(undo?.appliedEntries)) undo = sealAnalysisBatchUndo(undo, working, [entry.id]);
  }
  await commitLocalChanges({
    ...storagePayload(working),
    [STORAGE_KEYS.batchJob]: job,
    ...(Array.isArray(undo?.appliedEntries) ? { [STORAGE_KEYS.analysisBatchUndo]: undo } : {})
  });
  return {
    ok: true,
    facetCatalog: working.facetCatalog,
    analysisBatchJob: analysisBatchSummary(job)
  };
}

async function commitStagedRebuildResults(jobValue, stagingValue, state, results) {
  const stagedResult = await stageAnalysisRebuildResults(jobValue, stagingValue, state, results);
  let { job } = stagedResult;
  const { staging } = stagedResult;
  const summary = analysisBatchSummary(job);
  if (summary.status !== "completed" || summary.counts.failed) {
    await commitLocalChanges({
      [STORAGE_KEYS.batchJob]: job,
      [STORAGE_KEYS.analysisRebuildStaging]: staging
    });
    return { ok: true, analysisBatchJob: summary };
  }

  const finalized = await finalizeAnalysisRebuild(job, staging, domainState(state));
  const working = finalized.state;
  job = finalized.job;
  const undo = sealAnalysisBatchUndo(createAnalysisBatchUndo(job, state), working,
    working.entries.map((entry) => entry.id));
  await commitLocalChanges({
    ...storagePayload(working),
    [STORAGE_KEYS.batchJob]: job,
    [STORAGE_KEYS.analysisBatchUndo]: undo,
    [STORAGE_KEYS.analysisRebuildStaging]: { version: 1, jobId: job.id, committed: true, results: {} }
  });
  await libraryStorage.remove(STORAGE_KEYS.analysisRebuildStaging);
  return {
    ok: true,
    message: "全部案例已成功,固定标签树已原子切换",
    facetCatalog: working.facetCatalog,
    analysisBatchJob: analysisBatchSummary(job)
  };
}

async function updateDeepSeekBatch(action, jobId) {
  const stored = await libraryStorage.get([
    STORAGE_KEYS.batchJob,
    STORAGE_KEYS.analysisRebuildStaging
  ]);
  const current = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], jobId, "text_tags");
  if (action === "retry" && current.mode === "rebuild") {
    const recovery = analysisRebuildRecovery(current, stored[STORAGE_KEYS.analysisRebuildStaging]);
    if (!recovery.recoverable) {
      return { ok: false, message: "重建暂存结果不完整,已阻止重复付费;正式标签库保持不变" };
    }
  }
  const actions = {
    pause: pauseAnalysisBatch,
    resume: resumeAnalysisBatch,
    cancel: cancelAnalysisBatch,
    retry: retryFailedAnalysisItems
  };
  const next = actions[action](current);
  await commitLocalChanges({ [STORAGE_KEYS.batchJob]: next });
  if (next.status === "running") {
    await ensureAnalysisBatchAlarm(true);
    scheduleAnalysisBatchRunner();
  } else {
    await ensureAnalysisBatchAlarm(false);
  }
  if (action === "cancel" && current.mode === "rebuild") {
    await libraryStorage.remove(STORAGE_KEYS.analysisRebuildStaging);
  }
  const messages = {
    pause: "批量分析已暂停",
    resume: "批量分析已继续",
    cancel: "批量分析已取消",
    retry: current.mode === "rebuild" ? "仅剩余失败项已重新加入队列,已有暂存结果继续保留" : "失败项已重新加入队列"
  };
  return { ok: true, message: messages[action], analysisBatchJob: analysisBatchSummary(next) };
}

async function applyStagedAnalysisRebuild(jobId) {
  const stored = await libraryStorage.get([
    STORAGE_KEYS.batchJob,
    STORAGE_KEYS.analysisRebuildStaging
  ]);
  const job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], jobId, "text_tags");
  const recovery = analysisRebuildRecovery(job, stored[STORAGE_KEYS.analysisRebuildStaging]);
  if (!recovery.recoverable) {
    return { ok: false, message: "没有可安全应用的重建缓存,正式标签库保持不变" };
  }
  const state = await readState();
  const expectedRevision = job.resultCatalogRevision ?? job.catalogRevision;
  if (state.facetCatalog.revision !== expectedRevision) {
    return { ok: false, message: "创作词库已在重建后修改,不能安全应用旧缓存" };
  }
  const staleCount = job.items.filter((item) => {
    if (item.status !== "succeeded") return false;
    const entry = state.entries.find((candidate) => candidate.id === item.entryId);
    return !entry || canonicalTextAnalysisInput(entry, item.assetId).textRevision !== item.textRevision;
  }).length;
  if (staleCount) {
    return { ok: false, message: `${staleCount} 条成功案例的原文已变化,不能安全应用旧缓存` };
  }
  const finalized = await finalizePartialAnalysisRebuild(
    job,
    stored[STORAGE_KEYS.analysisRebuildStaging],
    domainState(state)
  );
  const undo = sealAnalysisBatchUndo(createAnalysisBatchUndo(job, state), finalized.state,
    finalized.state.entries.map((entry) => entry.id));
  await commitLocalChanges({
    ...storagePayload(finalized.state),
    [STORAGE_KEYS.batchJob]: finalized.job,
    [STORAGE_KEYS.analysisBatchUndo]: undo,
    [STORAGE_KEYS.analysisRebuildStaging]: { version: 1, jobId: job.id, committed: true, results: {} }
  });
  await libraryStorage.remove(STORAGE_KEYS.analysisRebuildStaging);
  const failedCount = analysisBatchSummary(job).counts.failed;
  return {
    ok: true,
    message: `已应用 ${recovery.stagedResultCount} 条成功结果,${failedCount} 条失败案例已转为待分析`,
    facetCatalog: finalized.state.facetCatalog,
    analysisBatchJob: analysisBatchSummary(finalized.job),
    canUndoAnalysisBatch: true
  };
}

async function undoDeepSeekBatch(jobId, confirmationToken) {
  const stored = await libraryStorage.get([
    STORAGE_KEYS.batchJob,
    STORAGE_KEYS.analysisBatchUndo
  ]);
  const job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], jobId, "text_tags");
  const undo = stored[STORAGE_KEYS.analysisBatchUndo];
  if (!undo || undo.jobId !== job.id) return { ok: false, message: "没有这次批量分析的撤回快照" };
  const state = await readState();
  const expectedRevision = job.resultCatalogRevision ?? job.catalogRevision;
  if (state.facetCatalog.revision !== expectedRevision) {
    return { ok: false, message: "创作词库已在批量分析后继续修改,不能安全自动撤回" };
  }
  const restored = restoreAnalysisBatchUndo(domainState(state), undo);
  await commitLocalChanges(storagePayload(restored), { guard: confirmationToken ? undoConfirmations.guard("UNDO_ANALYSIS_BATCH", confirmationToken, jobId) : undefined });
  await libraryStorage.remove([
    STORAGE_KEYS.batchJob,
    STORAGE_KEYS.analysisBatchUndo,
    STORAGE_KEYS.analysisRebuildStaging
  ]);
  return {
    ok: true,
    message: "已撤回本次批量分析,人工修改与案例原文保持不变",
    ...publicDomainState(restored),
    analysisBatchJob: null,
    canUndoAnalysisBatch: false
  };
}

async function previewVisionBatchTask(message) {
  const state = await readState();
  if (message.scope) message = { ...message, entryIds: selectAnalysisScope(state.entries, state.organizerState, normalizeAnalysisScope(message.scope)).map(item => item.id) };
  const configuration = await loadAiConfiguration();
  const settings = resolveVisionTaskSettings("imageAnalysis", configuration, { requireConfigured: false });
  const provider = settings[settings.activeProvider];
  const preview = previewVisionBatch(state.entries, {
    entryIds: message.entryIds,
    includeAllImages: message.includeAllImages,
    reanalyze: message.reanalyze,
    providerType: settings.activeProvider,
    model: provider.model
  });
  return { ok: true, preview };
}

async function previewVideoBatchTask(message) {
  const [state, configuration, stored] = await Promise.all([
    readState(),
    loadAiConfiguration(),
    libraryStorage.get(STORAGE_KEYS.analysisTasks)
  ]);
  if (message.scope) message = { ...message, entryIds: selectAnalysisScope(state.entries, state.organizerState, normalizeAnalysisScope(message.scope)).map(item => item.id) };
  const route = resolveVideoAnalysisTask(configuration);
  const selected = new Set((Array.isArray(message.entryIds) ? message.entryIds : []).map(String));
  const busy = new Set(normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]).items
    .filter((task) => task.request?.kind === "entry_video" && ["queued", "running"].includes(task.status))
    .map((task) => `${task.request.entryId}\u0000${task.request.assetId}`));
  const sendableAssetIds = [];
  const assetSnapshots = [];
  const exclusions = [];
  for (const entry of state.entries.filter((item) => selected.has(String(item.id)))) {
    const videos = entryMediaAssets(entry).filter((item) => item.kind === "video" && item.usage !== "poster");
    const primary = videos.find((asset) => asset.id === entry.primaryMediaId) || videos[0];
    const candidates = message.includeAllVideos ? videos : [primary].filter(Boolean);
    for (const asset of candidates) {
      const exclude = (category, reason) => exclusions.push({ entryId: entry.id, assetId: asset.id, title: entry.title, category, reason });
      if (asset.storageMode !== "managed") {
        exclude("non_local", "批量视频分析只发送案例库中的本地视频");
        continue;
      }
      if (busy.has(`${entry.id}\u0000${asset.id}`)) {
        exclude("busy", "这支视频已有单项或批量分析任务在运行");
        continue;
      }
      const blob = await getMediaBlob(asset.id);
      if (!blob) {
        exclude("missing", "本地视频文件缺失");
        continue;
      }
      let sourcePlan = "local-video";
      if (route.protocol === "chat_completions") {
        try {
          sourcePlan = chatCompletionsVideoSourcePlan({
            providerLabel: route.providerLabel,
            hasLocalVideo: true,
            videoMimeType: blob.type || asset.mimeType,
            localVideo: route.localVideo,
            preferPublicVideoUrl: route.preferPublicVideoUrl,
            publicVideoUrl: route.publicVideoUrl
          }).sourceKind;
        } catch (error) {
          exclude("incompatible", userMessage(error));
          continue;
        }
      }
      sendableAssetIds.push(asset.id);
      assetSnapshots.push({
        entryId: entry.id,
        assetId: asset.id,
        byteSize: blob.size,
        durationMs: asset.durationMs,
        fingerprint: await videoAssetFingerprint(blob),
        sourcePlan
      });
    }
  }
  const preview = previewVideoBatch(state.entries, {
    entryIds: message.entryIds,
    includeAllVideos: message.includeAllVideos,
    reanalyze: message.reanalyze,
    includeTags: message.includeTags,
    providerId: route.providerId,
    model: route.model,
    protocol: route.protocol,
    sourcePlan: new Set(assetSnapshots.map((item) => item.sourcePlan)).size === 1 ? assetSnapshots[0]?.sourcePlan || "" : "per-asset",
    endpoint: route.endpoint,
    localVideo: route.localVideo,
    preferPublicVideoUrl: route.preferPublicVideoUrl,
    publicVideoUrl: route.publicVideoUrl,
    concurrency: configuration.assignments.videoAnalysis.concurrency,
    sendableAssetIds,
    assetSnapshots
  });
  preview.exclusions = exclusions;
  preview.exclusionCounts = exclusions.reduce((counts, item) => {
    counts[item.category] = (counts[item.category] || 0) + 1;
    return counts;
  }, { busy: 0, missing: 0, incompatible: 0, non_local: 0 });
  return { ok: true, preview };
}

async function videoAssetFingerprint(blob) {
  if (!(blob instanceof Blob) || !blob.size) throw new Error("本地视频文件缺失");
  return await chunkedBlobFingerprint(blob);
}

async function createVideoBatchTask(message) {
  const [state, configuration] = await Promise.all([readState(), loadAiConfiguration()]);
  if (message.scope) message = { ...message, entryIds: selectAnalysisScope(state.entries, state.organizerState, normalizeAnalysisScope(message.scope)).map(item => item.id) };
  const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
  const previous = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
  if (previous && ["running", "paused"].includes(previous.status)
      && previous.items.some((item) => ["pending", "running"].includes(item.status))) {
    return { ok: false, message: "已有未完成的批量任务,请继续或取消后再新建" };
  }
  const previewResponse = await previewVideoBatchTask(message);
  const preview = previewResponse.preview;
  if (preview.excludedCount && message.confirmExclusions !== true) {
    return { ok: false, requiresExclusionConfirmation: true, preview, message: "部分视频不会发送,请确认排除项后继续" };
  }
  const outputLocale = message.outputLocale === "en" ? "en" : "zh-CN";
  const instruction = configuration.preferences.videoInstructionsByLocale?.[outputLocale]
    || configuration.preferences.videoInstructionsByLocale?.["zh-CN"];
  const job = createVideoBatchJob(state.entries, {
    entryIds: message.entryIds,
    includeAllVideos: message.includeAllVideos,
    reanalyze: message.reanalyze,
    includeTags: true,
    providerId: preview.providerId,
    model: preview.model,
    protocol: preview.protocol,
    sourcePlan: preview.sourcePlan,
    endpoint: preview.endpoint,
    localVideo: preview.localVideo,
    preferPublicVideoUrl: preview.preferPublicVideoUrl,
    publicVideoUrl: preview.publicVideoUrl,
    concurrency: preview.concurrency,
    sendableAssetIds: preview.items.map((item) => item.assetId),
    assetSnapshots: preview.items.map((item) => ({
      entryId: item.entryId,
      assetId: item.assetId,
      byteSize: item.byteSize,
      durationMs: item.durationMs,
      fingerprint: item.fingerprint,
      sourcePlan: item.sourcePlan
    })),
    instruction,
    contractVersion: VIDEO_RECONSTRUCTION_CONTRACT_VERSION,
    outputLocale
  });
  if (!sameAnalysisTargets(message.expectedItems, job.items)) {
    return { ok: false, previewChanged: true, message: "待分析案例已变化,请重新检查后确认费用" };
  }
  job.scope = normalizeAnalysisScope(message.scope);
  await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job });
  await libraryStorage.remove(STORAGE_KEYS.analysisBatchUndo);
  await ensureAnalysisBatchAlarm(true);
  scheduleAnalysisBatchRunner();
  return {
    ok: true,
    message: `已创建 ${job.requestCount} 支视频逆推任务`,
    visionBatchJob: analysisBatchSummary(job)
  };
}

async function createVisionBatchTask(message) {
  const state = await readState();
  if (message.scope) message = { ...message, entryIds: selectAnalysisScope(state.entries, state.organizerState, normalizeAnalysisScope(message.scope)).map(item => item.id) };
  const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
  const configuration = await loadAiConfiguration();
  const settings = resolveVisionTaskSettings("imageAnalysis", configuration, { requireConfigured: false });
  const provider = settings[settings.activeProvider];
  if (!provider.apiKey) return { ok: false, message: "请先保存当前图片服务的 API Key" };
  if (!settings.consent) return { ok: false, message: "请先确认主动分析时会发送当前截图" };
  const previous = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
  if (previous && ["running", "paused"].includes(previous.status) &&
      previous.items.some((item) => ["pending", "running"].includes(item.status))) {
    return { ok: false, message: "已有未完成的批量任务,请继续或取消后再新建" };
  }
  const job = createVisionBatchJob(state.entries, {
    entryIds: message.entryIds,
    includeAllImages: message.includeAllImages,
    reanalyze: message.reanalyze,
    providerType: settings.activeProvider,
    providerId: configuration.assignments.imageAnalysis.providerId,
    model: provider.model,
    outputProtocol: settings.activeProvider === "compatible" ? settings.compatible.structuredOutput : "json_schema",
    outputLocale: message.outputLocale,
    concurrency: configuration.assignments.imageAnalysis.concurrency
  });
  if (!sameAnalysisTargets(message.expectedItems, job.items)) {
    return { ok: false, previewChanged: true, message: "待分析案例已变化,请重新检查后确认费用" };
  }
  job.scope = normalizeAnalysisScope(message.scope);
  await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job });
  await libraryStorage.remove(STORAGE_KEYS.analysisBatchUndo);
  await ensureAnalysisBatchAlarm(true);
  scheduleAnalysisBatchRunner();
  return {
    ok: true,
    message: `已创建 ${job.requestCount} 张图片分析任务`,
    visionBatchJob: analysisBatchSummary(job)
  };
}

async function completeVisionBatchItem(message) {
  const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
  const job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], message.jobId, "vision");
  requireClaim(job, message.entryId, message.claimId, message.visualId);
  const usage = {
    promptTokens: Math.max(0, Number(message.usage?.inputTokens) || 0),
    completionTokens: Math.max(0, Number(message.usage?.outputTokens) || 0),
    totalTokens: Math.max(0, Number(message.usage?.totalTokens) || 0),
    cacheHits: message.cacheHit === true ? 1 : 0
  };
  const next = succeedAnalysisItem(job, message.entryId, message.claimId, usage, undefined, message);
  await commitLocalChanges({ [STORAGE_KEYS.batchJob]: next });
  return { ok: true, visionBatchJob: analysisBatchSummary(next) };
}

async function failVisionBatchItem(message) {
  const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
  const job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], message.jobId, "vision");
  requireClaim(job, message.entryId, message.claimId, message.visualId);
  const failed = failAnalysisItem(job, message.entryId, message.claimId, message.error);
  await commitLocalChanges({ [STORAGE_KEYS.batchJob]: failed });
  return { ok: true, visionBatchJob: analysisBatchSummary(failed) };
}

async function updateVisionBatch(action, jobId, options = {}) {
  const stored = await libraryStorage.get([STORAGE_KEYS.batchJob, STORAGE_KEYS.analysisTasks]);
  const current = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
  if (!current || current.id !== jobId || !["vision", "video"].includes(current.kind)) throw new Error("批量任务已经变化,请刷新后重试");
  const actions = {
    pause: pauseAnalysisBatch,
    resume: resumeAnalysisBatch,
    cancel: cancelAnalysisBatch,
    retry: retryFailedAnalysisItems
  };
  const next = action === "retry" && current.kind === "video"
    ? retryFailedAnalysisItems(current, {
        itemKeys: options.itemKeys,
        requireSelection: true,
        confirmDuplicateCharge: options.confirmDuplicateCharge
      })
    : actions[action](current);
  const changes = { [STORAGE_KEYS.batchJob]: next };
  if (current.kind === "video" && action === "cancel") {
    const taskState = normalizeAnalysisTaskRegistry(stored[STORAGE_KEYS.analysisTasks]);
    taskState.items = taskState.items.map((task) => task.request?.kind === "entry_video"
      && task.request.batchJobId === current.id && ["queued", "running"].includes(task.status)
      ? stopAnalysisTask(task)
      : task);
    changes[STORAGE_KEYS.analysisTasks] = taskState;
  }
  await commitLocalChanges(changes, { markSyncDirty: false });
  if (current.kind === "video" && action === "cancel") {
    for (const task of normalizeAnalysisTaskRegistry(changes[STORAGE_KEYS.analysisTasks]).items.filter((item) =>
      item.request?.batchJobId === current.id && item.status === "stopped")) {
      analysisTaskRunners.get(task.id)?.controller.abort();
      await notifyAnalysisTaskUpdated(task);
    }
  }
  if (next.status === "running") {
    await ensureAnalysisBatchAlarm(true);
    scheduleAnalysisBatchRunner();
  } else {
    await ensureAnalysisBatchAlarm(false);
  }
  return {
    ok: true,
    message: current.kind === "video"
      ? ({ pause: "批量视频逆推已暂停", resume: "批量视频逆推已继续", cancel: "批量视频逆推已取消;已完成结果仍保留", retry: "失败视频已重新加入队列" })[action]
      : ({ pause: "批量画面分析已暂停", resume: "批量画面分析已继续", cancel: "批量画面分析已取消", retry: "失败图片已重新加入队列" })[action],
    visionBatchJob: analysisBatchSummary(next)
  };
}

function scheduleAnalysisBatchRunner() {
  if (analysisBatchRunnerActive || analysisBatchRunnerTimer) return;
  analysisBatchRunnerTimer = setTimeout(() => {
    analysisBatchRunnerTimer = 0;
    void runPersistedAnalysisBatch();
  }, 0);
}

async function runPersistedAnalysisBatch() {
  if (analysisBatchRunnerActive) return;
  analysisBatchRunnerActive = true;
  let continueRunning = false;
  try {
    const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
    const initial = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
    if (!initial || initial.status !== "running") {
      await ensureAnalysisBatchAlarm(false);
      return;
    }
    if (initial.kind === "vision") {
      continueRunning = await runPersistedVisionBatchSlice(initial.id);
    } else if (initial.kind === "video") {
      continueRunning = await runPersistedVideoBatchSlice(initial.id);
    } else {
      continueRunning = await runPersistedTextBatchSlice(initial.id);
    }
    await ensureAnalysisBatchAlarm(continueRunning);
  } catch (error) {
    console.error("PromptDirector persisted analysis batch failed", error);
    const stored = await libraryStorage.get(STORAGE_KEYS.batchJob).catch(() => ({}));
    const current = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
    if (current?.status === "running") {
      const taskLabel = current.kind === "vision" ? "图片服务" : current.kind === "video" ? "视频服务" : "文字服务";
      const failed = failUnfinishedAnalysisItems(current, {
        message: `任务启动失败:${taskLabel}配置或后台运行状态无效,请检查 AI 服务后重试`,
        status: 500
      });
      await commitLocalChanges({ [STORAGE_KEYS.batchJob]: failed });
    }
    await ensureAnalysisBatchAlarm(false);
    continueRunning = false;
  } finally {
    analysisBatchRunnerActive = false;
    if (continueRunning) scheduleAnalysisBatchRunner();
  }
}

async function runPersistedTextBatchSlice(jobId) {
  const configuration = await loadAiConfiguration();
  const prepared = await enqueue(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
    let job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], jobId, "text_tags");
    if (job.status !== "running") return { job, claims: [], settings: null };
    const snapshotConfiguration = configurationForAssignment(configuration, "textTags", job);
    let settings;
    try {
      settings = resolveTextTaskSettings("textTags", snapshotConfiguration);
    } catch (error) {
      job = pauseAnalysisBatch(job);
      await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job });
      console.warn("PromptDirector text batch paused because its service snapshot is unavailable", userMessage(error));
      return { job, claims: [], settings: null };
    }
    const currentProfile = await analysisProfileFingerprint(settings, job.outputLocale);
    if (job.profileFingerprint && currentProfile !== job.profileFingerprint) {
      job = pauseAnalysisBatch(job);
      await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job });
      return { job, claims: [], settings: null };
    }
    job = recoverInterruptedAnalysisBatch(job);
    const claimed = claimAnalysisItems(job);
    await commitLocalChanges({ [STORAGE_KEYS.batchJob]: claimed.job });
    return { job: claimed.job, claims: claimed.claims, settings };
  });
  if (!prepared.claims.length || !prepared.settings) return false;
  const state = await readState();
  const entryById = new Map(state.entries.map((entry) => [entry.id, entry]));
  const results = await Promise.all(prepared.claims.map((claim) => analyzePersistedTextClaim(
    prepared.job,
    claim,
    entryById.get(claim.entryId),
    state.facetCatalog,
    prepared.settings
  )));
  const committed = await enqueue(() => commitDeepSeekBatchItems({ jobId, results }));
  return committed.analysisBatchJob?.status === "running";
}

async function analyzePersistedTextClaim(job, claim, entry, catalog, settings) {
  if (!entry) return persistedTextFailure(claim, "案例已不存在", 404);
  let serviceRequests = 0;
  try {
    assertCaseFilesReadable(entry);
    const analysisInput = canonicalTextAnalysisInput(entry, claim.assetId);
    const result = await runScheduledAnalysisWithRetries({
      key: `${job.providerId}:${job.model || job.analysisModel}:textTags`,
      concurrency: job.concurrency,
      task: async (requestBudget) => {
        serviceRequests += 1;
        return analyzeTextDetailedWithDeepSeek(entry, catalog, {
          ...settings,
          outputLocale: job.outputLocale
        }, fetch, { analysisInput, requestBudget });
      }
    });
    return {
      entryId: claim.entryId,
      claimId: claim.claimId,
      fingerprint: await textFingerprint(analysisInput.text),
      textRevision: claim.textRevision,
      assetId: analysisInput.assetId,
      tags: result.tags,
      normalizationDiagnostics: result.normalizationDiagnostics,
      attempts: {
        serviceRequests,
        outputCorrectionRequests: Number(result.attempts?.outputCorrectionRequests) || 0
      },
      usage: result.usage,
      model: result.model
    };
  } catch (error) {
    return persistedTextFailure(
      claim,
      userMessage(error),
      Number(error?.status) || 0,
      error?.usage,
      {
        serviceRequests,
        outputCorrectionRequests: Math.max(0, Number(error?.attempts?.outputCorrectionRequests) || 0)
      }
    );
  }
}

function persistedTextFailure(claim, message, status, usage, attempts) {
  return {
    entryId: claim.entryId,
    claimId: claim.claimId,
    textRevision: claim.textRevision,
    error: { message, status, usage, attempts }
  };
}

async function runPersistedVisionBatchSlice(jobId) {
  const configuration = await loadAiConfiguration();
  const prepared = await enqueue(async () => {
    const state = await readState();
    const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
    let job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], jobId, "vision");
    if (job.status !== "running") return { job, claims: [] };
    job = recoverInterruptedAnalysisBatch(reconcileVisionBatchResults(job, state.entries).job);
    const snapshotConfiguration = configurationForAssignment(configuration, "imageAnalysis", job);
    const settings = resolveVisionTaskSettings("imageAnalysis", snapshotConfiguration, { requireConfigured: false });
    const currentSettings = resolveVisionTaskSettings("imageAnalysis", configuration, { requireConfigured: false });
    const currentModel = currentSettings.activeProvider === "openai" ? currentSettings.openai.model : currentSettings.compatible.model;
    const snapshotModel = settings.activeProvider === "openai" ? settings.openai.model : settings.compatible.model;
    if (job.providerType !== currentSettings.activeProvider || job.model !== currentModel || job.providerType !== settings.activeProvider || job.model !== snapshotModel) {
      job = cancelAnalysisBatch(job);
      await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job });
      return { job, claims: [] };
    }
    const snapshotReady = publicVisionSettings(settings)[settings.activeProvider]?.configured === true;
    if (!snapshotReady || !settings.consent) {
      job = pauseAnalysisBatch(job);
      await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job });
      return { job, claims: [] };
    }
    const claimed = claimAnalysisItems(job);
    await commitLocalChanges({ [STORAGE_KEYS.batchJob]: claimed.job });
    return { job: claimed.job, claims: claimed.claims };
  });
  if (!prepared.claims.length) return false;
  await Promise.all(prepared.claims.map(async (claim) => {
    let result;
    try {
      result = await analyzeEntryImage(
        claim.entryId,
        claim.visualId,
        prepared.job.outputLocale,
        prepared.job.id,
        prepared.job.reanalyze,
        prepared.job,
        "user_batch"
      );
    } catch (error) {
      result = {
        ok: false,
        message: userMessage(error),
        status: Number(error?.status) || 0,
        usage: error?.usage,
        attempts: error?.attempts
      };
    }
    await enqueue(() => result.ok
      ? completeVisionBatchItem({
          jobId,
          entryId: claim.entryId,
          visualId: claim.visualId,
          claimId: claim.claimId,
          usage: result.usage,
          cacheHit: result.cacheHit,
          attempts: result.attempts,
          quality: result.quality
        })
      : failVisionBatchItem({
          jobId,
          entryId: claim.entryId,
          visualId: claim.visualId,
          claimId: claim.claimId,
          error: {
            message: result.message,
            status: result.status,
            usage: result.usage,
            attempts: result.attempts
          }
        }));
  }));
  const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
  return normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob])?.status === "running";
}

async function runPersistedVideoBatchSlice(jobId) {
  const configuration = await loadAiConfiguration();
  const prepared = await enqueue(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
    let job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], jobId, "video");
    if (job.status !== "running") return { job, claims: [] };
    let route;
    try {
      route = resolveVideoAnalysisTask(configuration);
    } catch {
      job = pauseAnalysisBatch(job);
      await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job });
      return { job, claims: [] };
    }
    if (!videoAnalysisRouteMatches(job, route)) {
      job = pauseAnalysisBatch(job);
      await commitLocalChanges({ [STORAGE_KEYS.batchJob]: job });
      return { job, claims: [] };
    }
    const available = Math.max(0, job.concurrency - job.items.filter((item) => item.status === "running").length);
    if (!available) return { job, claims: [] };
    const claimed = claimAnalysisItems(job, available);
    await commitLocalChanges({ [STORAGE_KEYS.batchJob]: claimed.job });
    return { job: claimed.job, claims: claimed.claims };
  });
  for (const claim of prepared.claims) {
    try {
      const response = await startOrJoinAnalysisTaskAction({
        kind: "entry_video",
        entryId: claim.entryId,
        assetId: claim.assetId,
        mode: "visual-reconstruction",
        instruction: prepared.job.instruction,
        includeTags: prepared.job.includeTags,
        batchJobId: prepared.job.id,
        batchClaimId: claim.claimId,
        sourceFingerprint: claim.fingerprint,
        protocol: prepared.job.protocol,
        sourceKind: claim.sourcePlan,
        routeEndpoint: prepared.job.endpoint,
        routeProviderId: prepared.job.providerId,
        routeModel: prepared.job.model,
        localVideo: prepared.job.localVideo,
        preferPublicVideoUrl: prepared.job.preferPublicVideoUrl,
        publicVideoUrl: prepared.job.publicVideoUrl,
        hasRouteSnapshot: true,
        outputLocale: prepared.job.outputLocale,
        priority: "user_batch",
        consumerId: `video-batch:${prepared.job.id}`,
        clientRequestId: `video-batch:${prepared.job.id}:${claim.entryId}:${claim.assetId}:${claim.claimId}`
      });
      if (response.task?.request?.batchJobId !== prepared.job.id) {
        const error = new Error("这支视频已有单项分析任务,未重复发送;完成后可重新预览批量分析");
        error.status = 409;
        throw error;
      }
    } catch (error) {
      await failVideoBatchClaim(prepared.job.id, claim, error);
    }
  }
  const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
  const current = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
  return Boolean(current?.status === "running" && current.items.some((item) => item.status === "pending"));
}

async function settleVideoBatchTask(task, actionResult) {
  const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
  const job = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob]);
  if (!job || job.kind !== "video" || job.id !== task.request.batchJobId || job.status === "canceled") return;
  const item = job.items.find((candidate) => candidate.entryId === task.request.entryId
    && candidate.assetId === task.request.assetId
    && candidate.claimId === task.request.batchClaimId
    && candidate.taskId === task.id
    && candidate.requestId === task.activeAttemptId
    && candidate.status === "running");
  if (!item) return;
  const budget = actionResult.requestBudget || task.attempts?.at(-1)?.requestBudget;
  const attempts = analysisRequestCounts(budget);
  let next;
  if (actionResult?.ok) {
    const usage = actionResult.analysis?.usage ?? actionResult.usage ?? {};
    next = succeedAnalysisItem(job, item.entryId, item.claimId, {
      promptTokens: usage.inputTokens,
      completionTokens: usage.outputTokens,
      totalTokens: usage.totalTokens
    }, undefined, { attempts, cost: actionResult.analysis?.cost ?? null });
  } else {
    next = failAnalysisItem(job, item.entryId, item.claimId, {
      message: actionResult?.message || "视频分析失败",
      status: actionResult?.status,
      usage: actionResult?.usage,
      attempts,
      diagnostic: actionResult?.diagnostic
    });
  }
  await commitLocalChanges({ [STORAGE_KEYS.batchJob]: next });
  if (next.status === "running") {
    await ensureAnalysisBatchAlarm(true);
    scheduleAnalysisBatchRunner();
  } else await ensureAnalysisBatchAlarm(false);
}

async function failVideoBatchClaim(jobId, claim, error) {
  const stored = await libraryStorage.get(STORAGE_KEYS.batchJob);
  const job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], jobId, "video");
  const next = failAnalysisItem(job, claim.entryId, claim.claimId, {
    message: userMessage(error),
    status: Number(error?.status) || 0,
    attempts: { serviceRequests: 0 }
  });
  await commitLocalChanges({ [STORAGE_KEYS.batchJob]: next });
}

async function ensureAnalysisBatchAlarm(running) {
  if (running) await chrome.alarms.create(ANALYSIS_BATCH_ALARM, { periodInMinutes: 1 });
  else await chrome.alarms.clear(ANALYSIS_BATCH_ALARM);
}

async function queueAutomaticVisionAnalysis(entryIdsValue, options = {}) {
  const entryIds = [...new Set((Array.isArray(entryIdsValue) ? entryIdsValue : []).map(String).filter(Boolean))];
  if (!entryIds.length) return false;
  const [state, stored] = await Promise.all([
    readState(),
    libraryStorage.get(STORAGE_KEYS.automaticVisionBatchJob)
  ]);
  const configuration = await loadAiConfiguration();
  const settings = resolveVisionTaskSettings("imageAnalysis", configuration, { requireConfigured: false });
  const publicSettings = publicVisionSettings(settings);
  if ((options.requireAutoImportSetting !== false && !settings.autoAnalyzeImports) ||
      !settings.consent || !publicSettings[settings.activeProvider].configured) return false;
  const job = buildAutomaticVisionJob(state.entries, entryIds,
    automaticVisionRoute(configuration, settings, state.uiPreferences),
    stored[STORAGE_KEYS.automaticVisionBatchJob]);
  if (!job) return false;
  await commitLocalChanges({ [STORAGE_KEYS.automaticVisionBatchJob]: job });
  await ensureAutomaticVisionAlarm(true);
  scheduleAutomaticVisionRunner();
  return true;
}

function automaticVisionRoute(configuration, settings, uiPreferences) {
  return {
    providerType: settings.activeProvider,
    providerId: configuration.assignments.imageAnalysis.providerId,
    model: settings[settings.activeProvider].model,
    outputProtocol: settings.activeProvider === "compatible" ? settings.compatible.structuredOutput : "json_schema",
    concurrency: configuration.assignments.imageAnalysis.concurrency,
    outputLocale: resolveLocale(uiPreferences, chrome.i18n.getUILanguage()) === "en" ? "en" : "zh-CN"
  };
}

function automaticVisionRouteMatches(job, configuration, settings) {
  return job.providerType === settings.activeProvider
    && job.model === settings[settings.activeProvider].model
    && String(job.providerId ?? "") === String(configuration.assignments.imageAnalysis.providerId ?? "");
}

function scheduleAutomaticVisionRunner() {
  if (automaticVisionRunnerActive || automaticVisionRunnerTimer) return;
  automaticVisionRunnerTimer = setTimeout(() => {
    automaticVisionRunnerTimer = 0;
    void runAutomaticVisionItem();
  }, 0);
}

async function runAutomaticVisionItem() {
  if (automaticVisionRunnerActive) return;
  automaticVisionRunnerActive = true;
  let continueRunning = false;
  try {
    const stored = await libraryStorage.get([
      STORAGE_KEYS.automaticVisionBatchJob
    ]);
    let job = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.automaticVisionBatchJob]);
    if (!job || job.kind !== "vision" || job.status !== "running") {
      await ensureAutomaticVisionAlarm(false);
      return;
    }
    const loadedConfiguration = await loadAiConfiguration();
    const configuration = configurationForAssignment(loadedConfiguration, "imageAnalysis", job);
    const settings = resolveVisionTaskSettings("imageAnalysis", configuration, { requireConfigured: false });
    const configured = publicVisionSettings(settings)[settings.activeProvider].configured;
    if (!settings.autoAnalyzeImports || !settings.consent || !configured) {
      await enqueue(async () => {
        const latestStored = await libraryStorage.get(STORAGE_KEYS.automaticVisionBatchJob);
        const latest = normalizeAnalysisBatchJob(latestStored[STORAGE_KEYS.automaticVisionBatchJob]);
        if (latest?.id !== job.id || latest.status !== "running") return;
        await commitLocalChanges({ [STORAGE_KEYS.automaticVisionBatchJob]: pauseAnalysisBatch(latest) });
      });
      await ensureAutomaticVisionAlarm(false);
      return;
    }
    const currentSettings = resolveVisionTaskSettings("imageAnalysis", loadedConfiguration, { requireConfigured: false });
    if (!automaticVisionRouteMatches(job, loadedConfiguration, currentSettings)) {
      // The image service changed: requeue unfinished images under the current service instead of paying the old one.
      continueRunning = await enqueue(async () => {
        const [latestStored, state] = await Promise.all([
          libraryStorage.get(STORAGE_KEYS.automaticVisionBatchJob),
          readState()
        ]);
        const latest = normalizeAnalysisBatchJob(latestStored[STORAGE_KEYS.automaticVisionBatchJob]);
        if (latest?.id !== job.id || latest.status !== "running") return latest?.kind === "vision" && latest.status === "running";
        if (!publicVisionSettings(currentSettings)[currentSettings.activeProvider].configured) {
          await commitLocalChanges({ [STORAGE_KEYS.automaticVisionBatchJob]: pauseAnalysisBatch(latest) });
          return false;
        }
        const rebuilt = buildAutomaticVisionJob(state.entries, [],
          automaticVisionRoute(loadedConfiguration, currentSettings, state.uiPreferences), latest);
        await commitLocalChanges({ [STORAGE_KEYS.automaticVisionBatchJob]: rebuilt ?? cancelAnalysisBatch(latest) });
        return Boolean(rebuilt);
      });
      await ensureAutomaticVisionAlarm(continueRunning);
      return;
    }
    const claimed = await enqueue(async () => {
      const [latestStored, state] = await Promise.all([
        libraryStorage.get(STORAGE_KEYS.automaticVisionBatchJob),
        readState()
      ]);
      const latest = normalizeAnalysisBatchJob(latestStored[STORAGE_KEYS.automaticVisionBatchJob]);
      if (latest?.id !== job.id || latest.status !== "running") {
        return { replaced: latest?.kind === "vision" && latest.status === "running", claims: [] };
      }
      const next = claimAnalysisItems(recoverInterruptedAnalysisBatch(reconcileVisionBatchResults(latest, state.entries).job));
      await commitLocalChanges({ [STORAGE_KEYS.automaticVisionBatchJob]: next.job });
      return next;
    });
    if (claimed.replaced) {
      continueRunning = true;
      return;
    }
    if (claimed.job) job = claimed.job;
    if (!claimed.claims.length) {
      await ensureAutomaticVisionAlarm(false);
      return;
    }
    await Promise.all(claimed.claims.map(async (claim) => {
      let result;
      try {
        result = await analyzeEntryImage(claim.entryId, claim.visualId, job.outputLocale, job.id, false, job, "background_import");
      } catch (error) {
        result = { ok: false, message: userMessage(error), status: Number(error?.status) || 0, usage: error?.usage };
      }
      await enqueue(async () => {
        const latestStored = await libraryStorage.get(STORAGE_KEYS.automaticVisionBatchJob);
        const latest = requireAnalysisBatch(latestStored[STORAGE_KEYS.automaticVisionBatchJob], job.id, "vision");
        requireClaim(latest, claim.entryId, claim.claimId, claim.visualId);
        const next = result.ok
          ? succeedAnalysisItem(latest, claim.entryId, claim.claimId, {
              promptTokens: result.usage?.inputTokens,
              completionTokens: result.usage?.outputTokens,
              totalTokens: result.usage?.totalTokens,
              cacheHits: result.cacheHit === true ? 1 : 0
            }, undefined, result)
          : failAnalysisItem(latest, claim.entryId, claim.claimId, {
              message: result.message,
              status: result.status,
              usage: result.usage,
              attempts: result.attempts
            });
        await commitLocalChanges({ [STORAGE_KEYS.automaticVisionBatchJob]: next });
        job = next;
      });
    }));
    continueRunning = job.status === "running";
    await ensureAutomaticVisionAlarm(continueRunning);
  } catch (error) {
    console.error("PromptDirector automatic vision analysis failed", error);
    await ensureAutomaticVisionAlarm(true);
  } finally {
    automaticVisionRunnerActive = false;
    if (continueRunning) scheduleAutomaticVisionRunner();
  }
}

async function ensureAutomaticVisionAlarm(running) {
  if (running) await chrome.alarms.create(AUTOMATIC_VISION_ALARM, { periodInMinutes: 1 });
  else await chrome.alarms.clear(AUTOMATIC_VISION_ALARM);
}

async function getVisionImageBlob(visualId) {
  return await getMediaBlob(visualId) ?? await getScreenshotBlob(visualId);
}

async function importAnalysisCandidates(payload) {
  if (!payload || !Array.isArray(payload.entries)) return { ok: false, message: "候选文件格式无效" };
  const state = await readState();
  const applied = applyAnalysisImport(domainState(state), payload);
  if (!applied.matchedCount) return { ok: false, message: "分析文件与当前案例库没有匹配的案例 ID" };
  const matchedIds = new Set(applied.matchedEntryIds);
  const analyzedAt = new Date().toISOString();
  const importedEntries = applied.state.entries.map((entry) => matchedIds.has(entry.id)
    ? { ...entry, analysisPending: false, analyzedAt }
    : entry);
  const analysisBaseline = await backfillLegacyAnalysisMeta(importedEntries);
  const importedState = { ...applied.state, entries: analysisBaseline.entries };
  await persistDomainState(importedState, domainState(state));
  const unmatched = applied.unmatchedCount
    ? `;另有 ${applied.unmatchedCount} 条未包含在本次分析的案例已保留原文和截图、清除旧候选,等待下次分析`
    : "";
  return {
    ok: true,
    message: `已整理 ${applied.matchedCount} 条案例:自动写入 ${applied.confirmedCount} 个明确标签${applied.suggestedCount ? `,仅保留 ${applied.suggestedCount} 个非常不确定项` : ",没有待确认项"}${unmatched}`,
    ...publicDomainState(importedState),
    canUndoFacetUpdate: true
  };
}

async function visionUndoWithout(entryId) {
  const stored = await libraryStorage.get(STORAGE_KEYS.visionAnalysisUndo);
  const next = { ...(stored[STORAGE_KEYS.visionAnalysisUndo] ?? {}) };
  delete next[entryId];
  return next;
}

async function visionUndoWithoutEntries(entryIds) {
  const stored = await libraryStorage.get(STORAGE_KEYS.visionAnalysisUndo);
  const next = { ...(stored[STORAGE_KEYS.visionAnalysisUndo] ?? {}) };
  for (const entryId of entryIds) delete next[entryId];
  return next;
}

async function previewFacetUpdate(change) {
  const state = await readState();
  const preview = previewFacetChange(domainState(state), change);
  return { ok: true, message: "请确认本次词库更新", preview };
}

async function applyFacetUpdate(preview) {
  const state = await readState();
  const applied = applyFacetChange(domainState(state), preview);
  await persistDomainState(applied.state, applied.undo, {
    entriesChanged: preview?.change?.type === "merge"
  });
  return { ok: true, message: "创作词库已更新,历史案例已同步", ...publicDomainState(applied.state), canUndoFacetUpdate: true };
}

async function restoreFacetDimensions(facetIds) {
  const state = await readState();
  const before = domainState(state);
  const facetCatalog = restoreArchivedFacets(state.facetCatalog, facetIds);
  if (facetCatalog.revision === state.facetCatalog.revision) {
    return { ok: false, message: "没有找到可恢复的已归档维度" };
  }
  const next = { ...before, facetCatalog };
  await persistDomainState(next, before, { entriesChanged: false });
  return {
    ok: true,
    message: "已归档维度已恢复,原案例标签重新可见",
    ...publicDomainState(next),
    canUndoFacetUpdate: true
  };
}

async function restoreFacetTags(nodeIds) {
  const state = await readState();
  const before = domainState(state);
  const facetCatalog = restoreArchivedNodes(state.facetCatalog, nodeIds);
  if (facetCatalog.revision === state.facetCatalog.revision) {
    return { ok: false, message: "没有找到可恢复的已归档标签" };
  }
  const next = { ...before, facetCatalog };
  await persistDomainState(next, before, { entriesChanged: false });
  return {
    ok: true,
    message: "已归档标签已恢复,原案例标签重新可见",
    ...publicDomainState(next),
    canUndoFacetUpdate: true
  };
}

async function previewLibraryMaintenance() {
  const [state, derivedMetadata] = await Promise.all([readState(), getAllDerivedMetadata()]);
  const targets = libraryMaintenanceTargets(state.entries, derivedMetadata);
  return {
    ok: true,
    message: "资料补全检查完成",
    preview: {
      caseCount: targets.classificationEntryIds.length,
      confirmed: targets.classificationEntryIds.length,
      suggested: 0,
      paletteCount: targets.paletteAssetIds.length,
      total: targets.classificationEntryIds.length + targets.paletteAssetIds.length,
      cases: []
    }
  };
}

async function startLibraryMaintenance() {
  const [state, derivedMetadata, stored] = await Promise.all([
    readState(),
    getAllDerivedMetadata(),
    libraryStorage.get(STORAGE_KEYS.libraryMaintenanceJob)
  ]);
  const current = normalizeLibraryMaintenanceJob(stored[STORAGE_KEYS.libraryMaintenanceJob]);
  if (current && ["running", "paused"].includes(current.status) && libraryMaintenanceSummary(current).remaining) {
    return { ok: false, message: "已有未完成的资料补全任务,请继续或取消后再开始" };
  }
  const targets = libraryMaintenanceTargets(state.entries, derivedMetadata);
  const job = createLibraryMaintenanceJob(targets);
  await commitLocalChanges({ [STORAGE_KEYS.libraryMaintenanceJob]: job });
  await ensureLibraryMaintenanceAlarm(job.status === "running");
  scheduleLibraryMaintenanceRunner();
  return {
    ok: true,
    message: job.status === "completed" ? "当前资料已经完整" : `已开始后台补全 ${libraryMaintenanceSummary(job).total} 项资料`,
    maintenanceJob: libraryMaintenanceSummary(job)
  };
}

async function enqueueAutomaticLibraryMaintenance(entriesValue) {
  const [derivedMetadata, stored] = await Promise.all([
    getAllDerivedMetadata(),
    libraryStorage.get(STORAGE_KEYS.libraryMaintenanceJob)
  ]);
  const targets = libraryMaintenanceTargets(entriesValue, derivedMetadata);
  if (!targets.classificationEntryIds.length && !targets.paletteAssetIds.length) return null;
  const job = extendLibraryMaintenanceJob(stored[STORAGE_KEYS.libraryMaintenanceJob], targets);
  await commitLocalChanges({ [STORAGE_KEYS.libraryMaintenanceJob]: job });
  await ensureLibraryMaintenanceAlarm(job.status === "running");
  if (job.status === "running") scheduleLibraryMaintenanceRunner();
  return libraryMaintenanceSummary(job);
}

async function libraryMaintenanceStatus() {
  const stored = await libraryStorage.get(STORAGE_KEYS.libraryMaintenanceJob);
  return { ok: true, maintenanceJob: libraryMaintenanceSummary(stored[STORAGE_KEYS.libraryMaintenanceJob]) };
}

async function updateLibraryMaintenance(action) {
  const stored = await libraryStorage.get(STORAGE_KEYS.libraryMaintenanceJob);
  const current = normalizeLibraryMaintenanceJob(stored[STORAGE_KEYS.libraryMaintenanceJob]);
  if (!current) return { ok: false, message: "没有可用的资料补全任务" };
  const actions = {
    pause: pauseLibraryMaintenance,
    resume: resumeLibraryMaintenance,
    cancel: cancelLibraryMaintenance,
    retry: retryLibraryMaintenanceFailures
  };
  const next = actions[action](current);
  await commitLocalChanges({ [STORAGE_KEYS.libraryMaintenanceJob]: next });
  await ensureLibraryMaintenanceAlarm(next.status === "running");
  if (next.status === "running") scheduleLibraryMaintenanceRunner();
  const messages = {
    pause: "资料补全已暂停",
    resume: "资料补全已继续",
    cancel: "资料补全已取消",
    retry: "失败项已重新加入后台任务"
  };
  return { ok: true, message: messages[action], maintenanceJob: libraryMaintenanceSummary(next) };
}

function libraryMaintenanceTargets(entriesValue, derivedMetadata) {
  const metadata = derivedMetadata instanceof Map ? derivedMetadata : new Map();
  const classificationEntryIds = [];
  const paletteAssetIds = [];
  const seenAssets = new Set();
  for (const entry of Array.isArray(entriesValue) ? entriesValue : []) {
    if (entry.classification?.status === "needs_review") classificationEntryIds.push(entry.id);
    for (const asset of entryMediaAssets(entry)) {
      if (asset.kind !== "image" || asset.usage === "poster" || seenAssets.has(asset.id)) continue;
      seenAssets.add(asset.id);
      const cachedPalette = metadata.get(asset.id)?.palette;
      const inlineCurrent = hasCurrentPalette(asset.palette);
      const cachedCurrent = hasCurrentPalette(cachedPalette);
      if (!inlineCurrent && !cachedCurrent) paletteAssetIds.push(asset.id);
    }
  }
  return { classificationEntryIds, paletteAssetIds };
}

function scheduleLibraryMaintenanceRunner() {
  if (maintenanceRunnerActive || maintenanceRunnerTimer) return;
  maintenanceRunnerTimer = setTimeout(() => {
    maintenanceRunnerTimer = 0;
    void runLibraryMaintenanceSlice();
  }, 0);
}

async function runLibraryMaintenanceSlice() {
  if (maintenanceRunnerActive) return;
  maintenanceRunnerActive = true;
  let continueRunning = false;
  try {
    const stored = await libraryStorage.get(STORAGE_KEYS.libraryMaintenanceJob);
    let job = normalizeLibraryMaintenanceJob(stored[STORAGE_KEYS.libraryMaintenanceJob]);
    if (!job || job.status !== "running") {
      await ensureLibraryMaintenanceAlarm(false);
      return;
    }
    job = await enqueue(() => completeMaintenanceClassifications(job));
    const state = await readState();
    const assets = new Map(state.entries.flatMap(entryMediaAssets).map((asset) => [asset.id, asset]));
    const started = performance.now();
    let processedInSlice = 0;
    while (job.status === "running" && nextLibraryMaintenanceItem(job)?.kind === "palette" &&
      (!processedInSlice || performance.now() - started < MAINTENANCE_SLICE_TARGET_MS)) {
      const item = nextLibraryMaintenanceItem(job);
      let result;
      try {
        const cached = await getDerivedMetadata(item.id);
        if (hasCurrentPalette(cached?.palette) || hasCurrentPalette(assets.get(item.id)?.palette)) result = { ok: true };
        else {
          await ensureOffscreenDocument();
          const analyzed = await chrome.runtime.sendMessage({
            target: "offscreen",
            type: "ANALYZE_STORED_SCREENSHOT",
            entryId: item.id
          });
          if (!analyzed?.ok || !analyzed.palette?.colors?.length) throw new Error(analyzed?.message || "无法生成色卡");
          const metadata = await saveDerivedMetadata(item.id, {
            ...cached,
            width: analyzed.width,
            height: analyzed.height,
            mimeType: analyzed.mimeType,
            byteSize: analyzed.byteSize,
            palette: analyzed.palette
          });
          void chrome.runtime.sendMessage({
            type: "LIBRARY_DERIVED_METADATA_UPDATED",
            assetId: item.id,
            metadata
          }).catch(() => undefined);
          result = { ok: true };
        }
      } catch (error) {
        result = { ok: false, message: userMessage(error) };
      }
      job = completeLibraryMaintenanceItem(job, result);
      processedInSlice += 1;
    }
    job = await persistLibraryMaintenanceProgress(job);
    if (!job) return;
    const summary = libraryMaintenanceSummary(job);
    void chrome.runtime.sendMessage({ type: "LIBRARY_MAINTENANCE_PROGRESS", maintenanceJob: summary }).catch(() => undefined);
    await ensureLibraryMaintenanceAlarm(job.status === "running");
    continueRunning = job.status === "running";
  } catch (error) {
    console.error("PromptDirector library maintenance failed", error);
    await ensureLibraryMaintenanceAlarm(true);
  } finally {
    maintenanceRunnerActive = false;
    if (continueRunning) scheduleLibraryMaintenanceRunner();
  }
}

async function persistLibraryMaintenanceProgress(progress) {
  return enqueue(async () => {
    const stored = await libraryStorage.get(STORAGE_KEYS.libraryMaintenanceJob);
    const next = mergeLibraryMaintenanceProgress(stored[STORAGE_KEYS.libraryMaintenanceJob], progress);
    if (!next || next.id !== progress.id) return next;
    await commitLocalChanges({ [STORAGE_KEYS.libraryMaintenanceJob]: next });
    return next;
  });
}

async function completeMaintenanceClassifications(jobValue) {
  let job = jobValue;
  if (nextLibraryMaintenanceItem(job)?.kind !== "classification") return job;
  const state = await readState();
  const remainingIds = new Set(job.classificationEntryIds.slice(job.classificationCursor));
  const entries = state.entries.map((entry) => {
    if (!remainingIds.has(entry.id)) return entry;
    if (entry.classification?.status !== "needs_review") return entry;
    return {
      ...entry,
      analysisPending: false,
      classification: classifyContent(entry, state.classificationRules, state.taxonomy)
    };
  });
  await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
  while (nextLibraryMaintenanceItem(job)?.kind === "classification") {
    job = completeLibraryMaintenanceItem(job, { ok: true });
  }
  return job;
}

async function ensureLibraryMaintenanceAlarm(running) {
  if (running) {
    await chrome.alarms.create(LIBRARY_MAINTENANCE_ALARM, { periodInMinutes: 1 });
  } else await chrome.alarms.clear(LIBRARY_MAINTENANCE_ALARM);
}

async function undoFacetUpdate(confirmationToken) {
  const state = await readState();
  const undone = undoFacetHistory(domainState(state), state.facetUndo);
  const update = {
    [STORAGE_KEYS.facetCatalog]: normalizeFacetCatalog(undone.state.facetCatalog),
    ...(undone.compoundsChanged ? { [STORAGE_KEYS.compoundCases]: undone.state.compoundCases } : {}),
    ...(undone.entriesChanged ? { [STORAGE_KEYS.entries]: undone.state.entries } : {})
  };
  if (undone.remainingSteps) update[STORAGE_KEYS.facetUndo] = undone.history;
  await commitLocalChanges(update, { guard: confirmationToken ? undoConfirmations.guard("UNDO_FACET_UPDATE", confirmationToken) : undefined });
  if (!undone.remainingSteps) await libraryStorage.remove(STORAGE_KEYS.facetUndo);
  return {
    ok: true,
    message: "已撤回上一步",
    ...publicDomainState(undone.state),
    canUndoFacetUpdate: undone.remainingSteps > 0,
    facetUndoCount: undone.remainingSteps
  };
}

function findEntry(state, entryId) {
  const entry = state.entries.find((item) => item.id === entryId);
  if (!entry) throw new Error("没有找到这条案例");
  assertCaseFilesReadable(entry);
  return entry;
}

function touchEntries(entriesValue, entryIdsValue, updatedAt = new Date().toISOString()) {
  const entryIds = new Set(Array.isArray(entryIdsValue) ? entryIdsValue : []);
  if (!entryIds.size) return entriesValue;
  return entriesValue.map((entry) => entryIds.has(entry.id) ? touchEntry(entry, updatedAt) : entry);
}

function userVisibleEntryChanges(beforeValue, afterValue) {
  const beforeById = new Map((Array.isArray(beforeValue) ? beforeValue : []).map((entry) => [entry.id, entry]));
  return (Array.isArray(afterValue) ? afterValue : [])
    .filter((entry) => beforeById.has(entry.id) && !userVisibleEntryEqual(beforeById.get(entry.id), entry))
    .map((entry) => entry.id);
}

function changedProjectEntryIds(beforeValue, afterValue) {
  const memberships = (value) => {
    const result = new Map();
    for (const collection of normalizeOrganizerState(value).collections) {
      for (const entryId of collection.entryIds) {
        const collectionIds = result.get(entryId) ?? [];
        collectionIds.push(collection.id);
        result.set(entryId, collectionIds);
      }
    }
    return result;
  };
  const before = memberships(beforeValue);
  const after = memberships(afterValue);
  const entryIds = new Set([...before.keys(), ...after.keys()]);
  return [...entryIds].filter((entryId) => {
    const left = (before.get(entryId) ?? []).toSorted();
    const right = (after.get(entryId) ?? []).toSorted();
    return !stringListsEqual(left, right);
  });
}

function requireAnalysisBatch(value, jobId, kind) {
  const job = normalizeAnalysisBatchJob(value);
  if (!job || (jobId && job.id !== jobId)) throw new Error("批量分析任务已变化,请刷新页面");
  if (kind && job.kind !== kind) throw new Error("另一种批量任务正在运行,请先完成或取消");
  return job;
}

function requireClaim(job, entryId, claimId, visualId = "") {
  const item = job.items.find((candidate) =>
    candidate.entryId === entryId &&
    candidate.claimId === claimId &&
    (!visualId || candidate.visualId === visualId)
  );
  if (!item || item.status !== "running" || item.claimId !== claimId) {
    throw new Error("这条批量分析结果已经失效,请刷新后继续");
  }
  return item;
}

function analysisMeta(message, fingerprint, analyzedAt, entry = {}) {
  return {
    ...(fingerprint ? { textFingerprint: fingerprint } : {}),
    textRevision: Math.max(1, Math.floor(Number(message.textRevision) || analysisRevisionMeta(entry).textRevision)),
    ...(String(message.assetId ?? "").trim() ? { assetId: String(message.assetId).trim() } : {}),
    promptVersion: ANALYSIS_PROMPT_VERSION,
    model: String(message.model ?? ""),
    analyzedAt,
    profileFingerprint: String(message.profileFingerprint ?? "").trim(),
    normalizationDiagnostics: (Array.isArray(message.normalizationDiagnostics) ? message.normalizationDiagnostics : []).map((item) => ({
      field: String(item?.field ?? ""),
      code: String(item?.code ?? ""),
      count: Math.max(0, Number(item?.count) || 0)
    })).filter((item) => item.field && item.code),
    attempts: {
      serviceRequests: Math.max(0, Number(message.attempts?.serviceRequests) || 0),
      outputCorrectionRequests: Math.max(0, Number(message.attempts?.outputCorrectionRequests) || 0)
    },
    usage: {
      promptTokens: Math.max(0, Number(message.usage?.promptTokens) || 0),
      completionTokens: Math.max(0, Number(message.usage?.completionTokens) || 0),
      totalTokens: Math.max(0, Number(message.usage?.totalTokens) || 0),
      cacheHitTokens: Math.max(0, Number(message.usage?.cacheHitTokens) || 0),
      cacheMissTokens: Math.max(0, Number(message.usage?.cacheMissTokens) || 0)
    }
  };
}

function analysisResultMessage(applied) {
  return `已写入 ${applied.appliedCount} 个检索标签`;
}

function domainState(state) {
  return {
    schemaVersion: SCHEMA_VERSION,
    entries: state.entries,
    trashState: normalizeTrashState(state.trashState),
    compoundCases: normalizeCompoundCases(state.compoundCases, state.entries),
    taxonomy: state.taxonomy,
    facetCatalog: state.facetCatalog,
    classificationRules: state.classificationRules,
    organizerState: normalizeOrganizerState(state.organizerState, state.entries.map((entry) => entry.id))
  };
}

function publicDomainState(state) {
  return {
    entries: enrichContentMeanings(state.entries, state.taxonomy),
    trashState: normalizeTrashState(state.trashState),
    compoundCases: normalizeCompoundCases(state.compoundCases, state.entries),
    taxonomy: state.taxonomy,
    facetCatalog: state.facetCatalog,
    classificationRules: state.classificationRules,
    organizerState: normalizeOrganizerState(state.organizerState, state.entries.map((entry) => entry.id))
  };
}

function publicLibraryState(state) {
  const {
    folderOwnershipBackup: _folderOwnershipBackup,
    facetUndo: _facetUndo,
    composerSessions: _composerSessions,
    lastSaveUndo,
    ...visibleState
  } = state;
  return {
    ...visibleState,
    entries: enrichContentMeanings(visibleState.entries, visibleState.taxonomy),
    canUndoLastSave: Boolean(lastSaveUndo)
  };
}

function folderBackupState(state) {
  return {
    entries: state.entries,
    trashState: normalizeTrashState(state.trashState),
    settings: state.settings,
    taxonomy: state.taxonomy,
    facetCatalog: state.facetCatalog,
    classificationRules: state.classificationRules,
    organizerState: state.organizerState,
    compoundCases: state.compoundCases,
    composerSettings: state.composerSettings,
    composerSessions: state.composerSessions,
    creativeExperimentSettings: state.creativeExperimentSettings,
    creativeRuns: state.creativeRuns,
    creativeSkills: state.creativeSkills
  };
}

function storagePayload(state) {
  return {
    [STORAGE_KEYS.schemaVersion]: SCHEMA_VERSION,
    [STORAGE_KEYS.entries]: state.entries,
    [STORAGE_KEYS.trashState]: normalizeTrashState(state.trashState),
    [STORAGE_KEYS.compoundCases]: normalizeCompoundCases(state.compoundCases, state.entries),
    [STORAGE_KEYS.taxonomy]: state.taxonomy,
    [STORAGE_KEYS.facetCatalog]: normalizeFacetCatalog(state.facetCatalog),
    [STORAGE_KEYS.classificationRules]: state.classificationRules,
    [STORAGE_KEYS.organizerState]: normalizeOrganizerState(state.organizerState, state.entries.map((entry) => entry.id))
  };
}


async function persistDomainState(state, undo, historyOptions) {
  const update = storagePayload(state);
  if (undo) {
    const stored = await libraryStorage.get(STORAGE_KEYS.facetUndo);
    update[STORAGE_KEYS.facetUndo] = appendFacetUndo(
      stored[STORAGE_KEYS.facetUndo], undo, state, historyOptions
    );
  }
  await commitLocalChanges(update);
  return update;
}

async function saveShareArchive(url, filename) {
  const response = await chrome.runtime.sendMessage({ target: 'offscreen', type: 'WRITE_SHARE_ARCHIVE', url, filename });
  if (!response?.ok) throw new Error(response?.message || '无法导出分享包');
  return response;
}

async function exportArchive(state, requestedEntryIds, directory = false) {
  if (!Array.isArray(requestedEntryIds) || !requestedEntryIds.length) throw new Error("请先选择要分享的案例");
  const exportState = selectLibraryPackage(state, requestedEntryIds);
  await migrateLegacyScreenshots(exportState.entries);
  const archive = await createArchiveUrl(exportState, true);
  try {
    if (directory) await saveShareArchive(archive.url, sharedArchivePath(state.settings.outputPath, archiveLocale(state)));
    else {
      const downloadId = await chrome.downloads.download({
        url: archive.url,
        filename: sharedArchivePath(state.settings.outputPath, archiveLocale(state)),
        conflictAction: "uniquify",
        saveAs: true
      });
      await waitForDownload(downloadId);
    }
  } finally {
    await chrome.runtime.sendMessage({
      target: "offscreen",
      type: "REVOKE_BLOB_URL",
      url: archive.url
    });
  }
  return {
    ok: true,
    message: `分享包已导出(${exportState.entries.length} 个案例、${archive.imageCount} 张截图)`,
    count: exportState.entries.length,
    settings: state.settings
  };
}

async function exportProjectArchive(state, collectionId, directory = false) {
  const exportState = selectProjectPackage(state, collectionId);
  const project = exportState.organizerState.collections[0];
  await migrateLegacyScreenshots(exportState.entries);
  const archive = await createArchiveUrl(exportState, true);
  try {
    if (directory) await saveShareArchive(archive.url, projectArchivePath(state.settings.outputPath, project.name, archiveLocale(state)));
    else {
      const downloadId = await chrome.downloads.download({
        url: archive.url,
        filename: projectArchivePath(state.settings.outputPath, project.name, archiveLocale(state)),
        conflictAction: "uniquify",
        saveAs: true
      });
      await waitForDownload(downloadId);
    }
  } finally {
    await chrome.runtime.sendMessage({
      target: "offscreen",
      type: "REVOKE_BLOB_URL",
      url: archive.url
    });
  }
  return {
    ok: true,
    message: `项目“${project.name}”已导出(${exportState.entries.length} 个案例、${archive.imageCount} 张图片)`,
    count: exportState.entries.length,
    imageCount: archive.imageCount
  };
}

async function exportCuratedSubmission(state, message = {}) {
  const prepared = prepareCuratedSubmissionState(state, {
    entryIds: message.entryIds,
    collectionId: message.collectionId
  });
  await migrateLegacyScreenshots(prepared.entries);
  await ensureOffscreenDocument();
  const result = await chrome.runtime.sendMessage({
    target: "offscreen",
    type: "CREATE_CURATED_SUBMISSION_URLS",
    ...prepared.state,
    locale: archiveLocale(state)
  });
  if (!result?.ok || !Array.isArray(result.outputs) || !result.outputs.length) {
    throw new Error(result?.message || "无法生成精选投稿包");
  }
  const downloadIds = [];
  try {
    for (const output of result.outputs) {
      const downloadId = await chrome.downloads.download({
        url: output.url,
        filename: output.filename,
        conflictAction: "uniquify",
        saveAs: false
      });
      downloadIds.push(downloadId);
      await waitForDownload(downloadId);
    }
  } finally {
    await Promise.allSettled(result.outputs.map((output) => chrome.runtime.sendMessage({
      target: "offscreen",
      type: "REVOKE_BLOB_URL",
      url: output.url
    })));
  }
  return {
    ok: true,
    submissionId: result.submissionId,
    count: result.caseCount,
    mediaCount: result.mediaCount,
    partCount: result.partCount,
    downloadIds,
    message: result.partCount > 1
      ? `投稿包已生成,共 ${result.partCount} 个分卷`
      : "投稿包已生成"
  };
}

async function exportCreativeExperiments(state) {
  if (!state.creativeRuns.some((run) => run.outputs.length)) {
    return { ok: false, message: "还没有可导出的真实生成结果" };
  }
  await ensureOffscreenDocument();
  const archive = await chrome.runtime.sendMessage({
    target: "offscreen",
    type: "CREATE_CREATIVE_EXPERIMENT_ARCHIVE_URL",
    composerSettings: state.composerSettings,
    composerSessions: state.composerSessions,
    creativeExperimentSettings: state.creativeExperimentSettings,
    creativeRuns: state.creativeRuns,
    creativeSkills: state.creativeSkills
  });
  if (!archive?.ok || !archive.url) throw new Error(archive?.message || "无法准备创作实验包");
  try {
    const downloadId = await chrome.downloads.download({
      url: archive.url,
      filename: experimentArchivePath(state.settings.outputPath, archiveLocale(state)),
      conflictAction: "uniquify",
      saveAs: false
    });
    await waitForDownload(downloadId);
  } finally {
    await chrome.runtime.sendMessage({
      target: "offscreen",
      type: "REVOKE_BLOB_URL",
      url: archive.url
    });
  }
  return {
    ok: true,
    message: `创作实验包已导出(${archive.runCount} 次运行、${archive.mediaCount ?? archive.imageCount} 项结果媒体)`
  };
}

function previewCreativeExperimentImport(state, experiments) {
  const result = mergeCreativeExperimentPackage(state, experiments);
  return {
    ok: true,
    sessionIdMap: result.sessionIdMap,
    runIdMap: result.runIdMap,
    importedRunCount: result.importedRunCount,
    importedOutputCount: result.importedOutputCount,
    visualIdMap: result.visualIdMap
  };
}

async function applyCreativeExperimentImport(state, message) {
  const result = mergeCreativeExperimentPackage(state, message.experiments, {
    sessionIdMap: message.sessionIdMap,
    runIdMap: message.runIdMap,
    visualIdMap: message.visualIdMap
  });
  await commitLocalChanges({
    [STORAGE_KEYS.composerSettings]: result.state.composerSettings,
    [STORAGE_KEYS.composerSessions]: result.state.composerSessions,
    [STORAGE_KEYS.creativeExperimentSettings]: result.state.creativeExperimentSettings,
    [STORAGE_KEYS.creativeRuns]: result.state.creativeRuns
  });
  return {
    ok: true,
    message: `已导入 ${result.importedRunCount} 次创作运行和 ${result.importedOutputCount} 项结果媒体`,
    creativeRuns: result.state.creativeRuns
  };
}

function previewLibraryImport(state, library, options = {}) {
  const result = planLibraryTransfer({
    currentState: state,
    inspection: transferInspectionMessage(library, options),
    options
  });
  return {
    ok: true,
    planToken: result.planToken,
    plan: result.context,
    mode: result.context.mode,
    conflicts: result.conflicts,
    rollback: result.rollback,
    resourceWrites: result.resourceWrites,
    entryIdMap: result.entryIdMap,
    compoundIdMap: result.compoundIdMap,
    visualIdMap: result.visualIdMap,
    createdVisualIdMap: result.createdVisualIdMap,
    sessionIdMap: result.sessionIdMap,
    runIdMap: result.runIdMap,
    skillIdMap: result.skillIdMap,
    packageAssetIdMap: result.packageAssetIdMap,
    createdEntryIds: result.createdEntryIds,
    importDiagnostics: result.importDiagnostics,
    importStats: result.importStats,
    importedCount: result.importedCount,
    remappedCount: result.remappedCount,
    skippedCount: result.skippedCount,
    importedRunCount: result.importedRunCount,
    importedOutputCount: result.importedOutputCount,
    importedSkillCount: result.importedSkillCount,
    skippedSkillCount: result.skippedSkillCount
  };
}

function previewLibraryImportBatch(state, message = {}) {
  const inspections = transferInspectionMessages(message.packages);
  return previewLibraryTransferBatch({
    currentState: state,
    inspections,
    options: {
      preserveLibraryConfiguration: message.preserveLibraryConfiguration === true,
      conflictResolutions: message.conflictResolutions
    }
  });
}
async function applyLibraryImport(state, message) {
  const stored = await libraryStorage.get(STORAGE_KEYS.libraryImportTransactions);
  const claim = claimLibraryImportTransaction(stored[STORAGE_KEYS.libraryImportTransactions], {
    operationId: message.operationId,
    planToken: message.planToken,
    stateValue: state,
    sourceValue: message.library,
    planValue: message.plan
  }, { resumePending: true });
  if (claim.replayed) return claim.result;
  if (!claim.acquired) {
    throw Object.assign(new Error("这次导入仍在提交中,请稍后重试"), {
      code: "IMPORT_TRANSACTION_PENDING"
    });
  }
  await commitLocalChanges({
    [STORAGE_KEYS.libraryImportTransactions]: claim.state
  }, { markSyncDirty: false });

  let result;
  let response;
  try {
    result = planLibraryTransfer({
      currentState: state,
      inspection: transferInspectionMessage(message.library, {
        sourceType: message.plan?.sourceType,
        importReport: message.plan?.importReport,
        resourceIndex: {
          mediaAssetIds: (message.plan?.resourceWrites ?? [])
            .filter((item) => item.resourceType === "media").map((item) => item.sourceId),
          skillAssetIds: (message.plan?.resourceWrites ?? [])
            .filter((item) => item.resourceType === "skill").map((item) => item.sourceId)
        }
      }),
      options: { preferredPlan: message.plan }
    });
    if (result.planToken !== message.planToken) {
      throw Object.assign(new Error("导入计划已经变化,请重新检查"), { code: "IMPORT_PLAN_STALE" });
    }
    response = libraryImportResponse(result);
    const exactReplace = result.context.mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE;
    const previousRecoveryPoint = normalizeLibraryReplacementRecoveryPoint(state.libraryReplacementRecoveryPoint);
    const recoveryPoint = exactReplace
      ? createLibraryReplacementRecoveryPoint(folderBackupState(state), {
          retainedAssetIds: result.rollback.retainedAssetIds
        })
      : previousRecoveryPoint;
    if (exactReplace) response.recoveryPointCreatedAt = recoveryPoint.createdAt;
    const completed = succeedLibraryImportTransaction(claim.state, claim.receipt, response);
    const update = {
      ...storagePayload(result.targetState),
      [STORAGE_KEYS.settings]: normalizeSettings(result.targetState.settings ?? state.settings),
      [STORAGE_KEYS.composerSettings]: normalizeComposerSettings(result.targetState.composerSettings ?? state.composerSettings),
      [STORAGE_KEYS.composerSessions]: normalizeComposerSessions(result.targetState.composerSessions ?? state.composerSessions),
      [STORAGE_KEYS.creativeExperimentSettings]: normalizeCreativeExperimentSettings(
        result.targetState.creativeExperimentSettings ?? state.creativeExperimentSettings
      ),
      [STORAGE_KEYS.creativeRuns]: normalizeCreativeRuns(result.targetState.creativeRuns ?? state.creativeRuns),
      [STORAGE_KEYS.creativeSkills]: normalizeCreativeSkillsState(result.targetState.creativeSkills ?? state.creativeSkills),
      [STORAGE_KEYS.libraryImportTransactions]: completed.state,
      ...(exactReplace ? { [STORAGE_KEYS.libraryReplacementRecoveryPoint]: recoveryPoint } : {})
    };
    await commitLocalChanges(update);
  } catch (error) {
    const stored = await libraryStorage.get(STORAGE_KEYS.libraryImportTransactions);
    const current = stored[STORAGE_KEYS.libraryImportTransactions];
    const completed = current?.items?.find(item => item.operationId === claim.receipt.operationId && item.status === "completed");
    if (completed) return completed.result;
    const failed = failLibraryImportTransaction(current, claim.receipt);
    await commitLocalChanges({
      [STORAGE_KEYS.libraryImportTransactions]: failed
    }, { markSyncDirty: false }).catch(() => undefined);
    throw error;
  }

  if (result.context.mode === LIBRARY_TRANSFER_MODES.EXACT_REPLACE) {
    try {
      const stored = await libraryStorage.get(STORAGE_KEYS.libraryReplacementRecoveryPoint);
      const obsoleteAssetIds = obsoleteRecoveryAssetIds(
        state.libraryReplacementRecoveryPoint,
        [...collectRetainedLocalAssetIds({ ...state, ...result.targetState, libraryReplacementRecoveryPoint: stored[STORAGE_KEYS.libraryReplacementRecoveryPoint] })],
        stored[STORAGE_KEYS.libraryReplacementRecoveryPoint]
      );
      await deleteMediaBlobs(obsoleteAssetIds);
    } catch (error) {
      console.error("Obsolete library recovery media cleanup failed", error);
    }
  }

  const importedEntryIds = result.createdEntryIds;
  if (importedEntryIds.length) {
    const importedEntryIdSet = new Set(importedEntryIds);
    await enqueueAutomaticLibraryMaintenance(
      result.targetState.entries.filter((entry) => importedEntryIdSet.has(entry.id))
    ).catch((error) => console.error("Imported library maintenance could not be queued", error));
  }
  if (importedEntryIds.length && message.autoAnalyze === true) {
    await queueAutomaticVisionAnalysis(importedEntryIds)
      .catch((error) => console.error("Imported library analysis could not be queued", error));
  }
  return response;
}

async function applyLibraryImportBatch(state, message) {
  const packages = Array.isArray(message.packages) ? message.packages : [];
  const sourceValue = packages.map((item) => item?.library);
  const stored = await libraryStorage.get(STORAGE_KEYS.libraryImportTransactions);
  const claim = claimLibraryImportTransaction(stored[STORAGE_KEYS.libraryImportTransactions], {
    operationId: message.operationId,
    planToken: message.planToken,
    stateValue: state,
    sourceValue,
    planValue: message.plan
  }, { resumePending: true });
  if (claim.replayed) return claim.result;
  if (!claim.acquired) {
    throw Object.assign(new Error("这次导入仍在提交中,请稍后重试"), {
      code: "IMPORT_TRANSACTION_PENDING"
    });
  }
  await commitLocalChanges({
    [STORAGE_KEYS.libraryImportTransactions]: claim.state
  }, { markSyncDirty: false });

  let result;
  let response;
  try {
    result = planLibraryTransferBatch({
      currentState: state,
      inspections: transferInspectionMessages(packages),
      options: { preferredPlan: message.plan }
    });
    if (!result.canApply) {
      throw Object.assign(new Error("批次仍有未处理的案例冲突"), { code: "IMPORT_CONFLICT_UNRESOLVED" });
    }
    if (result.planToken !== message.planToken) {
      throw Object.assign(new Error("导入计划已经变化,请重新检查"), { code: "IMPORT_PLAN_STALE" });
    }
    response = libraryImportResponse(result);
    const completed = succeedLibraryImportTransaction(claim.state, claim.receipt, response);
    await commitLocalChanges({
      ...storagePayload(result.targetState),
      [STORAGE_KEYS.settings]: normalizeSettings(result.targetState.settings ?? state.settings),
      [STORAGE_KEYS.composerSettings]: normalizeComposerSettings(result.targetState.composerSettings ?? state.composerSettings),
      [STORAGE_KEYS.composerSessions]: normalizeComposerSessions(result.targetState.composerSessions ?? state.composerSessions),
      [STORAGE_KEYS.creativeExperimentSettings]: normalizeCreativeExperimentSettings(
        result.targetState.creativeExperimentSettings ?? state.creativeExperimentSettings
      ),
      [STORAGE_KEYS.creativeRuns]: normalizeCreativeRuns(result.targetState.creativeRuns ?? state.creativeRuns),
      [STORAGE_KEYS.creativeSkills]: normalizeCreativeSkillsState(result.targetState.creativeSkills ?? state.creativeSkills),
      [STORAGE_KEYS.libraryImportTransactions]: completed.state
    });
  } catch (error) {
    const stored = await libraryStorage.get(STORAGE_KEYS.libraryImportTransactions);
    const current = stored[STORAGE_KEYS.libraryImportTransactions];
    const completed = current?.items?.find(item => item.operationId === claim.receipt.operationId && item.status === "completed");
    if (completed) return completed.result;
    const failed = failLibraryImportTransaction(current, claim.receipt);
    await commitLocalChanges({
      [STORAGE_KEYS.libraryImportTransactions]: failed
    }, { markSyncDirty: false }).catch(() => undefined);
    throw error;
  }

  if (result.createdEntryIds.length) {
    const importedEntryIdSet = new Set(result.createdEntryIds);
    await enqueueAutomaticLibraryMaintenance(
      result.targetState.entries.filter((entry) => importedEntryIdSet.has(entry.id))
    ).catch((error) => console.error("Imported library maintenance could not be queued", error));
  }
  if (result.createdEntryIds.length && message.autoAnalyze === true) {
    await queueAutomaticVisionAnalysis(result.createdEntryIds)
      .catch((error) => console.error("Imported library analysis could not be queued", error));
  }
  return response;
}

async function previewLibraryUndo(message) {
  const action = message.action;
  const extraKeys = {
    UNDO_FACET_UPDATE: [STORAGE_KEYS.facetUndo],
    UNDO_IMPORT_JOB: [STORAGE_KEYS.importJobs],
    UNDO_ANALYSIS_BATCH: [STORAGE_KEYS.batchJob, STORAGE_KEYS.analysisBatchUndo],
    RESTORE_LIBRARY_REPLACEMENT_POINT: [STORAGE_KEYS.libraryReplacementRecoveryPoint, STORAGE_KEYS.settings,
      STORAGE_KEYS.composerSettings, STORAGE_KEYS.composerSessions, STORAGE_KEYS.creativeExperimentSettings,
      STORAGE_KEYS.creativeRuns, STORAGE_KEYS.creativeSkills]
  }[action];
  if (!extraKeys) throw new Error("未知操作");
  return undoConfirmations.prepare(action, [CASE_LIBRARY_REVISION_KEY, ...extraKeys], async () => {
    const state = await readState();
    const identify = entry => ({ id: entry.id, title: entry.title || entry.id });
    if (action === "RESTORE_LIBRARY_REPLACEMENT_POINT") {
      const point = normalizeLibraryReplacementRecoveryPoint(state.libraryReplacementRecoveryPoint);
      if (!point) throw new Error("当前没有可回退的资料库状态");
      return { ok: true, expectedPointId: point.id, createdAt: point.createdAt,
        ...replacementImpact(folderBackupState(state), point.state) };
    }
    if (action === "UNDO_FACET_UPDATE") {
      const undone = undoFacetHistory(domainState(state), state.facetUndo);
      return { ok: true, cases: state.entries.filter((entry, index) => entry !== undone.state.entries[index]).map(identify) };
    }
    if (action === "UNDO_IMPORT_JOB") {
      const undone = undoImportJob(state.importJobs, message.jobId);
      const ids = new Set(undone.createdEntryIds);
      const cases = state.entries.filter(entry => ids.has(entry.id));
      if (cases.length !== ids.size || cases.some(entry => entry.importBatchId !== undone.job.importBatchId)) {
        throw new Error("导入案例已变化,未执行撤销");
      }
      return { ok: true, jobId: undone.job.id, cases: cases.map(identify) };
    }
    const stored = await libraryStorage.get([STORAGE_KEYS.batchJob, STORAGE_KEYS.analysisBatchUndo]);
    const job = requireAnalysisBatch(stored[STORAGE_KEYS.batchJob], message.jobId, "text_tags");
    const undo = stored[STORAGE_KEYS.analysisBatchUndo];
    if (!undo || undo.jobId !== job.id) throw new Error("没有这次批量分析的撤回快照");
    if (state.facetCatalog.revision !== (job.resultCatalogRevision ?? job.catalogRevision)) {
      throw new Error("创作词库已在批量分析后继续修改,不能安全自动撤回");
    }
    restoreAnalysisBatchUndo(domainState(state), undo);
    const ids = new Set(undo.appliedEntries.map(entry => entry.entryId));
    return { ok: true, jobId: job.id, cases: state.entries.filter(entry => ids.has(entry.id)).map(identify) };
  });
}

async function restoreLibraryReplacementPoint(state, message) {
  const point = normalizeLibraryReplacementRecoveryPoint(state.libraryReplacementRecoveryPoint);
  if (!point) return { ok: false, message: "当前没有可回退的资料库状态" };
  const operationId = String(message?.operationId || "").trim();
  const expectedPointId = String(message?.expectedPointId || "").trim();
  if (operationId && point.restoreReceipt?.operationId === operationId && point.restoreReceipt.sourcePointId === expectedPointId) {
    return libraryReplacementRestoreResponse(point);
  }
  if (!operationId || expectedPointId !== point.id) {
    return { ok: false, message: "回退点已经变化,请刷新资料库后重新确认" };
  }
  const guard = undoConfirmations.guard("RESTORE_LIBRARY_REPLACEMENT_POINT", message.confirmationToken);
  const currentManagedState = folderBackupState(state);
  const swapped = swapLibraryReplacementRecoveryPoint(currentManagedState, point, {
    retainedAssetIds: [...collectRetainedLocalAssetIds(currentManagedState)],
    restoreReceipt: { operationId, sourcePointId: expectedPointId }
  });
  await commitLocalChanges({
    ...storagePayload(swapped.targetState),
    [STORAGE_KEYS.settings]: normalizeSettings(swapped.targetState.settings ?? state.settings),
    [STORAGE_KEYS.composerSettings]: normalizeComposerSettings(swapped.targetState.composerSettings),
    [STORAGE_KEYS.composerSessions]: normalizeComposerSessions(swapped.targetState.composerSessions),
    [STORAGE_KEYS.creativeExperimentSettings]: normalizeCreativeExperimentSettings(
      swapped.targetState.creativeExperimentSettings
    ),
    [STORAGE_KEYS.creativeRuns]: normalizeCreativeRuns(swapped.targetState.creativeRuns),
    [STORAGE_KEYS.creativeSkills]: normalizeCreativeSkillsState(swapped.targetState.creativeSkills),
    [STORAGE_KEYS.libraryReplacementRecoveryPoint]: swapped.recoveryPoint
  }, { guard });
  return libraryReplacementRestoreResponse(swapped.recoveryPoint);
}

function libraryReplacementRestoreResponse(point) {
  return {
    ok: true,
    message: "已回退到上一次精确替换前的资料库;刚才的状态已保存为新的回退点",
    recoveryPointCreatedAt: point.createdAt
  };
}

function transferInspectionMessage(library, options = {}) {
  return {
    sourceType: Object.values(LIBRARY_TRANSFER_SOURCES).includes(options.sourceType)
      ? options.sourceType
      : LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,
    state: library,
    report: options.importReport ?? {
      status: Array.isArray(library?.importDiagnostics) && library.importDiagnostics.length ? "partial" : "ready",
      diagnostics: Array.isArray(library?.importDiagnostics) ? library.importDiagnostics : [],
      stats: library?.importStats && typeof library.importStats === "object" ? library.importStats : {}
    },
    resourceIndex: options.resourceIndex ?? { mediaAssetIds: [], skillAssetIds: [] }
  };
}

function transferInspectionMessages(packagesValue) {
  const packages = Array.isArray(packagesValue) ? packagesValue : [];
  if (!packages.length) throw new Error("请选择至少一个案例包");
  return packages.map((item) => transferInspectionMessage(item?.library, item));
}

function libraryImportResponse(result) {
  return {
    ok: true,
    message: result.importedCount || result.importedRunCount || result.importedSkillCount
      ? `已导入 ${result.importedCount} 个案例、${result.importedRunCount} 次创作运行和 ${result.importedSkillCount} 个 Skill${result.remappedCount ? `;其中 ${result.remappedCount} 个同源案例作为新副本导入,未覆盖旧数据` : ""}${result.skippedCount || result.skippedSkillCount ? `,跳过 ${result.skippedCount} 个已有案例和 ${result.skippedSkillCount} 个已有 Skill` : ""}`
      : `没有新增内容,${result.skippedCount} 个案例已经存在`,
    count: result.targetState.entries.length,
    importedCount: result.importedCount,
    remappedCount: result.remappedCount,
    skippedCount: result.skippedCount,
    importedRunCount: result.importedRunCount,
    importedOutputCount: result.importedOutputCount,
    importedSkillCount: result.importedSkillCount,
    skippedSkillCount: result.skippedSkillCount
  };
}

function previewCuratedImport(state, message) {
  const result = mergeCuratedLibraryPackage(state, message.library, {
    packageId: message.packageId,
    projectName: message.projectName,
    mode: message.mode
  });
  return curatedImportResponse(result);
}

async function applyCuratedImport(state, message) {
  const result = mergeCuratedLibraryPackage(state, message.library, {
    packageId: message.packageId,
    projectName: message.projectName,
    mode: message.mode,
    entryIdMap: message.entryIdMap,
    compoundIdMap: message.compoundIdMap,
    visualIdMap: message.visualIdMap,
    sessionIdMap: message.sessionIdMap,
    runIdMap: message.runIdMap
  });
  await commitLocalChanges({
    ...storagePayload(result.state),
    [STORAGE_KEYS.settings]: normalizeSettings(result.state.settings ?? state.settings),
    [STORAGE_KEYS.composerSettings]: normalizeComposerSettings(result.state.composerSettings ?? state.composerSettings),
    [STORAGE_KEYS.composerSessions]: normalizeComposerSessions(result.state.composerSessions ?? state.composerSessions),
    [STORAGE_KEYS.creativeExperimentSettings]: normalizeCreativeExperimentSettings(
      result.state.creativeExperimentSettings ?? state.creativeExperimentSettings
    ),
    [STORAGE_KEYS.creativeRuns]: normalizeCreativeRuns(result.state.creativeRuns ?? state.creativeRuns),
    [STORAGE_KEYS.creativeSkills]: normalizeCreativeSkillsState(result.state.creativeSkills ?? state.creativeSkills)
  });
  const warnings = [];
  if (result.importedEntryIds.length) {
    const importedEntryIdSet = new Set(result.importedEntryIds);
    try { await enqueueAutomaticLibraryMaintenance(result.state.entries.filter((entry) => importedEntryIdSet.has(entry.id))); }
    catch (error) { warnings.push(`案例已保存,自动整理未启动:${userMessage(error)}`); }
    try { await queueAutomaticVisionAnalysis(result.importedEntryIds); }
    catch (error) { warnings.push(`案例已保存,自动分析未启动:${userMessage(error)}`); }
  }
  return { ...curatedImportResponse(result), ...(warnings.length ? { warnings } : {}) };
}

function curatedImportResponse(result) {
  return {
    ok: true,
    entryIdMap: result.entryIdMap,
    compoundIdMap: result.compoundIdMap,
    visualIdMap: result.visualIdMap,
    sessionIdMap: result.sessionIdMap,
    runIdMap: result.runIdMap,
    importedCount: result.importedCount,
    existingCount: result.existingCount,
    sourceEntryIds: result.sourceEntryIds,
    importedSourceEntryIds: result.importedSourceEntryIds,
    entriesBySourceEntryId: result.entriesBySourceEntryId,
    importedEntryIds: result.importedEntryIds,
    importedVisualIds: result.importedVisualIds,
    projectId: result.projectId,
    count: result.state.entries.length
  };
}

function archiveLocale(state) {
  return resolveLocale(state.uiPreferences, chrome.i18n.getUILanguage()) === "en" ? "en" : "zh-CN";
}

// Export names follow the interface language and carry the local date, so repeated exports
// stay distinguishable without relying on the browser's "(1)" suffix.
function archiveName(locale, zh, en) {
  const now = new Date();
  const date = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map(part => String(part).padStart(2, "0")).join("-");
  return `${locale === "en" ? en : zh}-${date}.zip`;
}

function sharedArchivePath(outputPath, locale) {
  const normalized = normalizeSettings({ outputPath }).outputPath;
  const separator = normalized.lastIndexOf("/");
  const directory = separator >= 0 ? normalized.slice(0, separator + 1) : "";
  const filename = (separator >= 0 ? normalized.slice(separator + 1) : normalized).replace(/\.zip$/i, "");
  return `${directory}${archiveName(locale, `${filename}-分享`, `${filename}-Share`)}`;
}

function projectArchivePath(outputPath, projectName, locale) {
  const normalized = normalizeSettings({ outputPath }).outputPath;
  const separator = normalized.lastIndexOf("/");
  const directory = separator >= 0 ? normalized.slice(0, separator + 1) : "";
  const fallback = locale === "en" ? "Project" : "项目";
  const safeName = String(projectName ?? fallback).replace(/[<>:"/\\|?*\u0000-\u001f]/g, "-").trim() || fallback;
  return `${directory}${archiveName(locale, `PromptDirector-${safeName}-分享`, `PromptDirector-${safeName}-Share`)}`;
}

function experimentArchivePath(outputPath, locale) {
  const normalized = normalizeSettings({ outputPath }).outputPath;
  const separator = normalized.lastIndexOf("/");
  const directory = separator >= 0 ? normalized.slice(0, separator + 1) : "";
  return `${directory}${archiveName(locale, "PromptDirector-创作实验", "PromptDirector-Creative-Experiment")}`;
}

async function createArchiveUrl(state, sharing = false) {
  await ensureOffscreenDocument();
  const manifest = chrome.runtime.getManifest();
  const locale = resolveLocale(state.uiPreferences, chrome.i18n.getUILanguage());
  const result = await chrome.runtime.sendMessage({
    target: "offscreen",
    type: "CREATE_ARCHIVE_URL",
    entries: state.entries,
    settings: state.settings,
    taxonomy: state.taxonomy,
    facetCatalog: state.facetCatalog,
    classificationRules: state.classificationRules,
    organizerState: state.organizerState,
    compoundCases: state.compoundCases,
    composerSettings: sharing ? undefined : state.composerSettings,
    composerSessions: sharing ? [] : state.composerSessions,
    creativeExperimentSettings: sharing ? undefined : state.creativeExperimentSettings,
    creativeRuns: sharing ? [] : state.creativeRuns,
    creativeSkills: sharing ? { version: 1, items: [] } : state.creativeSkills,
    uiPreferences: state.uiPreferences,
    locale,
    sharing,
    installUrl: CHROME_WEB_STORE_URL,
    sourceUrl: manifest.homepage_url || ""
  });
  if (!result?.ok || !result.url) {
    throw new Error(result?.message || "无法准备案例库 ZIP");
  }
  return result;
}

async function connectSyncFolder(password, directoryId) {
  const directory = await getStagedSyncDirectoryHandle(directoryId);
  if (!directory) throw new Error("请先选择同步文件夹");
  await requireDirectoryPermission(directory);
  const vault = await createOrUnlockSyncVault(directory, String(password ?? ""));
  const stored = await libraryStorage.get(STORAGE_KEYS.syncSettings);
  const current = normalizeSyncSettings(stored[STORAGE_KEYS.syncSettings]);
  const changedVault = current.vaultId !== vault.header.vaultId;
  const settings = normalizeSyncSettings({
    ...current,
    enabled: true,
    vaultId: vault.header.vaultId,
    lastSyncAt: changedVault ? "" : current.lastSyncAt,
    lastError: "",
    lastErrorCode: ""
  });
  const previousConnection = {
    directory: await getSyncDirectoryHandle(),
    key: await getSyncCryptoKey()
  };
  await saveSyncConnection({ directory, key: vault.key });
  try {
    const update = { [STORAGE_KEYS.syncSettings]: settings };
    if (changedVault) update[STORAGE_KEYS.syncMeta] = normalizeSyncMeta({ localDirty: true });
    await commitLocalChanges(update);
  } catch (error) {
    await saveSyncConnection(previousConnection);
    throw error;
  }
  return {
    ok: true,
    connected: true,
    message: "同步文件夹已连接,尚未读取或合并资料;需要时请点击“立即同步”"
  };
}

async function unlockSyncVault(password) {
  const directory = await getSyncDirectoryHandle();
  if (!directory) throw new Error("本机没有保存同步文件夹,请重新选择");
  await requireDirectoryPermission(directory);
  const vault = await createOrUnlockSyncVault(directory, String(password ?? ""));
  const stored = await libraryStorage.get(STORAGE_KEYS.syncSettings);
  const current = normalizeSyncSettings(stored[STORAGE_KEYS.syncSettings]);
  if (current.vaultId && current.vaultId !== vault.header.vaultId) {
    throw new Error("这个文件夹不是此前连接的同步库,请使用“更换同步文件夹”");
  }
  const settings = normalizeSyncSettings({
    ...current,
    enabled: true,
    vaultId: vault.header.vaultId,
    lastError: "",
    lastErrorCode: ""
  });
  await saveSyncCryptoKey(vault.key);
  await commitLocalChanges({ [STORAGE_KEYS.syncSettings]: settings });
  return {
    ok: true,
    unlocked: true,
    message: "同步库已解锁,尚未读取或合并资料;需要时请点击“立即同步”"
  };
}

async function performManualSynchronization(start) {
  const stored = await libraryStorage.get(STORAGE_KEYS.syncSettings);
  const settings = normalizeSyncSettings(stored[STORAGE_KEYS.syncSettings]);
  if (!settings.enabled) {
    throw new Error("请先在“数据与同步”中选择同步文件夹");
  }
  const directory = await getSyncDirectoryHandle();
  if (!directory) throw await recordSyncError(settings, "同步文件夹需要重新选择");
  const permission = await directoryPermission(directory);
  if (permission !== "granted") throw await recordSyncError(settings, "同步文件夹权限已失效,请重新授权");
  const key = await getSyncCryptoKey();
  if (!key) throw await recordSyncError(settings, "同步库已锁定,请输入密码解锁");
  try {
    const vault = await openSyncVaultWithKey(directory, key, settings.vaultId);
    const result = await start({ vault, settings });
    if (result.canceled) {
      return {
        ...result,
        ok: true,
        libraryChanged: false,
        message: "本次同步已停止,本机未提交的资料没有改变"
      };
    }
    if (result.upToDate) {
      const pendingCleanupCount = Math.max(0, Number(result.cleanupPendingCount) || 0);
      return {
        ...result,
        ok: true,
        libraryChanged: false,
        message: pendingCleanupCount
          ? `两端资料已经一致;${pendingCleanupCount} 项本机过期媒体将在下次同步继续清理`
          : result.effects?.localMediaDeleted
            ? "两端资料没有变化;已完成本机过期媒体清理"
            : "两端没有变化,没有写入同步文件夹"
      };
    }
    return {
      ...result,
      ok: true,
      libraryChanged: result.effects?.localBusinessChanged === true,
      message: syncResultMessage(result)
    };
  } catch (error) {
    throw await recordSyncError(settings, error);
  }
}

async function commitManualSyncResult({ state, settings, meta, trackingOnly }) {
  syncApplyInProgress = true;
  try {
    const update = {
      [STORAGE_KEYS.syncSettings]: normalizeSyncSettings(settings),
      [STORAGE_KEYS.syncMeta]: normalizeSyncMeta(meta)
    };
    if (!trackingOnly) {
      Object.assign(update, synchronizedStatePayload(await readState(), state));
    }
    await commitLocalChanges(update);
  } finally {
    syncApplyInProgress = false;
  }
}

function syncResultMessage(result = {}) {
  const summary = result.changeSummary ?? {};
  const changes = [
    summary.added ? `新增 ${summary.added} 项` : "",
    summary.updated ? `更新 ${summary.updated} 项` : "",
    summary.deleted ? `删除 ${summary.deleted} 项` : "",
    summary.conflicts ? `保留 ${summary.conflicts} 个冲突副本` : ""
  ].filter(Boolean).join(",");
  const pendingCleanupCount = Math.max(0, Number(result.cleanupPendingCount) || 0);
  const cleanup = pendingCleanupCount
    ? `;${pendingCleanupCount} 项本机过期媒体将在下次同步继续清理`
    : "";
  const skippedMediaCount = Math.max(0, Number(result.skippedMediaCount) || 0);
  const salvage = skippedMediaCount
    ? `;已跳过并清理 ${skippedMediaCount} 项本机缺失媒体,其他资料已继续同步`
    : "";
  const skippedMediaDetails = syncSkippedMediaLabels(result.skippedMedia);
  const details = skippedMediaDetails.length ? `;缺失项:${skippedMediaDetails.join("、")}` : "";
  return `${changes ? `手动同步完成:${changes}` : "手动同步完成"}${salvage}${details}${cleanup}`;
}

function syncSkippedMediaLabels(itemsValue) {
  const labels = (Array.isArray(itemsValue) ? itemsValue : []).map((item) => {
    const owner = cleanSyncMessagePart(item?.ownerTitle);
    const source = cleanSyncMessagePart(item?.sourceTitle);
    if (owner && source && owner !== source) return `${owner} / ${source}`;
    return owner || source || cleanSyncMessagePart(item?.assetId);
  }).filter(Boolean);
  return [...new Set(labels)];
}

function cleanSyncMessagePart(value) {
  return String(value ?? "").replace(/[;;\r\n]+/gu, " ").trim();
}

function notifySyncProgress(progress = {}) {
  chrome.runtime.sendMessage({
    type: "SYNC_PROGRESS",
    phase: progress.phase,
    current: Math.max(0, Number(progress.current) || 0),
    total: Math.max(0, Number(progress.total) || 0)
  }).catch(() => undefined);
}

function synchronizedStatePayload(current, synced) {
  const entries = Array.isArray(synced.entries) ? synced.entries : current.entries;
  const next = {
    schemaVersion: SCHEMA_VERSION,
    entries,
    trashState: normalizeTrashState(synced.trashState ?? current.trashState),
    compoundCases: normalizeCompoundCases(synced.compoundCases ?? current.compoundCases, entries),
    taxonomy: normalizeTaxonomy(synced.taxonomy ?? current.taxonomy),
    facetCatalog: synced.facetCatalog ?? current.facetCatalog,
    classificationRules: synced.classificationRules ?? current.classificationRules,
    organizerState: normalizeOrganizerState(
      synced.organizerState ?? current.organizerState,
      entries.map((entry) => entry.id)
    )
  };
  const settings = normalizeSettings({
    ...current.settings,
    libraryTitle: synced.settings?.libraryTitle || current.settings.libraryTitle
  });
  return {
    ...storagePayload(next),
    [STORAGE_KEYS.settings]: settings,
    [STORAGE_KEYS.composerSettings]: normalizeComposerSettings(synced.composerSettings ?? current.composerSettings),
    [STORAGE_KEYS.composerSessions]: normalizeComposerSessions(synced.composerSessions ?? current.composerSessions),
    [STORAGE_KEYS.creativeExperimentSettings]: normalizeCreativeExperimentSettings(
      synced.creativeExperimentSettings ?? current.creativeExperimentSettings
    ),
    [STORAGE_KEYS.creativeRuns]: normalizeCreativeRuns(synced.creativeRuns ?? current.creativeRuns),
    [STORAGE_KEYS.creativeSkills]: normalizeCreativeSkillsState(synced.creativeSkills ?? current.creativeSkills)
  };
}

async function disconnectSyncFolder() {
  const stored = await libraryStorage.get(STORAGE_KEYS.syncSettings);
  const current = normalizeSyncSettings(stored[STORAGE_KEYS.syncSettings]);
  await clearSyncPrivateState();
  await commitLocalChanges({
    [STORAGE_KEYS.syncSettings]: normalizeSyncSettings({
      ...current,
      enabled: false,
      vaultId: "",
      lastError: "",
      lastErrorCode: ""
    })
  });
  await libraryStorage.remove(STORAGE_KEYS.syncMeta);
  return { ok: true, message: "已断开同步文件夹,本地案例没有删除" };
}

async function dataSafetyStatus(state) {
  const media = state.entries.flatMap((entry) => normalizeEntryMedia(entry).mediaAssets);
  return {
    ok: true,
    entryCount: state.entries.length,
    imageCount: state.entries.reduce((sum, entry) => sum + normalizeEntryVisuals(entry).visuals.length, 0),
    mediaCount: media.length,
    videoCount: media.filter((asset) => asset.kind === "video").length,
    documentCount: media.filter((asset) => asset.kind === "document").length,
    canRestoreReplacementPoint: Boolean(state.libraryReplacementRecoveryPoint),
    replacementPointId: state.libraryReplacementRecoveryPoint?.id || "",
    replacementPointCreatedAt: state.libraryReplacementRecoveryPoint?.createdAt || "",
    syncStatus: state.syncStatus
  };
}

async function publicSyncStatus(settingsValue) {
  const settings = normalizeSyncSettings(settingsValue);
  const metaStored = await libraryStorage.get(STORAGE_KEYS.syncMeta);
  const meta = normalizeSyncMeta(metaStored[STORAGE_KEYS.syncMeta]);
  const run = manualSyncController.status();
  const directory = await getSyncDirectoryHandle().catch(() => null);
  const permission = directory ? await directoryPermission(directory) : "missing";
  const unlocked = Boolean(await getSyncCryptoKey().catch(() => null));
  return {
    enabled: settings.enabled,
    connected: Boolean(settings.vaultId && directory),
    unlocked,
    permission,
    needsAuthorization: settings.enabled && permission !== "granted",
    lastSyncAt: settings.lastSyncAt,
    lastError: settings.lastError,
    lastErrorCode: settings.lastErrorCode,
    localDirty: meta.localDirty,
    dirtyAssetCount: meta.dirtyAssetIds.length,
    pendingCleanupAssetCount: meta.pendingCleanupAssetIds.length,
    ...run
  };
}

async function requireDirectoryPermission(directory) {
  const permission = await directoryPermission(directory);
  if (permission !== "granted") {
    throw new Error("同步文件夹尚未授权,请重新选择文件夹");
  }
}

async function directoryPermission(directory) {
  if (typeof directory.queryPermission !== "function") return "granted";
  return directory.queryPermission({ mode: "readwrite" });
}

async function recordSyncError(settings, failure) {
  const details = syncErrorDetails(failure);
  const message = details.message || "同步失败";
  const error = new Error(message);
  syncApplyInProgress = true;
  try {
    await commitLocalChanges({
      [STORAGE_KEYS.syncSettings]: normalizeSyncSettings({
        ...settings,
        lastError: message,
        lastErrorCode: details.code
      })
    });
  } finally {
    syncApplyInProgress = false;
  }
  return error;
}

async function migrateLegacyScreenshots(entries) {
  for (const entryValue of entries) {
    const entry = normalizeEntryVisuals(entryValue);
    if (!entry.visuals.some((visual) => visual.id === entry.id)) continue;
    const legacyKey = screenshotStorageKey(entry.id);
    const stored = await libraryStorage.get(legacyKey);
    const legacyDataUrl = stored[legacyKey];
    if (!legacyDataUrl) continue;

    let blob = await getScreenshotBlob(entry.id);
    if (!blob) {
      blob = await dataUrlToImageBlob(legacyDataUrl);
      await saveScreenshotBlob(entry.id, blob);
    }
    await libraryStorage.remove(legacyKey);
  }
}

async function dataUrlToImageBlob(value) {
  if (!/^data:image\/(?:png|jpeg|webp);base64,/.test(String(value ?? ""))) {
    throw new Error("旧版截图数据损坏,无法迁移");
  }
  const response = await fetch(value);
  const blob = await response.blob();
  if (!blob.type.startsWith("image/")) throw new Error("旧版截图格式无效");
  return blob;
}

async function ensureOffscreenDocument() {
  const documentUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH);
  const contexts = await chrome.runtime.getContexts({
    contextTypes: ["OFFSCREEN_DOCUMENT"],
    documentUrls: [documentUrl]
  });
  if (contexts.length) return;

  if (!creatingOffscreenDocument) {
    creatingOffscreenDocument = chrome.offscreen
      .createDocument({
        url: OFFSCREEN_DOCUMENT_PATH,
        reasons: ["BLOBS"],
        justification: "处理持久视频分析、媒体创作、截图裁剪和本地文件打包"
      })
      .finally(() => {
        creatingOffscreenDocument = null;
      });
  }
  await creatingOffscreenDocument;
}

async function recoverCreativeJobs() {
  const stored = await libraryStorage.get([
    STORAGE_KEYS.creativeJobs,
    STORAGE_KEYS.composerSessions
  ]);
  const creativeJobs = normalizeCreativeJobsState(stored[STORAGE_KEYS.creativeJobs]);
  const active = activeCreativeJob(creativeJobs);
  if (!active) return;
  const documentUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH);
  const contexts = await chrome.runtime.getContexts({
    contextTypes: ["OFFSCREEN_DOCUMENT"],
    documentUrls: [documentUrl]
  });
  if (contexts.length) {
    const response = await chrome.runtime.sendMessage({ target: "offscreen", type: "GET_CREATIVE_JOB_RUNNER" }).catch(() => null);
    if (response?.ok && response.jobId === active.id) return;
  }
  if (active.request.session.outputMode === "create_video" && active.remoteVideo && ["generation", "downloading"].includes(active.phase)) {
    try {
      await dispatchCreativeJob(active);
      return;
    } catch {
      // Continue to the explicit interrupted state below when the resumable runner cannot restart.
    }
  }
  const recoveryJobId = active.id;
  await enqueue(async () => {
    const latest = await libraryStorage.get([
      STORAGE_KEYS.creativeJobs,
      STORAGE_KEYS.composerSessions
    ]);
    const creativeJobs = normalizeCreativeJobsState(latest[STORAGE_KEYS.creativeJobs]);
    const active = activeCreativeJob(creativeJobs);
    if (!active || active.id !== recoveryJobId) return;
    const interrupted = interruptActiveCreativeJobs(creativeJobs);
    const interruptedJob = creativeJobById(interrupted, active.id);
    const sessions = normalizeComposerSessions(latest[STORAGE_KEYS.composerSessions]);
    const sourceSession = sessions.find((item) => item.id === active.sessionId) ?? active.request.session;
    let session = setComposerFailure(sourceSession, {
      userMessageId: active.userMessageId,
      phase: active.phase === "planning" ? "planning" : "streaming",
      kind: "storage",
      message: interruptedJob?.error?.message || "浏览器曾在任务完成前退出,结果状态未知,请手动重试",
      retryable: true
    });
    session = createComposerSession({
      ...session,
      assemblySnapshot: failComposerAssemblySnapshot(session.assemblySnapshot, {
        kind: "interrupted",
        actualStages: active.actualStages
      })
    });
    await commitLocalChanges({
      [STORAGE_KEYS.creativeJobs]: interrupted,
      [STORAGE_KEYS.composerSessions]: upsertSessionList(sessions, session)
    });
  });
}

async function showResultToast(tabId, message, isError) {
  if (!tabId) return;
  await chrome.scripting
    .executeScript({
      target: { tabId },
      func: showPageToast,
      args: [message, isError]
    })
    .catch(() => undefined);
}

async function notifySaved(count) {
  await chrome.action.setBadgeBackgroundColor({ color: "#176B56" });
  await chrome.action.setBadgeText({ text: String(count) });
  setTimeout(() => chrome.action.setBadgeText({ text: "" }), 1800);
}

async function notifyError(message) {
  await chrome.action.setBadgeBackgroundColor({ color: "#B42318" });
  await chrome.action.setBadgeText({ text: "!" });
  await chrome.action.setTitle({ title: `保存失败:${message}` });
  setTimeout(async () => {
    await chrome.action.setBadgeText({ text: "" });
    await chrome.action.setTitle({ title: "保存高亮提示词" });
  }, 3000);
}

function userMessage(error) {
  if (error instanceof Error) return error.message;
  return String(error || "保存失败");
}